A SQL injection detection method, system and storage medium
By integrating custom decision tree learning and grid search to optimize model parameters, and combining SQL honeypot verification and logging, this method solves the problems of inaccurate feature extraction and high resource consumption in existing SQL injection detection, achieving efficient and accurate SQL injection detection.
Patent Information
- Application Number
- CN202511795865.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-02
- Publication Date
- 2026-02-17
- Estimated Expiration
- 2045-12-02
AI Technical Summary
Existing SQL injection detection technologies suffer from problems such as inaccurate feature extraction, high false positive and false negative rates, performance dependence on machine learning classifiers and training set quality, difficulty in dealing with new types of SQL injection attacks, and high resource consumption.
A custom decision tree ensemble learning model is used to train the SQL injection detection model. The model parameters are optimized through grid search, and the detection capability and accuracy are improved by combining SQL honeypot verification and log recording.
It significantly improves the model's ability to detect diverse and complex SQL injection attacks, reduces false positive and false negative rates, enhances the model's adaptability and robustness, and ensures the accuracy and reliability of detection.
Smart Images

Figure CN121262008B_ABST
Abstract
Description
TECHNICAL FIELD
[0001] The application belongs to the technical field of network data security, and relates to a SQL injection detection method and system and a storage medium. BACKGROUND
[0002] Pattern matching is the most common SQL injection detection technology, which includes sequence alignment and rule pattern set and other different methods. Among them, the SQL injection detection method based on rule pattern set matches and detects according to the pattern extracted from the SQL statement and the pre-defined rule set, such as the SQL injection detection based on the Aho-Corasick pattern matching algorithm. The SQL injection detection method based on sequence alignment does not need to predefine a rule set or build a rule library, and it detects SQL injection by matching the SQL payload pattern string and the text string in a certain way bit by bit, such as the SQL injection detection based on the KMP string matching algorithm. The reliability of the pattern matching technology in detecting known SQL injection attacks is relatively high, but it is difficult to cope with new SQL injection attacks. In addition, the time overhead of this technology is large, and at the same time, since the rule library needs to be constructed in advance, a too large rule library will occupy too many system memory resources and affect the detection performance, and a too small rule library will lead to low SQL injection detection efficiency. Moreover, rule maintenance is difficult. The syntax and semantic analysis technology verifies the legality of dynamically generated SQL statements by constructing a syntax tree for SQL injection detection. For example, the dynamic coloring analysis method uses SQL lexical and syntax analysis technology to parse the SQL statement into a SQL syntax tree through taint analysis, and judges whether there is a SQL injection attack according to the taint state. However, in a web application, there may be a large number of code paths and input combinations, which will lead to incomplete coverage of all possible situations, and therefore there will be a high false negative phenomenon.
[0003] In recent years, using machine learning for SQL injection detection has also become a new research technology for domestic and foreign scholars. The technology first preprocesses the SQL payload data through different text processing methods, then extracts the SQL injection features and converts them into a vector form with strong representation as training data, then trains various machine learning models using the constructed training set, and finally converts the recognition and confirmation of SQL injection statements into a binary classification problem. At present, researchers mainly use N-gram, BoW, TF-IDF, FastText, Word2Vec and Bert methods to convert the original SQL statement into a word vector feature representing it, and use various machine learning models such as SVM, AdaBoost, LSTM and CNN to train and detect SQL injection attacks. However, these methods are difficult to extract SQL statement features, and usually have false detection rate, missed detection rate and other situations due to inaccurate feature extraction, and the performance of these methods depends largely on the choice of machine learning classifier, and the quality of the training set will also affect the performance of the detection. SUMMARY
[0004] In view of the problems that the SQL injection feature extraction in the current SQL injection detection cannot fully utilize the structure and context information of the SQL statement, and the existing machine learning algorithms have data imbalance, boundary ambiguity, overfitting and insufficient semantic understanding when training SQL injection and model prediction, which causes low detection efficiency, false detection and missed detection rate and other problems, the purpose of the present application is to provide a SQL injection detection method, system and storage medium, which trains a SQL injection detection model by self-defined decision tree integration learning, and optimizes and selects the optimal model through grid search, which not only significantly speeds up the model fitting, but also greatly improves the detection ability of the model for variable and complex SQL injection attacks.
[0005] The technical solution for achieving the purpose of the present application is:
[0006] A SQL injection detection method, comprising the following steps:
[0007] S01: parsing the HTTP traffic of the Web request;
[0008] S02: extracting the SQL injection feature vector;
[0009] S03: constructing a decision tree integration learning to train a SQL injection prediction model, and optimizing the training parameters through grid search to select the optimal model;
[0010] S04: calling the optimal model, inputting the extracted SQL injection feature vector into the decision tree structure and binary classification conditional probability of the model to obtain the prediction result.
[0011] In the preferred technical solution, step S02 extracting the SQL injection feature vector comprises:
[0012] For the HTTP payload data extracted through HTTP traffic analysis, extract feature data of multiple types of encoding, and construct multi-type encoding features;
[0013] Generate a multi-classification encoding prediction model for the multi-type encoding features through a multi-classification machine learning algorithm, and perform multi-classification encoding detection. According to the encoding result of the detection, perform flat decoding through a decoding scheduler to obtain decoded payload;
[0014] Extract the SQL injection feature vector from the obtained decoded payload.
[0015] In the preferred technical solution, step S03 comprises:
[0016] Setting model training parameters , SQL type sample balancing factor, SQL difficult sample focusing parameter, fitting parameter factor, SQL injection feature weight, L2 regularization parameter, learning rate, number of trees in the model, number of layers of the trained decision tree model, and respectively, the minimum and maximum values of information gain, and calling the loss function , represents the balance factor when SQL is normal payload and injection payload, represents the probability of the model predicting SQL as normal payload and injection payload, SQL difficult sample focusing parameter, smooth hinge loss function, represent the type value of the SQL payload feature, is the predicted value of the SQL payload feature through the model, and combines the information gain function , SQL injection feature weight, represents the sum of the first-order partial derivatives of the loss function in the left child set split out by the training set, represents the sum of the second-order partial derivatives of the loss function in the left child set split out by the training set, L2 regularization parameter, represents the sum of the first-order partial derivatives of the loss function in the right child set split out by the training set, represents the sum of the second-order partial derivatives of the loss function in the right child set split out by the training set, The sum of the first-order partial derivatives of the loss function in the training set, The sum of the second-order partial derivatives of the loss function in the data set, construct a decision tree ensemble learning training SQL injection prediction model , The SQL injection feature vector is trained by the training set: Wherein, the first Tree model For predicting residual error , K The total number of decision trees is;
[0017] The SQL injection prediction model obtained by training Test by test set, and according to F 1Score by grid search to select the optimal model.
[0018] In the preferred technical solution, the prediction result obtained in step S04 includes:
[0019] The SQL injection feature vector Input each decision tree structure in the model In, Indicates the split node set of the first Decision tree, Indicates the leaf node set of the first Decision tree, Indicates the candidate node set of the first Decision tree, Indicates the number of layers of the first Decision tree, Map So that Fall on a certain leaf node Of the tree;
[0020] According to the serial number Of the leaf node , get The residual prediction value corresponding to the decision tree model k , Wherein, ; Indicates the weight score of the leaf node , Indicates the weight score of the leaf node , Indicates the number of leaf nodes;
[0021] Add up the residual prediction values of all Trees, get the prediction value Of HTTP traffic ;
[0022] Convert to model prediction probability of SQL injection , compare with threshold , if , predict the HTTP traffic as SQL injection, otherwise, predict the HTTP traffic as normal HTTP traffic.
[0023] In the preferred technical solution, after step S04, it further includes, if predicted as SQL injection, calling SQL honeypot for SQL injection verification, including:
[0024] Receiving HTTP traffic through the listening unit and converting the traffic into SQL events through the event occurrence unit, simulating the SQL events through the simulation unit: assuming the IP address as the destination IP address, then starting the simulation service to the attempted port of the request, after the simulation service is started, combining the database unit to automatically respond to the request;
[0025] Capturing the error information and response data of the database unit through the capture unit, and judging whether the database is successfully SQL injected according to the error and data characteristics; the analysis unit receives these error and data characteristics, and combines the SQL load lexical, syntax and semantics to analyze whether it is normal or SQL injection phenomenon;
[0026] Reacting according to the analysis result through the scheduling unit: if the honeypot SQL injection is unsuccessful, the HTTP reverse transparent transmission traffic, otherwise, if the honeypot SQL injection is successful, controlling the response traffic.
[0027] In the preferred technical solution, the HTTP reverse transparent transmission includes:
[0028] Confirming through the TLS gateway that the TLS encryption handshake is complete and the certificate is valid, respectively detecting through the IP unit, the frequency control unit and the token unit, the detection including that the client IP is not in the recent abnormal list, the access frequency does not exceed the speed limit threshold, and the session token is complete;
[0029] Through the proxy unit, the request content of the real client is seamlessly sent to the specified service in the back-end business cluster through the forwarding unit in a zero-copy manner.
[0030] In the preferred technical solution, it further includes:
[0031] Determine which HTTP traffic to allow. Has the data been verified by a honeypot? If so, update the SQL injection sample set with any falsely detected normal HTTP traffic. D middle: , , , And retrain the model; This indicates the number of SQL injection samples. Indicates the first A SQL injection sample, Indicates the first The type of SQL injection sample;
[0032] If not, perform log analysis and update the SQL injection sample set with the missed SQL injection logs. D middle: , , , Then retrain the SQL injection prediction model. This indicates SQL injection log information.
[0033] In the preferred technical solution, step S04 is followed by SQL log recording, including:
[0034] HTTP traffic is traversed using data identification and traversal units respectively. Encoding payload Coding features Decoding payload SQL injection feature vector SQL injection prediction results ;
[0035] Combining log parsing unit and recording unit = Log_Extration ( src Record log information. This indicates SQL injection log information. Log_Extration This refers to performing log parsing, where src ∈{ }, ; Represents HTTP traffic Log information, Indicates the encoded payload Log information, Representing encoded features Log information, log information representing decoded payloads , log information representing SQL injection features , log information representing SQL injection prediction results ;
[0036] correlation analysis and record their correlation key information by Key unit log key = Key_Extration ( src ), Key_Extration ( src ) represents extracting correlation key information from src log key , record their log information in different log fields, and finally write into a log table log_table= , realizing structured SQL log recording operation.
[0037] The application further discloses a SQL injection detection system, comprising:
[0038] an HTTP traffic analysis module, which analyzes HTTP traffic of a Web request;
[0039] a feature extraction module, which extracts a SQL injection feature vector;
[0040] a SQL injection prediction model training module, which constructs a decision tree ensemble learning training SQL injection prediction model, and selects an optimal model by grid search optimization of training parameters;
[0041] a SQL injection model prediction module, which calls the optimal model, inputs the extracted SQL injection feature vector into a decision tree structure and a binary classification conditional probability of the model, and obtains a prediction result.
[0042] The application further discloses a computer storage medium, which stores a computer program, and the computer program is executed to realize the above-mentioned SQL injection detection method.
[0043] Compared with the prior art, the application has the following advantages:
[0044] The SQL injection feature fusion improves the quality of the SQL injection feature vector and has strong prediction adaptability to new data samples. In addition, the prediction accuracy of the model for unknown SQL injection of HTTP real-time traffic is also improved. The SQL injection prediction model is trained by self-defined decision tree for integrated learning, which significantly speeds up the model fitting. The SQL injection prediction model parameter optimization greatly improves the prediction ability of the model for various and complex SQL injection attacks. Through the test sample F 1- Score The test performs grid search to evaluate the optimal model to improve the timeliness of the model. Combined with SQL honeypot verification and SQL logging and analysis, the missed and wrong detection traffic is re-learned and trained, which improves the detection rate of the model and further reduces the false detection rate of the model.
[0045] In addition, the detection results are fed back to the training samples for repeated training to optimize the model, which not only further improves the accuracy of the model in predicting SQL injection, but also significantly improves the robustness of the SQL injection attack detection model in the confrontation environment. The SQL injection detection method combining model prediction and honeypot verification not only improves the detection generalization ability, but also guarantees the accuracy and reliability of the detection. Reverse transmission provides transparent and reliable communication for normal Web requests, ensuring system availability services. Through interception control and alarm response, not only can the attack of malicious SQL injection HTTP traffic on the backend business cluster be effectively resisted, the system data security can be effectively protected, but also the malicious attackers can be deterred, which provides more effective detection and defense means for the field of Web application security, and shows the practicality and market potential of the method in the SQL injection detection and defense. BRIEF DESCRIPTION OF DRAWINGS
[0046] Figure 1 The SQL injection detection method flowchart of the present embodiment;
[0047] Figure 2 The complete detection flowchart of the SQL injection detection system of the present embodiment. DETAILED DESCRIPTION
[0048] The principle of the present application is: the present application monitors the HTTP traffic of network Web requests in real time, parses the HTTP header, Method, URI, Version and Post load, extracts the HTTP load multi-type encoding features, uses multi-classification learning to flatten the decoding, further extracts the multi-dimensional SQL injection features, and converts them into the feature vectors required for SQL injection model training. In addition, according to the characteristics of SQL injection, a loss function is constructed, and the sample set (including the training set and the test set) is also subjected to multi-classification learning flattening decoding and SQL injection feature extraction, and then combined with the information gain and the self-defined decision tree with the SQL characteristic factor, the training set is used for integrated learning to train the SQL injection prediction model, and the test set and F 1- Score The optimal model is selected through grid search optimization. Finally, the real-time HTTP traffic features are predicted by the model to judge the SQL behavior, and the HTTP traffic predicted by the model as SQL injection is verified by the honeypot, and the HTTP traffic verified successfully is intercepted, controlled and alarmed. For the HTTP traffic predicted by the model as normal or the HTTP traffic verified unsuccessfully by the honeypot, the real-time HTTP traffic is released through HTTP reverse transmission, and the sample set is updated by combining log recording and analysis, and the model is retrained.
[0049] Embodiment 1:
[0050] As shown in Figure 1 A SQL injection detection method, comprising the following steps:
[0051] S01: parsing the HTTP traffic of Web requests;
[0052] S02: extracting the SQL injection feature vector;
[0053] S03: constructing a decision tree integrated learning to train a SQL injection prediction model, and selecting an optimal model through grid search optimization of training parameters;
[0054] S04: calling the optimal model, inputting the extracted SQL injection feature vector into the decision tree structure and binary classification conditional probability of the model to obtain a prediction result.
[0055] The present application is a SQL injection detection method combining model prediction and honeypot verification. The integrated learning model prediction of the present application has strong unknown SQL injection prediction adaptability for HTTP traffic. The SQL honeypot can accurately, stably and reliably verify SQL injection. Therefore, the combination of model prediction and honeypot verification in the present method improves the generalization ability of detection and guarantees the detection accuracy and reliability.
[0056] The retraining mechanism based on honeypot verification and log recording and analysis feeds the detection result into the training sample for repeated training, which greatly improves the accuracy of the SQL injection attack detection model in the confrontation environment and improves the timeliness of the model.
[0057] Innovative fusion of SQL injection feature vector representation: in order to enhance the understanding of the model to the SQL statement semantics, the HTTP real-time traffic analysis, HTTP load multi-type coding feature extraction and multi-classification learning flat decoding, and multi-dimensional structure SQL injection feature extraction and normalized feature vector construction are fused to strengthen the expression of SQL injection feature vector. This fusion not only improves the quality of SQL injection feature vector, but also improves the generalization ability of the model to new data samples, and further improves the accuracy of the model in detecting SQL injection of HTTP real-time traffic, especially in detecting unknown attack HTTP traffic.
[0058] According to the characteristics of SQL injection, the SQL type balance factor and the SQL difficult sample focusing parameter are introduced into the loss function. The loss function with the SQL type balance factor and the SQL difficult sample focusing parameter is introduced into the machine learning of SQL injection detection, which solves the problems of sample imbalance, boundary ambiguity and difficult learning of SQL load.
[0059] The SQL injection detection model is trained by self-defined decision tree integration learning, and the test set and F 1- Score The optimal model is selected by grid search optimization, which not only significantly speeds up the model fitting, but also greatly improves the detection ability of the model to various and complex SQL injection attacks. In addition, the SQL feature factor is introduced into the information gain, so that it pays more attention to the key SQL injection features in the training sample, and further improves the accuracy of the model in detecting SQL injection.
[0060] In another embodiment, a computer storage medium has a computer program stored thereon, which is executed to implement the above-mentioned SQL injection detection method. The following specific implementation method is adopted, which will not be described here.
[0061] In another embodiment, a SQL injection detection system comprises:
[0062] The HTTP traffic analysis module analyzes the HTTP traffic of the Web request;
[0063] The feature extraction module extracts the SQL injection feature vector;
[0064] The SQL injection prediction model training module constructs a decision tree integration learning to train the SQL injection prediction model, and selects the optimal model by grid search optimization of the training parameters;
[0065] The SQL injection model prediction module calls the optimal model, inputs the extracted SQL injection feature vector into the model decision tree structure and binary classification conditional probability, and obtains a prediction result.
[0066] Specifically, the working process of the SQL injection detection system is described below as an example of a preferred embodiment:
[0067] As shown in Figure 2 , the detailed steps include:
[0068] 1. Model checking. The present application first checks whether there is a trained model If not, it needs to jump to step 2 to train the model and save the model, otherwise it directly jumps to step 3 to enter the Web traffic monitoring state.
[0069] 2. Read sample set D . D The HTTP payload samples required for SQL injection prediction model training and testing, such as the collection of , etc. The sample set D is divided into training set and test set according to the characteristics of SQL injection in the ratio of 8:2 during model training and optimization. Among them, refers to HTTP payload with URL encoding, refers to HTTP payload with Base64 encoding, refers to HTTP payload with QR64 encoding, refers to HTTP payload with Unicode encoding, refers to HTTP payload with Hex encoding, refers to HTTP payload with HTML encoding. Jump to step 5.
[0070] 3. Web monitoring. Start the Web service port and wait for the user's Web request. If it is not a Web request, continue to monitor.
[0071] 4. HTTP traffic analysis. After receiving the user's Web request, the HTTP traffic of the Web request will be parsed by the HTTP payload extraction method to extract the HTTP payload: The method first determines whether the HTTP request uses TLS. If so, session verification is performed first, and then the decrypted byte stream is appended to a request object. Next, the streaming parsing state machine decodes the HTTP request line segment by segment: first, the request line is reconstructed to obtain the Method, URI, and Version; then, the headers are parsed line by line, using CRLF as the boundary, to obtain the original values. Then, normalization is performed: field names are normalized to lowercase and written to a hash table; field values are type-coded, for example, Content-Length is converted to an integer, and Cookie, Host, User-Agent, Authorization, and X-Forwarded-type fields are type-coded. The headers are then broken down into key-value pairs. Next, all raw values and the normalized results are written to the request context object. If the HTTP request carries entity data via POST or PUT, a buffer manager concatenates discontinuous or chunked data segments, then streams and decodes the entity data according to content types such as application / json and form, generating a request body key-value mapping. Finally, the structured object composed of Method, URI, Version, headers, and request body keys is serialized into a unified set of key-value pairs. .
[0072] 5. Multi-type encoding feature extraction. For data from the sample set in step 2 or HTTP payload data extracted through HTTP traffic parsing in step 4, the following steps are performed: The method extracts feature data with multiple encoding types, including URL, Base64, QR64, Unicode, Hex, and HTML, and constructs corresponding feature vectors. . .in, Its encoding types include URL encoding, Base64 encoding, QR64 encoding, Unicode encoding, Hex encoding, HTML encoding, as well as their combinations and nested encodings. This is a URL-encoded feature vector that includes feature characters such as "%" and "+". It is a Base64 encoded feature vector, which includes feature characters such as "=", " / ", "+" and a payload length modulo 4 value. This is a QR64 encoded feature vector, which includes replacement characters to prevent the Base64 encoded content from being URL encoded. It is a Unicode encoding feature vector that includes the frequency distribution of feature characters such as "\u" and "\U" as well as hexadecimal characters. The Hex-encoded feature vector includes feature characters such as "0x" or "\x" and the percentage of hexadecimal characters (0–9, A–F / a–f) in the string. The HTML-encoded feature vector includes feature characters such as "&" and ";", as well as the relative proportions of the occurrences of numeric entities (…;) and hexadecimal entities (…;).
[0073] The method can be implemented using existing methods, which will not be elaborated here.
[0074] 6. Multi-class learning flattened decoding. Based on the multi-type coding features extracted in step 5, a multi-class coding prediction model is generated using a multi-class machine learning algorithm: Then, load the multi-class coding prediction model. And perform multi-class coding detection: Encoding type set .in, URL enc Indicates URL encoding. Base64 enc This indicates Base64 encoding. Indicates QR64 encoding. Unicode enc Indicates Unicode encoding. Hex enc Indicates Hex encoding. HTML enc Indicates HTML encoding. NONE This indicates no encoding. The function represents each category j The predicted probability.
[0075] Next, based on the detected encoding results, the decoding scheduler simultaneously schedules URL, Base64, QR64, Unicode, Hex, and HTML decoding subprocesses for flattening decoding: A collection of various decoding subprocesses .in, Dispatcher It is a scheduler, based on Function predicts different j Type, schedule the corresponding decoding subprocess pair Perform decoding operation. This indicates the URL decoding sub-process. This indicates the Base64 decoding sub-process. This indicates the QR64 decoding sub-process. This indicates the Unicode decoding sub-process. This indicates the Hex decoding sub-process. This represents the HTML decoding sub-process. Finally, the decoded payload is recorded and output. .
[0076] 7. Multidimensional SQL injection feature extraction. .in, pl dec This is the clean HTTP payload after decoding in step 6. Sqli _ Feature_Extration Used to extract SQL injection characteristics from clean HTTP payloads, through Sqli _ Feature_Extration The method sequentially extracts multi-dimensional feature vectors from the feature group, including basic size, grammatical structure, grammatical interpretation, complexity, comprehensive description, and character separation. The basic scale feature vector includes features such as the length of the clean HTTP payload and the number of words. The feature vector is constructed for the syntax, which includes features such as single quotes, double quotes, left parentheses, right parentheses, single quote parity flags, double quote parity flags, left parentheses parity flags, and right parentheses parity flags. The feature vector for grammatical interpretation includes features such as special symbols and annotation symbols. This is a complexity feature vector, which includes features such as logical operators and arithmetic operators. To comprehensively describe the feature vector, it includes features such as the number of hexadecimal numbers, the number of letters, the number of numbers, the number of SQL keywords, and the number of SQL functions. This is a character-separating feature vector, which includes whitespace character features.
[0077] 8. Multidimensional SQL Injection Feature Check. If the sample contains an SQL injection feature vector, proceed to step 9 to train the SQL injection prediction model. If the sample contains an SQL injection feature vector from HTTP traffic, proceed to step 11 to perform SQL injection detection.
[0078] 9. Training the SQL injection prediction model. Setting model training parameters. Call the loss function And combined with information gain function Model training using the training set: Among them, the first Tree model Used to predict residuals , For inclusion The model predictions of the decision tree K The total number of decision trees.
[0079] is a SQL type sample balancing factor, which is set according to the SQL sample type setting, and is used to alleviate the influence of type imbalance on loss weight distribution;
[0080] is a SQL difficult sample focus parameter, which is used to control the degree of SQL difficult sample suppression;
[0081] is a fitting parameter factor, which is used to control the cost of splitting operation to prevent overfitting;
[0082] is a weight of SQL injection features, which is set according to different SQL injection feature types extracted by SQL load, and is used to train optimal SQL injection features and optimal split points;
[0083] is an L2 regularization parameter, which is used to control the size of leaf node weights to enhance the generalization ability;
[0084] is a learning rate, which is used to control the influence of each decision tree model on the entire SQL injection prediction model to balance between convergence speed and robustness;
[0085] is the number of trees in the model, which is used to control the number of rounds of model training;
[0086] is the number of layers of the decision tree model, which not only covers shallow models but also includes deeper models;
[0087] and are the minimum and maximum values of information gain, respectively, which are used to train optimal SQL injection features and optimal split points.
[0088] represents the balance factor when the SQL is normal load and injection load. When the SQL is normal load, When the SQL is injection load, .
[0089] represents the probability that the model predicts the SQL as normal load and injection load. When the model predicts the SQL as normal load, where represents the probability that the model predicts the SQL as normal load. When the model predicts the SQL as injection load, .
[0090] is a SQL difficult sample focus parameter.
[0091] Type value representing the SQL payload feature.
[0092] Predicted value for the SQL payload feature by the model.
[0093] Weight for the SQL injection feature, Sum of first-order partial derivatives of the loss function in the left child split out of the training set, Sum of second-order partial derivatives of the loss function in the left child split out of the training set, L2 regularization parameter, Sum of first-order partial derivatives of the loss function in the right child split out of the training set, Sum of second-order partial derivatives of the loss function in the right child split out of the training set, Sum of first-order partial derivatives of the loss function in the training set, Sum of second-order partial derivatives of the loss function in the training set.
[0094] 10. Optimal SQL injection prediction model selection. For the SQL injection prediction model trained in step 9 Test on the test set and select the optimal model according to F 1- Score Select the optimal model by grid search Output. Go to step 3. Greatly improve the detection ability of the model for variable and complex SQL injection attacks. In addition, combined with retraining the optimized model, not only further improve the accuracy of the model in predicting SQL injection, but also significantly improve the robustness of the SQL injection attack detection model in the confrontation environment.
[0095] 11. SQL injection model prediction. Call the optimal SQL injection prediction model trained in step 10 Predict on the HTTP traffic from the Web request : . Probability that the prediction result is the SQL injection type.
[0096] First, the SQL injection feature vector of the HTTP traffic is brought into each decision tree structure in the model, denotes the set of split nodes of the th decision tree, denotes the set of leaf nodes of the th decision tree, denotes the set of candidate nodes of the th decision tree, denotes the The number of layers in a decision tree. Will be Perform mapping so that It falls on a leaf node of the tree. Above, that is Secondly, based on the leaf nodes Serial number ,get The residual prediction value corresponding to this decision tree model .in, . Represents leaf nodes Weighted scores Represents leaf nodes Weighted scores This indicates the number of leaf nodes.
[0097] Then, all of them The HTTP traffic is obtained by summing the residual predictions of each tree. Predicted value This allows the model's predictions to gradually approach the true values. Then, through... ,Will Converting model predictions into SQL injection ( The probability of ) Finally, by setting a threshold and will With threshold The comparisons are then made to obtain the final prediction result. If Then predict the HTTP traffic containing SQL injection, i.e. .if Then predict the This is normal HTTP traffic, i.e. If SQL injection is predicted, proceed to step 12 to call the SQL honeypot for SQL injection verification. If normal HTTP traffic is predicted, proceed to step 13 to call the SQL logging module to record normal HTTP traffic and payload logs.
[0098] 12. SQL honeypot verification. shv = Sql_Honeypot_Validation ( Honeypot verification results shv ∈{ SQLI , NONE The SQL honeypot verification method of the present invention. Sql_Honeypot_Validation It consists of a listening unit, an event generation unit, a simulation unit, a database unit, a capture unit, an analysis unit, and a scheduling unit. The SQL honeypot first receives HTTP traffic through the listening unit. And through the event generation unit Traffic is converted into SQL events. These SQL events are then simulated using a simulation unit: assuming your IP address is... The destination IP address, and then... The request attempts to start a simulation service on the specified port. Once started, the simulation service will automatically respond in conjunction with the database unit. The request is then processed. Next, the capture unit captures the error messages and response data from the database unit, and determines whether the database has been successfully injected using SQL based on these error and data characteristics. Then, the analysis unit receives these error and data characteristics and combines them with... The SQL payload is analyzed lexically, syntactically, and semantically to determine whether it behaves normally or is an SQL injection vulnerability. Finally, the scheduling unit reacts based on the analysis results: if the honeypot SQL injection fails, it jumps to step 14 for reverse pass-through. Traffic. Otherwise, if the honeypot SQL injection succeeds, proceed to step 16 to control the response. flow.
[0099] 13. SQL log recording. log _ table = Sqli _ Log (). The SQL logging method of this invention Sqli _ Log By analyzing HTTP traffic Encoding payload Coding features Decoding payload SQL injection characteristics SQL injection prediction results The system parses, correlates, and merges data to achieve unified generation and recording of SQL logs. It includes data identification units, traversal units, parsing units, recording units, and key units. This is part of the SQL log recording method. Sqli _ Log In the process, the data is first traversed through data recognition and traversal units respectively. , , , , and Secondly, combining the log parsing unit and the recording unit log tfc = Log_Extration ( src Record their log information, among which src ∈{ }, Furthermore, key information related to these elements is analyzed and recorded through key unit association, such as client IP, request method, status code, and detection results. log key = Key_Extration ( src Then, their log information is recorded in different log fields, and finally merged and written into the log table. log_table= This enables structured SQL logging operations.
[0100] 14. HTTP reverse pass-through. HTTP _ Reverse_Proxy ( This invention utilizes an HTTP reverse pass-through method. HTTP _ Reverse_Proxy To ensure the smooth flow of normal data, HTTP reverse pass-through consists of a TLS gateway unit, IP unit, frequency control unit, token unit, proxy unit, and forwarding unit. For HTTP traffic with detected normal SQL, the TLS gateway first verifies that the TLS handshake is complete and the certificate is valid. Next, the IP unit, frequency control unit, and token unit perform checks to ensure the client IP is not on any recent anomaly lists, the access frequency does not exceed the rate limit threshold, and the session token is intact. Finally, the proxy unit, acting as the requesting client, seamlessly forwards the actual client's request content to the designated service in the backend business cluster using a zero-copy method via the forwarding unit.
[0101] 15. Model retraining. Sqli _ Model_Refit (). Determine which HTTP traffic to allow. Has it been verified by a honeypot? If so, update the SQL injection sample set with the falsely detected normal HTTP traffic. D middle: , , , Then retrain the model. If not, perform log analysis as needed. Log _ Analysis ( log_table And update the SQL injection sample set with the missed SQL injection logs. D middle: , , , Then, the SQL injection prediction model was retrained. This indicates the number of SQL injection samples. Indicates the first A SQL injection sample, Indicates the first The type of SQL injection sample; This indicates SQL injection log information.
[0102] 16. HTTP Flow Control Response. This involves predicting HTTP traffic using SQL injection models and verifying it with SQL honeypots. In the event of SQL injection, this invention will target the HTTP traffic. Intercept and control and The system requests an alarm response from the user. The HTTP traffic interception control and alarm response method includes a status unit, a control unit, and a response unit. First, the interception method is set through the status unit. sql _ status = SQLI _ HTTP _ FORBIDDEN This indicates a 403 Forbidden error. Then, control is intercepted via the control unit. flow, HTTP _ Control ( ). HTTP _ Control Indicates according to sql _ status The interception method Perform appropriate flow control. Finally, send a response to the sender through the response unit. The user is requested to output alarm information. HTTP _ Say ( ). HTTP _ Say This indicates that a response operation is sent to the traffic sender (user). This indicates that an alert message should be sent to the traffic sender.
[0103] 17. Determine if the SQL injection detection is complete. If not, proceed to step 3 to continue monitoring web requests. Otherwise, complete the SQL injection detection.
[0104] The above embodiments are preferred embodiments of the present invention, but the embodiments of the present invention are not limited to the above embodiments. Any changes, modifications, substitutions, combinations, or simplifications made without departing from the spirit and principle of the present invention shall be considered equivalent substitutions and shall be included within the protection scope of the present invention.
Claims
1. A method for detecting SQL injection, characterized in that, Includes the following steps: S01: Parse the HTTP traffic of web requests; S02: Extract SQL injection feature vectors; S03: Construct a decision tree ensemble learning model to train an SQL injection prediction model, and optimize the training parameters using grid search to select the optimal model; specifically including: setting model training parameters. , For SQL type sample balance factors, For focusing parameters on SQL hard samples, For fitting parameter factors, Weights of features injected into SQL. For L2 regularization parameters, For learning rate, The number of trees in the model. To determine the number of layers in the decision tree model, and The loss function is called to find the minimum and maximum information gain, respectively. , This represents the balance factor when SQL is used for normal load and injected load. This indicates the probability that the model predicts the SQL to be either a normal load or an injected load. For focusing parameters on SQL hard samples, For smooth hinge loss function, The type value representing the SQL payload characteristic. The SQL load features are represented by the model's predicted values, combined with the information gain function. , Weights of features injected into SQL. This represents the sum of the first-order partial derivatives of the loss function in the left subset of the training set. This represents the sum of the second-order partial derivatives of the loss function in the left subset of the training set. For L2 regularization parameters, This represents the sum of the first-order partial derivatives of the loss function in the right subset of the training set. This represents the sum of the second-order partial derivatives of the loss function in the right subset of the training set. The sum of the first-order partial derivatives of the loss function in the training set. The sum of the second-order partial derivatives of the loss function in the dataset is used to construct a decision tree ensemble learning training model for SQL injection prediction. , Inject feature vectors into the SQL query and train the model using the training set: , among which, the Tree model Used to predict residuals , For inclusion The model predictions of the decision tree K The total number of decision trees; SQL injection prediction model obtained from training Test using the test set, and based on F A score is used to select the optimal model through grid search; S04: Call the optimal model, input the extracted SQL injection feature vector into the decision tree structure and binary classification conditional probability in the model, and obtain the prediction result.
2. The SQL injection detection method according to claim 1, characterized in that, Step S02, extracting SQL injection feature vectors, includes: For HTTP payload data extracted through HTTP traffic parsing, feature data of various encoding types are extracted, and multi-type encoding features are constructed. A multi-class coding prediction model is generated from multi-class coding features using a multi-class machine learning algorithm, and multi-class coding detection is performed. Based on the detected coding results, the decoding is flattened and decoded by a decoding scheduler to obtain the decoding payload. Extract SQL injection feature vectors from the obtained decoded payload.
3. The SQL injection detection method according to claim 1, characterized in that, The prediction results obtained in step S04 include: SQL injection signature vector Each decision tree structure in the input model middle, Indicates the first The set of split nodes of a decision tree. Indicates the first The set of leaf nodes of a decision tree. Indicates the first The set of candidate nodes for a decision tree. Indicates the first The number of layers in a decision tree. right Perform mapping so that It falls on a leaf node of the tree. superior; Based on leaf nodes Serial number ,get In the k The residual prediction values of the model corresponding to each decision tree ,in, ; Represents leaf nodes Weighted scores Represents leaf nodes Weighted scores Indicates the number of leaf nodes; All of The HTTP traffic is obtained by summing the residual predictions of each decision tree. Predicted value ; Will Converted into the probability of SQL injection predicted by the model. ,Will With threshold Compare, if Then predict the If the HTTP traffic contains SQL injection vulnerabilities, then predict the following: This is normal HTTP traffic.
4. The SQL injection detection method according to claim 3, characterized in that, Step S04 is followed by, if SQL injection is predicted, then an SQL honeypot is invoked to verify the SQL injection, including: HTTP traffic is received through the listening unit. And through the event generation unit Traffic is converted into SQL events, and these SQL events are simulated using a simulation unit: assuming your IP address is... The destination IP address, and then... The request requests the port to start the simulation service. Once started, the simulation service will automatically respond in conjunction with the database unit. The request; The capture unit captures error messages and response data from the database unit, and determines whether the database has been successfully injected using SQL based on the characteristics of the error messages and response data; the analysis unit analyzes the characteristics of the error messages and response data received, and combines them with... The SQL payload is analyzed in terms of lexical, syntactic and semantic aspects to determine whether the behavior is normal or an SQL injection phenomenon. The scheduling unit reacts based on the analysis results: if honeypot SQL injection fails, HTTP reverse passthrough is performed. Traffic; otherwise, if the honeypot SQL injection succeeds, control the response. flow.
5. The SQL injection detection method according to claim 4, characterized in that, HTTP reverse passthrough includes: The TLS gateway confirms that the TLS encrypted handshake has been completed and the certificate is valid. The detection is performed through the IP unit, frequency control unit and token unit respectively. The detection includes that the client IP is not in the recent abnormal list, the access frequency does not exceed the rate limit threshold, and the session token is complete. The proxy unit acts as the request client, seamlessly sending the request content from the actual client to the designated service in the backend business cluster in a zero-copy manner through the forwarding unit.
6. The SQL injection detection method according to claim 4, characterized in that, Also includes: Determine which HTTP traffic to allow. Has the data been verified by a honeypot? If so, update the SQL injection sample set with any falsely detected normal HTTP traffic. D middle: , , , And retrain the model; This indicates the number of SQL injection samples. Indicates the first A SQL injection sample, Indicates the first The type of SQL injection sample; If not, perform log analysis and update the SQL injection sample set with the missed SQL injection logs. D middle: , , , Then retrain the SQL injection prediction model. This indicates SQL injection log information.
7. The SQL injection detection method according to claim 4, characterized in that, Step S04 is followed by SQL log recording, including: HTTP traffic is traversed using data identification and traversal units respectively. Encoding payload Coding features Decoding payload SQL injection feature vector SQL injection prediction results ; Combining log parsing unit and recording unit = Log_Extration ( src Record log information. This indicates SQL injection log information. Log_Extration This refers to performing log parsing, where src ∈{ }, ; Represents HTTP traffic Log information, Indicates the encoded payload Log information, Representing encoded features Log information, Indicates decoding payload Log information, Indicates SQL injection characteristics Log information, Indicates the SQL injection prediction result Log information; Key cell association analysis and recording of their key association information. log key = Key_Extration ( src ), Key_ Extration ( src ) indicates from src Extract relevant key information log key Their log information is recorded in different log fields, and finally merged and written into the log table. log_table= This enables structured SQL logging operations.
8. An SQL injection detection system, characterized in that, include: The HTTP traffic parsing module parses the HTTP traffic of web requests; The feature extraction module extracts SQL injection feature vectors. The SQL injection prediction model training module constructs a decision tree ensemble learning model for training SQL injection prediction, and optimizes the training parameters through grid search to select the optimal model. Specifically, this includes setting model training parameters. , For SQL type sample balance factors, For focusing parameters on SQL hard samples, For fitting parameter factors, Weights of features injected into SQL. For L2 regularization parameters, For learning rate, The number of trees in the model. To determine the number of layers in the decision tree model, and The loss function is called to find the minimum and maximum information gain, respectively. , This represents the balance factor when SQL is used for normal load and injected load. This indicates the probability that the model predicts the SQL to be either a normal load or an injected load. For focusing parameters on SQL hard samples, For smooth hinge loss function, The type value representing the SQL payload characteristic. The SQL load features are represented by the model's predicted values, combined with the information gain function. , Weights of features injected into SQL. This represents the sum of the first-order partial derivatives of the loss function in the left subset of the training set. This represents the sum of the second-order partial derivatives of the loss function in the left subset of the training set. For L2 regularization parameters, This represents the sum of the first-order partial derivatives of the loss function in the right subset of the training set. This represents the sum of the second-order partial derivatives of the loss function in the right subset of the training set. The sum of the first-order partial derivatives of the loss function in the training set. The sum of the second-order partial derivatives of the loss function in the dataset is used to construct a decision tree ensemble learning training model for SQL injection prediction. , Inject feature vectors into the SQL query and train the model using the training set: , among which, the Tree model Used to predict residuals , For inclusion The model predictions of the decision tree K The total number of decision trees; SQL injection prediction model obtained from training Test using the test set, and based on F A score is used to select the optimal model through grid search; The SQL injection model prediction module calls the optimal model, inputs the extracted SQL injection feature vector into the decision tree structure and binary classification conditional probability in the model, and obtains the prediction result.
9. A computer storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the SQL injection detection method according to any one of claims 1-7.
Citation Information
Patent Citations
Machine learning-based SQL injection detection method, and database security system
CN108549814A
SQL injection attack detection method and device based on HTTP flow, equipment and medium
CN115333776A