SQL (Structured Query Language) injection detection method and system and storage medium
This SQL injection detection method, which integrates custom decision tree ensemble learning and grid search optimization, combined with honeypot verification and logging, solves the problems of insufficient feature extraction and inaccurate model training in existing technologies, improving the efficiency and accuracy of SQL injection detection, especially in the face of unknown attacks.
Patent Information
- Application Number
- CN202511795865.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-02
- Publication Date
- 2026-01-02
- Estimated Expiration
- 2045-12-02
AI Technical Summary
Existing SQL injection detection technologies suffer from insufficient feature extraction, data imbalance during model training, blurred boundaries, overfitting, and insufficient semantic understanding, resulting in low detection efficiency, high false positive and false negative rates, and difficulty in dealing with new SQL injection attacks.
A custom decision tree is used for ensemble learning to train the SQL injection detection model. The model parameters are optimized through grid search. Combined with SQL honeypot verification and log recording and analysis, the detection capability and accuracy of the model are improved.
It significantly improves the model's ability to detect diverse and complex SQL injection attacks, reduces the false detection rate, enhances the predictive adaptability and robustness of detection to new data samples, and ensures the accuracy and reliability of detection.
Smart Images

Figure CN121262008A_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 in the prior art that the SQL injection feature extraction 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 the SQL injection and model prediction, resulting in 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 the 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: A SQL injection detection method, comprising the following steps: S01: parsing the HTTP traffic of the Web request; S02: extracting a SQL injection feature vector; 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; 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.
[0006] In the preferred technical solution, step S02 extracts a SQL injection feature vector, comprising: The HTTP payload data extracted by HTTP traffic analysis is extracted to extract a plurality of types of encoded feature data, and a plurality of types of encoded features are constructed. A plurality of classification encoding prediction models are generated by a plurality of classification machine learning algorithms for the plurality of types of encoded features, and a plurality of classification encoding detection is performed. According to the encoding result of the detection, a flat decoding is performed through a decoding scheduler to obtain a decoded load. The decoded load obtained is extracted to extract a SQL injection feature vector.
[0007] In the preferred technical solution, step S03 comprises: Setting model training parameters , is a SQL type sample balance factor, is a SQL difficult sample focusing parameter, is a fitting parameter factor, is the weight of the SQL injection feature, is an L2 regularization parameter, is a learning rate, is the number of trees in the model, is the number of layers of the trained decision tree model, and respectively represent the minimum and maximum values of information gain, and the loss function , represents the balance factor when SQL is normal load and injection load, represents the probability that the model predicts SQL as normal load and injection load, is a SQL difficult sample focusing parameter, is a smooth hinge loss function, represents the type value of the SQL load feature, is the predicted value of the SQL load feature through the model, and is combined with the information gain function , is the weight of the SQL injection feature, represents the sum of the first-order partial derivatives of the loss function in the left child set split from the training set, represents the sum of the second-order partial derivatives of the loss function in the left child set split from the training set, is an L2 regularization parameter, represents the sum of the first-order partial derivatives of the loss function in the right child set split from the training set, represents the sum of the second-order partial derivatives of the loss function in the right child set split from the training set, is the sum of the first-order partial derivatives of the loss function in the training set, is the sum of the second-order partial derivatives of the loss function in the data set, and a decision tree ensemble learning training SQL injection prediction model is constructed , Inject feature vectors into the SQL query and train the model using the training set: , among which, the Tree model Used to predict residuals , K The total number of decision trees; SQL injection prediction model trained Test using the test set, and based on F The optimal model is selected using a grid search with a score of 1.
[0008] In the preferred technical solution, 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 decision tree model k Corresponding residual prediction value ,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 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: For normal HTTP traffic.
[0009] In the preferred technical solution, after step S04, it further includes: if predicted as SQL injection, calling SQL honeypot for SQL injection verification, including: Receiving HTTP traffic through the listening unit And through the event occurrence unit Converting the traffic into SQL events, and simulating the SQL events through the simulation unit: assuming the IP address as The destination IP address, then starting the simulation service to the Request attempted port, after the simulation service is started, combining the database unit to automatically respond to the request of ; 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 analyzes them in combination with the SQL load lexical, syntax and semantics of , to determine whether it is normal behavior or SQL injection phenomenon; Through the scheduling unit, the analysis result is reacted: if the honeypot SQL injection is unsuccessful, the HTTP reverse transparent transmission Traffic, otherwise, if the honeypot SQL injection is successful, control the response Traffic.
[0010] In the preferred technical solution, the HTTP reverse transparent transmission includes: Confirming through the TLS gateway that its TLS encryption handshake is complete and the certificate is valid, and detecting through the IP unit, the frequency control unit and the token unit respectively, 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; Through the proxy unit, the request content of the real client is seamlessly sent to the specified service in the backend business cluster through the forwarding unit in a zero-copy manner.
[0011] In the preferred technical solution, it further includes: Judging whether the released HTTP traffic Has been verified by the honeypot, if so, updating the misdetected HTTP normal traffic to the SQL injection sample set D : , , , And retraining the model; 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.
[0012] In the preferred technical solution, 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 logkey log information of them are recorded in different log fields and finally fused to write into a log table log_table= to realize a structured SQL log recording operation.
[0013] The application further discloses a SQL injection detection system, which comprises: an HTTP traffic analysis module, which analyzes HTTP traffic of a web request; a feature extraction module, which extracts a SQL injection feature vector; 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; 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.
[0014] The application further discloses a computer storage medium, which stores a computer program, and the computer program is executed to realize the SQL injection detection method.
[0015] Compared with the prior art, the application has the following advantages: The SQL injection feature fusion improves the quality of the SQL injection feature vector and has strong prediction adaptability to new data samples, and further improves the prediction accuracy of unknown SQL injection of the model on real-time HTTP traffic. F 1- Score The grid search is evaluated by testing to improve the timeliness of the model.
[0016] Further, the detection result is fed back to the training sample 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 generalization ability of detection, but also guarantees the accuracy and reliability of 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 a deterrent effect on malicious attackers can be formed, providing more effective detection and defense means for the field of Web application security, and showing the practicability and market potential of the method in the SQL injection detection and defense. BRIEF DESCRIPTION OF DRAWINGS
[0017] Figure 1 a flow chart of the SQL injection detection method of the embodiment; Figure 2 a complete detection flow chart of the SQL injection detection system of the embodiment. DETAILED DESCRIPTION
[0018] The principle of the present application is that 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 multi-type encoding features of the HTTP load, uses multi-classification learning to flatten and decode, further extracts multi-dimensional SQL injection features, and converts them into feature vectors required for training the SQL injection model. 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 and decoding and SQL injection feature extraction, and then the information gain with the SQL feature factor and the self-defined decision tree are combined to train the SQL injection prediction model through the training set, 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 judged by the model prediction for 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 and 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 in combination with log recording and analysis, and the model is retrained.
[0019] Embodiment 1: As shown in the figure, a SQL injection detection method comprises the following steps: Figure 1 S01: parsing HTTP traffic of Web request; S02: extracting SQL injection feature vector; S03: constructing decision tree ensemble learning training SQL injection prediction model, and selecting optimal model by grid search optimization training parameter; S04: calling optimal model, inputting extracted SQL injection feature vector into model decision tree structure and binary classification conditional probability to obtain prediction result.
[0020] The application is a SQL injection detection method combining model prediction and honeypot verification. The integrated learning model prediction of the application has strong unknown SQL injection prediction adaptability to HTTP traffic. The SQL honeypot can accurately, stably and reliably verify SQL injection. Therefore, the combination of model prediction and honeypot verification not only improves the generalization ability of detection, but also ensures the detection accuracy and reliability.
[0021] Based on the retraining mechanism of honeypot verification and log recording and analysis, the detection results are fed back to the training samples for repeated training, which not only greatly improves the accuracy of the SQL injection attack detection model in the confrontation environment, but also improves the timeliness of the model.
[0022] Innovative fusion of SQL injection feature vector representation: in order to enhance the understanding of SQL statement semantics by the model, the fusion of HTTP real-time traffic parsing, HTTP payload multi-type encoding feature extraction and multi-classification learning flat decoding, and multi-dimensional structure SQL injection feature extraction and normalized feature vector construction is used 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. In addition, it also improves the accuracy of the model in detecting SQL injection of HTTP real-time traffic, especially in detecting unknown attack HTTP traffic.
[0023] According to the characteristics of SQL injection, SQL type balance factor and SQL difficult sample focusing parameter are introduced in the loss function. In the machine learning of SQL injection detection, the loss function with SQL type balance factor and SQL difficult sample focusing parameter is introduced to solve the problems of sample imbalance, boundary ambiguity and difficult learning of SQL payload.
[0024] The SQL injection detection model is trained by self-defined decision tree ensemble learning, and the test set and F 1- ScoreThe optimal model is optimized and selected through the grid search, which not only significantly accelerates the fitting of the model, but also greatly improves the detection ability of the model on the multiple 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 samples, and further improves the accuracy of the model in detecting SQL injection.
[0025] In another embodiment, a computer storage medium has stored thereon a computer program which, when executed, implements the above-described SQL injection detection method. The following specific implementation method is adopted, which will not be described here.
[0026] In another embodiment, a SQL injection detection system comprises: An HTTP traffic analysis module analyzes the HTTP traffic of the Web request; A feature extraction module extracts a SQL injection feature vector; A SQL injection prediction model training module constructs a decision tree ensemble learning to train a SQL injection prediction model, and optimizes the training parameters through the grid search to select the optimal model; A 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 of the model, and obtains a prediction result.
[0027] Specifically, the following describes the working process of the SQL injection detection system with the preferred embodiment as an example: As shown in Figure 2 , the detailed steps include: 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.
[0028] 2. Read the 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 the HTTP payload with URL encoding, refers to the HTTP payload with Base64 encoding, refers to the HTTP payload with QR64 encoding, refers to the HTTP payload with Unicode encoding, refers to the HTTP payload with Hex encoding, Refers to the HTTP payload with HTML encoding. Jump to step 5.
[0029] 3. Web Listening. Start the web service port and wait for user web requests. If it is not a web request, continue listening.
[0030] 4. HTTP Traffic Parsing. Upon receiving a user's web request, the HTTP payload will be extracted using the HTTP payload extraction method (…). HTTP traffic for web requests Perform parsing and extract the HTTP payload: .exist 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. .
[0031] 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. URL encoding feature vector, which includes "%" and "+" and other feature characters. Base64 encoding feature vector, which includes "=" and " / " and "+" and other feature characters and the modulus 4 value of the payload length. QR64 encoding feature vector, which includes the replacement characters to prevent the Base64 encoded content from being URL encoded. Unicode encoding feature vector, which includes "\u" and "\U" and other feature characters and the frequency distribution of hexadecimal characters. Hex encoding feature vector, which includes "0x" or "\x" and other feature characters and the proportion of hexadecimal characters (0-9, A-F / a-f) in the string. HTML encoding feature vector, which includes "&" and ";" and other feature characters and the relative proportion of the number of occurrences of numeric entities (…) and hexadecimal entities (…).
[0032] The method can be implemented by using existing methods, which will not be described here.
[0033] 6. Multi-classification learning and flat decoding. Based on the multi-type encoding features extracted in step 5, a multi-classification encoding prediction model is generated through a multi-classification machine learning algorithm: . Then, the multi-classification encoding prediction model is loaded and multi-classification encoding detection is performed: , the encoding type set . Among them, URL enc represents URL encoding, Base64 enc represents Base64 encoding, represents QR64 encoding, Unicode enc represents Unicode encoding, Hex enc represents Hex encoding, HTML enc represents HTML encoding, NONE and no encoding. The function represents the prediction probability of each category j .
[0034] Then, according to the detected encoding result, URL, Base64, QR64, Unicode, Hex, and HTML decoding sub-processes are simultaneously scheduled through a decoding scheduler to perform flat decoding: , the set of various decoding sub-processes . Among them, Dispatcher is a scheduler that schedules the decoding sub-processes according to FunctionPredictDifferent j Types, schedule corresponding decoding sub-processes to perform decoding operations, representing URL decoding sub-processes, representing Base64 decoding sub-processes, representing QR64 decoding sub-processes, representing Unicode decoding sub-processes, representing Hex decoding sub-processes, representing HTML decoding sub-processes. Finally, record and output the decoded payload .
[0035] 7. Multi-dimensional SQL injection feature extraction. . Among them, pl dec is the clean HTTP payload after step 6 decoding, Sqli _ Feature_Extration SQL injection features of the clean HTTP payload are extracted by Sqli _ Feature_Extration The method extracts basic size, syntax structure, syntax interpretation, complexity, comprehensive description, character separation, and other multi-dimensional feature vectors in the feature group in turn. is the basic size feature vector, which includes features such as the length and word number of the clean HTTP payload. is the syntax structure feature vector, which includes features such as single quotation marks, double quotation marks, left parentheses, right parentheses, single quotation mark parity flag, double quotation mark parity flag, left parenthesis parity flag, and right parenthesis parity flag. is the syntax interpretation feature vector, which includes features such as special symbols and comment symbols. is the complexity feature vector, which includes features such as logical operators and arithmetic operators. is the comprehensive description feature vector, which 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. is the character separation feature vector, which includes features such as white space characters.
[0036] 8. Multi-dimensional SQL injection feature checking. If it is the SQL injection feature vector of the sample, go to step 9 for SQL injection prediction model training. If it is the SQL injection feature vector of the HTTP flow, go to step 11 for SQI injection detection.
[0037] 9. SQL injection prediction model training. Set model training parameters , call the loss function , and combine the information gain function Model training is performed on the training set: . Wherein, the first Tree model is used to predict the residual error , is the prediction value of the model containing a decision tree, K is the total number of decision trees.
[0038] is the SQL type sample balancing factor, which is set according to the SQL sample type, and is used to alleviate the influence of type imbalance on loss weight distribution; is the SQL difficult sample focusing parameter, which is used to control the degree of SQL difficult sample suppression; is the fitting parameter factor, which is used to control the cost of splitting operation to prevent overfitting; is the weight of SQL injection feature, 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; is the L2 regularization parameter, which is used to control the size of leaf node weight to enhance the generalization ability; is the 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; is the number of trees in the model, which is used to control the number of training rounds; is the number of layers of the decision tree model, which not only covers shallow models but also includes deeper models; and are the minimum and maximum values of information gain, respectively, which are used to train optimal SQL injection features and optimal split points.
[0039] represents the balance factor when SQL is normal load and injection load. When SQL is normal load, When SQL is injection load, .
[0040] represents the probability that the model predicts SQL as normal load and injection load. When the model predicts SQL as normal load, wherein represents the probability that the model predicts SQL as normal load. When the model predicts SQL as injection load, .
[0041] focusing parameter for SQL-like samples.
[0042] type value representing a SQL payload feature.
[0043] predicted value for a SQL payload feature through a model.
[0044] weight for a SQL injection feature, sum of first-order partial derivatives of a loss function in a left child split out of a training set, sum of second-order partial derivatives of a loss function in a left child split out of a training set, L2 regularization parameter, sum of first-order partial derivatives of a loss function in a right child split out of a training set, sum of second-order partial derivatives of a loss function in a right child split out of a training set, sum of first-order partial derivatives of a loss function in a training set, sum of second-order partial derivatives of a loss function in a training set.
[0045] 10, optimal SQL injection prediction model selection. The SQL injection prediction model trained in step 9 is tested on a test set, and the model with the best performance is selected as the optimal SQL injection prediction model. by testing set, and according to F 1- Score optimal model is selected by grid search output. Go to step 3. Greatly improve the detection ability of the model to the variable and complex SQL injection attack. In addition, combined with the retraining optimization model, not only further improve the accuracy of the model to predict SQL injection, but also significantly improve the robustness of the SQL injection attack detection model in the confrontation environment.
[0046] 11, SQL injection model prediction. The optimal SQL injection prediction model trained in step 10 is called to predict the HTTP traffic from the Web request : . probability that the prediction result is a SQL injection type.
[0047] First, the SQL injection feature vector of the HTTP traffic is brought into each decision tree structure in the model , denotes a set of split nodes of the i-th decision tree, denotes the i-th decision tree, denotes the i-th decision tree, denotes the i-th decision tree, 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. Will to 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.
[0048] 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.
[0049] 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_ValidationIt 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.
[0050] 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 whichsrc ∈{ }, 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 conclusion. 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.
[0051] 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.
[0052] 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.
[0053] 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.
[0054] 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.
[0055] 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 training model for SQL injection prediction, and select the optimal model by optimizing the training parameters 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 of 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, Step S03 includes: Set 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 for training, 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 trained Test using the test set, and based on F The optimal model is selected using a grid search with a score of 1.
4. The SQL injection detection method according to claim 3, 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 decision tree model k Corresponding residual prediction value ,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 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.
5. The SQL injection detection method according to claim 4, 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 these error and data characteristics; the analysis unit receives these error and data characteristics 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.
6. The SQL injection detection method according to claim 5, characterized in that, HTTP reverse passthrough includes: The TLS gateway confirms that the TLS encrypted handshake is complete and the certificate is valid. The detection is performed through the IP unit, frequency control unit and token unit. 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.
7. The SQL injection detection method according to claim 5, 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.
8. The SQL injection detection method according to claim 5, 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.
9. 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 training SQL injection prediction model and selects the optimal model by optimizing the training parameters 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.
10. A computer storage medium having a computer program stored thereon, characterized in that, When the computer program is executed, it implements the SQL injection detection method according to any one of claims 1-8.
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