A database auditing system SQL injection detection method based on syntax tree comparison
By generating a baseline SQL statement and a malicious syntax tree and comparing them, this technology solves the problems of high false positive rate, high false negative risk, and insufficient flexibility in SQL injection detection in existing technologies. It achieves high-precision SQL injection detection and real-time defense, thereby improving the security of database systems.
Patent Information
- Application Number
- CN202411344255.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-09-25
- Publication Date
- 2025-12-30
- Estimated Expiration
- 2044-09-25
AI Technical Summary
Existing keyword-matching-based SQL injection detection methods suffer from high false positive rates, false negative risks, lack of semantic understanding, difficulty in recognizing complex queries, and insufficient flexibility, resulting in poor detection performance in practical applications.
A syntax tree-based comparison method is adopted, using the ANTLR parser to generate a baseline and malicious syntax tree of SQL statements. By comparing the structure, operation depth and logic of the syntax trees, the level of SQL injection attack is distinguished and corresponding warning operations are performed.
It improves the accuracy of SQL injection detection, reduces the false positive rate and the risk of false negatives, enables refined detection and real-time defense of SQL injection behavior, and enhances the security defense capabilities of the database system.
Smart Images

Figure CN119180027B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to a method for judging SQL injection behavior in the field of database auditing, and more particularly to a method for detecting SQL injection in a database auditing system based on syntax tree comparison. Background Technology
[0002] Many current database auditing systems use keyword matching to detect SQL injection attacks. This method involves pre-setting a list of potentially malicious SQL keywords (such as "or 1=1", "and 1=1", etc.) and then searching for these keywords in received SQL statements. If a matching keyword is detected, the system assumes the SQL statement may contain an SQL injection attack and triggers the corresponding security response mechanism. The main drawback is that...
[0003] High false alarm rate:
[0004] False alarms in normal business scenarios: Many legitimate business SQL statements also contain expressions like "and 1=1", especially when dynamically constructing SQL statements. To simplify logic or maintain code consistency, developers may intentionally use such seemingly "suspicious" expressions. This leads to frequent false alarms in actual applications, causing unnecessary trouble and workload for administrators.
[0005] Lack of semantic understanding: Keyword matching methods cannot deeply understand the semantics and context of SQL statements, thus failing to accurately distinguish between legitimate expressions and malicious injection code. Even if two SQL statements are structurally very similar, their execution intent and results may be drastically different.
[0006] Risk of underreporting:
[0007] Variant attacks evade detection: Attackers can use techniques such as encoding, commenting, or concatenating malicious SQL statements to bypass keyword matching detection rules. These variant attack methods make it difficult for keyword matching-based methods to comprehensively cover all potential SQL injection threats.
[0008] Complex queries are difficult to identify: For complex query statements that contain multiple subqueries, complex conditional logic, or special SQL functions, keyword matching methods often fail to accurately determine whether they contain SQL injection behavior.
[0009] Insufficient flexibility:
[0010] Difficulty adapting to different databases: Different database systems may support different SQL dialects and syntax features. Keyword-based matching methods often struggle to adapt to these differences, leading to inconsistent detection results across different database environments.
[0011] Difficult to scalable and maintain: As new SQL keywords and attack techniques constantly emerge, keyword-based matching methods require continuous updates and maintenance of their keyword lists. However, this update process is often cumbersome and time-consuming, and it is difficult to guarantee comprehensiveness and timeliness.
[0012] In summary, keyword-based SQL injection detection methods suffer from drawbacks in practical applications, including high false positive rates, high false negative rates, and insufficient flexibility. Summary of the Invention
[0013] Purpose of the Invention: The purpose of this invention is to provide a SQL injection detection method for database auditing systems based on syntax tree comparison. This method can refine the detection layers of SQL injection, apply different defense methods to reduce false positive rates and false negative risks, and improve adaptability. Another purpose of this invention is to improve the accuracy of SQL injection detection while minimizing system resources, thereby improving the accuracy of SQL injection detection while maintaining strong system defense capabilities. Furthermore, it provides more granular response modes based on different SQL injection behaviors, allowing administrators and the system to focus more on addressing attacks, thus improving the database system's defense capabilities against SQL injection attacks.
[0014] Technical Solution: A SQL injection detection method for database auditing systems based on syntax tree comparison, implemented according to the following steps in the database auditing system:
[0015] 1) Obtain the SQL statements executed in the database auditing system as input;
[0016] 2) Preprocess the input SQL statement;
[0017] 3) After preprocessing and screening, ANTLR is used to build a baseline syntax tree for SQL statements that do not contain malicious characters;
[0018] 4) Use ANTLR to construct a malicious syntax tree for SQL statements containing malicious characters after preprocessing and screening;
[0019] 5) Compare the constructed baseline syntax tree with the malicious syntax tree;
[0020] 6) Obtain the comparison results of the baseline syntax tree and the malicious syntax tree obtained in step 5), and perform attack judgment on the SQL statement corresponding to the malicious syntax tree;
[0021] 7) Perform different early warning operations based on the attack judgment results obtained in step 6);
[0022] 8) Generate a detailed test report.
[0023] ANTLR is a powerful parser generation tool that can parse SQL statements into abstract syntax trees (ASTs) based on predefined syntax rules. Through the hierarchical structure of the AST, the system can clearly identify the key elements in the SQL statement, such as the table, fields, and operation types (e.g., SELECT, INSERT, UPDATE, DELETE), thus providing a precise basis for subsequent data classification and grading.
[0024] In this application, preprocessing can initially segment SQL statements, allowing the SQL statements to be compared to be split, reducing the system resource consumption of character traversal. Then, by comparing the baseline syntax tree and the malicious syntax tree, it is possible to more accurately determine whether an injection behavior has occurred, improving detection accuracy. Combined with different early warning operations, the defense behavior is refined, rather than all injection behaviors being identified as high-risk operations and consuming system resources. This ensures that limited defense capabilities are not redundant and wasted, and that administrators are not overwhelmed by dealing with various low-risk behaviors.
[0025] Furthermore, in step 2), the preprocessing operation includes the following steps:
[0026] A) Initialize the input SQL statement;
[0027] B) Obtain a pre-defined malicious character library;
[0028] C) Compare the initialized SQL statement with the malicious character database in step B) for quick screening. If malicious characters are found, proceed to step 4) to build a malicious syntax tree. If no malicious characters are found, proceed to step 3) to build a baseline syntax tree.
[0029] The pre-defined malicious character library (such as common SQL injection keywords, special symbols, etc.) is a standard technique in this field. You can refer to the OWASP SQL Injection Check Sheet (https: / / www.invicti.com / blog / web-security / sql-injection-cheat-sheet / ).
[0030] Furthermore, in the preprocessing operation of step 2), the initialization of the input SQL statement includes the following steps:
[0031] a) Obtain the input SQL statement;
[0032] b) Identify and remove comments from SQL statements;
[0033] c) Formatting statements: unify the case of SQL statements, remove unnecessary spaces and newlines, and insert spaces between keywords and symbols;
[0034] d) Remove irrelevant characters: including removing redundant semicolons, redundant parentheses, and redundant meaningless characters;
[0035] e) Standardize SQL keywords and symbols, including keyword alignment and symbol alignment;
[0036] f) Verify the integrity of the SQL statement to ensure it is executable.
[0037] Since the SQL statement has already been executed, it is executable before initialization. After initialization, the verification is performed again to check for any errors in the initialization process.
[0038] Furthermore, in steps 3) and 4), constructing the baseline syntax tree and the malicious syntax tree both include the following steps:
[0039] A) Define SQL syntax rules for ANTLR based on the SQL syntax rules in the database auditing system;
[0040] B) Use ANTLR to parse the preprocessed SQL statement to obtain a baseline syntax tree or malicious syntax tree containing the syntax structure and operation hierarchy of the SQL statement.
[0041] Malicious characters can only determine the basic presence of injection operations. However, further judgment is needed to determine whether the injection operation is an attempt to inject or an injection attack. By using ANTLR's syntax tree, invalid comparison nodes can be removed, and key nodes can be retained, making the comparison more efficient. This improves the efficiency and accuracy of the comparison and reduces the risk of false negatives.
[0042] Further, in step 5), the constructed baseline syntax tree is compared with the malicious syntax tree, including structural comparison, operation depth comparison, and logical comparison. The structural comparison includes comparison of node types, number of nodes, and relationships between nodes. The operation depth comparison calculates and compares the depths of the two, paying attention to whether there is an unusual increase in depth. The logical comparison assesses whether changes in the malicious syntax tree affect the execution logic of the SQL statement, especially checking whether conditional expressions and data manipulation statements have undergone unexpected changes.
[0043] Further, in step 6), the comparison results of the baseline syntax tree and the malicious syntax tree obtained in step 5) are obtained, and it is checked whether the differences can be used as evidence of an injection attack. Specifically, if the malicious syntax tree and the baseline syntax tree have the intention to cause the SQL statement to perform unauthorized operations or change the original query in terms of structure and logic, it is determined to be a successful SQL injection attack; if the malicious syntax tree and the baseline syntax tree have small differences in structure and logic and do not affect the overall execution logic, but have potential risks due to the presence of malicious characters, it is determined to be a low-risk SQL injection attempt.
[0044] By classifying SQL injection behaviors, different warning actions can be taken for each level of behavior, reducing the workload of administrators and allowing them to focus more on dealing with high-risk behaviors, thereby improving the system's defense capabilities.
[0045] Furthermore, in step 7), SQL injection attacks are marked as high-risk behaviors, high-priority alarms are triggered immediately, and blocking measures are taken to prevent further damage; SQL injection attempts are marked as low-risk behaviors, low-priority alarms are generated for administrator reference and subsequent analysis.
[0046] Low-risk behavior does not mean it is meaningless. It may lead to subsequent injection attacks due to injection attempts, so it can be used as a reference and for analysis by administrators.
[0047] Furthermore, in step 8), the detailed detection report includes at least the malicious SQL statement, the comparison results between the baseline syntax tree and the malicious syntax tree, the attack type, and the scope of impact.
[0048] It is important to clarify that the ultimate goal of this step is to organize the identified malicious syntax trees. Once a certain number of basic malicious syntax trees are collected, a malicious syntax tree library can be formed. By directly comparing SQL statements with the malicious syntax trees in the library, system resources are further saved and detection efficiency is improved. Furthermore, since the malicious syntax trees can also return values, iterative loops can be formed to create a machine learning model, further improving the malicious syntax tree library and enhancing detection accuracy.
[0049] Beneficial effects: Compared with the prior art, the present invention has the following advantages:
[0050] 1. By constructing a syntax tree of SQL statements based on ANTLR and performing comparative analysis, this application can deeply analyze the structure and logic of SQL statements, thereby more accurately identifying SQL injection attacks and distinguishing between two levels: attempted injection and successful attack. This hierarchical detection capability helps reduce false positives and false negatives and improve detection accuracy.
[0051] 2. Since the attack behavior has been subdivided, the classified attack behavior can also be differentiated into multiple warnings, so that the limited system resources and administrators will not be occupied by frequent low-risk false alarms, thus improving the overall resource allocation efficiency of the system.
[0052] 3. Combined with a database auditing system, since this application targets SQL statements in execution, it can achieve real-time auditing of database operations and immediate detection of SQL injection attacks. Once SQL injection behavior is detected, the system can quickly determine its threat level and trigger corresponding alarms and emergency response mechanisms. For SQL injections that have been successfully launched, measures can be taken immediately to block and repair them, effectively preventing the situation from escalating.
[0053] 4. By distinguishing between two levels of SQL injection attacks—attempted injection and successful attack—this application provides database administrators and security teams with more detailed threat intelligence. This intelligence helps to develop more targeted defense strategies, such as strengthening monitoring during specific time periods, optimizing database configurations, and updating security patches, thereby further improving the database's security defense capabilities. Attached Figure Description
[0054] Figure 1 This is a flowchart of the present invention. Detailed Implementation
[0055] To make the technical solution of the present invention clearer, the present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments.
[0056] Example
[0057] As attached Figure 1 As shown, a SQL injection detection method for a database auditing system based on syntax tree comparison is implemented according to the following steps in the database auditing system:
[0058] 1) Obtain the SQL statements executed in the database auditing system as input;
[0059] 2) Preprocess the input SQL statement;
[0060] The preprocessing operation includes the following steps:
[0061] A) Initialize the input SQL statement;
[0062] Initialization includes the following steps: obtaining the input SQL statement; identifying and removing comments in the SQL statement; formatting the statement: unifying the case of the SQL statement, removing redundant spaces and newlines, and inserting spaces between keywords and symbols; removing irrelevant characters: including removing redundant semicolons, redundant parentheses, and redundant meaningless characters; standardizing SQL keywords and symbols, including keyword alignment and symbol alignment; and verifying the integrity of the SQL statement to ensure its execution.
[0063] B) Obtain a pre-defined malicious character library;
[0064] The pre-defined malicious character library (such as common SQL injection keywords, special symbols, etc.) is a standard technique in this field. You can refer to the OWASP SQL Injection Check Sheet (https: / / www.invicti.com / blog / web-security / sql-injection-cheat-sheet / ).
[0065] C) Compare the initialized SQL statement with the malicious character database in step B) for quick screening. If malicious characters are found, proceed to step 4) to build a malicious syntax tree. If no malicious characters are found, proceed to step 3) to build a baseline syntax tree.
[0066] Example statement:
[0067] / / Pseudocode: SQL Injection Detection
[0068] function detectSQLInjection(inputSQL):
[0069] / / Preprocessing initialization and screening operations to determine if malicious content is included.
[0070] `if containsMaliciousChars(inputSQL)` / / Implementation details: Iterates through the SQL statement, checks if it contains preset malicious characters, and returns a boolean value.
[0071] / / Assign values to SQL statements containing malicious content and mark them.
[0072] markedAsSuspicious=True
[0073] 3) After preprocessing and screening, ANTLR is used to build a baseline syntax tree for SQL statements that do not contain malicious characters;
[0074] Statement example:
[0075] / / If it does not contain malicious content, it is considered a clean SQL statement, and a baseline syntax tree is built.
[0076] else:
[0077] baseAST = parseSQLToAST(inputSQL) / / Use the SQL parser to convert the SQL statement into an AST.
[0078] / / Returns the AST object
[0079] markedAsSuspicious = False
[0080] 4) Use ANTLR to construct a malicious syntax tree for SQL statements containing malicious characters after preprocessing and screening;
[0081] Constructing both the baseline syntax tree and the malicious syntax tree includes the following steps:
[0082] A) Define SQL syntax rules for ANTLR based on the SQL syntax rules in the database auditing system;
[0083] B) Use ANTLR to parse the preprocessed SQL statement to obtain a baseline syntax tree or malicious syntax tree containing the syntax structure and operation hierarchy of the SQL statement.
[0084] / / If marked as suspicious, perform further testing.
[0085] if markedAsSuspicious:
[0086] maliciousAST = parseSQLToAST(inputSQL) / / Parse potentially malicious SQL into an AST.
[0087] 5) Compare the constructed baseline syntax tree with the malicious syntax tree;
[0088] The completed baseline syntax tree is compared with the malicious syntax tree, including structural comparison, operation depth comparison, and logical comparison. The structural comparison includes comparison of node types, number of nodes, and relationships between nodes. The operation depth comparison calculates and compares the depth of the two, paying attention to whether there is any abnormal increase in depth. The logical comparison assesses whether changes in the malicious syntax tree affect the execution logic of SQL statements, especially checking whether conditional expressions and data manipulation statements have undergone unexpected changes.
[0089] Example statement: / / Step 3: Syntax tree comparison
[0090] differences = compareASTs(baseAST, maliciousAST) / / Returns the differences between the two
[0091] Specifically,
[0092] / / Auxiliary function: Logic for comparing two ASTs
[0093] function compareLogic(node1,node2):
[0094] / / If the operation types of the two nodes are different, the logic will not match.
[0095] if node1.operation! =node2.operation:
[0096] return False
[0097] / / Compare child nodes
[0098] for child1,child2 in zip(node1.children,node2.children):
[0099] if not compareLogic(child1,child2):
[0100] return False
[0101] / / Return True if all nodes match
[0102] return True
[0103] / / Auxiliary function: Calculate the depth of the AST
[0104] function depth(astNode):
[0105] if astNode is None:
[0106] return 0
[0107] else:
[0108] childDepths=[depth(child)for child in astNode.children]
[0109] return 1+max(childDepths,default=0)
[0110] Compare the syntax tree structure results:
[0111] if baseAST.structure! =maliciousAST.structure:
[0112] differences.append("Structural difference detected")
[0113] Compare the syntax tree depth results:
[0114] if baseAST.depth()! =maliciousAST.depth():
[0115] differences.append("Depth difference detected")
[0116] Compare the logical results of the syntax tree:
[0117] if not compareLogic(baseAST,maliciousAST):
[0118] differences.append("Logical difference detected")
[0119] / / Return the list of differences
[0120] return differences
[0121] 6) Obtain the comparison results of the baseline syntax tree and the malicious syntax tree obtained in step 5), and perform attack judgment on the SQL statement corresponding to the malicious syntax tree;
[0122] Obtain the comparison results of the baseline syntax tree and the malicious syntax tree obtained in step 5), and check whether the differences can serve as evidence of an injection attack. Specifically, if the malicious syntax tree and the baseline syntax tree have the same structure and logic that could lead to the execution of unauthorized operations or alteration of the original query, it is considered a successful SQL injection attack. If the malicious syntax tree and the baseline syntax tree have minor differences in structure and logic that do not affect the overall execution logic, but there is a potential risk due to the presence of malicious characters, it is considered a low-risk SQL injection attempt.
[0123] Example statement: / / Step 4: Malicious statement analysis and attack determination
[0124] attackType, severity = analyzeDifferences(differences) / / Determine the attack type and severity
[0125] Specifically:
[0126] / / Auxiliary function: Analyzes differences and determines attack type and severity
[0127] function analyzeDifferences(differences):
[0128] / / If discrepancies exist, further analysis is needed to determine whether it was an attempted or successful injection attack.
[0129] if"Structural difference detected"in differences or
[0130] "Depth difference detected" in differences or
[0131] "Logical difference detected" in differences:
[0132] / / Syntax tree error, possibly indicating successful SQL injection.
[0133] attackType="SQL Injection Successful"
[0134] severity = "High"
[0135] else:
[0136] / / No major anomalies found in the syntax tree; this could be an SQL injection attempt.
[0137] attackType="SQL Injection Attempt"
[0138] severity = "Low"
[0139] / / Returns the attack type and severity
[0140] return attackType,severity
[0141] 7) Perform different early warning operations based on the attack judgment results obtained in step 6);
[0142] For SQL injection attacks, mark them as high-risk behaviors, immediately trigger high-priority alerts, and take blocking measures to prevent further damage; for SQL injection attempts, mark them as low-risk behaviors, generate low-priority alerts, and provide them to administrators for reference and subsequent analysis.
[0143] Example statement: / / Generate alarm
[0144] generateAlert(attackType, severity) / / Generates alert information based on the attack type and severity.
[0145] else:
[0146] Clean SQL statements, no alerts required.
[0147] print("SQL statement is clean.")
[0148] 8) Generate a detailed test report.
[0149] A detailed detection report should include at least the malicious SQL statement, the comparison results between the baseline syntax tree and the malicious syntax tree, the attack type, and the scope of impact.
[0150] The embodiments described above are merely illustrative of several implementations of the present invention, and while the descriptions are specific and detailed, they should not be construed as limiting the scope of the present invention. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of the present invention, and these modifications and improvements all fall within the scope of protection of the present invention. Therefore, the scope of protection of this patent should be determined by the appended claims.
Claims
1. A database auditing system SQL injection detection method based on syntax tree comparison, characterized in that: In the database audit system, the following steps are implemented: 1) Obtain the SQL statements executed in the database audit system as input; 2) Preprocess the input SQL statements; 3) After preprocessing screening, use ANTLR to build a benchmark syntax tree for SQL statements without malicious characters; 4) Use ANTLR to build a malicious syntax tree for SQL statements with malicious characters after preprocessing screening; 5) Compare the benchmark syntax tree and the malicious syntax tree built in step 5); 6) Obtain the comparison results of the benchmark syntax tree and the malicious syntax tree in step 5), and determine the attack on the SQL statement corresponding to the malicious syntax tree; 7) Perform different warning operations according to the attack judgment result obtained in step 6); 8) Generate a detailed detection report; In step 6), obtain the comparison results of the benchmark syntax tree and the malicious syntax tree in step 5), and check if the difference part can be used as evidence of injection attack. If the malicious syntax tree and the benchmark syntax tree have different structures and logic that can cause unauthorized operation or change the original query intent of the SQL statement, it is determined as a successful SQL injection attack; If the malicious syntax tree and the benchmark syntax tree have small differences in structure and logic, but do not affect the overall execution logic, and there is a potential risk due to the existence of malicious characters, it is determined as a low-risk SQL injection attempt.
2. The syntax tree comparison based database auditing system SQL injection detection method of claim 1, wherein: In step 2), the preprocessing operation includes the following steps: A) Initialize the input SQL statement; B) Obtain a pre-set malicious character library; C) Compare the initialized SQL statement with the malicious character library in step B) for quick screening. If there are malicious characters, proceed to step 4) to build a malicious syntax tree. If there are no malicious characters, proceed to step 3) to build a benchmark syntax tree.
3. The syntax tree comparison based database auditing system SQL injection detection method of claim 2, wherein: In the preprocessing operation of step 2), initializing the input SQL statement includes the following steps: a) Obtain the input SQL statement; b) Identify and delete comments in the SQL statement; c) Format the statement: unify the case of the SQL statement, remove unnecessary spaces and line breaks, and insert spaces between keywords and symbols; d) Remove irrelevant characters: including removing unnecessary semicolons, removing unnecessary parentheses, and removing unnecessary meaningless characters; e) Standardize SQL keywords and symbols, including keyword alignment and symbol alignment; f) Verify the integrity of the SQL statement to ensure its executability.
4. The syntax tree comparison based database auditing system SQL injection detection method of claim 1, wherein: In steps 3) and 4), building a benchmark syntax tree and a malicious syntax tree both include the following steps: A) Define the SQL syntax rules of ANTLR according to the SQL syntax rules in the database audit system; B) Use ANTLR to parse the preprocessed SQL statement to obtain a benchmark syntax tree or a malicious syntax tree containing the syntax structure and operation level of the SQL statement.
5. The syntax tree comparison based database auditing system SQL injection detection method of claim 1, wherein: In the step 5), the constructed reference syntax tree and the malicious syntax tree are compared, including structure comparison, operation depth comparison and logic comparison, wherein the structure comparison includes node type comparison, node number comparison and relationship comparison between nodes; the operation depth comparison is to calculate and compare the depths of the two, and it is noted that whether there is an abnormal increase in the depth; the logic comparison is to evaluate whether the changes in the malicious syntax tree affect the execution logic of the SQL statement, and the logic comparison includes checking whether the condition expression and the data operation statement are changed unexpectedly.
6. The syntax tree comparison based database auditing system SQL injection detection method of claim 1, wherein: In the step 7), for the SQL injection attack, the behavior is marked as high-risk, a high-priority alarm is triggered immediately, and a blocking measure is taken to prevent further damage; for the SQL injection attempt, the behavior is marked as low-risk, a low-priority alarm is generated for the administrator to refer to and subsequent analysis.
7. The syntax tree comparison based database auditing system SQL injection detection method of claim 1, wherein: In the step 8), the detailed detection report at least includes the malicious SQL statement, the comparison result of the reference syntax tree and the malicious syntax tree, the attack type and the influence range.
Citation Information
Patent Citations
Method for detecting SQL (structured query language) injection vulnerability
CN102185930A
Grammatical analysis-based SQL injection prevention method and device
CN107526968A
SQL (Structured Query Language) injection detection method and device
CN114443685A
