Storage type XSS attack detection method and device based on large language model
Through multiple rounds of expansion and evaluation and optimization of prompt word and program dependency graph decomposition based on large language model, the problem of insufficient accuracy and real-time detection of storage XSS attacks in the prior art is solved, and efficient and accurate storage XSS attack detection is achieved to adapt to dynamic threat environments.
Patent Information
- Application Number
- CN202510328580.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-19
- Publication Date
- 2025-07-18
AI Technical Summary
The prior art is difficult to detect and defend against storage XSS attacks efficiently and accurately, and the defense mechanism is susceptible to server configuration and sandbox bypass technology, resulting in defense failure.
The storage XSS attack detection method based on the large language model is adopted, and the optimization prompt words are optimized through multiple rounds of expansion and evaluation, and a program dependency graph is generated for structured decomposition. The large language model is used to determine whether the code fragment is a storage XSS attack vector, and the code is decomposed by the gradient descent optimization prompt words and community detection algorithm to ensure the accuracy and adaptability of the detection.
It realizes efficient and accurate storage XSS attack detection, reduces computing costs, improves adaptability, avoids defense failure caused by server breach or sandbox bypass, and adapts to dynamic threat environments.
Smart Images

Figure CN120337215A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of Web network security, and in particular to a method and device for detecting stored XSS attacks based on large language models. Background Art
[0002] Cross-site scripting (XSS) attack is a common Web security threat. Attackers inject malicious scripts into Web interfaces, causing these scripts to execute in the user's browser, thereby obtaining sensitive user information, tampering with page content, or hijacking user sessions. XSS attacks can be divided into two categories: reflected XSS and stored XSS. The malicious script of reflected XSS is triggered by a user request, while the malicious script of stored XSS is persistently stored on the server side, such as in a database or cache. For example, in an online forum scenario, an attacker may inject malicious JavaScript code into a comment. When other users access the page, the code is executed and steals their account information, forming a typical stored XSS attack.
[0003] Currently, mainstream browsers detect and defend against reflected XSS attacks by performing differential comparison on HTTP (HyperText Transfer Protocol) requests and responses. However, the malicious code of stored XSS has already resided on the server side in advance, and the victim's browser only passively executes the injected content, resulting in the failure of the defense mechanism based on request-response comparison. Due to the persistence, concealment, and wide spread of stored XSS attacks, their harm is particularly prominent in scenarios such as financial transactions and social media, and a targeted defense solution is urgently needed.
[0004] The existing defense technologies mainly include content security policy (CSP), sandbox mechanism, and traditional filtering measures. Among them, CSP restricts the script source through declarative policies, but its effectiveness completely depends on the integrity of the server-side configuration. Once the server is compromised, attackers can tamper with or disable the CSP policy, rendering its defense capabilities ineffective. In addition, the complex configuration requirements and cross-browser compatibility issues of CSP further hinder its widespread application. The sandbox mechanism restricts code behavior by isolating the execution environment, but the continuously evolving sandbox bypass techniques and inherent defense constraints result in a limited defense scope and vulnerability to complex side-channel attacks. At the same time, there are compatibility differences in the sandbox among different browser versions and system environments, making it difficult to provide consistent protection. The traditional filtering measures include input validation and output encoding to achieve defense by filtering or escaping malicious content, but these measures highly depend on the security of the server side. If the server is compromised, attackers can bypass or disable the filtering rules, leading to the complete failure of the defense mechanism. Summary of the Invention
[0005] The technical problem to be solved by the present invention lies in: aiming at the technical problems existing in the prior art, the present invention provides a storage-type XSS attack detection method and device based on a large language model, which are simple to implement, low in cost, high in detection accuracy, efficiency, real-time performance and adaptability, and can detect storage-type XSS attacks in the network in real time, efficiently and accurately, ensuring user privacy and the security of Web application programs.
[0006] To solve the above technical problems, the technical solution proposed by the present invention is:
[0007] A storage-type XSS attack detection method based on a large language model, comprising:
[0008] In the prompt word learning stage, an initial prompt word input is received, the prompt word expander expands the initial prompt word, and the expanded prompt words are evaluated for performance to screen out the prompt words that meet the preset performance indicators. The screened prompt words are further expanded and evaluated in multiple rounds until the prompt words that meet the optimization conditions are obtained and used as the optimized prompt words;
[0009] In the defense work stage, the code to be detected is received and the program dependence graph of the code to be detected is generated. The program dependence graph is converted into a weighted undirected graph. The edges of the weighted undirected graph respectively represent that the nodes belong to the control flow dependence relationship or the data flow dependence relationship, and different weights are configured for the edges of the control flow dependence and the data flow dependence. The weighted undirected graph of the program dependence graph is decomposed into multiple subgraphs with consistent program structures, and multiple subprogram dependence graphs are obtained. Each node in each subprogram dependence graph is traversed and the original structure of the program is retained. The nodes are sequentially converted back to the original code format to obtain code representation segments. The code representation segments and the optimized prompt words are input into the large language model, and the large language model determines whether each code segment is an attack vector of storage-type XSS to obtain the final speculation result.
[0010] As a further improvement of the method of the present invention: in the prompt word learning stage, the expansion of the initial prompt word includes:
[0011] The code sample set composed of labeled attack vectors and non-attack vectors is divided into a training set and a test set;
[0012] The initial prompt word is used to guide the large language model to predict the code in the training set in sequence, and the prediction result is compared with the true label, and the code samples with incorrect predictions are screened out as the incorrect sample set;
[0013] Based on the gradient descent method, randomly select the code with incorrect prediction and the current prompt word in the incorrect sample set to generate the reason for the error, and optimize the current prompt word according to the generated reason for the error to expand and generate new prompt words.
[0014] As a further improvement of the method of the present invention: in the prompt word learning stage, the performance of the expanded generated prompt words is evaluated to screen out the prompt words that meet the preset performance indicators, and the screened prompt words are further expanded and evaluated in multiple rounds, including: inputting the newly generated prompt words and the original prompt words into the prompt word selection stage for multiple rounds of expansion and evaluation. In each round, the performance of the expanded generated prompt words and the original prompt words is predicted on the test set to obtain performance scores, and multiple prompt words with the highest performance scores are selected as the input for the next round until the optimized prompt words are finally obtained.
[0015] As a further improvement of the method of the present invention: the function expression for determining the prompt word selection priority according to the performance score is:
[0016]
[0017] Where p select represents the prompt word selection priority, Q t (p i ) represents the performance score of the i-th prompt word at time step t, N t (p) represents the total number of times the i-th prompt word is evaluated, weighted rand k represents selecting k prompt words using the weighted random selection function, c represents the exploration coefficient, and lnt represents the natural logarithm of time step t.
[0018] As a further improvement of the method of the present invention: in the defense working stage, generating the program dependence graph of the code to be detected includes:
[0019] Receiving the JavaScript code to be tested, adding data flow and control flow information to the program AST, and generating the corresponding program dependence graph;
[0020] Identifying and integrating the expression nodes in the program dependence graph and the subtrees associated with the expression nodes, and retaining the integrated result as a complete unit.
[0021] As a further improvement of the method of the present invention: it also includes optimizing the generated program dependence graph by using control flow optimization, data flow optimization, and redundant code elimination strategies. The control flow optimization is to merge the statement nodes with a single child node to generate composite nodes to simplify the structure of the program dependence graph and retain the original control flow semantics; the data flow optimization includes a constant propagation mechanism and a copy propagation mechanism. The constant propagation mechanism is used to identify and propagate statically computable expressions and propagate the expressions to related nodes; the copy propagation mechanism replaces the copied variable with the original value of the variable by tracking the assignment operation; the redundant code elimination strategy is to remove redundant code.
[0022] As a further improvement of the method of the present invention: decomposing the program dependence graph of the code to be detected into multiple subgraphs with consistent program structures, and the decomposition to obtain multiple subroutine dependence graphs further includes:
[0023] Generating a weighted undirected graph according to the program dependence graph, wherein the weight assigned to the edge of the control flow dependence is higher than the weight assigned to the edge of the data flow dependence, the control flow represents the execution sequence relationship between various operations in the program, and the data flow represents the dependence relationship between data in the program;
[0024] Using the community detection algorithm to partition the weighted undirected graph into multiple subgraphs. During the community detection process, the modularity Q is calculated, and the functional subgraphs consistent with the structure of the program to be tested are identified by maximizing the Q modularity, and the number of AST nodes in each community is restricted not to exceed the preset threshold θ ast , and finally multiple subgraphs are obtained by partitioning.
[0025] As a further improvement of the method of the present invention: during the process of calculating the modularity Q using the Louvain algorithm, the optimized Louvain algorithm is used to detect the modularity quality in the weighted undirected graph, and the optimized Louvain algorithm calculates the modularity according to the following formula:
[0026]
[0027] where Q represents the modularity, m represents the total edge weight, w ij represents the edge weight between nodes i and j, k i represents the weighted degree of node i, k j represents the weighted degree of node j, c i represents the community to which node i belongs, the Kronecker delta function δ represents a function for judging whether nodes i and j belong to the same community, N AST (C) represents the number of AST nodes in community C, θ ast represents the maximum number of AST nodes allowed in each community, and λ represents the penalty coefficient for controlling the importance of this constraint.
[0028] As a further improvement of the method of the present invention: during the community detection process, the following formula is used to calculate the modularity gain ΔQ when node i is reassigned to community C:
[0029]
[0030] where Σ in represents the total weight of the edges within community C, k i,in represents the edge weight connecting node i to other nodes in community C, Σ tot represents the total weight of all the edges connecting the nodes in community C, k iDenote the total weight of all edges connected to node i, ΔN AST (C) represents the change in the constraint on the number of AST nodes when adding node i to community C, and m represents the total edge weight.
[0031] The present invention also provides a computer device for executing a stored XSS attack detection method based on a large language model, including a processor and a memory. The memory is used to store a computer program, and the processor is used to execute the computer program to execute the stored XSS attack detection method based on the large language model as described above
[0032] Compared with the prior art, the beneficial effects of the present invention are as follows:
[0033] 1. By optimizing the prompt words in the prompt word learning stage by means of multi-round expansion and evaluation, the present invention can obtain optimized prompt words that can accurately guide the large language model to perform code analysis. Then, using the program dependence graph to structurally decompose complex code, retaining the original structure and generating code representation fragments, enabling the large language model to more efficiently and accurately identify stored XSS attacks, overcoming the deficiencies of traditional defense methods in terms of accuracy, real-time performance, and fine granularity. At the same time, it does not require relying on server-side configuration or a specific execution environment, can avoid defense failure caused by server compromise or sandbox bypass technology, and does not require large-scale labeled data and frequent model updates. It can also reduce the computing cost while improving adaptability, and can better adapt to the dynamic threat environment, thereby achieving more accurate, comprehensive, flexible, and efficient detection of stored XSS attacks.
[0034] 2. The present invention further realizes the optimization of prompt words based on the gradient descent iteration optimization method. By optimizing the input prompt words, the detection ability of the large language model is improved, enabling the prompt words to more accurately guide the large language model to accurately identify stored XSS attack vectors without modifying the underlying model. It can not only improve the efficiency and accuracy of detection, but also enhance the flexibility of detection, making it possible to quickly adapt to different detection tasks and scenarios.
[0035] 3. The present invention further generates the PDG of the code to be detected, and then uses the community detection algorithm to decompose it into multiple subgraphs consistent with the structure of the program to be detected. It can use the PDG and the community detection algorithm to split the code into sub-code segments while maintaining logical integrity, making the internal structure of the split subgraphs tightly meet high modularity, ensuring consistency with the logical structure of the JavaScript program, and taking into account the high efficiency and high fine granularity of the large model judgment. BRIEF DESCRIPTION OF THE DRAWINGS
[0036] Figure 1 It is a schematic structural diagram of the stored XSS attack detection method based on a large language model in an embodiment of the present invention.
[0037] Figure 2 This is a schematic diagram of the input and output predicted by the large language model in the embodiments of the present invention.
[0038] Figure 3 This is a schematic diagram of the input and output for the large language model to find the cause of the error in the embodiments of the present invention.
[0039] Figure 4 This is a schematic diagram of the input and output for the large language model to update the prompt in the embodiments of the present invention. Detailed implementation manners
[0040] Next, the technical solutions in the embodiments of the present invention will be clearly and completely described in conjunction with the accompanying drawings in the embodiments of the present invention. Obviously, the described embodiments are only a part of the embodiments of the present invention, rather than all the embodiments. All other embodiments obtained by those of ordinary skill in the art based on the embodiments of the present invention without creative efforts shall fall within the protection scope of the present invention.
[0041] The security defense solution based on the large language model (LLM) can achieve code behavior analysis by fine-tuning or training the model, and can perform excellently in specific scenarios. However, in the prior art, the security defense solution based on the LLM usually needs to rely on large-scale labeled data and frequent model updates, resulting in high computational costs and real-time defects. Although the Retrieval-Augmented Generation (RAG) technology can enhance the detection ability by using the knowledge base, its excessive dependence on historical data limits the real-time decision-making efficiency in a dynamic threat environment. In addition, the security defense solution based on the LLM in the prior art needs to train or fine-tune the model, and cannot directly adapt to rapidly evolving attack methods, making it difficult to meet the requirements of real-time and fine-grained analysis for stored XSS defense.
[0042] In the present invention, during the prompt learning phase, after receiving the initial prompt, the prompt is optimized through multiple rounds of expansion and evaluation, and an optimized prompt that can accurately guide the large language model to perform code analysis can be obtained; then, during the defense phase, a program dependence graph (PDG) of the code to be detected is generated, and the complex code is structurally decomposed using the program dependence graph into multiple subgraphs with consistent program structures, and then code representation fragments are generated while preserving the original structure. The code representation fragments are used to identify stored XSS attacks with the help of the large language model, which can identify stored XSS attacks more efficiently and accurately. It can not only improve the efficiency and real-time performance of the large model's judgment, but also ensure a high-fine-grained analysis of the defense against stored XSS, overcome the deficiencies of traditional defense methods in terms of accuracy, real-time performance, and fine-grainedness, and at the same time does not require server-side configuration or a specific execution environment, which can avoid defense failures caused by server breaches or sandbox bypass techniques. At the same time, it does not require large-scale labeled data and frequent model updates, can reduce the computing cost while improving adaptability, can better adapt to the dynamic threat environment, and thus achieve more accurate, comprehensive, flexible, and efficient detection of stored XSS attacks.
[0043] As Figure 1 shown, the method for detecting stored XSS attacks based on a large language model in this embodiment includes:
[0044] Step 1: In the prompt learning phase, receive the input of the initial prompt. The prompt expander expands the initial prompt and evaluates the performance of the expanded prompts to screen out the prompts that meet the preset performance indicators. The selected prompts are then expanded and evaluated in multiple rounds until the prompts that meet the optimization conditions are obtained and used as the optimized prompts.
[0045] Step 2: In the defense phase, receive the code to be detected and generate a program dependence graph (PDG) of the code to be detected. Decompose the program dependence graph of the code to be detected into multiple subgraphs with consistent program structures to obtain multiple sub-program dependence graphs. Traverse the nodes in each sub-program dependence graph and preserve the original structure of the program, and sequentially convert the nodes back to the original code format to obtain code representation fragments. Input the code representation fragments and the optimized prompts into the large language model, and the large language model determines whether each code fragment is an attack vector of stored XSS to obtain the final speculation result.
[0046] In this embodiment, during the prompt learning phase, expanding the initial prompt includes:
[0047] Step 101: Divide the code sample set composed of labeled attack vectors and non-attack vectors into a training set and a test set.
[0048] Step 102: Use the initial prompt to guide the large language model to predict the code in the training set in sequence, compare the prediction results with the true labels, and select the code samples with incorrect predictions as the error sample set;
[0049] Step 103: Randomly select the code with incorrect prediction and the current prompt in the error sample set to generate the error reason, and optimize the current prompt according to the generated error reason to expand and generate a new prompt.
[0050] In this embodiment, the optimization of the prompt is achieved by adopting the iterative optimization method of gradient descent, that is, applying the iterative optimization logic of gradient descent to the discontinuous space of natural language prompts, so that the "debugging thinking" of the prompt (such as analyzing the error reason) can be encoded into an automated process, realizing the optimization of the discrete space based on the LLM, so that the large model can be accurately guided to perform code analysis.
[0051] Specifically, first execute the prompt expansion stage. At this time, use the initial prompt to guide the large language model to make predictions on the code in the training set in sequence, and select the code with different prediction results from the labels as the error sample set; randomly select the code with incorrect prediction and the current prompt in the error sample set as the generated error reason in sequence, and then provide this prompt and the generated error reason to the large language model together. The large language model improves the prompt according to the prompt and the error reason to generate a new prompt, and then inputs the newly generated prompt and the original prompt into the prompt selection stage; in the prompt selection stage, the original prompt and the newly generated prompt at the current stage are predicted by using the input-output test method of the large language model to find the error reason on the test set, and then the prompt with the best performance is selected from multiple prompts.
[0052] In this embodiment, in the prompt learning stage, the performance of the expanded and generated prompts is evaluated to screen out the prompts that meet the preset performance indicators, and multiple rounds of expansion and evaluation are performed on the screened prompts, including: inputting the newly generated prompt and the original prompt generated by the expansion into the prompt selection stage to perform multiple rounds of expansion and evaluation in the prompt selection stage. In each round, the performance of the expanded and generated prompt and the original prompt is predicted on the test set to obtain the performance score, and multiple prompts with the highest performance scores are selected and used as the input for the next round until the optimized prompt is finally obtained.
[0053] Specifically, use the large language model to predict the original prompt and the newly generated prompt on the test set, calculate the performance scores of each prompt, and determine the prompt selection priority according to the performance scores to select the prompt with the best performance from multiple prompts. Performance score Qt (p i ) can reflect the performance of the i-th prompt at time step t on the test dataset. N t (p) represents the total number of times the prompt is evaluated. After T rounds of testing, the best k prompts are selected to enter the next round of expansion phase. In the last round, the best prompt is selected as the optimized prompt.
[0054] In this embodiment, an improved multi-armed bandit algorithm is formed by improving the traditional multi-armed bandit algorithm. The improved multi-armed bandit algorithm is used to calculate the prompt selection priority to select the prompt with the best performance from multiple prompts. The calculation expression of the prompt selection priority is:
[0055]
[0056] where p select represents the prompt selection priority, Q t (p i ) represents the performance score of the i-th prompt at time step t, and the total number of times each prompt is evaluated is recorded. N t (p) represents the total number of times the i-th prompt is evaluated. weighted rand k represents selecting k prompts using a weighted random selection function. c represents the exploration coefficient, and lnt represents the natural logarithm of time step t.
[0057] The weighted random selection function calculates the dynamic weight for each candidate p i and then performs non-repetitive sampling together. The higher the weight, the greater the probability that the candidate is selected. In this embodiment, by selecting prompts according to the selection strategy as shown in the above formula (1), based on the probability-based confidence upper bound balance strategy, the performance score Q t (p i ) and the evaluation times N t (p) are used to calculate the dynamic weight of each candidate p i Through the weighted random selection method, k prompts are selected. Compared with the traditional direct selection strategy of selecting the k highest values, it can not only select the largest k values, but also has a certain probability of selecting values other than the largest k values, which can increase the possibility of more exploration, balance the utilization and exploration of candidates, and thus improve the effect of prompt optimization. By the above method, this embodiment can fully optimize the prompts, enabling more accurate guidance for the large language model to perform code analysis.
[0058] In a specific application embodiment, such as
[0059] In the specific application embodiment, such as Figure 2As shown, when the large language model seeks the reason for the error, the model input: {{prompt}} is the currently used prompt, and {{error_sthing}} is the code where the prediction result is inconsistent with the label; the output result {{reason}} is the reason why the current prompt predicts this code incorrectly. In the prompt expansion stage (gradient descent), the initial prompt is used to guide the large language model to make predictions on the codes in the training set in turn, and the prediction results are compared with the true labels. The codes with different prediction results and labels are selected as the error sample set. Randomly select the incorrectly predicted code and the current prompt from the error sample set in turn as Figure 3 shown in the input-output process of the large language model to find the reason for the error, generate the reason for the error for {{error_string}}, and then input this prompt and the generated {{reason}} together to Figure 4 shown in the input-output process of the large language model to update the prompt. Let the large language model improve and generate a new prompt for this prompt and this error. The newly generated prompt and the original prompt are all input to the prompt selection stage. Among them, the input-output of the large language model to update the prompt is: {{prompt}} is the currently predicted prompt, {{reason}} is the reason for the incorrect prediction, and {{number of new prompts}} is the number of new prompts that need to be generated by this prompt; the output result {{new prompt}} is the newly generated prompt after the current prompt improves the error.
[0060] In the defense work stage of this embodiment, the program dependence graph generated for the code to be detected includes:
[0061] Step 201: Receive the JavaScript code to be tested, add data flow and control flow information to the program AST, and generate the corresponding program dependence graph;
[0062] Step 202: Identify and integrate the expression nodes in the program dependence graph and the subtrees associated with the expression nodes, and retain the integrated result as a complete unit.
[0063] Specifically, first, generate the PDG of the code from the javascript code received by the browser. This module adds data flow and control flow information on the basis of the program AST. By identifying and integrating the expression nodes in the PDG and their associated subtrees and retaining them as complete units, the semantic integrity can be effectively maintained and it is convenient for subsequent subgraph segmentation.
[0064] This embodiment further includes optimizing the generated program dependence graph by adopting control flow optimization, data flow optimization, and redundant code elimination strategies. The PDG is optimized through three strategic optimization techniques: control flow optimization, data flow optimization, and redundant code elimination, which can improve the expression efficiency of the PDG while retaining the core semantic information. Among them, control flow optimization is to merge statement nodes with a single child node to generate composite nodes, which not only retains the original control flow semantics but also simplifies the graph structure. For example, a folding operation is performed on each statement node and its single child node to form a unified composite node. Data flow optimization includes two complementary mechanisms: constant propagation mechanism and copy propagation mechanism. The constant propagation mechanism is used to identify and propagate statically computable expressions and propagate the expressions to relevant nodes; the copy propagation mechanism replaces the copied variable with the original value of the variable by tracking assignment operations. These two mechanisms work together to improve the compactness and efficiency of code representation. The redundant code elimination strategy is to remove redundant code, which can significantly reduce the scale of the PDG while completely retaining the core program logic. The redundant code includes print operations for debugging or logging, unused code segments, etc.
[0065] In this embodiment, decomposing the program dependence graph of the code to be detected into multiple subgraphs with consistent program structures. The decomposition to obtain multiple subprogram dependence graphs further includes:
[0066] Step 211: Generate a weighted undirected graph according to the program dependence graph. Among them, the weight assigned to the edge of control flow dependence is higher than the weight assigned to the edge of data flow dependence. Control flow represents the execution sequence relationship between various operations in the program, and data flow represents the dependence relationship between data in the program.
[0067] Specifically, convert the program dependence graph into a weighted undirected graph. The edge of control flow dependence is assigned a higher weight (w c ), and the edge of data flow dependence is assigned a lower weight (w d ). Through this weight setting (w c >> w d ), the importance of control flow in determining the functional structure of the code can be highlighted, avoiding splitting the key execution path into different subgraphs. And because the locality of data flow dependence is relatively strong, while control flow dependence has a greater impact on the overall program structure, through the differential processing of control flow and data flow dependence, the subgraphs after partitioning can retain the core execution logic.
[0068] Step 212: Use the community detection algorithm to partition the weighted undirected graph into multiple subgraphs. During the community detection process, calculate the modularity Q and identify the functional subgraphs that are consistent with the structure of the detected JavaScript program by maximizing the modularity Q, that is, identify communities with dense internal connections and sparse external connections. Each identified community corresponds to a subgraph, and limit the number of AST nodes in each community not to exceed the preset threshold θ ast , if allocating a certain node to a certain community causes N AST (C)>θ ast , then the node will be reallocated to other communities or a new community will be created. Finally, multiple subgraphs are obtained to ensure that when the generated subgraphs are provided as input to the LLM, the length of the converted tokens is within a controllable range.
[0069] Specifically, generate a weighted graph through the PDG, and then use the community detection algorithm to decompose the graph into multiple weighted graph subgraphs. The nodes of the weighted graph subgraphs correspond to the PDG subgraphs. In the first stage, convert the PDG into a weighted undirected graph G. The edges of control flow dependencies are assigned higher weights (w c ), and the edges of data flow dependencies are assigned lower weights (w d ). Through this way of setting weights (w c >>w d ), the importance of the control flow in determining the functional structure of the code can be highlighted; in the second stage, based on the community detection algorithm, perform subgraph decomposition. In the weighted graph, due to the high weights of the control flow edges, by maximizing the modularity Q, it is possible to tend to divide the code regions with dense control flows into the same community, thereby identifying communities (subgraphs) with dense internal connections and sparse external connections, while maintaining the integrity of the control flow structure inside the subgraph and consistency with the program functional logic.
[0070] In this embodiment, to match JavaScript, optimize the Louvain algorithm, and use the optimized Louvain algorithm to detect the modularity in the weighted undirected graph. The optimized Louvain algorithm specifically calculates the modularity according to the following formula:
[0071]
[0072] Among them, Q represents the modularity index of community detection, m represents the total edge weight, w ij represents the edge weight between nodes i and j, k i represents the weighted degree of node i, k j represents the weighted degree of node j, c i represents the community to which node i belongs, and the Kroneckerdelta function δ represents used to determine whether nodes i and j belong to the same community, N AST(C) represents the number of AST nodes in community C, and θ ast represents the maximum number of AST nodes allowed in each community, and λ represents the penalty coefficient controlling the importance of this constraint.
[0073] Calculate modularity in the above way. By setting an additional penalty term λ∑ C max(0, N AST (C) - θ ast ), an AST node constraint and a dynamic penalty mechanism are introduced, which can ensure that the number of AST nodes in each community is lower than the predefined upper limit θ during the community detection process ast , generate a code representation adapted to the LLM input, improve the analysis efficiency, and can also achieve function-oriented partitioning, giving priority to maintaining the integrity of control-flow intensive areas, ensuring that the subgraph is consistent with the program functional logic. At the same time, using the logically complete subgraph can more clearly expose the behavior of XSS attack vectors, thereby improving the detection accuracy.
[0074] In the community detection process of this embodiment, the modularity gain ΔQ when node i is reassigned to community C can be specifically calculated by the following formula:
[0075]
[0076] Among them, Σ in represents the total weight of the edges within community C, k i,in represents the weight of the edge connecting node i to other nodes in community C, Σ tot represents the total weight of all edges connecting the nodes in community C, k i represents the total weight of all edges connecting node i, and ΔN AST (C) represents the change in the AST node number constraint when node i is added to community C, and m represents the total edge weight. Through this penalty term, the modularity calculation directly considers the AST node constraint.
[0077] Calculate the modularity gain ΔQ in the above way. Since a penalty term λΔNAST(C) is set for migrations that cause AST node overrun, it can force the algorithm to satisfy the scale constraint while pursuing high Q, making the finally partitioned subgraph satisfy both high modularity (tight internal structure) and AST node limits (complete semantic units), thus being highly consistent with the logical structure of the JavaScript program.
[0078] Through the above steps, the finally generated set of PDG subgraphs can be obtained. Then, the sub-PDGs in the sub-PDG set are transformed into an optimized format suitable for LLM analysis; traverse the AST nodes in each PDG, preserve the original structure of the program, and then sequentially transform these ASTs back into JavaScript code to obtain code representation fragments; finally, use the optimized prompts to perform input-output predictions on the large language model for the code representation fragments (the prediction method is as Figure 2 shown), and if a stored attack vector is found, intercept the stored attack vector.
[0079] The present invention also provides a computer device for executing a method for detecting stored XSS attacks based on a large language model, including a processor and a memory. The memory is used to store a computer program, and the processor is used to execute the computer program to execute the method for detecting stored XSS attacks based on a large language model.
[0080] It can be understood that the above method of this embodiment can be executed by a single device, such as a computer or a server, etc., or can also be applied to a distributed scenario where multiple devices cooperate with each other to complete. In the case of a distributed scenario, one of the multiple devices can only execute one or more steps of the above method of this embodiment, and the multiple devices interact with each other to complete the above method. The processor can be implemented in the form of a general-purpose CPU, a microprocessor, an application-specific integrated circuit, or one or more integrated circuits, etc., and is used to execute relevant programs to implement the above method of this embodiment. The memory can be implemented in the form of a read-only memory ROM, a random access memory RAM, a static storage device, and a dynamic storage device, etc. The memory can store an operating system and other application programs. When implementing the above method of this embodiment through software or firmware, the relevant program codes are stored in the memory and are called and executed by the processor.
[0081] The above is only a preferred embodiment of the present invention and does not impose any form of limitation on the present invention. Although the present invention has been disclosed above with a preferred embodiment, it is not intended to limit the present invention. Therefore, any simple modification, equivalent change, and modification made to the above embodiment based on the technical essence of the present invention without departing from the technical solution of the present invention shall fall within the scope of protection of the technical solution of the present invention.
Claims
1. A storage - type XSS attack detection method based on large - language models, characterized in that, Including: In the prompt learning stage, an initial prompt is received. The prompt extender expands the initial prompt, and performs performance evaluation on the expanded prompts to filter out the prompts that meet the preset performance metrics. The filtered prompts are then expanded and evaluated in multiple rounds until the prompts that meet the optimization conditions are obtained and used as the optimized prompts. In the defense work stage, the code to be detected is received and a program dependence graph of the code to be detected is generated. The program dependence graph is converted into a weighted undirected graph. The edges of the weighted undirected graph respectively represent that the nodes belong to control flow dependence relationship or data flow dependence relationship, and different weights are configured for the edges of control flow dependence and data flow dependence. The weighted undirected graph of the program dependence graph is decomposed into multiple subgraphs with consistent program structures, and multiple subprogram dependence graphs are obtained. Each node in each subprogram dependence graph is traversed and the original structure of the program is retained, and the nodes are sequentially converted back to the original code format to obtain code representation segments. The code representation segments and the optimized prompts are input into the large language model, and the large language model determines whether each code segment is an attack vector of stored XSS to obtain the final speculation result.
2. The storage - type XSS attack detection method based on a large - language model according to claim 1, wherein, In the prompt learning stage, expanding the initial prompt includes: Dividing the code sample set composed of labeled attack vectors and non-attack vectors into a training set and a test set; Using the initial prompt to guide the large language model to predict the code in the training set in sequence, and comparing the prediction results with the true labels, and filtering out the code samples with incorrect predictions as the incorrect sample set; Randomly select the code with incorrect prediction and the current prompt in the incorrect sample set to generate the reason for the error, and optimize the current prompt according to the generated reason for the error to expand and generate a new prompt.
3. The storage-based XSS attack detection method based on a large language model according to claim 1, characterized in that In the prompt learning stage, performing performance evaluation on the expanded prompts to filter out the prompts that meet the preset performance metrics, and performing multiple rounds of expansion and evaluation on the filtered prompts includes: inputting the newly generated prompts and the original prompts into the prompt selection stage to perform multiple rounds of expansion and evaluation in the prompt selection stage. In each round, the performance prediction of the expanded prompts and the original prompts on the test set is obtained to get the performance score. The prompt selection priority is determined according to the performance score, and multiple prompts with the highest performance scores are selected as the input for the next round until the optimized prompts are finally obtained.
4. The storage - type XSS attack detection method based on a large - language model according to claim 3, wherein, The function expression for determining the prompt selection priority according to the performance score is: Among them, p select represents the prompt word selection priority, Q t (p i ) represents the performance score of the i-th prompt word at time step t, N t (p) represents the total number of times the i-th prompt word is evaluated, weighted rand k represents selecting k prompt words using the weighted random selection function, c represents the exploration coefficient, and ln t represents the natural logarithm of time step t.
5. The storage-based XSS attack detection method based on a large language model according to claim 1, wherein In the defense work stage, generating the program dependence graph of the code to be detected includes: Receiving the JavaScript code to be tested, adding data flow and control flow information to the program AST, and generating the corresponding program dependence graph; Identifying and integrating the expression nodes in the program dependence graph and the subtrees associated with the expression nodes, and retaining the integrated result as a complete unit.
6. The storage-based XSS attack detection method based on a large language model according to claim 5, wherein, It also includes optimizing the generated program dependence graph by adopting control flow optimization, data flow optimization and redundant code elimination strategies. The control flow optimization is to merge statement nodes with a single child node to generate composite nodes, so as to simplify the structure of the program dependence graph and retain the original control flow semantics; the data flow optimization includes a constant propagation mechanism and a copy propagation mechanism. The constant propagation mechanism is used to identify and propagate statically computable expressions and propagate the expressions to relevant nodes; the copy propagation mechanism replaces the copied variable with the original value of the variable by tracking assignment operations; the redundant code elimination strategy is to remove redundant code.
7. The method for detecting stored XSS attacks based on large language models according to any one of claims 1 to 6, characterized in that, Decomposing the program dependence graph of the code to be detected into multiple subgraphs with consistent program structures. The decomposition to obtain multiple subprogram dependence graphs further includes: Generating a weighted undirected graph according to the program dependence graph, wherein the edges of control flow dependence are assigned higher weights than the edges of data flow dependence. The control flow represents the execution sequence relationship between various operations in the program, and the data flow represents the dependence relationship between data in the program; The weighted undirected graph is segmented into multiple subgraphs by using a community detection algorithm. During the community detection process, the modularity Q is calculated, and the functional subgraphs consistent with the structure of the program to be tested are identified by maximizing the Q modularity. The number of AST nodes in each community is restricted not to exceed the preset threshold θ ast , and finally multiple subgraphs are obtained by segmentation.
8. The method for detecting stored XSS attacks based on large language models according to claim 7, wherein In the process of calculating the modularity Q, an optimized Louvain algorithm is used to detect the modularity quality in the weighted undirected graph. The optimized Louvain algorithm calculates the modularity according to the following formula: Among them, Q represents modularity, m represents the total edge weight, w ij represents the edge weight between nodes i and j, k i represents the weighted degree of node i, k j represents the weighted degree of node j, c i represents the community to which node i belongs, the Kronecker delta function δ is used to determine whether nodes i and j belong to the same community, N AST (C) represents the number of AST nodes in community C, θ ast represents the maximum number of AST nodes allowed in each community, and λ represents the penalty coefficient that controls the importance of this constraint.
9. The storage-based XSS attack detection method based on a large language model according to claim 7, wherein, In the process of community detection, the following formula is used to calculate the modularity gain ΔQ when node i is reassigned to community C: Among them, Σ in represents the total weight of the edges within community C, k i,in represents the edge weight connecting node i to other nodes in community C, Σ tot represents the total weight of all edges connecting the nodes of community C, k i represents the total weight of all edges connecting node i, ΔN AST (C) represents the change in the AST node number constraint when adding node i to community C, and m represents the total edge weight.
10. A computer device for implementing a storage-based XSS attack detection method based on a large language model, comprising a processor and a memory, the memory being used for storing computer programs, characterized in that, The processor is used to execute the computer program to perform the storage-type XSS attack detection method based on the large language model according to any one of claims 1 to 9.
Citation Information
Cited By
Prompt word logic configuration method based on context semantic enhancement
CN120725027A
Large model security vulnerability detection method based on multi-agent reinforcement learning
CN120805146A
Model vulnerability detection system and method for aerospace field
CN122286788A
A model vulnerability detection system and method for aerospace field
CN122286788B