File size: 2,561 Bytes
6960b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os
import sys
import unittest

# Add root to path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from detection.ai_detector import VulnerabilityDetector

class TestJavaDetection(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.detector = VulnerabilityDetector()

    def test_java_sqli_detection(self):
        # The user-provided Java SQLi snippet
        code = """
// Get username from parameters
String username = request.getParameter("username");
// Create a statement from database connection
Statement statement = connection.createStatement();  
// Create unsafe query by concatenating user defined data with query string
String query = "SELECT secret FROM Users WHERE (username = '" + username + "' AND NOT role = 'admin')";
// Execute query and return the results
ResultSet result = statement.executeQuery(query);
        """
        cwe, name, confidence, line, desc = self.detector.predict(code)
        
        print(f"DEBUG: Detected {cwe} - {name} (Conf: {confidence}) at line {line}")
        print(f"DEBUG: Description: {desc}")
        
        self.assertEqual(cwe, "CWE-89")
        # Regex data-flow should catch this with high confidence (1.0)
        self.assertEqual(confidence, 1.0)
        # Line where it's used in executeQuery
        self.assertEqual(line, 9)

    def test_java_cmd_injection(self):
        code = """
String script = request.getParameter("script");
Runtime.getRuntime().exec("sh " + script);
        """
        cwe, name, confidence, line, desc = self.detector.predict(code)
        self.assertEqual(cwe, "CWE-78")
        self.assertEqual(confidence, 1.0)

    def test_safe_java_jdbc(self):
        code = """
String username = request.getParameter("username");
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE username = ?");
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
        """
        cwe, name, confidence, line, desc = self.detector.predict(code)
        # Should NOT be caught by simple regex data-flow as pstmt.executeQuery() doesn't contain the tainted var name directly
        self.assertNotEqual(confidence, 1.0)

if __name__ == '__main__':
    test = TestJavaDetection()
    test.setUpClass()
    print("--- Running Java SQLi Test ---")
    test.test_java_sqli_detection()
    print("--- Running Java Cmd Inj Test ---")
    test.test_java_cmd_injection()
    print("--- Running Safe Java JDBC Test ---")
    test.test_safe_java_jdbc()
    print("--- All tests finished ---")