Cross-site scripting attack detection method, electronic device, and storage medium
Patent Information
- Application Number
- CN202611024191.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-10
- Publication Date
- 2026-09-11
- Estimated Expiration
- 2046-07-10
AI Technical Summary
机器学习驱动的检测方法虽尝试通过神经网络模型捕捉异常模式,但高度依赖训练数据的质量与覆盖范围,模型可解释性差且对对抗样本攻击敏感
[0014] The beneficial effects of this application are as follows: By encoding bypass elimination of network request packets, character-level deformations are absorbed during the elimination process, effectively addressing encoding variant attacks and reducing false positive rates. Detection ends when the target field does not match the fingerprint, effectively reducing detection overhead. Streaming lexical analysis of the target field optimizes the time complexity of the detection process. Context-independent detection predicates are used for matching, allowing it to be deployed independently at the WAF entry point without relying on complete DOM parsing results and output context information. Therefore, this application's embodiment combines preprocessing, fingerprint matching, streaming lexical analysis, and context-independent predicate matching to form a highly efficient, accurate, and robust XSS attack detection system. This system effectively controls computational resource consumption while ensuring high accuracy, and possesses good generalization ability and deployment flexibility, thus simultaneously meeting the four requirements of high accuracy, low false positives, linear time complexity, and context-independent deployment, significantly improving network security protection capabilities.
Smart Images

