A sql injection detection and protection method and system based on blood analysis
Patent Information
- Application Number
- CN202611281271.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-24
- Publication Date
- 2026-10-16
AI Technical Summary
[0004]一是检测精度不足,仅依赖字符串级匹配,无法区分关键字处于字面量参数位置还是SQL语法结构位置,也难以兼容SQL在格式、写法、参数值上的正常差异,误报与漏报问题突出;
[0044]本申请提供了一种基于血缘分析的SQL注入检测防护方法,以唯一SQL事件标识将原始SQL、绑定参数、审批状态、语义指纹、抽象语法树、事件血缘子图、检测证据、风险等级和处置结果关联为同一事件链路,使各环节的中间数据和处理结果能够相互验证,实现从处置结果到输入来源的端到端溯源。
Smart Images

Figure CN122926419A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of database security and network security protection technology, and in particular to a method and system for detecting and protecting against SQL injection based on lineage analysis. Background Technology
[0002] Databases are the core infrastructure of information systems such as government affairs, finance, enterprise management, and data platforms. Business applications generate SQL statements based on external input to complete data query, write, modify, or delete operations. If the application's validation of input content, parameter position, or access permissions is insufficient, attackers can inject malicious SQL fragments to tamper with the execution logic, leading to security risks such as sensitive data leakage, data tampering, permission bypassing, and business interruption. Moreover, attacks often conceal their characteristics through coding distortion and multi-stage calls.
[0003] Existing protection solutions mostly focus on feature rule matching, web application firewalls, and database auditing, which have three core limitations:
[0004] First, the detection accuracy is insufficient. It relies solely on string-level matching and cannot distinguish whether the keyword is in the position of a literal parameter or in the position of an SQL syntax structure. It is also difficult to be compatible with normal differences in SQL format, writing style, and parameter values, resulting in prominent issues of false positives and false negatives.
[0005] Second, the lack of end-to-end tracing capability makes it impossible to trace the flow path of input between services, variables, and table fields. It is difficult to form a complete chain of evidence for second-order injection that is written before read, and it is easy to include static related objects that did not participate in this execution in the scope of risk, resulting in a distorted assessment of the scope of impact.
[0006] Third, the handling is not in line with the risks. The classification and judgment are not based on the context such as the data sensitivity level, the attributes of the access subject, and the business approval status. The protective actions are out of touch with the actual degree of harm, making it difficult to balance security protection and business availability. Summary of the Invention
[0007] To address the shortcomings of existing technologies, the present invention aims to provide a method and system for detecting and protecting against SQL injection based on lineage analysis, thereby achieving accurate identification of complex SQL injections, end-to-end tracing, and protection that matches the actual impact.
[0008] The objective of this invention is achieved through the following technical solution:
[0009] A method for detecting and protecting against SQL injection based on lineage analysis includes the following steps:
[0010] Collect the SQL statements to be executed by the application, binding parameters, approval status and business context, assign a unique SQL event identifier to each SQL execution, and perform normalization preprocessing on the SQL statements. The normalization preprocessing includes: separating literals from SQL structure, replacing literals with type placeholders to generate semantic fingerprints, so that SQL statements with the same semantics but different literal parameter values are grouped into the same SQL template.
[0011] The normalized SQL statement is parsed into an abstract syntax tree. The data objects involved in the SQL statement are extracted as lineage nodes, and the data flow relationship between the data objects is extracted as directed edges to construct an event lineage subgraph. The sensitivity level of the data objects is determined. When external input from the binding parameters or business context enters the data storage location, an untrusted input label is marked on the corresponding lineage node. The sensitivity level label and the untrusted input label are propagated along the directed edges actually traversed by the SQL execution in the event lineage subgraph. Static related objects that did not participate in the current execution are not included in the label propagation and impact scope calculation.
[0012] Perform multidimensional detection on the original SQL, abstract syntax tree, event lineage subgraph, and business context. The multidimensional detection includes at least pattern detection, behavior baseline comparison, and second-order injection-specific detection, and outputs a unified evidence set. The second-order injection-specific detection forms evidence based on the write edge and secondary call edge in the event lineage subgraph. The secondary call edge establishes cross-time sequence relationships through data storage location, fields, value digests, and timestamps.
[0013] Based on the unified evidence set and event lineage subgraph, the risk value is determined and a disposal instruction corresponding to the risk level is generated.
[0014] Perform graded protection actions according to the disposal instructions.
[0015] In one embodiment, generating a semantic fingerprint includes: calculating a digest by combining operation type, target object, SQL structure, function, and parameter position; the semantic fingerprint serves as an index for parsing cache, business baseline comparison, and alarm deduplication.
[0016] The standardized preprocessing also includes: identifying database dialects, cleaning up meaningless whitespace characters, and standardizing the representation of keywords and functions; restoring the encoded content according to a limited number of layers, saving the original text, the restoration results of each layer, and the decoding path; and marking segments that cannot be decoded according to the limited number of layers as anomalies and transferring them to the conservative detection process.
[0017] In one embodiment, the lineage node includes at least one of request parameters, variables, tables, fields, temporary objects, and output terminals; the data flow relationship includes at least one of read relationship, write relationship, join relationship, filter relationship, calculation relationship, aggregation relationship, and export relationship; each directed edge records the SQL event identifier, transformation expression, service identifier, account identifier, timestamp, and confidence level;
[0018] The propagation rules for the sensitivity level labels are as follows: computed columns, field aliases, temporary objects, and exported results inherit the highest sensitivity level from the upstream data source; sensitivity level labels are only allowed to be downgraded when data objects with sensitivity level labels have undergone approved de-identification operations, hash operations, or compliant aggregation operations; field renaming and data transfer storage do not clear the assigned sensitivity level labels and untrusted input labels.
[0019] In one embodiment, the method for establishing cross-service and cross-time sequence associations in the event lineage subgraph includes:
[0020] For synchronous calls, upstream and downstream SQL events are associated based on the call chain identifier;
[0021] For asynchronous calls, the production and consumption events are associated based on the message key;
[0022] For scenarios where writing precedes reading, a secondary call edge is established between the write event and the subsequent execution event based on the data storage location, field identifier, value summary, and timestamp, forming an evidence chain covering the initial write, storage, and secondary execution.
[0023] In one embodiment, the pattern detection simultaneously examines the original text, decoded text, token sequence, and abstract syntax tree to identify tautologies, UNION queries, stacked delimiters, anomalous comments, dangerous functions, system table probes, and code bypasses; wherein, the detection based on the abstract syntax tree is used to determine whether the suspicious keyword is located in a literal position or an SQL structure position, and combines the event lineage subgraph to confirm whether the external input actually reaches the corresponding structure position;
[0024] The behavioral baseline comparison establishes a behavioral baseline based on five dimensions: user, role, interface, tenant, and SQL template, and compares the degree of deviation between the current event and the historical access pattern.
[0025] The multidimensional detection also includes time-based blind injection detection and Boolean blind injection detection. The time-based blind injection detection compares the latency distribution differences of the same SQL template under similar load conditions, and the Boolean blind injection detection compares the differences in the returned results of paired requests under the same input conditions.
[0026] In one embodiment, determining the risk value includes: normalizing the data sensitivity score D, the scope of influence score I, the attack matching score A, the business context score B, and the historical risk score H respectively, and then calculating the risk value by weighting them according to preset weights, and limiting the calculation result to the range of 0 to 100.
[0027] Among them, business operations with an approval status of "approved" only reduce the business context score B, and do not offset the attack matching score A corresponding to the confirmed SQL injection attack evidence.
[0028] In one embodiment, the preset weight is: R = 0.30D + 0.20I + 0.30A + 0.10B + 0.10H.
[0029] In one embodiment, the mapping relationship between the risk level and the graded protection actions is as follows:
[0030] Risk values from 0 to 20 are classified as Level 1 low risk, requiring execution record monitoring and bypass auditing;
[0031] Risk values of 21 to 40 are classified as Level 2 low to medium risk, with added detailed evidence retention, strategy observation, and rectification prompts;
[0032] Risk values of 41 to 60 are classified into three levels of medium risk, triggering alarms and generating parameterized reconstruction candidates and shadow verification tasks;
[0033] Risk values of 61 to 80 are classified into four levels of medium to high risk, and temporary downgrading, manual review, and controlled gray-scale release are implemented.
[0034] A risk value of 81 to 100 is classified as a five-level high-risk level, which will immediately block execution and trigger traffic restrictions, circuit breakers, and temporary blacklists.
[0035] All temporary actions are configured with their scope of application, effective period, and automatic termination conditions.
[0036] In one embodiment, the execution conditions for parameterized reconstruction are as follows: priority is given to matching registered SQL templates, parameter types and access permissions are verified one by one, syntax compliance checks and shadow verification are performed, and only after all verifications pass can it be replaced with a pre-compiled parameterized query; for positions that cannot be parameterized, such as dynamic table names and sorting directions, verification is performed according to the allowed list, and requests that fail the verification are not automatically replaced but are transferred to manual processing.
[0037] A SQL injection detection and protection system based on lineage analysis includes:
[0038] The data acquisition module is used to collect the SQL statements to be executed by the application, binding parameters, approval status and business context, generate a unique SQL event identifier, and perform SQL statement normalization preprocessing. The normalization preprocessing includes: separating literals from SQL structure, replacing literals with type placeholders to generate semantic fingerprints, so that SQL statements with the same semantics but different literal parameter values are grouped into the same SQL template.
[0039] The lineage analysis module is used to parse normalized SQL into an abstract syntax tree, extract the data objects involved in the SQL statement as lineage nodes, extract the data flow relationship between data objects as directed edges, and construct an event lineage subgraph; determine the data sensitivity level, and when external input from the binding parameters or business context enters the data storage location, mark the corresponding lineage node with an untrusted input label, propagate the sensitivity level label and untrusted input label along the directed edges actually traversed in this SQL execution, and exclude static related objects that did not participate in this execution from the label propagation and impact scope calculation, and output the affected fields, related tables and downstream exits;
[0040] The SQL injection detection module receives raw SQL, abstract syntax tree, event lineage subgraph, and business context, performs execution pattern detection, behavior baseline comparison, and special detection, and outputs a unified evidence set. The special detection includes second-order injection special detection, which forms evidence based on the write edge and secondary call edge in the event lineage subgraph.
[0041] The protection decision module is used to determine the risk value and generate disposal instructions corresponding to the risk level based on a unified evidence set and event lineage subgraph.
[0042] The response execution module is used to execute graded protection actions corresponding to the risk level according to the disposal instructions.
[0043] Compared with the prior art, the beneficial effects of the present invention include at least the following:
[0044] This application provides a SQL injection detection and protection method based on lineage analysis. It uses a unique SQL event identifier to associate the original SQL, binding parameters, approval status, semantic fingerprint, abstract syntax tree, event lineage subgraph, detection evidence, risk level and handling result into the same event chain, so that the intermediate data and processing results of each link can be mutually verified, and end-to-end traceability from the handling result to the input source can be achieved.
[0045] This method propagates untrusted input labels and sensitivity level labels only along the directed edges actually traversed in this SQL execution, excluding statically associated objects that did not participate in this execution, thus ensuring that the impact range assessment results are accurately consistent with the actual data flow.
[0046] This method replaces literals with type placeholders and then generates semantic fingerprints by combining operation type, target object, SQL structure, function and parameter position. This allows SQL statements with the same semantics but different textual forms to be grouped into the same template, fundamentally reducing false positives and false negatives caused by differences in format and parameter values.
[0047] This method combines original text, decoded text, token sequence, abstract syntax tree, behavior baseline and lineage path for multi-level detection, and establishes secondary call edges through three elements: storage location + value digest + timestamp, to achieve end-to-end tracing of second-order injection and effective identification of time-based blind injection and Boolean blind injection.
[0048] This method integrates five scores—data sensitivity, scope of impact, attack matching degree, business context, and historical risk—into a five-level risk decision, ensuring that protective actions, from bypass auditing to immediate blocking, correspond to the actual degree of harm, while preventing the approval channel from being used to bypass attack judgment.
[0049] This method aggregates end-to-end audit records according to SQL event identifiers, feeds back manual review conclusions and operational data to the business baseline calibration and rule optimization process, so that protection capabilities are continuously improved during operation and the risks of false alarms and false alarms are effectively controlled. Attached Figure Description
[0050] Figure 1 This is a flowchart illustrating an SQL injection detection and protection method based on lineage analysis according to an embodiment of the present invention.
[0051] Figure 2 This is a schematic diagram of the SQL normalization preprocessing and semantic fingerprint generation process of an SQL injection detection and protection method based on lineage analysis according to an embodiment of the present invention.
[0052] Figure 3 This is a schematic diagram illustrating the process of event lineage subgraph construction and tag propagation in an SQL injection detection and protection method based on lineage analysis according to an embodiment of the present invention.
[0053] Figure 4 This is a flowchart illustrating the second-order injection-specific detection process of an SQL injection detection and protection method based on lineage analysis according to an embodiment of the present invention.
[0054] Figure 5 This is a flowchart of an SQL injection detection and protection system based on lineage analysis according to an embodiment of the present invention. Detailed Implementation
[0055] Exemplary embodiments will now be described more fully with reference to the accompanying drawings. However, these exemplary embodiments can be implemented in many forms and should not be construed as limited to the embodiments set forth herein; rather, they are provided to make the invention more thorough and complete, and to fully convey the concept of the exemplary embodiments to those skilled in the art.
[0056] For ease of understanding, the detailed execution process of the method of the present invention will first be described using steps S1 to S5 as the main thread, and then the various modules of the system that implement the method will be explained. The correspondence between each step and the system module is as follows: step S1 is executed by the data acquisition module, step S2 is executed by the lineage analysis module, step S3 is executed by the SQL injection detection module, step S4 is executed by the protection decision module, and step S5 is executed by the response execution module.
[0057] This invention employs a technical framework encompassing event acquisition and standardization, lineage construction and tag propagation, multi-dimensional detection and evidence fusion, risk calculation and strategy matching, and response execution and feedback updates. The system's inputs include the SQL to be executed, binding parameters, execution result summary, approval status, and its business context. Outputs include detection evidence associated with the SQL event, actual impact scope, risk level, handling instructions, and audit records. Each SQL execution is assigned a unique SQL event identifier, and subsequent intermediate data and processing results are linked through this identifier, preventing different detection components from generating isolated results that cannot be mutually verified.
[0058] like Figure 1 As shown, embodiments of this application provide a SQL injection detection and protection method based on lineage analysis, including the following steps: S1-S5. This method uses SQL events as the associated unit, normalizes the SQL text form through semantic fingerprinting, propagates untrusted input labels and sensitivity level labels along the actual lineage path traversed in this execution, reconstructs the second-order injection cross-temporal evidence chain based on write edges and secondary call edges, and integrates multi-dimensional detection evidence with data sensitivity, impact scope, business context, and historical risks into a tiered handling decision, thereby achieving accurate identification of complex SQL injections, end-to-end source tracing, and tiered protection matching the actual impact.
[0059] S1: Data Acquisition and Normalization Preprocessing
[0060] When a request reaches the database access point, the data acquisition module obtains the SQL statement to be executed by the application, binding parameters, execution result summary, approval status, and business context, and assigns a unique SQL event identifier to each SQL execution. The system associates the source IP, session information, user information, role and permission information, tenant, interface name, call chain identifier, target database, execution time, execution time, and number of returned rows with this event identifier. Passwords, tokens, and the original values of sensitive data are not included in the detection record; only mask values or summary values that meet the detection requirements are retained. By using unique SQL event identifiers, scattered collected information is associated into traceable event units, providing a unified anchor point for end-to-end traceability.
[0061] like Figure 2 As shown, the collected SQL statements enter the normalization preprocessing stage, which specifically includes the following processing:
[0062] (1) Database dialect identification. Identify the database type to which the SQL statement belongs, and normalize the dialect-specific syntax of MySQL backticks, Oracle DUAL tables, SQL Server square brackets, etc. into a unified representation, so as to eliminate the impact of dialect differences on subsequent analysis.
[0063] (2) Whitespace cleanup and keyword unification. Clean up meaningless whitespace characters in SQL statements, unify keywords to a uniform case, and normalize the equivalent function representation to a standard representation, so that SQL statements with the same semantics but different syntaxes become similar at the text level.
[0064] (3) Encoding Restoration. URL encoding, Unicode encoding, Base64 encoding, and hexadecimal encoding are restored sequentially according to a predetermined number of layers. The original text, the restoration results of each layer, and the decoding path are saved. Segments that cannot be decoded according to the predetermined number of layers are marked as abnormal and transferred to the conservative detection process.
[0065] (4) Literal Separation. Lexical scanning is performed on the SQL statement to identify and separate the literals and SQL structures in the SQL text. Literals refer to the specific parameter values that appear in the SQL statement in the form of strings, numbers, Boolean values, etc.; SQL structures refer to the keywords, identifiers, operators and syntax symbols that make up the syntactic skeleton.
[0066] (5) Semantic fingerprint generation. The separated literals are replaced with corresponding type placeholders, and then a summary is calculated by combining five dimensions: operation type, target object, SQL structure, function, and parameter position to form a semantic fingerprint. SQL statements with the same semantics but different literal parameter values are thus grouped into the same SQL template. This semantic fingerprint serves as an index for parsing caching, business baseline comparison, and alarm deduplication.
[0067] Semantic fingerprinting groups SQL statements with the same semantics but different textual forms into the same template, eliminating false positives and false negatives caused by differences in format, syntax, and parameter values at the source. At the same time, it retains parameter type information, so that abnormal changes in parameter types under the same template can be detected.
[0068] S2: Event lineage subgraph construction and tag propagation
[0069] like Figure 3 As shown, the lineage analysis module receives normalized SQL and semantic fingerprints, and performs the following processing:
[0070] S2.1 Abstract Syntax Tree Parsing
[0071] The normalized SQL statement is parsed into an abstract syntax tree, mapping queries, writes, subqueries, common table expressions, and stored procedure calls to a unified intermediate structure. When parsing fails, the system retains the failure location and exception token, does not generate unverified complete lineage relationships, and transfers the corresponding event to a conservative detection process.
[0072] S2.2 Bloodline Node and Directed Edge Extraction
[0073] The request parameters, variables, tables, fields, temporary objects, and output endpoints are extracted from the abstract syntax tree to form lineage nodes; read, write, join, filter, compute, aggregate, and export operations are formed into directed edges. Each directed edge records the SQL event identifier, transformation expression, service identifier, account identifier, timestamp, and confidence level. The graph structure composed of nodes and directed edges fully depicts the data objects involved in this SQL execution and their flow relationships, providing a structured foundation for accurately determining the scope of impact.
[0074] S2.3 Assignment of Untrusted Input Labels
[0075] When external input from bound parameters or business context enters the data storage location (i.e., is written to a table field), an untrusted input tag is marked on the corresponding lineage node. The untrusted input tag is associated with an SQL event identifier, recording the source interface, arrival time, and original carrier of the input. External input includes, but is not limited to, HTTP request parameters, API call parameters, message queue message content, and input data in batch processing tasks.
[0076] S2.4 Label Propagation Rules
[0077] The system determines the sensitivity level of data objects and propagates the sensitivity level label and untrusted input label along the directed edges actually traversed by the current SQL execution in the event lineage subgraph. The propagation process follows these rules:
[0078] (1) Propagation only along the edges actually traversed. Static associated objects that did not participate in this execution are not included in the label propagation and scope of influence calculation. For example, if table A has a foreign key relationship with table B in the data dictionary, but the SQL does not access table B through this foreign key, then table B and its fields will not be labeled.
[0079] (2) Sensitivity level inheritance. Computed columns, field aliases, temporary objects, and exported results inherit the highest sensitivity level from the upstream data source.
[0080] (3) Downgrade restrictions. Sensitivity level labels are allowed to be downgraded only when data objects with sensitivity level labels have undergone approved de-identification, hashing, or compliant aggregation operations.
[0081] (4) Label retention. Field renaming and data transfer storage do not clear the assigned sensitivity level labels and untrusted input labels.
[0082] Labels are propagated only along the directed edges that were actually traversed in this operation, excluding statically associated objects that did not participate in this execution, thus ensuring that the impact range assessment results are accurately consistent with the actual data flow.
[0083] S2.5 Cross-service and Cross-time-series Association
[0084] For synchronous calls, upstream and downstream SQL events are associated based on the call chain identifier;
[0085] For asynchronous calls, the production and consumption events are associated based on the message key;
[0086] For scenarios where writing precedes reading, a secondary call edge is established between the write event and subsequent execution events based on the data storage location, field identifier, value summary, and timestamp, forming an evidence chain covering the initial write, storage, and secondary execution. The lineage analysis module ultimately outputs an event lineage subgraph, tag propagation results, affected fields, related tables, and downstream exits.
[0087] By matching the call chain identifier, message key, and the three elements of "storage location + value digest + timestamp", cross-service and cross-time-series SQL events are associated as a complete chain, enabling the complete reconstruction of the second-order injection attack path of write-before-read.
[0088] S3: Multidimensional Detection and Unified Evidence Output
[0089] The SQL injection detection module receives the raw SQL, abstract syntax tree, event lineage subgraph, and business context, performs the following detections, and outputs a unified evidence set:
[0090] S3.1 mode detection
[0091] Pattern detection examines data at four levels simultaneously: raw text, decoded text, token sequence, and abstract syntax tree, identifying tautologies, UNION queries, stacked delimiters, anomalous comments, dangerous functions, system table probes, and encoding bypasses.
[0092] The detection based on the abstract syntax tree (AST) is used to determine whether a suspicious keyword is located in a literal or SQL structure position: when the suspicious keyword appears in a value node, it is determined to be in a literal position; when the suspicious keyword appears in a syntax node and changes the SQL statement structure, it is determined to be in an SQL structure position. The system combines an event lineage subgraph to confirm whether external input actually reaches the corresponding structure position, thus distinguishing between normal parameters containing only similar characters and injected inputs that change the SQL structure. By combining four levels of detection and AST position determination, the system accurately distinguishes between similar characters in parameter values and injected payloads in the structure, fundamentally solving the false positive problem caused by semantic differences in keyword positions.
[0093] S3.2 Behavioral Baseline Comparison
[0094] A behavioral baseline is established based on five dimensions: user, role, interface, tenant, and SQL template. Each dimension records the historical access patterns of the entity during normal business operations, including access frequency distribution, SQL template distribution, access time period distribution, and target data object range. The deviation of the current event from the historical baseline is calculated, and evidence of abnormal behavior is generated when the deviation exceeds a preset threshold. By characterizing normal access patterns across these five dimensions, low-frequency and covert injection attempts can be identified due to deviations from the baseline.
[0095] S3.3 Second-Order Injection Specialized Detection
[0096] like Figure 4 As shown, the second-order injection detection method forms evidence based on write edges and secondary call edges in the event lineage subgraph. Secondary call edges establish cross-temporal relationships through data storage location, fields, value digests, and timestamps: when the target field of a subsequent read event matches the storage location of a historical write event, the value digest matches, and the timestamps satisfy the chronological order, a secondary call edge is established between the write event and the execution event. The system checks whether untrusted input enters the SQL structure location in subsequent execution events; if it does, it is determined to be a second-order injection attack. By linking cross-temporal write and execution events into a complete chain of evidence using the three elements of "storage location + value digest + timestamp," end-to-end tracing of second-order injections is achieved.
[0097] S3.4 Time-Blind Betting and Boolean Blind Betting Special Test
[0098] The temporal blind injection detection method compares the latency distribution differences of the same SQL template under similar load conditions. Evidence of temporal blind injection is generated when the latency distribution shows a significant shift before and after injection. The Boolean blind injection detection method compares the differences in the returned results of paired requests under the same input conditions. Evidence of Boolean blind injection is generated when there are systematic differences in the returned results of the true / false branches of the conditions. Based on the statistical comparison of latency distribution and return differences, variants of blind injection attacks independent of syntax features are identified.
[0099] S3.5 Unified Evidence Output
[0100] Each detector outputs the evidence type, hit location, input source, confidence level, and description. All evidence constitutes a unified evidence set. Individual detection results with low confidence are only one piece of evidence and do not directly trigger irreversible actions.
[0101] The heterogeneous results from multiple detectors are normalized into a unified evidence structure, making the evidence comparable and fusionable. Low-confidence evidence does not trigger irreversible actions on its own, reducing the risk of business interruption caused by false alarms.
[0102] S4: Risk Assessment and Decision-Making
[0103] The protection decision-making module determines the risk value and generates disposal instructions corresponding to the risk level based on a unified evidence set and event lineage subgraph.
[0104] S4.1 Five-Dimensional Rating
[0105] (1) Data Sensitivity Score D. Determined based on the sensitivity level of the affected data objects in the event lineage subgraph. Sensitivity levels are divided into Level 1 core sensitive data (such as ID card numbers, bank card numbers, password digests), Level 2 important sensitive data (such as contact information, addresses), and Level 3 general sensitive data (such as dictionary tables, configuration items) according to the data classification and grading system. The score is calculated based on the highest sensitivity level actually accessed and the number of sensitive objects in this event.
[0106] (2) Impact Scope Score I. Based on the affected fields, related tables and downstream exits output by the lineage analysis module, the score is determined by comprehensively considering the number of affected data objects, the breadth of cross-table associations and the sensitivity of downstream exits.
[0107] (3) Attack matching score A. Based on the strength of the detected evidence in the unified evidence set, the score is determined by comprehensively considering the number of evidence, the diversity of evidence types, the confidence of each piece of evidence, and the danger of the hit location.
[0108] (4) Business Context Score B. Determined based on the collected approval status, access subject attributes, and business scenario. Anonymous access, unauthorized interface calls, cross-tenant data requests, access during abnormal periods, and high-frequency requests within a short period increase the score; business operations with an approval status of "approved" decrease the score.
[0109] (5) Historical Risk Score H. Determined based on the historical risk records of the access subject, SQL template or interface, including the number of historical alarms, the number of historical blockings, the number of attacks confirmed by manual review and the status of vulnerability remediation.
[0110] Risk is comprehensively quantified from five dimensions: data sensitivity, scope of impact, attack matching degree, business context, and historical risks, so that the risk value matches the actual degree of harm and avoids the assessment bias caused by a single dimension.
[0111] S4.2 Weighted Calculation
[0112] After the five scores are normalized, a risk value R is calculated by weighting them according to preset weights, and the calculation result is limited to the range of 0 to 100. In one embodiment, the preset weights are: R = 0.30D + 0.20I + 0.30A + 0.10B + 0.10H.
[0113] Business operations with an "approved" status only lower the business context score (B), and do not offset the attack matching score (A) corresponding to confirmed SQL injection attack evidence. The approval status only affects the business context dimension score, does not dilute confirmed attack evidence, and prevents attackers from using the approval process to circumvent high-risk assessments.
[0114] S4.3 Risk Level Mapping
[0115] The risk value is mapped to the following five levels: risk value 0 to 20 is Level 1 Low Risk; risk value 21 to 40 is Level 2 Low-Medium Risk; risk value 41 to 60 is Level 3 Medium Risk; risk value 61 to 80 is Level 4 Medium-High Risk; and risk value 81 to 100 is Level 5 High Risk. The protection decision module writes the action, scope of application, validity period, and rollback conditions into the disposal instruction, which is then processed by the response execution module.
[0116] The five-level risk mapping enables precise correspondence between protective actions and risk values, achieving a tiered approach from audit observation to immediate intervention.
[0117] S5: Graded protection implementation
[0118] The response execution module receives the disposal instruction, verifies the policy version, scope of application, validity period and rollback conditions, and then executes the graded protection action corresponding to the risk level according to the disposal instruction.
[0119] S5.1 Level 5 Protection Action
[0120] Level 1 (low risk) executes monitoring and bypass auditing; Level 2 (low-to-medium risk) adds detailed evidence retention, strategy observation, and rectification prompts; Level 3 (medium risk) triggers alarms and generates parameterized reconstruction candidates and shadow verification tasks; Level 4 (medium-to-high risk) executes temporary demotion, manual review, and controlled gray-scale release; Level 5 (high risk) immediately blocks execution and links with rate limiting, circuit breaking, and temporary blacklists. All temporary actions have defined scope of application, effective period, and automatic release conditions.
[0121] A tiered approach to handling incidents ensures business continuity during low-risk events and timely prevention of high-risk events, achieving a balance between security and business availability.
[0122] S5.2 Parametric Reconstruction
[0123] For events requiring parameterized refactoring, registered SQL templates are matched first, and parameter types and access permissions are verified one by one. Syntax compliance checks and shadow verification are performed, and only after all verifications pass can the pre-compiled parameterized query be replaced. For non-parameterized locations such as dynamic table names and sorting directions, verification is performed according to the allowed list. Requests that fail verification are not automatically replaced and are transferred to manual processing.
[0124] The parameterized refactoring process undergoes multiple verifications, including template matching, type validation, permission validation, syntax checking, and shadow verification, before replacement is executed, ensuring that the repair action itself does not introduce new security risks or business failures.
[0125] S5.3 Interception and Rate Limiting
[0126] The request interception unit can terminate abnormal database calls and roll back uncommitted transactions. Rate limiting policies can be applied according to the access subject, IP address, business interface, or tenant. During controlled gray-scale release, risk indicators and business operation indicators are continuously monitored. If anomalies occur, release is terminated and rollback is performed according to the handling instructions.
[0127] The interception, traffic restriction, and gray-scale release all have effective scopes and rollback conditions, making high-risk handling actions controllable and reversible.
[0128] S5.4 Audit Archiving and Feedback Updates
[0129] The system aggregates processed SQL statements, business contexts, event lineage subgraphs, sensitivity level tags, detection evidence chains, risk scores, policy versions, execution results, and rollback records according to SQL event identifiers. Alarms are aggregated and deduplicated based on event fingerprints and time windows before being sent to the relevant responsible persons. Manual review of conclusions, business anomaly records, vulnerability remediation status, and rollback results are written back to the event database. Normal business events are used to calibrate business baselines, while attack events, after desensitization, quality verification, and approval, are used for rule optimization or anomaly model training. If the false alarm rate, detection latency, or business anomaly rate exceeds a preset threshold during gray-scale or formal operation, the system lowers the automatic execution level or rolls back to a stable policy version.
[0130] The entire audit record is collected using SQL event identifiers, and manual review and operational data are fed back to the baseline and rule update process to form a continuously optimized protection closed loop.
[0131] like Figure 5 As shown in the figure, embodiments of this application also provide an SQL injection detection and protection system based on lineage analysis, including: a data acquisition module, a lineage analysis module, an SQL injection detection module, a protection decision module, and a response execution module.
[0132] The data acquisition module is used to collect the SQL statements to be executed by the application, binding parameters, approval status, and business context, generate unique SQL event identifiers, and perform SQL statement normalization preprocessing. The normalization preprocessing includes separating literals from SQL structures, replacing literals with type placeholders, and generating semantic fingerprints, so that SQL statements with the same semantics but different literal parameter values are grouped into the same SQL template. The specific processing flow of the data acquisition module is as described in S1.
[0133] The lineage analysis module parses normalized SQL into an abstract syntax tree, extracts data objects involved in the SQL statement as lineage nodes, extracts data flow relationships between data objects as directed edges, and constructs an event lineage subgraph. It determines data sensitivity levels, and when external input from the bound parameters or business context enters the data storage location, it marks the corresponding lineage node as an untrusted input. The sensitivity level label and the untrusted input label are propagated along the directed edges actually traversed during the SQL execution. Static related objects not involved in this execution are not included in the label propagation and impact calculation. The module outputs the affected fields, related tables, and downstream exit points. The specific processing flow of the lineage analysis module is as described in S2.
[0134] The SQL injection detection module receives raw SQL, an abstract syntax tree, an event lineage subgraph, and business context. It performs execution pattern detection, behavior baseline comparison, and specific detection, outputting a unified evidence set. The specific detection includes second-order injection detection, which forms evidence based on write edges and secondary call edges in the event lineage subgraph. The specific processing flow of the SQL injection detection module is described in S3.
[0135] The protection decision-making module is used to determine risk values and generate corresponding action instructions based on a unified evidence set and event lineage subgraph. The specific processing flow of the protection decision-making module is described in S4.
[0136] The response execution module is used to execute graded protection actions corresponding to the risk level according to the disposal instructions. The specific processing flow of the response execution module is as described in S5.
[0137] The output of the data acquisition module is connected to the input of the lineage analysis module. The output of the lineage analysis module is connected to the input of the SQL injection detection module and the protection decision module. The output of the SQL injection detection module is connected to the input of the protection decision module. The output of the protection decision module is connected to the input of the response execution module.
[0138] The system consists of five interconnected modules forming a unified event chain. The data acquisition module standardizes SQL events and generates semantic fingerprints. The lineage analysis module propagates untrusted input labels and sensitivity level labels along the directed edges actually traversed during the execution and outputs the precise scope of impact. The SQL injection detection module forms second-order injection evidence based on write edges and secondary call edges and outputs a unified evidence set. The protection decision module integrates attack evidence and business impact into tiered handling instructions. The response execution module executes tiered protection actions according to risk levels, thereby achieving accurate identification of complex SQL injections, end-to-end tracing, and protection that matches the actual impact.
[0139] Example 1: Normal parameter binding login query
[0140] The application executes `SELECT * FROM users WHERE username=? AND password=?`, binding parameters `username='admin'` and `password='123456'`, and the approval status is "approved".
[0141] The data acquisition module assigns a unique SQL event identifier to this SQL event and collects the bound parameters and approval status. Normalization preprocessing replaces the literals 'admin' and '123456' with string placeholders, generating a semantic fingerprint.
[0142] The lineage analysis module parses the abstract syntax tree, extracts the `users` table, and the `username` and `password` fields as lineage nodes to establish read relationships. External input only appears in literal parameter positions. Untrusted input tags are propagated to value nodes and confirmed as normal parameter passing by SQL structure position determination, without generating attack evidence.
[0143] The SQL injection detection module's execution pattern detection and behavior baseline comparison revealed no attack characteristics such as constant truth conditions or UNION queries. The access pattern was consistent with the historical baseline, and no valid attack evidence was found in the unified evidence set.
[0144] The protection decision module determined that the data sensitivity score D was low, the impact range score I was low, the attack matching score A was 0, the business context score B was low, and the historical risk score H was low. The weighted calculation yielded a risk value R of less than 20 points, which was judged as a level 1 low risk.
[0145] The response execution module allows the query, saving only the anonymized records and bypass audit results.
[0146] like Figure 4 As shown, Example 2: Detection of Second-Order Injection Attacks
[0147] The attacker submitted the username 'admin'-- through the registration interface.
[0148] First write event (E1): The application executes INSERT INTO users(username) VALUES(?), binding the parameter 'admin'--. The lineage analysis module recognizes the external input 'admin'-- and enters the storage location of the users.username field. It marks the input as untrusted on the corresponding lineage node and records the storage location as users.username, the value digest as HASH('admin\'--'), and the timestamp as T1.
[0149] Secondary execution event (E2): The scheduled task reads the users.username field and constructs an SQL statement through string concatenation: SELECT * FROM orders WHERE owner='+username+', meaning the read field value is directly concatenated to the condition value position of the WHERE clause. The lineage analysis module detects that the currently read field matches the storage location of the record in E1, the value summary matches, and the timestamp T2 is later than T1. Based on this, a secondary call edge is established between write event E1 and execution event E2.
[0150] Evidence Formation and Handling: The SQL injection detection module's second-order injection-specific detection forms evidence based on the write edge and the secondary call edge: the external input 'admin'—entering from the registration interface, stored in the users.username field, is then read and concatenated into the WHERE clause structure of the SQL statement, forming a consistent condition. A complete evidence chain covering the initial write, storage, and secondary execution is formed in the unified evidence set. The protection decision module determines that the attack matching score A is high, the data sensitivity score D is medium-high, the impact scope score I is medium-high, the business context score B is medium (non-approval operation), and the historical risk score H is medium. The weighted calculation yields a risk value R exceeding 81 points, classifying it as a level 5 high-risk operation. The response execution module immediately blocks the SQL execution, rolls back uncommitted transactions, triggers an alarm, and saves a complete tracing record containing the correlation between events E1 and E2.
[0151] Although embodiments of the present invention have been shown and described above, it is understood that the above embodiments are exemplary and should not be construed as limiting the present invention. Those skilled in the art can make changes, modifications, substitutions and variations to the above embodiments within the scope of the invention without departing from the principles and spirit of the invention, and all such changes should fall within the protection scope of the claims of the present invention.
Claims
1. A method for detecting and protecting against SQL injection based on lineage analysis, characterized in that, Includes the following steps: Collect the SQL statements to be executed by the application, binding parameters, approval status and business context, assign a unique SQL event identifier to each SQL execution, and perform normalization preprocessing on the SQL statements. The normalization preprocessing includes: separating literals from SQL structure, replacing literals with type placeholders to generate semantic fingerprints, so that SQL statements with the same semantics but different literal parameter values are grouped into the same SQL template. The normalized SQL statement is parsed into an abstract syntax tree. The data objects involved in the SQL statement are extracted as lineage nodes, and the data flow relationship between the data objects is extracted as directed edges to construct an event lineage subgraph. The sensitivity level of the data objects is determined. When external input from the binding parameters or business context enters the data storage location, an untrusted input label is marked on the corresponding lineage node. The sensitivity level label and the untrusted input label are propagated along the directed edges actually traversed by the SQL execution in the event lineage subgraph. Static related objects that did not participate in the current execution are not included in the label propagation and impact scope calculation. Perform multidimensional detection on the original SQL, abstract syntax tree, event lineage subgraph, and business context. The multidimensional detection includes at least pattern detection, behavior baseline comparison, and second-order injection-specific detection, and outputs a unified evidence set. The second-order injection-specific detection forms evidence based on the write edge and secondary call edge in the event lineage subgraph. The secondary call edge establishes cross-time sequence relationships through data storage location, fields, value digests, and timestamps. Based on the unified evidence set and event lineage subgraph, the risk value is determined and a disposal instruction corresponding to the risk level is generated. Perform graded protection actions according to the disposal instructions.
2. The SQL injection detection and protection method based on lineage analysis as described in claim 1, characterized in that, The generation of semantic fingerprints includes: calculating a digest by combining operation type, target object, SQL structure, function and parameter position; the semantic fingerprint serves as an index for parsing cache, business baseline comparison and alarm deduplication; The standardized preprocessing also includes: identifying database dialects, cleaning up meaningless whitespace characters, and standardizing the representation of keywords and functions; restoring the encoded content according to a limited number of layers, saving the original text, the restoration results of each layer, and the decoding path; and marking segments that cannot be decoded according to the limited number of layers as anomalies and transferring them to the conservative detection process.
3. The SQL injection detection and protection method based on lineage analysis as described in claim 1, characterized in that, The lineage node includes at least one of request parameters, variables, tables, fields, temporary objects, and output terminals; the data flow relationship includes at least one of read relationship, write relationship, join relationship, filter relationship, calculation relationship, aggregation relationship, and export relationship; each directed edge records the SQL event identifier, transformation expression, service identifier, account identifier, timestamp, and confidence level; The propagation rule for the sensitivity level label is as follows: computed columns, field aliases, temporary objects, and exported results inherit the highest sensitivity level from the upstream data source; Sensitivity level labels are only allowed to be downgraded when data objects with sensitivity level labels have undergone approved de-identification, hashing, or compliant aggregation operations; field renaming and data transfer storage do not clear the assigned sensitivity level labels and untrusted input labels.
4. The SQL injection detection and protection method based on lineage analysis as described in claim 1, characterized in that, The methods for establishing cross-service and cross-time sequence associations in the event lineage subgraph include: For synchronous calls, upstream and downstream SQL events are associated based on the call chain identifier; For asynchronous calls, the production and consumption events are associated based on the message key; For scenarios where writing precedes reading, a secondary call edge is established between the write event and the subsequent execution event based on the data storage location, field identifier, value summary, and timestamp, forming an evidence chain covering the initial write, storage, and secondary execution.
5. The SQL injection detection and protection method based on lineage analysis as described in claim 1, characterized in that, The pattern detection simultaneously examines the original text, decoded text, token sequence, and abstract syntax tree to identify tautologies, UNION queries, stacked delimiters, abnormal comments, dangerous functions, system table probes, and encoding bypasses. Among these, the detection based on the abstract syntax tree is used to determine whether the suspicious keyword is located in a literal position or an SQL structure position, and combines the event lineage subgraph to confirm whether the external input has actually reached the corresponding structure position. The behavioral baseline comparison establishes a behavioral baseline based on five dimensions: user, role, interface, tenant, and SQL template, and compares the degree of deviation between the current event and the historical access pattern. The multidimensional detection also includes time-based blind injection detection and Boolean blind injection detection. The time-based blind injection detection compares the latency distribution differences of the same SQL template under similar load conditions, and the Boolean blind injection detection compares the differences in the returned results of paired requests under the same input conditions.
6. The SQL injection detection and protection method based on lineage analysis as described in claim 1, characterized in that, The determination of the risk value includes: normalizing the data sensitivity score D, the scope of impact score I, the attack matching score A, the business context score B, and the historical risk score H respectively, and then calculating the risk value by weighting them according to the preset weights, and limiting the calculation result to the range of 0 to 100. Among them, business operations with an approval status of "approved" only reduce the business context score B, and do not offset the attack matching score A corresponding to the confirmed SQL injection attack evidence.
7. The SQL injection detection and protection method based on lineage analysis as described in claim 6, characterized in that, The preset weights are: R = 0.30D + 0.20I + 0.30A + 0.10B + 0.10H.
8. The SQL injection detection and protection method based on lineage analysis as described in claim 1, characterized in that, The mapping relationship between the risk level and the graded protection actions is as follows: Risk values from 0 to 20 are classified as Level 1 low risk, requiring execution record monitoring and bypass auditing; Risk values of 21 to 40 are classified as Level 2 low to medium risk, with added detailed evidence retention, strategy observation, and rectification prompts; Risk values of 41 to 60 are classified into three levels of medium risk, triggering alarms and generating parameterized reconstruction candidates and shadow verification tasks; Risk values of 61 to 80 are classified into four levels of medium to high risk, and temporary downgrading, manual review, and controlled gray-scale release are implemented. A risk value of 81 to 100 is classified as a five-level high-risk level, which will immediately block execution and trigger traffic restrictions, circuit breakers, and temporary blacklists. All temporary actions are configured with their scope of application, effective period, and automatic termination conditions.
9. The SQL injection detection and protection method based on lineage analysis as described in claim 8, characterized in that, The execution conditions for parameterized refactoring are as follows: priority is given to matching registered SQL templates, parameter types and access permissions are verified one by one, syntax compliance checks and shadow verification are performed, and only after all verifications pass can it be replaced with a pre-compiled parameterized query; for positions that cannot be parameterized, such as dynamic table names and sorting directions, verification is performed according to the allowed list, and requests that fail the verification will not be automatically replaced but will be transferred to manual processing.
10. A SQL injection detection and protection system based on lineage analysis, characterized in that, include: The data acquisition module is used to collect the SQL statements to be executed by the application, binding parameters, approval status and business context, generate unique SQL event identifiers, and perform SQL statement normalization preprocessing. The normalization preprocessing includes: separating literals from SQL structures, replacing literals with type placeholders to generate semantic fingerprints, and grouping SQL statements with the same semantics but different literal parameter values into the same SQL template. The lineage analysis module is used to parse normalized SQL into an abstract syntax tree, extract the data objects involved in the SQL statement as lineage nodes, extract the data flow relationship between data objects as directed edges, and construct an event lineage subgraph; determine the data sensitivity level, and when external input from the binding parameters or business context enters the data storage location, mark the corresponding lineage node with an untrusted input label, propagate the sensitivity level label and untrusted input label along the directed edges actually traversed in this SQL execution, and exclude static related objects that did not participate in this execution from the label propagation and impact scope calculation, and output the affected fields, related tables and downstream exits; The SQL injection detection module receives raw SQL, abstract syntax tree, event lineage subgraph, and business context, performs execution pattern detection, behavior baseline comparison, and special detection, and outputs a unified evidence set. The special detection includes second-order injection special detection, which forms evidence based on the write edge and secondary call edge in the event lineage subgraph. The protection decision module is used to determine the risk value and generate disposal instructions corresponding to the risk level based on a unified evidence set and event lineage subgraph. The response execution module is used to execute graded protection actions corresponding to the risk level according to the disposal instructions.