Figure CN122554233B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of network security technology, and in particular to a method for detecting cross-site scripting attacks, an electronic device, and a storage medium. Background Technology
[0002] Existing cross-site scripting (XSS) attack detection technologies face multiple challenges in practical applications, struggling to effectively address the increasingly complex network threat environment. Blacklist-based detection methods, which rely on regular expression signatures to match known attack payloads, suffer from a core weakness: vulnerability to encoded variant attacks. Context-aware detection methods based on full HTML parsers, while capable of semantic layer analysis, suffer from high browser-level parser state machine complexity and significant memory consumption. Detection schemes based on cleanup libraries overly rely on output context information, and their design goal is content cleanup rather than attack identification. Machine learning-driven detection methods attempt to capture anomalous patterns through neural network models, but they are highly dependent on the quality and coverage of training data, exhibiting poor model interpretability and sensitivity to adversarial attacks. These limitations collectively prevent existing solutions from achieving a balance between high-precision detection, low false positive control, linear time complexity, and context-independent deployment. Their performance is particularly inadequate when dealing with encoded bypass variants and high-concurrency traffic, severely hindering the practical deployment effectiveness of security protection systems. Summary of the Invention
[0003] The purpose of this application is to provide a cross-site scripting attack detection method, electronic device, and storage medium that can effectively deal with code variant attacks, reduce false alarm rate, and ensure linear time complexity.
[0004] This application provides a method for detecting cross-site scripting attacks, including: Obtain network request messages; The network request message is preprocessed to eliminate encoding bypass and form the field to be detected; Determine whether the field to be detected matches a fingerprint in a preset fingerprint rule set; If no match is found, a detection result indicating that the attack did not occur is generated; If a match is found, streaming lexical analysis is performed on the target field of the fingerprint in the fingerprint rule set to extract the corresponding structured information. Based on multiple context-independent detection predicates, the target field and the structured information are matched to determine the target detection predicates that pass the match; the detection predicates correspond to the corresponding attack types. Based on the target detection predicate, a detection result representing the risk of attack is generated.
[0005] In some embodiments, the preprocessing of the network request message includes: Extract target fields from multiple semantic regions in the network request message; The target field is recursively decoded and normalized to obtain a normalized field; The normalized field is filtered for validity to obtain the field to be detected.
[0006] In some embodiments, determining whether the field to be detected matches a fingerprint in a preset fingerprint rule set includes: The field to be detected is matched with all fingerprints in the fingerprint rule set in a single scan to determine whether the field to be detected matches the fingerprint; the time complexity of the single scan matching depends only on the length of the field to be detected.
[0007] In some embodiments, the streaming lexical analysis processing of the target field of the fingerprint matching the fingerprint rule set includes: A finite state automaton with multiple states is used to scan the target field to extract the label name, attribute set, and closure flag as the structured information.
[0008] In some embodiments, matching the target field and the structured information based on multiple context-independent detection predicates includes: Based on a preset strategy order, multiple detection predicates are invoked; The target field and the structured information are simultaneously matched with the detection predicate until the first detection predicate matches either the target field or the structured information. The first matching detection predicate is used as the target detection predicate.
[0009] In some embodiments, the detection predicates are abstracted from corresponding XSS attack vectors and divided into at least two predicate groups according to the coverage of the XSS attack vectors. The step of invoking multiple detection predicates based on a preset strategy order includes: Within the current evaluation period, invoke the predicate group with the smallest coverage.
[0010] In some embodiments, generating detection results representing an attack risk based on the target detection predicate includes: Determine the original confidence value of the target detection predicate; The original confidence values are mapped to obtain the corresponding risk level labels; Based on the risk level label, a detection result indicating the presence of an attack risk is generated.
[0011] In some embodiments, the cross-site scripting attack detection method further includes: When the detection result indicates that the attack risk is lower than a preset risk condition, the target field and / or the field in the structured information corresponding to the target detection predicate are extracted to obtain the target field; When the number of target fields reaches a preset threshold within a preset detection period, the target fields are combined and reconstructed to obtain a reconstructed load. Based on multiple detection predicates, the reconstructed payload is matched. If a target detection predicate that passes the match is found, a detection result representing the existence of a multi-stage attack is generated.
[0012] This application also provides an electronic device, which includes a memory and a processor. The memory stores a computer program, and the processor executes the computer program to implement the cross-site scripting attack detection method described above.
[0013] This application also provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the cross-site scripting attack detection method described above.
[0014] The beneficial effects of this application are as follows: By encoding bypass elimination of network request packets, character-level deformations are absorbed during the elimination process, effectively addressing encoding variant attacks and reducing false positive rates. Detection ends when the target field does not match the fingerprint, effectively reducing detection overhead. Streaming lexical analysis of the target field optimizes the time complexity of the detection process. Context-independent detection predicates are used for matching, allowing it to be deployed independently at the WAF entry point without relying on complete DOM parsing results and output context information. Therefore, this application's embodiment combines preprocessing, fingerprint matching, streaming lexical analysis, and context-independent predicate matching to form a highly efficient, accurate, and robust XSS attack detection system. This system effectively controls computational resource consumption while ensuring high accuracy, and possesses good generalization ability and deployment flexibility, thus simultaneously meeting the four requirements of high accuracy, low false positives, linear time complexity, and context-independent deployment, significantly improving network security protection capabilities. Attached Figure Description
[0015] Figure 1 This diagram illustrates the application environment of the cross-site scripting attack detection method provided in this embodiment.
[0016] Figure 2 This is a flowchart of the cross-site scripting attack detection method provided in the embodiments of this application.
[0017] Figure 3 This is a flowchart of a method for preprocessing network request messages provided in an embodiment of this application.
[0018] Figure 4 This is a flowchart of a method for matching target fields and structured information provided in an embodiment of this application.
[0019] Figure 5 This is a flowchart of a method for representing the detection results based on the target detection predicate generation method provided in this application embodiment, which identifies the risk of attack.
[0020] Figure 6 This is a schematic diagram of the hardware structure of the electronic device provided in the embodiments of this application. Detailed Implementation
[0021] To make the objectives, technical solutions, and advantages of this application clearer, the following detailed description is provided in conjunction with the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the scope of this application.
[0022] It should be noted that although functional modules are divided in the device schematic diagram and a logical order is shown in the flowchart, in some cases, the steps shown may be performed in a different order than the module division in the device or the order in the flowchart. The terms "first," "second," etc., in the specification, claims, and drawings are used to distinguish similar objects and are not used to describe a specific order or sequence.
[0023] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this application belongs. The terminology used herein is for the purpose of describing embodiments of this application only and is not intended to limit this application. Furthermore, the information, data, and signals involved in the embodiments of this application are all authorized by relevant parties or have been fully authorized by all parties, and the collection, use, and processing of related data comply with the relevant laws, regulations, and standards of the relevant countries and regions.
[0024] In real-time network traffic inspection, cross-site scripting (XSS) attack detection faces technical challenges such as encoding bypass, parsing latency, context dependence, and model vulnerability. These issues prevent detection systems from simultaneously maintaining high accuracy, low false positive rate, linear time complexity, and context-independent deployment in high-concurrency scenarios. Specifically, insufficient detection accuracy increases the risk of missed attacks, while excessive processing latency reduces system throughput, making it difficult to effectively implement security protection mechanisms. Encoding distortion techniques render blacklist detection ineffective; millisecond-level latency introduced by full HTML parsers accumulates under tens of thousands of QPS; context-dependent schemes cannot be reused due to a lack of output information; and machine learning models are unable to independently assume online protection responsibilities due to inference latency and vulnerability to adversarial examples. For example, in the deployment of web application firewalls on large e-commerce platforms, attackers may use multi-layered encoding techniques to construct XSS payloads in the face of sudden high-traffic HTTP requests. When the detection system uses a blacklist method based on regular expression signatures, it cannot effectively identify combinations and variations of percent sign encoding and attribute concatenation, allowing variant attacks to bypass detection. If it switches to a full HTML parser for context-aware detection, the latency introduced by the parsing process on a single request accumulates under high QPS, causing request processing queue backlog and prolonged system response time. In this scenario, the detection mechanism cannot accurately capture new attack vectors, nor can it meet the performance requirements of real-time interception, exposing the fundamental contradiction between efficiency and accuracy in the detection scheme. Furthermore, the cleanup library solution relies on the complete DOM parsing results and output context information, and lacks corresponding context at the WAF entry point, making it impossible to apply directly, thus plunging the system into a dilemma between protection capabilities and performance metrics.
[0025] If the aforementioned issues are not addressed, XSS attacks could successfully inject and execute malicious scripts, leading to user session hijacking or sensitive data leakage. The unreliability of the detection system will weaken overall security capabilities and increase business operational risks. Furthermore, performance bottlenecks may force the system to reduce detection intensity, further amplifying security vulnerabilities and creating a negative feedback loop of continuously declining protection capabilities. Therefore, there is an urgent need for a technical solution that can achieve high-precision detection while maintaining linear time complexity.
[0026] Based on this, embodiments of this application provide a cross-site scripting attack detection method, electronic device, and storage medium. By preprocessing to eliminate encoding bypass and combining single-pass scanning matching with streaming lexical analysis, context-independent detection of structured information is achieved. It can effectively deal with encoding variant attacks, reduce false alarm rate, and ensure linear time complexity, making it suitable for high-concurrency network environments.
[0027] Figure 1 This diagram illustrates the application environment of the cross-site scripting attack detection method provided in this embodiment. Figure 1As shown, this method is applied to a cross-site scripting (XSS) attack detection system. The system includes a terminal 101 and a server 102. Terminal 101 and server 102 are connected via a network. Terminal 101 can be at least one of a mobile phone, tablet, laptop, or in-vehicle terminal. Server 102 can be a standalone server or a server cluster consisting of several servers. Terminal 101 sends network request messages to server 102. Server 102 receives the network request messages, preprocesses them to eliminate encoding bypasses and form a field to be detected, determines whether the field to be detected matches a fingerprint in a preset fingerprint rule set. If it does not match, a detection result indicating no attack is generated. If it matches, streaming lexical analysis is performed on the target field that matches the fingerprint in the fingerprint rule set to extract corresponding structured information. Based on multiple context-independent detection predicates, the target field and structured information are matched to determine the matching target detection predicate. Based on the target detection predicate, a detection result indicating an attack risk is generated. The detection predicate corresponds to the corresponding attack type.
[0028] It should be understood that Figure 1 The application scenarios shown are merely examples. In practical applications, the cross-site scripting attack detection method provided in this application embodiment can also be applied to other scenarios. For example, the above-described cross-site scripting attack detection method can be directly applied to terminal 101. Terminal 101 is used to acquire network request packets, preprocess the network request packets to eliminate encoding bypasses and form fields to be detected, determine whether the fields to be detected match the fingerprints in the preset fingerprint rule set, if not, generate a detection result indicating no attack, if matching, perform streaming lexical analysis on the target fields that match the fingerprints in the fingerprint rule set to extract the corresponding structured information, match the target fields and structured information based on multiple context-independent detection predicates to determine the target detection predicates that have passed the match, and generate a detection result indicating an attack risk based on the target detection predicates.
[0029] See Figure 2 In one embodiment, a cross-site scripting attack detection method is provided, wherein the execution subject of the method is a terminal or a server, including but not limited to steps S201 to S207.
[0030] Step S201: Obtain the network request message.
[0031] A network request message is a data unit transmitted in network communication, such as an HTTP request message, which carries the request information sent by the client to the server and may include parts such as URL, request header, and request body.
[0032] Network request messages can be obtained in several ways. For example, they can be captured directly through the network interface, and HTTP request messages can be parsed from them. Alternatively, received HTTP requests can be forwarded to the detection module by an upstream proxy server or load balancer. Furthermore, they can also be obtained by reading request records stored in log files.
[0033] Step S202: Preprocess the network request message to eliminate encoding bypass and form the field to be detected.
[0034] Encoding bypass refers to the act of attackers using various encoding methods (such as URL encoding, HTML entity encoding, etc.) to obfuscate malicious payloads in order to circumvent security detection mechanisms. Eliminating encoding bypass involves restoring these encodings to their original form.
[0035] Preprocessing the network request message can involve performing a one-time URL decoding on specific parameter values or request body content to restore some encoded characters. Alternatively, it can involve extracting all string content from the network request message and removing non-visible characters to form a preliminary field to be detected.
[0036] Step S203: Determine whether the field to be detected matches a fingerprint in the preset fingerprint rule set.
[0037] If the match is not found, proceed to step S204; if the match is found, proceed to step S205.
[0038] A fingerprint rule set refers to a predefined set of patterns or features used to quickly identify known attack payloads or malicious behaviors. A fingerprint can be a regular expression, a string pattern, or other matching rules. A fingerprint within a fingerprint rule set refers to a single pattern or feature within that set. When a field to be detected matches a fingerprint, it indicates a potential attack risk.
[0039] To determine whether a field to be detected matches a fingerprint in a pre-defined fingerprint rule set, one approach is to sequentially match the field against each regular expression in the fingerprint rule set. If any regular expression matches successfully, the field is considered to have matched the fingerprint. Alternatively, a string set containing common XSS attack keywords can be constructed, and the field to be detected can be checked for these keywords.
[0040] Step S204: Generate detection results that characterize non-attacks.
[0041] If the field to be detected does not match any fingerprint, a detection result indicating no attack is generated. This means that the network request message did not detect any known threats in the initial fingerprint detection stage and can be determined to be secure.
[0042] Step S205: Perform streaming lexical analysis on the target field of the fingerprint in the fingerprint rule set to extract the corresponding structured information.
[0043] Streaming lexical analysis refers to the process of scanning a data stream character by character or word by word and decomposing it into a series of meaningful lexical units (tokens) according to preset lexical rules. This process typically does not rely on complete grammatical structures, but focuses on identifying basic constituent elements.
[0044] Structured information refers to data with a specific organizational form extracted from a target field through streaming lexical analysis. Examples include tag names and attributes extracted from HTML fragments.
[0045] If the field to be detected matches a fingerprint, then streaming lexical analysis is performed on the target field that matches the fingerprint rule set. This can be done by dividing the target field into a series of independent lexical units based on preset delimiters (such as spaces, quotation marks, angle brackets, etc.). These lexical units can be simply stored in a list as preliminary structured information.
[0046] Step S206: Based on multiple context-independent detection predicates, match the target field and structured information to determine the target detection predicates that have passed the match.
[0047] Detection predicates correspond to specific attack types. Context-independent detection predicates are a set of logical rules or conditions used to determine the presence of an attack. The judgment of a detection predicate does not depend on the complete semantic context of the request, but is based on the target fields and structured information themselves. Each detection predicate typically corresponds to one or more specific attack types. An attack type refers to the specific category of malicious behavior identified by the detection predicate, such as reflected XSS, stored XSS, etc.
[0048] Matching the target field with the structured information can be done using a predefined series of independent logical rules, each checking for specific pattern combinations. One detection predicate might check for the existence of a specific HTML tag combined with a JavaScript event attribute, while another might check for the existence of a specific function call. During matching, all predefined detection predicates can be iterated over, and the condition of each predicate can be independently evaluated. Once the condition of a detection predicate is met, it is recorded as a successfully matched target detection predicate.
[0049] Step S207: Based on the target detection predicate, generate detection results that represent the risk of attack.
[0050] Based on this target detection predicate, a detection result representing the presence of attack risk is generated. This can be achieved by directly outputting the attack type associated with the matched detection predicate, such as "XSS attack". Alternatively, a fixed risk warning can be generated based on the preset risk level of the predicate, such as "High-risk attack exists".
[0051] The following example will provide a more detailed explanation of the above technical solution: Suppose a web application receives a search query from a user and displays it on a page. An attacker attempts to carry out a cross-site scripting (XSS) attack by submitting a query containing malicious script.
[0052] A typical network request message might look like this: `GET / search?query=%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E HTTP / 1.1`.
[0053] First, obtain the network request message.
[0054] Next, the network request message is preprocessed. The query parameter `query` in the URL is identified, and its value `%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E` is extracted. To eliminate encoding bypass, this value is URL decoded to obtain ` src=x onerror=alert(1)>`. The decoded string is then used as the field to be detected.
[0055] Then, the field to be detected is determined. src=x onerror=alert(1)>`Whether a fingerprint was found in the preset fingerprint rule set. The fingerprint rule set may contain a simple regular expression, such as ` / <\s` img\s+[^>] `onerror / i` is used to match strings containing `` The pattern of the `tag` and `onerror` attribute. In this example, the field to be detected successfully matched the fingerprint.
[0056] Since the field to be detected matches the fingerprint, the target field will be... The string `src=x onerror=alert(1)>` undergoes streaming lexical analysis. During this process, `img` is identified as the tag name, and `src=x` and `onerror=alert(1)` are identified as attributes. This information is extracted and organized into structured information, such as a list containing tag names and attribute key-value pairs.
[0057] Furthermore, based on multiple context-independent detection predicates, the target field and the structured information are matched. A detection predicate might be designed to identify "when..." The attack pattern is defined as "when the tag contains the `onerror` attribute". This detection predicate checks for the presence of an `img` tag in the structured information and the presence of `onerror` in its attribute list. In this example, the condition of the detection predicate is met, therefore the detection predicate is determined to be a successful target detection predicate. This target detection predicate is associated with the attack type "reflected XSS attack".
[0058] Finally, based on the target detection predicate, a detection result representing the attack risk is generated. For example, a detection report is output indicating that the network request is at risk of a "reflected XSS attack," and may suggest corresponding blocking or alerting measures. Through the above steps, even if the attack payload is simply encoded, this method can effectively identify and report potential cross-site scripting attacks.
[0059] Based on the above examples, the cross-site scripting attack detection method proposed in this embodiment demonstrates significant technical contributions. Compared with existing technologies, this method effectively overcomes the limitations of traditional solutions through a multi-stage, layered, and progressive detection mechanism.
[0060] For example, compared to blacklist detection schemes that rely solely on regular expression signatures, this method further introduces streaming lexical analysis and context-independent predicate matching after fingerprint matching. In the example above, even if the attacker uses the URL encoding form `%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E`, this method can eliminate the encoding bypass through the preprocessing step and identify the `` after subsequent lexical analysis and predicate matching. The `onerror` attribute in the tag is a key malicious feature. This enables this method to effectively deal with variant attacks such as encoding bypass and attribute concatenation, significantly improving detection accuracy and reducing false positive rate, and avoiding the weakness of traditional regular expression matching being easily bypassed.
[0061] Furthermore, this method avoids dependence on a full HTML parser, thus solving the problems of high computational overhead and difficulty in meeting real-time requirements of existing context-aware detection schemes. In the example, streaming lexical analysis only performs local, lightweight analysis on the target field to extract necessary structured information, rather than building a complete DOM tree. This design optimizes the time complexity of the detection process, enabling real-time interception at tens of thousands of QPS without incurring millisecond-level parsing latency.
[0062] Furthermore, this method employs context-independent detection predicates for matching, enabling it to be deployed independently at the WAF entry point (HTTP request layer) without relying on complete DOM parsing results and output context information. This contrasts with context-dependent detection schemes based on cleansing libraries, which lack corresponding context at the WAF entry point and cannot be directly reused. The context-independent nature of this method significantly enhances its deployment flexibility and applicability.
[0063] In summary, this embodiment combines preprocessing, fingerprint matching, streaming lexical analysis, and context-free predicate matching to form an efficient, accurate, and robust XSS attack detection system. This system effectively controls computational resource consumption while ensuring high accuracy, and possesses good generalization ability and deployment flexibility. Therefore, it can simultaneously meet the four requirements of high accuracy, low false positives, linear time complexity, and context-free deployment, significantly improving network security protection capabilities.
[0064] See Figure 3 In one embodiment, the method for preprocessing network request messages includes, but is not limited to, steps S301 to S303.
[0065] Step S301: Extract the target fields of multiple semantic regions in the network request message.
[0066] Semantic regions can cover the URL path of an HTTP request, query parameters, form data in a POST request body, specific fields in a JSON or XML payload, and HTTP header information (such as User-Agent, Referer, Cookie, etc.).
[0067] Extracting target fields from multiple semantic regions in a network request message can be achieved by using a dedicated HTTP protocol parser, URL parser, or JSON / XML parser to structurally traverse the message content, identify and extract key-value pairs or data blocks related to user input. Alternatively, a pre-defined rule set can be configured to utilize regular expressions or other pattern matching techniques to identify and extract fields that match specific patterns from the original message text.
[0068] In one specific embodiment, target fields of multiple semantic regions are extracted from the network request message, and the network request message is... The field values are parsed and extracted according to the five core semantic regions, and the region set is generated. As shown in the formula below: , The URL area extracts the path components of the request line, the ARGS area extracts the parameter values from the query string, the HEADERS area parses each header line by line to extract the value portion, the COOKIE area further breaks down the request into name=value pairs separated by semicolons and extracts the value, and the BODY area is processed by the Content-Type branch and parsed into name=value pairs. Each target field is represented as a triple T=(zone, name, value), where... 'name' is the field name (can be empty). For field values; target field set .in, For byte alphabet, It is the complete set of finite byte strings. M represents the number of fields.
[0069] Step S302: Perform recursive decoding and normalization on the target field to obtain the normalized field.
[0070] In some embodiments, the recursive decoding normalization process includes detecting and decoding six encoding types in a predetermined order: percent sign encoding, hexadecimal escape, octal escape, HTML entity encoding, Unicode escape, and Base64 encoding, setting a fixed decoding depth or terminating early when no decoding is triggered in a certain round.
[0071] Recursive decoding and normalization of the target field can be performed by first attempting to decode the percent sign encoding. If successful, the decoded string is then checked against all encoding types again. The decoding process can have a fixed decoding depth, such as a maximum of five layers, to prevent infinite loops. Alternatively, the decoding process can terminate prematurely if no decodeable encoding type is found in a complete round of encoding type detection. This mechanism ensures that even if an attacker employs a complex encoding chain, their original intent can still be effectively revealed.
[0072] In a specific embodiment, recursive decoding and normalization of the target field can be performed by iterating through the value part of each target field T and recursively decoding it, with a decoding depth of K=10, or terminating early when no decoder is triggered in a certain round, to obtain the normalized field. The decoder internally detects six encodings in sequence: percent sign encoding, hexadecimal escape sequences, octal escape sequences, HTML entity encoding, Unicode escape sequences, and Base64. The final normalized field set is then generated. for: .
[0073] Step S303: Perform validity filtering on the normalized field to obtain the field to be tested.
[0074] In some embodiments, validity filtering includes filtering empty fields, skipping excessively long fields whose length exceeds a preset threshold, and skipping binary data fields.
[0075] In a specific embodiment, boundary truncation and validity filtering of the normalized field can be performed by filtering empty fields, skipping excessively long fields, and skipping binary data fields to obtain a set of fields to be detected. : , in, To limit the maximum field length, For length calculation, This is a binary judgment function that makes a judgment based on a threshold for the proportion of unprintable bytes.
[0076] The proposed solution, through the aforementioned refined preprocessing steps, effectively addresses challenges such as encoding obfuscation, data redundancy, and anomalous data types in network request messages. First, by extracting target fields from multiple semantic regions, it ensures comprehensive coverage of all potential attack payload points, avoiding omissions of critical detection areas. Subsequently, the recursive decoding and normalization mechanism systematically reconstructs various encoding forms used by attackers to hide malicious payloads, effectively revealing them regardless of their nesting depth, thus significantly improving the visibility of the attack payload. Furthermore, the validity filtering mechanism removes irrelevant noise data, such as empty fields, excessively long fields, or binary data. This not only reduces the computational burden of subsequent fingerprint matching and lexical analysis stages but also avoids false positives or performance degradation caused by processing invalid data. Through this series of synergistic preprocessing steps, the final detected fields are highly pure, standardized data that truly reflects the attack intent, greatly improving the accuracy, robustness, and efficiency of the entire cross-site scripting attack detection system.
[0077] In some embodiments, determining whether the field to be detected matches a fingerprint in a preset fingerprint rule set includes: performing a single-pass scan to match the field to be detected with all fingerprints in the fingerprint rule set to determine whether the field to be detected matches a fingerprint.
[0078] The time complexity of single-pass scanning matching depends only on the length of the field to be detected. One way to achieve this time complexity is to preprocess the fingerprint rule set before matching, for example by constructing a trie or an Aho-Corasick automaton. These data structures ensure that when scanning the field to be detected, regardless of the size of the fingerprint rule set, the overhead for processing each character is at a constant level. Another implementation method adopts technologies such as hash matching or Bloom Filter. By precomputing the hash values of fingerprints and calculating and comparing the hash values of substrings when scanning the field to be detected, rapid lookup can be achieved with a certain probability, and the time complexity is mainly affected by the length of the field to be detected.
[0079] In a specific embodiment, the short fingerprints contributed by each detection predicate during the initialization phase (such as <script, onerror, javascript:, alert(, etc.) are collected into a fingerprint rule set , which is compiled into an AC multi-pattern matching automaton during the startup phase , and will not be modified during the operation phase.
[0080] Single-pass scanning matching between the field to be detected and all fingerprints in the fingerprint rule set may adopt a multi-pattern matching algorithm, such as the Aho-Corasick algorithm. This algorithm can construct the fingerprint rule set into a finite state automaton, and then perform a single scan on the field to be detected to simultaneously find the occurrences of all fingerprints. It can also use an optimized regular expression engine, which compiles the fingerprint rule set into a composite and efficient regular expression, and uses its internal finite state automaton mechanism to perform single-scan matching on the field to be detected. This is to determine whether the field to be detected hits a fingerprint, and clarifies the goal of the matching operation, that is, to determine whether there is any pattern in the field to be detected that matches a fingerprint in the fingerprint rule set, so as to provide a clear hit judgment result. In actual operation, once a part matching any fingerprint is found in the field to be detected, it can be immediately determined as a hit, and the subsequent matching process can be optionally terminated, thereby further saving computing resources. Alternatively, all hit fingerprints and their positions can be recorded, and a comprehensive hit status is finally returned.
[0081] In a specific embodiment, performing single-pass scanning matching between the field to be detected and all fingerprints in the fingerprint rule set may include inputting each field to be detected into for single-byte single-pass scanning, and maintaining an active state set during the process; after scanning is completed, a pre-filtering Boolean determination is output : , that as long as contains Output 1 if any fingerprint substring is found, otherwise output 0; Scan time complexity: ,and Irrelevant, among which .
[0082] like If the value is 0, the current field is directly identified as a non-XSS risk, generating a detection result indicating no attack, and it is not included in subsequent detection; if... Then, streaming lexical analysis is performed on the target field of the fingerprint in the fingerprint rule set.
[0083] This application's solution, after acquiring and preprocessing network request packets to form the field to be detected, no longer employs the traditional method of comparing fingerprints one by one. Instead, it processes the fingerprint rule set as a whole. By pre-compiling or constructing all fingerprints in the rule set into an efficient matching structure, it enables simultaneous and parallel comparison with all fingerprints when scanning the field to be detected. This single-pass scanning matching mechanism ensures that the computational overhead of the matching process is primarily determined by the length of the field to be detected, and is independent of the number of fingerprints in the rule set. This means that even with a very large fingerprint rule set, it can maintain a high matching speed, avoiding performance bottlenecks caused by the expansion of the rule set. In this way, the detection method of this application can significantly improve processing efficiency and responsiveness while ensuring detection accuracy, making it particularly suitable for scenarios requiring real-time processing of large amounts of network traffic.
[0084] In some embodiments, streaming lexical analysis is performed on the target field of the fingerprint in the fingerprint rule set, including: using a finite state automaton containing multiple states to scan the target field to extract the tag name, attribute set and closure flag as structured information.
[0085] In some embodiments, the states of the finite state automaton include text states, tag name states, attribute name states, quoted attribute value states, unquoted attribute value states, closing tag states, and self-closing tag states. In addition to text states, tag name states, attribute name states, quoted attribute value states, unquoted attribute value states, closing tag states, and self-closing tag states, the automaton may also include comment states, script block states, etc., to handle more complex HTML structures.
[0086] This application's solution employs a finite state automaton with multiple states to perform streaming lexical analysis on the target field, effectively solving the problem of accurately extracting structured information from complex attack payloads. Specifically, after a network request packet is preprocessed and determined to have matched a fingerprint in a predefined fingerprint rule set, its target field is fed into the finite state automaton for scanning. This automaton predefines multiple states and their transition rules, including text state, tag name state, attribute name state, quoted attribute value state, unquoted attribute value state, closed tag state, and self-closing tag state. During scanning, the automaton switches states according to the current state and the characters read, following a predefined logic, and simultaneously performs information extraction operations. For example, when the automaton recognizes the tag start character "<", it switches from text state to tag name state and begins collecting tag names; when it recognizes an attribute name, it enters either quoted attribute value state or unquoted attribute value state depending on the attribute value's citation, and extracts the attribute name and attribute value. Through this deterministic state transition and information extraction mechanism, the automaton can accurately extract label names, attribute sets, and closure flags from the target field and organize this information into structured data. This structured information is then provided to context-independent detection predicates for matching, greatly improving the accuracy and efficiency of subsequent detection. Compared to directly performing pattern matching on the original target field, this method of first performing streaming lexical analysis and extracting structured information allows the detection predicates to make judgments based on clearer and more standardized data, thereby more effectively identifying attack patterns hidden in complex payloads and reducing the risk of false positives and false negatives.
[0087] In a specific embodiment, a finite state automaton Its state set: , Wherein, the initial state , H is the set of states that produce triples. This represents the state transition process. This represents the complete set of finite byte strings.
[0088] State transition function during word parsing and scanning The process is as follows: Text status: Upon reading <, and with the following byte being an ASCII letter, proceed to the next character. Status: Started collecting tag names; Upon reading <, and with the immediately following byte being / , the transition is made to the next character. Marked as a closed label; If a < is encountered, and the following byte is a number, whitespace, or other non-alphabetic character →, it is considered an invalid tag and left unattended. ; The remaining bytes → remain Then, it accelerates and jumps to the next < character; TagName Status (Collection Tag Name): When you read letters, numbers, -, _, stay on the page. Append to the tag name buffer; Upon reading an ASCII whitespace, the label name ends; proceed to the next location. Start parsing the attribute area; Upon reading the end of the tag name (>→), a triplet is generated. Transfer back . Indicates the empty set; Read / (followed by >) → Transfer to Producing triplet and return ; Closing state (closed label)< / …> ): Skip the blank space after the slash and collect the tag names (same rules). ); Reading > → produces triplet Transfer back ; Upon reaching the end of the input, if no > is found, output partial triples (trying to identify them), return. ; AttrName status (collected attribute key): If a byte that is not equal to, not a whitespace, not greater than, not perpendicular to, or not plus is encountered, and begins with a letter or an underscore, then it is left in the current location. Append to the key buffer; Reading the =→ key indicates the end of the collection; skip the spaces on both sides of the equals sign; then read:; Encountering "or" → move to (Record quotation mark type to register) ); Encountering other non-whitespace bytes → transfer to ; Reading a blank page means it has no attributes (key is not empty, value is an empty string), and it is stored in the database.
[0089] / and + → are considered attribute separators and should be left in the text. ; Reading until the end of the attribute section (>→), a triplet is generated, and the data is transferred back. ; AttrValueQuoted status (quoted attribute value): Reading a non-matching quote byte → leave it in. , append to the value buffer (speeds up the jump to matching quotes); Reading the quotation marks that match the beginning ( → Value collection complete, storage To the attribute set, transfer back ; When the input reaches the end, the value is truncated, the existing content is stored, and the data is transferred back. ; AttrValueUnquoted status (attribute value without quotes): Reading a non-whitespace, non->, non-+, or non- / byte → leave it in the current location. Append to the value buffer; When you read / →, it is treated as an HTML unquoted separator (e.g., ...).<img / src=x / onerror=alert(1)> Value cutoff, storage Transfer back ; If a blank space or + / → value is encountered, store the data. Transfer back ; Read until the value reaches its limit, then store. Produce triples and transfer them back. ; SelfClosing state (self-closing tag / >): Reading > → produces triplet Transfer back (The c-values for self-closing and open labels are the same, both being 0; the closing flag only appears when...) (State set to 1) Global rules: from If the input reaches the end in any state other than normal, the currently captured triples will be generated (unclosed labels will be identified as best as possible), and the scan will terminate. The entire process does not track the nesting level of tags, does not build a DOM tree, and the state machine only focuses on the current tag boundary at any position; Among them, the closing mark Only State output, both self-closed and ordinary open labels are taken ;from If the current state reaches EOF, the captured content will be generated (to the best of our ability to identify it). The entire process does not build a DOM tree or track nesting levels.
[0090] In one specific embodiment, scanning the target field can be performed by starting a scan at each < character position in the field to be detected, and then proceeding according to... Follow the state progression until a ">" is encountered or the end of the input is reached, at which point a triple is produced. ,in, The tag name is a byte sequence. For attribute key-value pairs gather, This is a closing flag. All triples generated at the < position in a network request message form a sequence, as shown in the following formula: , when If there is no < character in the output, m=0, and an empty sequence is output. Efforts are made to identify unclosed tags; for unclosed tags caused by input truncation (such as large HTTP packets being fragmented or field values being quoted), the captured attributes are... It is still included in the output to avoid missing some semantic information; the DOM tree is not built, and error recovery is not performed. Example: = After a single pass of SPFSA scanning, the output is: .
[0091] See Figure 4 In one embodiment, the method for matching target fields and structured information includes, but is not limited to, steps S401 to S403.
[0092] Step S401: Based on the preset strategy order, call multiple detection predicates.
[0093] The strategy order refers to a pre-determined set of rules or priorities for invoking detection predicates before predicate matching is performed. This strategy order can be set based on various factors. For example, it can be sorted according to the severity of the attack vectors corresponding to the detection predicates, prioritizing predicates corresponding to high-risk attack vectors; or it can be sorted according to the matching efficiency of the detection predicates, prioritizing predicates with faster matching speeds. By pre-setting the strategy order, the detection process can be optimized, improving detection efficiency and accuracy.
[0094] In some embodiments, the detection predicates are abstracted from the corresponding XSS attack vectors and divided into at least two predicate groups according to the coverage of the XSS attack vectors. Multiple detection predicates are invoked based on a preset policy order, including invoking the predicate group with the smallest coverage within the current evaluation period.
[0095] The coverage of a detection predicate refers to the breadth or specificity of the XSS attack vectors it can identify. Grouping these predicates according to their coverage, such as into "general predicate groups" and "specific predicate groups," or more finely into multiple levels, helps with subsequent strategic invocation.
[0096] The proposed solution first employs refined management of detection predicates. Specifically, detection predicates are not generated arbitrarily but are abstracted and extracted from a large number of XSS attack vectors, ensuring their practicality and specificity. Furthermore, these predicates are divided into at least two predicate groups based on the range of XSS attack vectors they cover; for example, there could be predicate groups targeting general attack patterns and predicate groups targeting specific, covert attack patterns. In actual detection, when multiple detection predicates need to be called for matching, instead of simply traversing all predicates in a fixed strategic order, the predicate groups with the smallest coverage are prioritized within the current evaluation period. This strategy of prioritizing the use of predicate groups with the smallest coverage allows for the initial attempt to identify XSS attacks with strong specificity and obvious attack characteristics. Since these predicates typically target more specific and refined attack patterns, once a match is found, the attack type can be quickly and accurately determined, and corresponding detection results can be generated. This avoids investing significant computational resources in early stages to match general predicates with broad coverage that may lead to more ambiguity or require more verification. In this way, the solution significantly improves detection efficiency while maintaining detection accuracy and reducing unnecessary computational overhead, making the entire detection process more efficient and accurate.
[0097] In one specific embodiment, the detection predicates are divided into three groups according to the detection level, with increasing coverage: , , , Each detection predicate is of the form of The binary Boolean function whose value depends only on (X, H(X)) and not on any context {HTMLbody, attribute, script, URL, CSS}, etc. The detection targets for each predicate group are as follows: (Essential, mandatory check group): Covers the most direct attack vectors with extremely low false positives.
[0098] Detection <script>标签注入,最经典的脚本执行向量。
[0099] :检测标签属性键命中HTML5 标准事件处理器集合(||=73,含onerror、onclick、onload等)是绕过<script>过滤的最常用的替代向量。
[0100] (Standard,标准组):覆盖主流绕过技巧与编码变形。
[0101] :检测危险标签集合D(如<iframe>、<object>、<embed>、<svg>、等可加载外部资源或承载脚本上下文的标签)。
[0102] :检测CSS expression(...)、-moz-binding、behavior等 IE / Gecko 历史脚本入口标签。
[0103] :检测<iframe srcdoc="...">内联 HTML 文档注入,绕过常规标签黑名单。
[0104] :检测属性边界逃逸模式(引号 + 空白 + on事件名 + 等号),针对模板拼接场景的越界注入。
[0105] :检测javascript:URI 协议(剥离空白后非 no-op 白名单的形式),常出现在href、action、src等 URL 属性中。
[0106] :检测vbscript:URI 协议(IE 历史向量,至今仍存于部分嵌入场景)。
[0107] :检测客户端模板注入(Client-Side Template Injection),如 AngularJS{{...}}、Vue 表达式中的constructor链。
[0108] :检测 PoC 函数调用,要求前置单词边界+括号内非空实参,避免命中合法变量名。
[0109] (Full,完整组):覆盖较隐蔽或对抗性更强的向量。
[0110] :检测data:text / html或data:image / svg+xml等可承载脚本的 data URI形式。
[0111] :检测 DOM sink 函数调用(如document.write、innerHTML、eval、setTimeout字符串参数),针对反射型与 DOM 型 XSS。
[0112] :检测构造器链(如[].constructor.constructor("...")()、Function("...")()),属于 JS 沙箱逃逸的典型模式。
[0113] 步骤S402,将目标字段和结构化信息同时与检测谓词进行匹配,直至首个检测谓词匹配目标字段或结构化信息为止。
[0114] 在一个具体的实施例中,将目标字段和结构化信息同时与检测谓词进行匹配,可以是利用谓词集合中的检测谓词对目标字段和结构化信息进行判定,最终得到检测谓词的布尔判定值。为过滤之后的字节流,表示流式HTML词法分析模块输出的三元组。定义谓词评估算子Eval,将任一谓词序列应用到输入即可产出布尔向量,如下公式所示:,其中,Eval表示统一通用接口。以计算为例,给出函数的具体内部实现过程,首先枚举每个三元组的属性键值对集合,对中的每个键取小写后查HTML5 标准事件处理器集合,如果存在任一属性键命中为1,否则为0,如下公式所示:,其中,为小写函数,其他的函数的内部实现也参考此公式。
[0115] 本实施例设置的策略顺序为,其中表示列表有序拼接;按照中顺序逐个评估输入,遇首命中即返回,其余不再计算,如下公式所示:,其中,Y(·)表示级联计算函数,表示首次命中返回的结果。
[0116] 步骤S403,以首个匹配的检测谓词,作为目标检测谓词。
[0117] 本申请的方案在上述跨站脚本攻击检测方法中,为高效且准确地识别潜在的攻击风险,引入优化的匹配策略。具体而言,首先根据预设的策略顺序,对多个检测谓词进行组织和调用。该策略顺序可以确保那些更具代表性、危害性更高或匹配效率更优的谓词能够被优先考虑。在调用过程中,经过预处理的目标字段和从其中抽取的结构化信息作为一个整体,与当前调用的检测谓词进行比对。这种同时匹配的方式使得检测谓词能够全面地分析原始数据及其语法结构,从而提高匹配的准确性。一旦有任何一个检测谓词成功地匹配了目标字段或结构化信息,匹配过程便会立即终止,并将该首个匹配的检测谓词确定为目标检测谓词。这种机制避免了对所有谓词进行穷尽式匹配,显著提升了检测效率,并确保了最终确定的目标检测谓词是基于预设优先级和实际匹配情况的最优选择,从而为后续生成表征攻击风险的检测结果提供了坚实的基础。
[0118] 参阅图5,在一实施例中,基于目标检测谓词生成表征存在攻击风险的检测结果的方法包括但不限于步骤S501至步骤S503。
[0119] 步骤S501,确定目标检测谓词的原始置信值。
[0120] 步骤S502,对原始置信值进行映射处理,得到相应的风险等级标签。
[0121] 步骤S503,基于风险等级标签,生成表征存在攻击风险的检测结果。
[0122] 本申请的方案通过在确定目标检测谓词后,首先量化其原始置信值,随后将该置信值映射为易于理解和操作的风险等级标签,最终将带有风险等级标签的检测结果输出。这一过程使得检测结果从简单的"存在攻击风险”提升为"存在特定风险等级的攻击风险”,为后续的安全响应提供了更精细化的决策依据。通过这种方式,安全运营人员能够根据攻击的实际风险等级,优先处理高风险事件,合理分配安全资源,从而显著提升了安全事件响应的效率和准确性。
[0123] 在一个具体的实施例中,目标检测谓词的原始置信值score由静态映射给定,其中,a表示标签id,其score值由攻击向量的明确性决定,例如,标签注入、事件处理器等明确无歧义的向量取,属性边界逃逸、javascript:URI 等需语境判定的向量取,PoC 函数调用、DOM sink 等存在业务场景重名可能的向量取。
[0124] 将原始置信值通过分档函数映射为三级标签,计算如下公式所示:,将检测结果d扩展为带分档标签的形式,如下公式所示,得到命中的标签id和风险等级标签:。
[0125] 在一些实施例中,该跨站脚本攻击检测方法还包括:在检测结果表征攻击风险低于预设的风险条件时,提取目标字段和 / 或结构化信息中与目标检测谓词对应的字段,得到目标字段;在预设的检测周期内目标字段的数量达到预设的数量阈值时,对目标字段进行组合重构,得到重构载荷;基于多个检测谓词,对重构载荷进行匹配,若存在匹配通过的目标检测谓词,则生成表征存在多阶段攻击的检测结果。
[0126] 风险条件可以是一个风险等级阈值,例如"低风险”或"无风险”,或者是一个置信度分数。当检测结果低于此条件时,并不意味着该请求完全无害,而是可能作为多阶段攻击的一部分。
[0127] 目标字段是指在初步检测过程中,被识别为与某个检测谓词相关联的特定数据片段。这可以是从网络请求报文中提取的原始参数值、URL路径、HTTP头信息等,也可以是经过流式词法分析后得到的标签名、属性集、闭合标志等结构化信息。提取这些字段是为了后续的累积和组合分析,即使它们单独出现时风险较低。
[0128] 检测周期是一个时间窗口,例如数秒、数分钟或数小时,用于收集潜在的攻击片段。所述预设的数量阈值是指在该检测周期内,需要收集到的目标字段的最小数量,例如2个、3个或更多。
[0129] 本申请的方案通过引入多阶段攻击检测机制,有效弥补了单一请求检测的局限性。具体而言,当单个网络请求报文经过预处理、指纹匹配和词法分析后,如果其检测结果表征的攻击风险低于预设的风险条件,并不会立即将其判定为无害。相反,它会智能地提取出与目标检测谓词相关的目标字段或结构化信息。这些被提取的字段,即使单独来看风险较低,但可能作为多阶段攻击的组成部分。在一个预设的检测周期内持续收集这些目标字段。一旦在检测周期内收集到的目标字段数量达到预设的数量阈值,将这些分散的字段进行组合重构,形成一个完整的重构载荷。随后,该重构载荷会再次基于多个检测谓词进行匹配。如果重构载荷能够匹配到某个检测谓词,则表明这些看似无害的请求实际上共同构成了一个完整的攻击载荷,从而生成表征存在多阶段攻击的检测结果。这种机制使得能够"连接”不同请求中的攻击片段,识别出那些通过分阶段传输来规避传统检测手段的复杂攻击,从而显著提升了跨站脚本攻击检测的全面性和准确性。
[0130] 下面通过一个具体的例子进行说明。假设一个攻击者试图通过两次HTTP请求来注入一个XSS攻击载荷。第一次请求:`GET / search?param=<script>`;第二次请求:`GET / search?param=alert(document.cookie)< / script> In the above detection method, upon receiving the first request, after preprocessing, fingerprint matching, and lexical analysis, it is possible to discover... <script>`标签,但由于其不构成完整的攻击载荷,检测结果可能表征为"低风险”,低于预设的风险条件。此时,提取出"`<script>`”作为目标字段。随后,当接收到第二次请求时,同样经过检测,`alert(document.cookie)< / script> Individually, it might be judged as "low risk". We extract "`alert(document.cookie)` as another target field. Assume the preset detection period is 5 seconds and the preset quantity threshold is 2. Within 5 seconds, both target fields are collected. At this point, we combine and reconstruct these two target fields to obtain the reconstructed payload: <script>alert(document.cookie)< / script>Next, the reconstructed payload is matched based on multiple detection predicates. Because of "` <script>alert(document.cookie)< / script> The `"" is a typical XSS attack payload, which will match the corresponding detection predicate. Therefore, the generated detection results represent a multi-stage attack, successfully identifying this type of attack that evades detection by segmented transmission.
[0131] This application also provides an electronic device. Figure 6 This is a schematic diagram of the hardware structure of the electronic device provided in an embodiment of this application. For example... Figure 6 As shown, the electronic device in this embodiment mainly includes a processor 601 and a memory 602. The memory 602 can be configured to store a program for executing the cross-site scripting attack detection method of the above-described method embodiments. The processor 601 can be configured to execute the program in the memory 602, which includes, but is not limited to, a program for executing the cross-site scripting attack detection method of the above-described method embodiments. For ease of explanation, only the parts related to the embodiments of this application are shown. For specific technical details not disclosed, please refer to the method section of the embodiments of this application.
[0132] In some embodiments, the electronic device may include multiple processors 601 and multiple memories 602. The program executing the cross-site scripting (XSS) attack detection method of the above-described method embodiments can be divided into multiple subroutines. Each subroutine can be loaded and run by a processor 601 to perform different steps of the XSS attack detection method of the above-described method embodiments. Specifically, each subroutine can be stored in a different memory 602, and each processor 601 can be configured to execute programs in one or more memories 602 to jointly implement the XSS attack detection method of the above-described method embodiments. That is, each processor 601 executes different steps of the XSS attack detection method of the above-described method embodiments to jointly implement the XSS attack detection method of the above-described method embodiments.
[0133] The aforementioned multiple processors 601 can be processors deployed on the same device. For example, the aforementioned electronic device can be a high-performance device composed of multiple processors, and the aforementioned multiple processors 601 can be processors configured on that high-performance device. Alternatively, the aforementioned multiple processors 601 can also be processors deployed on different devices. For example, the aforementioned electronic device can be a server cluster, and the aforementioned multiple processors 601 can be processors on different servers within the server cluster.
[0134] This application also provides a computer-readable storage medium. In one embodiment of the computer-readable storage medium according to this application, the computer-readable storage medium can be configured to store a program that performs the cross-site scripting attack detection method of the above-described method embodiments. This program can be loaded and run by a processor to implement the cross-site scripting attack detection method. For ease of explanation, only the parts related to the embodiments of this application are shown; for specific technical details not disclosed, please refer to the method section of the embodiments of this application. The computer-readable storage medium can be a memory formed by various electronic devices. Optionally, in the embodiments of this application, the computer-readable storage medium is a non-transitory computer-readable storage medium.
[0135] The cross-site scripting (XSS) attack detection method, electronic device, and storage medium provided in this application eliminate the encoding bypass of network request packets. Character-level deformations are absorbed during the elimination process, effectively addressing encoding variant attacks and reducing false positive rates. Detection ends when the target field does not match the fingerprint, effectively reducing detection overhead. Streaming lexical analysis of the target field optimizes the time complexity of the detection process. Context-independent detection predicates are used for matching, allowing independent deployment at the WAF entry point without relying on complete DOM parsing results and output context information. Therefore, this application combines preprocessing, fingerprint matching, streaming lexical analysis, and context-independent predicate matching to form a highly efficient, accurate, and robust XSS attack detection system. This system effectively controls computational resource consumption while ensuring high accuracy, and possesses good generalization ability and deployment flexibility, thus simultaneously meeting the four requirements of high accuracy, low false positives, linear time complexity, and context-independent deployment, significantly improving network security protection capabilities.
[0136] Exemplary embodiments of this disclosure have been specifically shown and described above. It should be understood that this disclosure is not limited to the detailed structures, arrangements, or implementations described herein; rather, this disclosure is intended to cover various modifications and equivalent arrangements contained within the spirit and scope of the appended claims.
Claims
1. A cross-site scripting attack detection method characterized by, include: Obtain network request messages; The network request message is preprocessed to eliminate encoding bypass and form the field to be detected; Determine whether the field to be detected matches a fingerprint in a preset fingerprint rule set; If no match is found, a detection result indicating that the attack did not occur is generated; If a match is found, streaming lexical analysis is performed on the target field of the fingerprint in the fingerprint rule set to extract the corresponding structured information. Based on multiple context-independent detection predicates, the target field and the structured information are matched to determine the target detection predicates that pass the match; the detection predicates correspond to the corresponding attack types; the detection predicates are abstracted from the corresponding XSS attack vectors and are divided into at least two predicate groups according to the coverage of the XSS attack vectors; Based on the target detection predicate, a detection result representing the risk of attack is generated.
2. The cross-site scripting attack detection method of claim 1, wherein, The preprocessing of the network request message includes: Extract target fields from multiple semantic regions in the network request message; The target field is recursively decoded and normalized to obtain a normalized field; The normalized field is filtered for validity to obtain the field to be detected.
3. The cross-site scripting attack detection method of claim 1, wherein, The step of determining whether the field to be detected matches a fingerprint in a preset fingerprint rule set includes: The field to be detected is matched with all fingerprints in the fingerprint rule set in a single scan to determine whether the field to be detected matches the fingerprint; the time complexity of the single scan matching depends only on the length of the field to be detected.
4. The cross-site scripting attack detection method of claim 1, wherein, The streaming lexical analysis processing of the target field of the fingerprint that matches the fingerprint rule set includes: A finite state automaton with multiple states is used to scan the target field to extract the label name, attribute set, and closure flag as the structured information.
5. The cross-site scripting attack detection method of claim 1, wherein, The matching of the target field and the structured information based on multiple context-independent detection predicates includes: Based on a preset strategy order, multiple detection predicates are invoked; The target field and the structured information are simultaneously matched with the detection predicate until the first detection predicate matches either the target field or the structured information. The first matching detection predicate is used as the target detection predicate.
6. The cross-site scripting attack detection method according to claim 5, characterized in that, The process of invoking multiple detection predicates based on a preset strategy order includes: Within the current evaluation period, invoke the predicate group with the smallest coverage.
7. The cross-site scripting attack detection method according to claim 1, characterized in that, The step of generating detection results representing the presence of attack risk based on the target detection predicate includes: Determine the original confidence value of the target detection predicate; The original confidence values are mapped to obtain the corresponding risk level labels; Based on the risk level label, a detection result indicating the presence of an attack risk is generated.
8. The cross-site scripting attack detection method according to claim 1, characterized in that, Also includes: When the detection result indicates that the attack risk is lower than a preset risk condition, the target field and / or the field in the structured information corresponding to the target detection predicate are extracted to obtain the target field; When the number of target fields reaches a preset threshold within a preset detection period, the target fields are combined and reconstructed to obtain a reconstructed load. Based on multiple detection predicates, the reconstructed payload is matched. If a target detection predicate that passes the match is found, a detection result representing the existence of a multi-stage attack is generated.
9. An electronic device, characterized in that, The electronic device includes a memory and a processor. The memory stores a computer program, and when the processor executes the computer program, it implements the cross-site scripting attack detection method according to any one of claims 1 to 8.
10. A computer-readable storage medium storing a computer program, characterized in that, When the computer program is executed by a processor, it implements the cross-site scripting attack detection method according to any one of claims 1 to 8.
Citation Information
Patent Citations
Detection method and device for cross site scripting and firewall with device
CN102833269A
XSS attack identification method and device, equipment and medium
CN113067792A