Intelligent detection method for code security vulnerabilities based on large models
By constructing a business state graph and sandbox simulation, combined with a large language model and rule engine, lightweight context modeling and dual-channel verification are performed, solving the complexity and efficiency problems of code security detection in existing technologies, and achieving efficient and accurate code security detection.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Filing Date
- 2026-05-25
- Publication Date
- 2026-07-14
Smart Images

Figure CN122389031A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of code security detection and business logic vulnerability modeling, and in particular to an intelligent detection method for code security vulnerabilities based on large models. Background Technology
[0002] In the current field of code security testing and business logic vulnerability modeling, mainstream technologies mainly include static analysis, symbolic execution, knowledge graphs, multi-model linkage reasoning, and deep learning large language models for auditing source code and identifying security vulnerabilities. In recent years, the industry has gradually introduced large models (such as large language models) into security testing tasks to enhance the understanding of code semantics, complex business processes, and potential risk scenarios. Some products and academic research have attempted to use knowledge graph construction, end-to-end discriminant networks, and process mining to assist models in achieving large-scale business logic vulnerability detection. For example, formal rule verification or automated path traversal can be used to discover risks such as unauthorized access, payment process bypass, and sensitive operation out-of-bounds violations. However, while these general solutions ensure detection accuracy, they face many practical bottlenecks such as high engineering complexity, low reasoning efficiency, and weak cross-session state awareness, resulting in limited adaptability and practical effectiveness in high-concurrency, highly process-oriented business systems such as finance and e-commerce.
[0003] The main shortcomings of existing technologies are reflected in the following aspects: First, most large models only treat source code as static text input, ignoring the dynamic evolution of key state variables during actual business operations, and have limited ability to perceive changes in high-order business context. Second, the commonly used full knowledge graph or multi-model cascaded inference solutions have high computational load and large deployment complexity, which does not meet the realistic requirements of low resource consumption and high responsiveness in a DevOps environment. Third, the lack of interpretable intermediate semantic anchors and efficient collaboration mechanisms between models and rule engines makes it difficult for the system to effectively filter out false positives and achieve targeted model optimization. In practical applications, these deficiencies make it difficult for the system to simultaneously achieve the depth of detection granularity, the breadth of industry applicability, and the maintainability of the model without sacrificing inference speed. Summary of the Invention
[0004] This application provides an intelligent detection method for code security vulnerabilities based on a large model, which aims to solve one of the problems or issues of the existing technology mentioned in the background.
[0005] The intelligent code security vulnerability detection method based on a large model provided in this application specifically includes: S1: Extract business entities and state transition events from the source code and supporting documentation, and construct an initial business state graph containing nodes representing business states and directed edges representing legal state transition operations.
[0006] S2: Based on the initial business state diagram, perform sandbox simulation on the target business module to capture snapshots of key state variables at the entry and exit points of each function in the real call chain to form a time-stamped original sequence of state trajectories.
[0007] S3: Perform lossless compression processing on the original sequence of the state trajectory, retaining only the key frames of state transition permission changes or sensitive data transfers to generate a compact business state trajectory summary.
[0008] S4: The compact business state trajectory summary is structured into dynamic semantic anchors containing preceding states, actions, subsequent states, and constraints, and the dynamic semantic anchors are embedded into the corresponding positions of the large language model input sequence.
[0009] S5: Utilize a large language model embedded with the dynamic semantic anchors to perform inference operations and generate a logical consistency judgment result based on the actual business stage of the current analysis code segment.
[0010] S6: Call the rule engine to perform formal verification on the logical consistency judgment result, and output the candidate vulnerability label only when the two conclusions are consistent and the preset confidence threshold is met.
[0011] S7: For high-frequency false alarm scenarios, automatically extract the hot zones of attention weights of the large language model and the conflict points of the rule engine, and generate minimum perturbation adversarial samples based on the conflict points to fine-tune the discrimination boundary of the business logic vulnerability detection model in a specific business semantic dimension.
[0012] S8: Update the parameters of the business logic vulnerability detection model based on the discriminant boundary fine-tuned by the minimum perturbation adversarial sample, and complete the closed-loop optimization iteration of the multi-step business logic context modeling capability.
[0013] The intelligent code security vulnerability detection method based on a large model provided in this application has the following beneficial effects: (1) By constructing a lightweight context modeling mechanism based on business state graph and compressed trajectory summary, the technical defects of traditional large models in processing long-term business logic, such as attention dispersion, high inference latency and large memory overhead, are effectively overcome. This solution adopts an adaptive sliding window and key frame extraction strategy, retaining only semantically significant events such as state transition, permission change and sensitive data flow, to achieve lossless compression of the original call chain, reducing the length of the input context to less than 20% of the original sequence, significantly improving the model response speed and deployment efficiency, while ensuring the integrity and traceability of the critical path of the business process, solving the noise inundation and context expansion problems caused by global splicing of full logs or code fragments in existing methods, and enhancing the model's ability to accurately identify real business stages.
[0014] (2) The introduction of dynamic semantic anchor injection and dual-channel verification collaboration mechanism significantly improves the accuracy and credibility of AI auditing system in complex business logic judgment; by structuring the compressed trajectory summary into a quadruple of <preceding state|action|subsequent state|constraint> and inserting it into the corresponding position of the prompt sequence in a local embedding manner, the model attention is precisely aligned in the spatiotemporal dimension, enabling it to focus on the specific business context in which the current analysis code is located; on this basis, the front channel generates logical consistency inference by a large language model, and the back channel synchronously calls a lightweight rule engine for formal verification. The two conclusions must be consistent and pass the confidence threshold judgment before a vulnerability alarm can be triggered, effectively suppressing false alarms and false negatives caused by training bias of a single model; this mechanism avoids high-cost architecture dependencies such as multi-model cascading, reinforcement learning exploration or thought chain unfolding, and significantly improves the stability and interpretability of logical vulnerability detection without increasing the scale of model parameters.
[0015] (3) Design a closed-loop feedback optimization path based on attention hotspot analysis and adversarial example inversion to give the system the ability to continuously evolve and effectively address the problem of ambiguous semantic discrimination boundaries in high-frequency false alarm scenarios; when conflicts occur in dual-channel verification, the system automatically extracts the inconsistency between the model's attention area and the rule assertion, generates minimal perturbation adversarial examples for targeted fine-tuning, thereby finely adjusting the model's inference preferences in specific business semantic dimensions (such as the pre-real-name authentication and the atomicity of state transitions); this process does not require retraining the entire model, nor does it require introducing GAN enhancement or large-scale labeled data, and has the ability to Its advantages of low resource consumption and rapid iteration support automated integration in DevOps pipelines. The overall technical path abandons the heavy-load paradigms such as full knowledge graph construction and multi-level Transformer parallel computing, and instead uses "trajectory compression - anchor point alignment - dual-channel verification" as the core framework. While maintaining the simplicity of the single large model architecture, it achieves efficient, accurate and explainable audit coverage for highly state-dependent systems such as financial transactions, e-commerce fulfillment, and government approvals, significantly enhancing the feasibility and potential for large-scale promotion of AI-assisted security detection in real industrial scenarios.
[0016] In summary, this method integrates lightweight trajectory modeling, dynamic semantic anchor guidance, and a dual-channel collaborative verification mechanism to construct an AI-enhanced auditing system that combines high performance, high reliability, and adaptive evolution capabilities. Without sacrificing the model's expressive power, it effectively balances the contradiction between the context depth required for understanding complex business logic and system operating efficiency. It is not only significantly superior to traditional high-overhead solutions that rely on full information input or multi-model stacking, but also achieves comprehensive breakthroughs in multiple dimensions such as vulnerability detection accuracy, inference real-time performance, deployment flexibility, and result interpretability. It provides a practical technical paradigm for intelligent code auditing in fields with high security requirements. Attached Figure Description
[0017] Figure 1 This is the main flowchart of a code security vulnerability intelligent detection method based on a large model.
[0018] Figure 2 This is a sub-flowchart of a code security vulnerability intelligent detection method based on a large model.
[0019] Figure 3 This is another sub-flowchart of the intelligent code security vulnerability detection method based on a large model. Detailed Implementation
[0020] Embodiments of the present invention are described in detail below, examples of which are shown in the accompanying drawings, wherein the same or similar reference numerals denote the same or similar elements or elements having the same or similar functions throughout. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain the present invention, and should not be construed as limiting the present invention.
[0021] The following disclosure provides many different embodiments or examples for implementing different structures of the invention. To simplify the disclosure, specific examples of components and arrangements are described below. Of course, these are merely examples and are not intended to limit the invention. Furthermore, reference numerals and / or letters may be repeated in different examples; such repetition is for simplification and clarity and does not in itself indicate a relationship between the various embodiments and / or arrangements discussed.
[0022] like Figure 1 As shown, this application provides an intelligent code security vulnerability detection method based on a large model, specifically including: S1: Extract business entities and state transition events from the source code and supporting documentation, and construct an initial business state graph containing nodes representing business states and directed edges representing legal state transition operations.
[0023] S2: Based on the initial business state diagram, perform sandbox simulation on the target business module to capture snapshots of key state variables at the entry and exit points of each function in the real call chain to form a time-stamped original sequence of state trajectories.
[0024] S3: Perform lossless compression processing on the original sequence of the state trajectory, retaining only the key frames of state transition permission changes or sensitive data transfers to generate a compact business state trajectory summary.
[0025] S4: The compact business state trajectory summary is structured into dynamic semantic anchors containing preceding states, actions, subsequent states, and constraints, and the dynamic semantic anchors are embedded into the corresponding positions of the large language model input sequence.
[0026] S5: Utilize a large language model embedded with the dynamic semantic anchors to perform inference operations and generate a logical consistency judgment result based on the actual business stage of the current analysis code segment.
[0027] S6: Call the rule engine to perform formal verification on the logical consistency judgment result, and output the candidate vulnerability label only when the two conclusions are consistent and the preset confidence threshold is met.
[0028] S7: For high-frequency false alarm scenarios, automatically extract the hot zones of attention weights of the large language model and the conflict points of the rule engine, and generate minimum perturbation adversarial samples based on the conflict points to fine-tune the discrimination boundary of the business logic vulnerability detection model in a specific business semantic dimension.
[0029] S8: Update the parameters of the business logic vulnerability detection model based on the discriminant boundary fine-tuned by the minimum perturbation adversarial sample, and complete the closed-loop optimization iteration of the multi-step business logic context modeling capability.
[0030] Step S1: Extract business entities and state transition events from the source code and supporting documentation, and construct an initial business state graph containing nodes representing business states and directed edges representing legitimate state transition operations. Specifically, this includes: S1.1: Perform lexical analysis and semantic parsing on multilingual source code files and supporting technical documents to extract candidate business entity sets and potential state identifier lists, thereby obtaining raw data of structured business elements.
[0031] Perform uniform formatting preprocessing on multilingual source code files and accompanying technical documentation to remove comments, blank lines, and irrelevant characters to ensure the consistency and parsability of the input sequence for subsequent parsing.
[0032] Based on the lexical analyzer, language-specific keywords, identifiers, and symbol tables are defined for languages such as Java, Python, Go, and C / C++. The source code is scanned segment by segment using regular expression pattern matching and finite state automata to generate a lexical list containing lexical categories, position indices, and syntax pointers.
[0033] A semantic parser is applied to the list of lexical terms, and an abstract syntax tree (AST) is generated to establish a unified semantic node model for multiple languages. Identifiers with business semantics, such as classes, methods, interfaces, enumerations, and global variables, are mapped to preliminary candidate business entities, and their scope and dependencies are marked in the tree structure.
[0034] Natural Language Processing (NLP) is used to parse the supporting technical documents such as API descriptions and business process diagrams. Named Entity Recognition (NER) model is used to extract business-related proper nouns and state description phrases. These are then cross-compared with the candidate business entities obtained from source code parsing to complete and correct the set of business entities.
[0035] Identify variables or constants with state semantics from the multilingual unified semantic node model and the document entity set output by NER, match them with a pre-defined state identifier pattern library, such as patterns named by state enumeration values, boolean flags, and stage strings, and extract a list of potential state identifiers to ensure coverage of both code and document sources.
[0036] Through the aforementioned chain of lexical analysis and semantic parsing, the original source code and document content are transformed into structured business element raw data, providing a complete and accurate input foundation for subsequent control flow analysis and state event identification, and realizing the unified extraction and format standardization of business entity sets and state identifier lists.
[0037] S1.2: Based on the original data of the structured business elements, perform control flow analysis and data flow tracing operations to identify state assignment statements and conditional branch logic in the function call chain, thereby generating a sequence of state transition events with contextual dependencies.
[0038] Based on the original structured business element data from step S1.1, the control flow analysis module of the multi-language code parser is loaded. The abstract syntax tree construction result of this module is used as the input of the initial control flow graph. A set of directed control flow nodes is generated based on the start and end nodes of function calls.
[0039] The above set of directed control flow nodes is input into the data flow tracer. A data flow dependency graph is built according to a predefined set of sensitive variables. The position and execution conditions of state assignment statements are resolved along the function call chain using depth-first traversal. The control flow nodes related to the assignment statements and condition branches are associated in a time sequence to form a preliminary state transition mapping table.
[0040] The path filtering operation is performed on the preliminary state transition mapping table. The predicate evaluation module is called to analyze the conditional branch logic expression. The Boolean algebra simplification method is used to decompose the complex conditions into a set of decidable predicates. These predicates are then bound to state transition events to ensure the accuracy of the contextual dependencies of the event sequence.
[0041] For state assignment statements with nested or cross-module calls, cross-scope data stream merging is performed. By unifying variable namespaces and eliminating intermediate variable aliases, they are merged into a unified state identifier, avoiding the loss of event sequences due to naming differences.
[0042] The filtered and merged state transition events are sorted according to the call chain order, and combined with the execution topology of the control flow nodes to generate the final state transition event sequence with context dependencies.
[0043] This chain-like processing method transforms the original structured business element data from step S1.1 into a sequence of state transition events that can be normalized by subsequent business semantic mapping rules, enabling accurate identification of state assignment statements and conditional branch logic in the function call chain.
[0044] S1.3: Normalize the state transition event sequence using predefined business semantic mapping rules to eliminate naming differences and confirm legitimate state transition paths, thereby constructing a standardized business state transition relationship graph.
[0045] S1.4: Perform graph theory modeling operations based on the standardized business state transition relationship graph to map the uniquely determined business state as a graph node and the legal state transition operation as a directed edge, thereby outputting an initial business state graph containing node attributes and edge constraints.
[0046] For the established standardized business state transition graph, the input conditions include a set of nodes, node business semantic attributes, an edge set, and edge constraints. Each node is guaranteed to be unique within the graph and has undergone naming normalization. Based on the input node set, node mapping is performed, instantiating each unique business state as a node object in the graph data structure. This node object contains an ID, a business semantic label, a location index, and a context reference pointer, ensuring accurate state location in subsequent simulations. Based on the input edge set, directed edge mapping is implemented, transforming each record representing a legal state transition into an edge object. This edge object possesses a starting node ID, an ending node ID, a trigger action identifier, and a constraint reference, ensuring consistency in the transition direction and logic. Graph theory modeling operations are performed on the node and edge objects. An internal connection matrix of the business state graph is generated through adjacency list construction to achieve efficient traversal and path lookup between nodes. Attribute binding is performed on the adjacency list construction results, attaching node attributes and edge constraints to matrix elements and path metadata, respectively, forming a two-layer association structure containing both semantics and logic. Connectivity checks and loop detection are performed on the global business state graph. Depth-first search is used to ensure that all nodes are reachable from the initial state, and closed-loop paths are marked to help identify potential logical loop risks. Through the above graph theory modeling and processing methods, the standardized migration relationships obtained in the previous step are transformed into an initial business state graph with node attributes and edge constraints, realizing an accurate and structured representation of business states and legal migrations, and providing highly complete and executable graph data input for subsequent sandbox simulation.
[0047] For example, an e-commerce order processing module has a standardized business state transition graph containing 6 nodes (order creation, payment pending confirmation, payment successful, shipment triggered, receipt confirmed, and order completed) and 7 legal transition edges. Node attributes include a state number ranging from 1 to 6, a business semantic label such as "payment pending confirmation" corresponding to the payment gateway waiting state, and edge constraints such as "payment interface call" as the trigger action identifier when the starting point is 2 and the ending point is 3, and "payment token valid" as the constraint condition. In actual execution, the node mapping stage encapsulates the state number and semantic label into the node object, and the edge mapping stage encapsulates the starting and ending point numbers, trigger actions, and constraints into the edge object. A 6×6 connection matrix is generated by constructing an adjacency list, with matrix elements recording the transition paths and bound constraint pointers. Depth-first search is used in connectivity detection, starting from node 1, ensuring that all nodes are reachable and that the path 2→3→4→5→6 is closed without risk of a cycle. In this scenario, the initial business state graph effectively represents the state topology and constraint logic of e-commerce order processing. The output graph data structure can directly drive the execution of test cases covering all migration paths in subsequent sandbox simulations, thereby significantly improving the accuracy and stability of state context capture.
[0048] Step S2: Based on the initial business state diagram, perform sandbox simulation on the target business module to capture snapshots of key state variables at the entry and exit points of each function in the real call chain to form a timestamped original sequence of state trajectories. Specifically, this includes: S2.1: Obtain the node attributes and edge constraints in the initial business state graph, use virtualization container technology to build an isolated sandbox simulation environment, and deploy the compilation artifacts and dependent libraries of the target business module into this environment to generate a lightweight sandbox simulation instance with independent running capabilities that does not affect the host system.
[0049] The system retrieves node attributes and edge constraints from the initial business state graph, transforming the business state identifiers of each node, their corresponding attribute values, and the triggering conditions and constraint rules of the edges into structured configuration data adapted for virtualization deployment. This structured configuration data is input into the virtualization container building module, which uses a lightweight virtualization engine to generate a base container image with resource isolation capabilities. During image building, a specific version of the runtime environment and a security sandbox control component are embedded, enabling the image to execute in a closed environment without write permissions to external systems. After the container image is generated, the compiled artifacts of the target business module are loaded. The compiled executable files, along with associated static resources and dynamic link libraries, are layered and mounted according to the dependency chain in the initial business state graph, ensuring that each dependent module can be correctly parsed and invoked during container runtime. Version consistency verification logic is introduced during container mounting, performing hash digest comparisons on the compiled artifacts and dependent libraries and matching them with the version fingerprints recorded in the business state graph configuration. If the verification matches, deployment is allowed; otherwise, an automatic rollback mechanism is triggered to ensure consistency between the simulation environment and the analysis target. After deployment, network and I / O isolation policies are configured, a dedicated subnet is bound through a virtual network interface, and kernel-based namespace isolation is enabled to block access to sensitive resources on the host machine from within the container, achieving a fully controllable execution environment. Through the above virtualization construction and configuration methods, the initial business state diagram result from the previous step is transformed into a lightweight sandbox simulation instance with independent running capabilities and the ability to securely capture business call chains, achieving the expected technical effect of zero interference to the host system during simulation execution.
[0050] For example, during the sandbox simulation construction of the financial transaction business module, node attributes in the initial business state diagram are extracted, including state ID, permission level, and data flow type. Edge constraints include state transition trigger events and input validation rules. This data is used to generate a JSON configuration file, which serves as input for container construction. A lightweight virtualization system based on KVM is invoked to create an image, pre-installing the Python 3.9 runtime and a dedicated security detection plugin. The compiled output of the target business module, orderservice.bin, and its dependencies, libcrypto.so and libdbconn.so, are mounted layered in the image's / data and / usr / lib directories. The SHA-256 hash of the compiled output is the plain text "4f2a...". After confirming consistency with the fingerprint value recorded in the business state diagram configuration, the mounting is completed. Inside the deployed container, netns isolation is set through a namespace policy, allowing the container to access only the simulation subnet 10.0.3.0 / 24, and write permissions to the host file system are disabled. After the lightweight sandbox was built, it was able to execute orderservice.bin and trigger all the legal state transition paths defined in the state graph. During the simulation, the CPU utilization of the host system remained at a stable level and no resource contention occurred, verifying the independence and security of the simulation instance.
[0051] S2.2: Based on the lightweight sandbox simulation instance, load the predefined business scenario test case set, drive the internal execution engine of the sandbox to simulate multi-user concurrent request interaction, so as to trigger the execution flow of the real call chain covering all legal state transition paths in the initial business state diagram.
[0052] When loading the business scenario test case set, the structured description file of the test case set is parsed into executable request sequence information and mapped to the request generator module of the sandbox simulation environment to ensure that all requests meet the legal state transition entry conditions in the initial business state diagram.
[0053] The parsed request sequence information is parallelized according to the concurrency configuration parameters. The multi-threaded execution engine inside the sandbox is called to instantiate multiple user session threads, and an independent session context identifier is bound to each thread to isolate the data flow and control flow of different user requests.
[0054] In a multi-user session thread, the priority of request execution is dynamically adjusted. The path coverage target is calculated based on the state transition topology in the initial business state graph. The priority of requests on uncovered paths is increased, and the scheduling strategy that maximizes path coverage is implemented through the scheduler's priority queue.
[0055] When executing request interactions, the internal network protocol simulation module of the sandbox generates HTTP, WebSocket, or RPC communication packets that conform to the actual deployment environment of the target business module, and injects the parameter values and operation instructions defined in the test cases into the communication packets to trigger cross-state migration of business logic.
[0056] The sandbox's call chain tracing interface records each cross-state transition operation generated by the execution engine in real time as a call chain event object. The call chain event object includes the triggered state edge identifier, action type, and session context ID, providing complete execution flow information for subsequent instrumentation and listening.
[0057] Through the above concurrent execution and path coverage scheduling processing, the lightweight sandbox simulation instance generated in the previous step is transformed into a real call chain execution flow that can cover all legal state transition paths in the initial business state graph, achieving comprehensive triggering and accurate simulation effects for multi-step business logic.
[0058] S2.3: Instrument the function call instructions in the actual call chain execution flow, and when a function entry breakpoint and a function exit breakpoint are detected, extract the values of key state variables in the memory stack to generate a set of original observation records containing function identifiers and state snapshot data.
[0059] For the actual call chain execution flow from step S2.2, parse the symbolic information of the function call instructions and the call stack structure to locate the instrumentable instruction segments and the breakpoints at the function entry and exit points.
[0060] Inject instrumentation listening logic at the located breakpoint, set up a memory stack variable collector, and perform key state variable capture operations at the moment the breakpoint is triggered.
[0061] Based on the node attributes and edge constraints in the business state diagram, a decision list for key state variables is defined. Only variables that satisfy the decision list are numerically extracted to avoid redundant data collection.
[0062] The extracted key state variable values are immediately encoded and bound to function identifiers, and an index relationship is established between them and the unique identifier of the function call to ensure the consistency of subsequent timing analysis.
[0063] The values of state variables bound to function identifiers are stored in the original observation record set to ensure that the collected data maintains structural consistency and has traceability.
[0064] By using instrumentation listening logic and breakpoint acquisition mechanism, the actual call chain execution flow of the previous step is transformed into a raw observation record set containing function identifiers and state snapshot data, thereby achieving accurate capture of dynamic state changes in the simulated business call chain.
[0065] S2.4: Based on the original observation record set, extract the high-precision monotonic clock counter value of the system as the time reference, and perform triplet association encapsulation processing on the function identifier, state snapshot data and time reference to generate a state variable snapshot event stream with microsecond-level timestamps.
[0066] S2.5: Perform serialization and reorganization operations on the snapshot event stream of state variables with microsecond-level timestamps in ascending order of timestamps to eliminate out-of-order interference caused by concurrent threads, so as to output the original sequence of state trajectories with timestamps that strictly reflects the timing characteristics of business logic.
[0067] It receives a state variable snapshot event stream with microsecond-level timestamps as input, obtains the function identifier, state snapshot data and high-precision time base information contained therein, and confirms that there is an out-of-order arrangement phenomenon caused by multi-threaded concurrent execution in the event stream.
[0068] The input event stream is sorted globally in ascending order according to the timestamp field. Stable sorting is used to ensure that the original capture order under the same timestamp is not destroyed, and the sorting operation is applied to the complete triple structure to maintain the synchronization consistency of the data fields.
[0069] Identify state snapshots belonging to the same thread execution path in the sorted event stream, construct a mapping table between thread unique identifiers and event indices, and independently group the event sequences of each thread so that subsequent merging and regularization operations can eliminate cross-interference between threads.
[0070] For the grouped thread event sequence, a continuity detection based on timestamp difference is performed. The time base difference between adjacent events is calculated and compared with a preset thread slice threshold. If the difference is lower than the threshold, it is considered a continuous segment. If it is higher than the threshold, it is marked as a thread switching point, thereby clarifying the boundary position of the disordered event.
[0071] Based on thread switching point information, all thread event sequences are serialized and recombined across groups. Events from different threads with monotonically increasing time bases are inserted into a unified time-series linked list structure according to their global timestamp order, ensuring the global time sequence consistency of the business state flow.
[0072] Through the above sorting, grouping, continuity detection and cross-group recombination processing, the results of the previous step are transformed into a time-stamped original sequence of state trajectories that strictly reflects the actual execution order of business logic, thereby completely eliminating concurrent out-of-order interference and accurately preserving temporal characteristics.
[0073] For example, in the sandbox simulation of the financial transaction business module, a total of 1850 snapshot event streams of state variables with microsecond-level timestamps were captured, including call records from 4 concurrent threads. The timestamp range of the input events was 2,100,000 to 2,150,000 microseconds, the thread slicing threshold was set to 200 microseconds, and the sorting algorithm chosen was the highly stable TimSort. During the sorting process, after the mapping table between thread ID and event index was established, the event time difference of thread A was at most 150 microseconds, and it was judged as a continuous segment; events with a time difference of 350 microseconds in thread B were marked as switching points. Based on the switching point information, during cross-thread reorganization, the events after the switching point of thread B were inserted into the global linked list according to their timestamps, maintaining a globally monotonically increasing trend. In the final output original sequence of timestamped state trajectories, the total number of events remained at 1850, the out-of-order interference was completely eliminated, the temporal characteristics of the business logic state evolution were significantly improved, and the subsequent S3 adaptive compression was able to extract key state transition points under high signal-to-noise ratio conditions.
[0074] like Figure 2 As shown, step S3 involves lossless compression of the original state trajectory sequence, retaining only key frames indicating state transitions, permission changes, or sensitive data transfers to generate a compact business state trajectory summary. Specifically, this includes: S3.1: Obtain the state variable snapshot event stream with microsecond-level timestamps, and perform segmentation processing on the state variable snapshot event stream to generate an initial sliding window sequence containing state evolution features within continuous time slices.
[0075] The system acquires snapshot event streams of state variables with microsecond-level timestamps as processing objects. It reads the timestamp, state variable identifier, and value from each event stream element and establishes a time index to ensure time series consistency. Based on the business entropy calculation method, it evaluates the information content of the sequence, using an adaptive window length strategy to determine the start and end ranges of segmentation. The window length is adjusted based on the fluctuation range of business entropy values between adjacent state segments. A sliding window generation operation is performed on the sequence, mapping the set of state variable snapshots covered by the current window to state evolution feature vectors within the time slice. The window movement step size is limited by a preset maximum information loss tolerance threshold. The business entropy value is calculated using the following formula: Here, p(s) represents the probability distribution of state variable values within the window, and H is the window's business entropy value, used to measure the information complexity of state changes. Based on the rate of change of H, the window boundaries are dynamically adjusted so that window cutting occurs when state evolution information is maximized. An initial sliding window sequence containing state evolution features within continuous time slices is generated. Each window is bound to its corresponding time index and state snapshot set, forming a standardized window data structure that can be used for subsequent differential comparison and state mutation detection. Through adaptive window length and information content evaluation processing, the event stream obtained in the previous step is transformed into segmented initial sliding window sequence data, achieving local structuring and information redundancy control of the original state trajectory sequence.
[0076] For example, in the state trajectory compression processing of a certain online payment business module, an event stream generated by sandbox simulation is obtained, with a length of 5000 events and a timestamp accuracy of 1 microsecond. State variables include account authentication status, order payment status, and inventory deduction status. The initial window length is set to 50 events, and the maximum information loss tolerance threshold is 0.05. When calculating the business entropy value of the first window, the probability distribution of variables such as account authentication status and order payment status is statistically analyzed. For example, if the proportion of events with a successful account authentication status is 0.8 and the proportion of events with a failed authentication status is 0.2, then p(s) are 0.8 and 0.2 respectively. Substituting these into the entropy value formula above, we get H≈0.7219. Based on the detection results of the entropy value change rate of adjacent windows exceeding the threshold, the window length is adjusted to 40 or 60 events to ensure that the cutting position covers the peak entropy value segment. The final number of initial sliding window sequences generated was 120, with an average window length of 41 events. The information complexity within the window remained stable in the range of 0.7 to 0.75, which significantly improved the accuracy and stability of subsequent identification of key state mutation points.
[0077] S3.2: Based on the initial sliding window sequence, a differential comparison mechanism is used to perform numerical change rate calculation and logical flag detection operations on the snapshots of adjacent state variables within the window, so as to identify a set of key state change points that characterize business state transitions, user permission changes, or sensitive data transfers.
[0078] Based on the initial sliding window sequence output by step S3.1, the input object is a set of state variable snapshots collected within consecutive time slices, which contains the variable values and corresponding time stamps for each service call node.
[0079] Perform differential operations on snapshots of adjacent state variables within the window, select the numerical domain or logical domain comparison method according to the type of variable value, calculate the rate of change for numerical domain difference, perform flag bit detection on logical domain variables, retrieve changes in flag bits such as permission level, session identifier, and sensitive data flow according to the business rule mapping table, and encode the change pattern into predefined logical event labels.
[0080] Cross-matching is performed on the difference operation results and logical event labels to calculate the snapshot index set of those whose numerical change rate exceeds the threshold or whose logical event labels hit the sensitive rules, forming a candidate set of key state mutation points.
[0081] Further correlation analysis was performed on each mutation point in the candidate set to identify mutation points with multiple variables changing in tandem within the same time slice, and these mutation points were marked as high-priority mutation points to ensure that critical business nodes are not lost in the subsequent compression process.
[0082] By combining differential comparison and logical flag detection, the initial sliding window sequence generated in step S3.1 is transformed into a set of key state mutation points that include business state transitions, user permission changes, or sensitive data transfers, thereby achieving accurate identification of mutation nodes before time-series compression.
[0083] For example, in a financial transaction detection scenario, the initial sliding window sequence includes snapshots of account status variables collected every 100 microseconds. These variables include balance, transaction status code, and permission level flags. The balance variable is calculated using a rate of change; a rate exceeding 0.2 is considered a significant change. For the transaction status code variable, logical flag detection is performed, identifying transition events from "pending payment" to "settled" based on a rule mapping table. For the permission level flag variable, events indicating a user's privilege escalation from level 2 to level 3 are detected. These matching results are integrated into a candidate mutation point set, and correlation analysis confirms the linkage between a sudden increase in balance and privilege escalation within the same time slice, designating these as high-priority mutation points. In practice, this method significantly improves the detection rate of key business logic nodes, ensuring that the subsequently compressed and generated compact business state trajectory summary fully preserves the key states affecting vulnerability assessment.
[0084] S3.3: For the non-critical intervals between the set of critical state mutation points, apply the isomorphic state merging strategy to perform redundant elimination and aggregation operations on state variable snapshots with the same business semantic identifier and no intermediate side effects, so as to generate a sparse state frame sequence that eliminates temporal noise.
[0085] For the set of critical state mutation points output by S3.2, receive the set and its location index in the original sequence of state trajectories, and select the snapshots of state variables between the set of mutation points as non-critical interval processing objects.
[0086] Perform a business semantic identifier mapping operation on all state variable snapshots in non-critical intervals, match and verify their field information with the predefined business semantic table, and filter out the snapshot group with completely identical business semantic identifiers as the homogeneous candidate set.
[0087] Side effect detection is performed on adjacent state snapshots in the homogeneous candidate set. Static data dependency analysis and dynamic stack change rate analysis are used to determine whether they introduce weight changes, sensitive data transfers or permission status changes in business logic. Snapshot pairs without side effects are marked as mergeable units.
[0088] Redundancy removal is performed on mergeable units, removing other state snapshots except for the retained frames in time sequence. At the same time, the context constraints and variable value ranges are aggregated in the retained frames to form aggregated state frames and their timestamps are updated to the start mutation point time of the interval.
[0089] The updated aggregated state frame sequence is subjected to consistency verification to verify that the merged sequence maintains the legality and integrity of the original business state evolution in terms of time sequence, and eliminates the time sequence noise introduced by thread out-of-order and irrelevant variable updates in the original sequence.
[0090] By employing a homogeneous state merging strategy, redundant state snapshots in non-critical intervals are transformed into aggregated state frame sequences, achieving sparse sequence output and providing a low-redundancy data foundation for lossless coding compression of S3.4.
[0091] S3.4: Perform lossless encoding compression processing on the sparse state frame sequence, and map the retained key state mutation points and their context constraints into standardized binary data blocks to output a compact business state trajectory summary with minimal storage overhead and complete preservation of business logic topology features.
[0092] like Figure 3 As shown, step S4 involves structuring the compact business state trajectory summary into dynamic semantic anchors that include preceding states, actions, subsequent states, and constraints, and embedding these dynamic semantic anchors into corresponding positions in the large language model input sequence. Specifically, this includes: S4.1: Obtain keyframe data from the compact business state trajectory summary, extract fields and encapsulate semantics for the preceding state, action, subsequent state and constraints to generate standardized dynamic semantic anchor original objects, ensuring that business logic elements are fully preserved and have clear boundary markings.
[0093] S4.2: Based on the original objects of the dynamic semantic anchors, the execution sequence of the code segment to be detected in the call chain is analyzed using a business context position alignment strategy. The relative offset between each original object of the dynamic semantic anchor and the line number or function entry is calculated to generate a dynamic semantic anchor positioning sequence with precise position index, thereby achieving spatiotemporal matching between the abstract logical state and the physical location of the specific code.
[0094] Obtain the quadruple data structure and field composition of the original object of the dynamic semantic anchor, call the business call chain parser to perform execution timing analysis of the function call chain to which the code segment to be detected belongs, and identify the physical line number range of each function entry and exit in the call chain and their relative order in the execution flow.
[0095] The temporal structure of the call chain is mapped one by one to the preceding state, action, following state and constraint fields in the dynamic semantic anchor. For each anchor original object, the corresponding code physical position offset is calculated. The offset is defined as the difference between the timestamp position of the business state transition event where the anchor is located in the call chain and the starting position of the code line number.
[0096] Multidimensional position alignment is adopted, and the time offset and function offset are normalized to form a spatiotemporal alignment index with a unified dimension. Based on this index, a bidirectional index relationship between anchor points and code line numbers / function entry points is established to ensure that anchor points are completely matched with the corresponding code segments in both temporal and spatial dimensions.
[0097] The bidirectional index relationship is stored as a location index table, which contains fields such as anchor identifier, corresponding code physical location, time offset value and execution flow sequence number. The table is sorted in ascending order according to the execution order of the call chain so that anchor hints can be accurately inserted when constructing the subsequent model input sequence.
[0098] A dynamic semantic anchor point location sequence is generated using a location index table. This location sequence is arranged according to the execution time sequence, and each element carries a precise location index value, realizing spatiotemporal matching from abstract business logic state to specific code physical location.
[0099] By combining a business context positioning strategy with an offset calculation model, the original dynamic semantic anchor object from the previous step is transformed into a dynamic semantic anchor positioning sequence with precise location indexes, achieving a spatiotemporal matching effect between abstract logical states and specific code physical locations.
[0100] S4.3: For the dynamic semantic anchor positioning sequence with precise location index, the attention-guided prompting engineering template is applied to convert the quadruple content into natural language description instructions, and special markers are added to the keywords in the instructions to strengthen the model's attention weight, so as to generate dynamic semantic anchor enhanced prompt text with high interpretability and optimize the semantic understanding depth of the large language model for complex state transitions.
[0101] For dynamic semantic anchor point positioning sequences with precise location indexes, a preset attention guidance prompt engineering template is loaded, and the quadruple content of each dynamic semantic anchor point is extracted into a preceding state field, an action field, a following state field, and a constraint field, and then semantically categorized and mapped.
[0102] Attention-guided prompting templates are predefined text structuring transformation patterns used to convert the four-tuples (preceding state, action, subsequent state, and constraint) in dynamic semantic anchors into natural language descriptions. Special markers are added to enhance the model's focus on key business semantics during inference. The core function of this template is to enhance the large language model's semantic understanding of complex state transitions in code snippets, guiding the model's self-attention mechanism to focus on code regions highly relevant to business logic consistency judgments (such as permission verification points, state transition conditions, and sensitive operation calls), thereby improving the model's accuracy and interpretability in detecting multi-step business logic vulnerabilities such as unauthorized access and payment bypass.
[0103] The attention guidance prompt template consists of the following elements: The quadruple field mapping rule defines how to convert the preceding state field, action field, following state field, and constraint field of a dynamic semantic anchor into causal descriptive phrases in natural language. For example, the preceding state is mapped to "in the state of...", the action is mapped to "perform the operation of...", the following state is mapped to "lead to the result of...", and the constraint is mapped to "must satisfy the condition of...".
[0104] Keyword recognition dictionary: Pre-set high-risk action verbs (such as "withdraw", "transfer", "delete", "unauthorized") and sensitive permission nouns (such as "administrator", "unverified", "unauthorized") related to business logic vulnerabilities, used to automatically mark key components in the converted text.
[0105] Special token encoding specifications: Define the token format used to enhance model attention weights, such as inserting tokens before and after keywords. <strong>、 <attention>Specific tags, or separators such as [KEY] and [COND], can enable the model to distinguish between ordinary tokens and high-attention tokens during the word segmentation and embedding stages.
[0106] Weight prior distribution matrix: Preset initial weight coefficients (e.g., 0.7–1.2) for each special marker. During model inference, these coefficients are injected into the query of the self-attention mechanism through the attention-guided prompting engineering template. In key matching calculations, this enables explicit biasing of key semantic regions.
[0107] By using the aforementioned attention-guided prompting engineering template, this invention transforms structured business state information into an efficient prompting format for large language models, guiding the model to automatically focus on the core semantic regions that affect logical consistency determination during the inference phase, thereby significantly improving the accuracy and interpretability of vulnerability detection.
[0108] Based on the business semantic classification results, each field is processed into natural language transcription, transforming the logical state change process into instruction text with clear cause-and-effect and constraint descriptions, and calling keyword detection to identify key action verbs and sensitive permission nouns.
[0109] Special markers are applied to the detected key action verbs and sensitive permission nouns, and their encoded values are inserted into the corresponding positions in the instruction text to construct a sequence of semantic units with weighted labels.
[0110] By combining the code line number or function entry offset index recorded in the dynamic semantic anchor positioning sequence, the above-mentioned marked semantic unit sequence is reordered according to the precise position index, so that each reinforcement label is strictly aligned with the corresponding business stage code fragment in the model input token stream.
[0111] Perform attention weight prior distribution calculation, embed the preset weight values of the reinforcement labels in the model input into the weight distribution matrix of the prompt engineering template, and enhance the model's attention to these labels during inference by adjusting the weight coefficients of each label position in the matrix.
[0112] By using the aforementioned attention-guided prompt engineering template conversion and tag encoding processing methods, the four-tuple content in the location sequence is transformed into dynamic semantic anchor enhanced prompt text that has high interpretability and can accurately match the model's attention region, thereby achieving a deep improvement in the semantic understanding of complex state transitions by the large language model.
[0113] For example, in the dynamic semantic anchor positioning sequence for the financial transaction business module, the preceding state field is "Account not verified with real name", the action field is "Call withdrawal interface", the following state field is "Account balance decreases", the constraint field is "Real name verification must be completed", and the line number offset index is 120. The loaded attention guidance prompt engineering template transcribes this quadruple into a natural language instruction: "If the account is not verified with real name, calling the withdrawal interface will result in a decrease in balance. This process must satisfy the constraint of completing real name verification." Special markers are added to "Call withdrawal interface" and "Real name verification must be completed" respectively, and the encoding value is set to a high-priority reinforcement label weight of 0.85. The prompt text is positioned at the corresponding position in the input token stream according to the line number offset index 120, and the attention coefficient at that position is added to the weight distribution matrix. This enhances the model's ability to capture context when analyzing corresponding code segments. After performing the above processing, the model can significantly improve the accuracy of identifying unauthorized withdrawal scenarios during the inference phase, and maintain a low false positive rate and high interpretability in testing and verification.
[0114] S4.4: Receive the highly interpretable dynamic semantic anchor enhanced prompt text, perform dynamic injection operation of input sequence, insert the prompt text into the corresponding slice position of the original input token stream of the large language model according to the position index in the dynamic semantic anchor positioning sequence, so as to construct a dynamic semantic anchor fusion input sequence containing local business context information, and complete the final form transformation from static code data to dynamic logic perception data.
[0115] This step receives highly interpretable dynamic semantic anchor-enhanced prompt text as input. A mapping relationship is established between the position index values in the dynamic semantic anchor positioning sequence and the original input token stream of the large language model. The prompt text is matched one by one to the corresponding token slice positions according to the positioning sequence, and token stream segmentation is performed to form an insertable local context slot structure. Context fusion is applied to the token fragments in each slot, inserting the four-tuple description of the prompt text as a natural language token sequence, and adding weight guidance markers on both sides of the insertion point to ensure that the model focuses on this business context in subsequent inference. Sequence consistency verification is performed on the entire inserted token stream, including token length, position offset, and semantic continuity verification, to ensure that the dynamic injection operation does not destroy the syntactic and semantic integrity of the original model input. Encoding and mapping processing is performed on the verified token stream, converting the fused context information from static code data into an input sequence format with dynamic logic awareness capabilities, generating a dynamic semantic anchor fusion input sequence containing local business context information, which is then output to the subsequent inference module. Through the above dynamic injection and fusion processing, the highly interpretable dynamic semantic anchors constructed in the previous step are transformed into contextual augmentation data that can be directly perceived by large language models, realizing the final form transformation of model input from static code data to dynamic logically perceptible data.
[0116] Step S5: Utilize a large language model embedded with the dynamic semantic anchors to perform inference operations, generating a logical consistency judgment result based on the actual business stage of the currently analyzed code snippet. Specifically, this includes: S5.1: Obtain the model input sequence containing dynamic semantic anchors and the code fragment to be analyzed. Calculate the matching degree between the query vector and the key vector based on the self-attention mechanism of the large language model to generate an initial attention weight matrix that represents the strength of the association between the code token and the business state.
[0117] It receives a structured token stream containing a dynamic semantic anchor fusion input sequence and the corresponding code fragment to be analyzed, and loads it into the input buffer of the large language model to construct an input matrix that can simultaneously carry local business context information and source code semantic features.
[0118] The model performs an embedding mapping on the input matrix based on the internal encoder structure, converting the text tokens into a high-dimensional dense vector representation, and adds positional encoding in the embedding layer to preserve the relative order of each token in the sequence.
[0119] In the self-attention calculation stage, the embedded vector is linearly projected onto the query vector and the key vector, and the query vector is weighted according to the dynamic semantic anchor position index to enhance the information proportion of the business context token in the matching process.
[0120] The matching degree between the query and the key is calculated using a scaled dot product attention mechanism, specifically by solving the matching value matrix using the following formula: Where Q is the query vector matrix, K is the key vector matrix, d is the embedding dimension, and each element in the matching degree matrix A represents the association strength between the corresponding code token and the business status token.
[0121] An initial attention weight matrix is generated by performing a multiplication operation between the matching value matrix A and the value vector matrix V. This matrix quantifies the degree of focus of each token on other tokens in real numerical form and preserves the high matching coefficient of the dynamic semantic anchor tokens.
[0122] The initial attention weight matrix is output to the subsequent sparsity filtering process, providing basic data for the extraction of high-confidence business context dependencies.
[0123] By calculating the matching degree between the query and the key through a self-attention mechanism and forming an initial attention weight matrix, the input containing dynamic semantic anchors is transformed into association strength data that can be used for subsequent filtering, thereby enabling the model to accurately focus under multi-step business logic context conditions.
[0124] S5.2: Perform sparsity filtering on the initial attention weight matrix, and filter out low-relevance connections according to a preset threshold to extract a focused attention mask that contains only high-confidence business context dependencies.
[0125] The initial attention weight matrix, which represents the strength of the association between code tokens and business status, is set to be sparsified as input. The input objects include the two-dimensional weight matrix output by the self-attention mechanism, the token index list corresponding to the dynamic semantic anchors, and the preset relevance threshold.
[0126] Based on the initial matrix structure, a linear threshold function is called to perform element-by-element comparison calculations on the matrix elements. Each weight value is then subjected to a difference operation with the correlation threshold to generate a Boolean mask matrix. The true values in the mask matrix correspond to strong correlation connections that are higher than the threshold.
[0127] By performing the Hadamard product operation between the mask matrix and the initial weight matrix, the matrix elements corresponding to false values in the Boolean mask are eliminated, and weakly correlated connections below the threshold are set to zero, thus achieving the effect of sparsity.
[0128] The sparsified matrix is subjected to local region aggregation calculation centered on the token index where the dynamic semantic anchor is located. The weight values of the highly relevant local regions are summed and normalized to a total weight sum of 1 to form a focused attention weight distribution.
[0129] Matrix pruning is used to filter out the top K connections with the highest weight values in the focus attention weight distribution and generate the final focus attention mask. This mask only retains the high-confidence business context dependency between dynamic semantic anchors and code tokens.
[0130] By using sparsity filtering and local aggregation processing, the initial attention weight matrix from the previous step is transformed into a focused attention mask that only contains high-confidence business context dependencies, thereby reducing noise interference and improving the accuracy of subsequent local context-aware vector construction.
[0131] S5.3: Use the focused attention mask to perform weighted aggregation operation on the hidden layer state of the large language model, and fuse the scattered context information into a local context-aware vector that represents the semantic features of the current business stage.
[0132] Obtain the focus attention mask and the corresponding hidden layer state tensor of the large language model obtained by step S5.2. Set the dimension of the mask matrix to be consistent with the hidden layer state matrix to ensure element-level operation compatibility.
[0133] The element-wise product operation is performed on the focus attention mask matrix and the hidden layer state matrix, setting the weight values of low-relevance contexts to zero and retaining the implicit representation components of high-confidence business contexts, thereby forming a weighted hidden layer local state matrix.
[0134] In the weighted local state matrix of the hidden layer, the weighted sum of each feature dimension is calculated to achieve information aggregation. Specifically, a summation operation is performed on the sequence dimension of the hidden layer and normalized according to the mask weights to compress the scattered business context information into a fixed-length vector representation.
[0135] The local context-aware vector is calculated using a normalized weighted aggregation formula: Where v is the local context-aware vector, w is the attention mask weight value at index i, and h is the hidden layer state element at index i.
[0136] The generated local context-aware vectors are normalized and scaled to adapt their numerical range to the input specifications of the subsequent logical discriminant head network, while retaining the maximum amount of business semantic discriminant information.
[0137] Through mask-guided weighted aggregation operations, the high-confidence attention features from the previous step are transformed into quantitative local context-aware vectors that represent the semantic features of the current business stage, enabling cross-function and cross-state business semantic condensation and structured input.
[0138] S5.4: Based on the local context-aware vector input to the pre-trained logic discriminant head network, perform forward propagation inference calculation to output the original logical consistency probability distribution describing the degree of conformity between the current code behavior and the business rules.
[0139] Based on the input conditions of the local context-aware vector, the vector is transmitted to the input port of the pre-trained logical discriminant head network to establish a mapping connection with the high-confidence business context dependency extracted in the previous step.
[0140] The received local context-aware vector is subjected to weight normalization to eliminate the influence of scale differences of different feature components on subsequent calculations. Then, the vector is linearly projected onto the first layer weight matrix of the logical discriminant head network through matrix multiplication to obtain the initial activation value matrix.
[0141] The initial activation value matrix is input into the multi-layer nonlinear activation unit of the logic discriminant head network, and each component is transformed element-wise using a preset activation function (such as ReLU or GELU) to enhance the ability to discriminate complex state transition relationships.
[0142] Batch normalization is performed on the feature representation after nonlinear transformation. The dynamic adjustment of mean and variance is used to suppress the internal covariate bias during the training phase, thereby stabilizing the network inference process.
[0143] The normalized feature representation is input to the probability generation module of the output layer. The Softmax function is used to exponentially normalize the linear combination result of the conformity labels of each business rule to obtain the original logical consistency probability distribution, as shown in the following formula: Where P(y=k|x) represents the conditional probability of predicting class k given input x, and z k z represents the activation value of the k-th neuron in the output layer. j denoted by , where k is the target class index, j is the class traversal index, and x is the local context-aware vector.
[0144] Through the aforementioned forward propagation inference calculation, the local context-aware vector from the previous step is transformed into a probability distribution of original logical consistency that represents the degree to which the current code behavior conforms to business rules, thereby achieving a probabilistic output of business logic consistency judgment.
[0145] S5.5: Perform maximum likelihood estimation and confidence mapping on the original logical consistency probability distribution to transform the probability values into explicit binary or multi-dimensional logical state labels to generate the final business logic consistency judgment result.
[0146] Step S6: Invoke the rule engine to perform formal verification on the logical consistency judgment result, and output candidate vulnerability tags only when the two conclusions are consistent and a preset confidence threshold is met. Specifically, this includes: S6.1: Obtain the logical consistency judgment result and the corresponding dynamic semantic anchor context output by the front-channel inference operation, and perform structured parsing processing on the logical consistency judgment result to extract standardized inference triples containing business action type, state transition path and permission constraint conditions, so as to provide a unified input data format for subsequent formal verification.
[0147] The rule engine is the core component of this invention, serving as the post-channel verification unit. It is used to formally verify the logical consistency of the output from the front-channel inference of the large language model. Based on formal security rules in a pre-built rule base, the engine converts the business action types, state transition paths, and permission constraints inferred by the model into specific rule constraint expressions. It then uses a Boolean satisfiability solver to determine the consistency between the model's conclusions and the rules. Only when the model output matches the rule engine's conclusions and the comprehensive verification confidence score exceeds a threshold is a candidate vulnerability label output, thereby effectively reducing the false positive rate and enhancing the credibility of the detection results.
[0148] The rules engine consists of the following five parts: Rule base: Stores a predefined set of formal security rules. Each rule includes a business action type, preconditions, state transition constraints, and post-assertions. Rules are expressed in logical formulas or constraint languages (such as SMT-LIB) and support symbolic execution and constraint solving.
[0149] Rule matching module: Based on the business action type in the standardized inference triple, it retrieves matching rule entries from the rule base, performs redundancy removal, and returns a candidate rule set.
[0150] Symbolic execution instantiation module: binds abstract variables in candidate rules to specific state machine variables, and generates a sequence of specific rule constraint expressions for the current business scenario through symbolic execution.
[0151] Boolean satisfiability solvers (such as SAT solvers or SMT solvers): logically map specific rule constraint expressions to state transition paths, solve for truth values, and output a Boolean flag indicating rule compliance.
[0152] The scoring fusion module combines the rule compliance Boolean flag and the model's original confidence level to perform a weighted fusion calculation and output a comprehensive verification confidence score for final vulnerability determination.
[0153] Building the rule base: Rule source: Based on common business logic vulnerability patterns (such as unauthorized access, payment bypass, state tampering, etc.), combined with domain expert knowledge and historical vulnerability data, general formal security rules are summarized.
[0154] Rule expression: Each rule adopts predicate logic or condition-action form, for example: "IF (user role==normal user AND operation==withdraw AND account real-name status==unverified) THEN prohibit operation" is converted into logical constraint: "(role=normal ∧ action=withdraw ∧ auth=false) → false".
[0155] Rule storage: Rules are stored in a rule base in a structured format (such as JSON or database tables). Each rule includes a business action type, a set of preconditions, state transition constraints, and post-assertions. Each rule is also labeled with priority and applicable business scenario tags for easy retrieval.
[0156] Rule validation: The rules are tested in an offline environment using known vulnerability samples and normal samples. The rule thresholds and condition granularity are adjusted to ensure a balance between the accuracy and recall of the rule engine.
[0157] Building the rules engine: Rule matching module implementation: A hash table is established to map business action types to rule indexes, enabling rule retrieval with O(1) time complexity. A rule redundancy removal algorithm is designed to eliminate duplicate rules with inclusion relationships or subset relationships through a rule dependency graph.
[0158] Symbolic execution instantiation module: integrates a lightweight symbolic execution engine (such as Python binding based on Z3), and provides interfaces for variable binding, path condition collection and constraint solving.
[0159] Boolean solver integration: Using open-source SAT / SMT solvers (such as MiniSAT, Z3) as the backend, the rule constraint expressions are converted into conjunctive normal form (CNF) and solved.
[0160] Scoring fusion module: Design a weighted fusion formula and calibrate the weight coefficients w and v using historical validation set data to enable the comprehensive confidence score to effectively distinguish between real vulnerabilities and false alarms.
[0161] Rule base maintenance and updates: When new types of business logic vulnerabilities emerge, security experts supplement the corresponding rules, which are then added to the database after offline testing and verification. False positive analysis results are used periodically to refine the rules, such as relaxing overly strict rules or tightening overly lenient rules.
[0162] Through the aforementioned rule engine and its rule base, this invention achieves formal verification and dual verification of the reasoning results of large language models, significantly improving the accuracy and reliability of business logic vulnerability detection, while maintaining low computational overhead, making it suitable for automated security analysis of large-scale codebases.
[0163] S6.2: Based on the business action type in the standardized inference triple, retrieve the matching formal security rule set from the pre-built rule base, and use symbolic execution to instantiate the formal security rule set to generate a specific rule constraint expression sequence for the current business scenario, thus establishing a benchmark reference system for formal verification.
[0164] Based on the business action type input in the standardized inference triplet, receive unified format data generated by S6.1 that includes business action type, state transition path and permission constraints.
[0165] The rule base index module is invoked to perform a matching retrieval operation in the rule base according to the business action type. The formal security rule entries defined in the rule base are matched precisely with the input business action type and semantic similarity matched to form a preliminary candidate rule set.
[0166] Redundancy removal is performed on the preliminary candidate rule set. Redundant rules generated by condition inclusion relationships or triggering conditions being subsets of each other are eliminated using the rule dependency graph, while rule entries with independent verification significance are retained.
[0167] Symbolic execution is used to load the deduplication rule set, and the abstract variables in the rules are symbolically bound to the variable identifiers in the state machine. A symbolic execution path stack is constructed to map the state transition logic of the input business action to the rule structure.
[0168] During symbolic execution, path constraints are solved on the conditional expressions of the rules. The constraint solver is used to convert the path conditions into Boolean expressions and then parse them.
[0169] For entries in the solution results where satisfiability is true and path conditions fully match rule conditions, generate specific rule constraint expressions, maintain formal precision using logical operators and variable mapping relationships, and add these expressions to the sequence of specific rule constraint expressions for the current business scenario.
[0170] Through the above symbolic execution and constraint solving processes, the standardized inference triples from the previous step are transformed into a sequence of specific rule constraint expressions that can be directly used for subsequent verification, thereby establishing a formal verification benchmark reference system.
[0171] S6.3: Logically map and compare the sequence of specific rule constraint expressions with the state transition paths in the standardized inference triples, and use a Boolean satisfiability solver to perform truth value determination on the mapping relationship in order to calculate the rule compliance Boolean flag that represents the degree of compliance between the model inference conclusion and the formal rules, and preliminarily identify potential logical conflict points.
[0172] The input conditions include the specific rule constraint expression sequence and the parsed state transition path in the standardized inference triplet. Both are in a unified symbolic representation and have clear logical references.
[0173] The sequence of rule constraint expressions is loaded into the Boolean mapping construction unit. A one-to-one mapping table is established between each state node in the state transition path and the corresponding rule constraint. The node identifier and the rule entity identifier are compared by hash index to confirm the matching candidate group.
[0174] For each matching candidate group, perform logical relation decomposition to break down the composite rule constraint into atomic conditions and match them one by one with the action edge conditions of the state transition path. Mark the mismatched conditions as potential conflict candidates.
[0175] The mapping relationship is input into the Boolean satisfiability solver to construct a CNF (Conjunctive Normal Form) structure, generate a set of Boolean variables by variable name and value range, and convert atomic conditions into Boolean clauses to form a complete solvable problem instance.
[0176] The solver performs backtracking search and conflict-driven clause learning, calculates the truth value of each mapping relationship, and generates a rule compliance Boolean flag based on the solution results. A true flag indicates that the model's reasoning conclusion is completely consistent with the rule constraints, while a false flag indicates that there is a logical conflict that violates the rules.
[0177] This processing method transforms the instantiation rules and inference triplet paths from the previous step into satisfiability verification results, enabling accurate determination of the consistency between the model's inference conclusions and the rules.
[0178] For example, in a financial transaction business logic detection scenario, the state transition path of the standardized inference triplet is set to "real-name authentication completed → withdrawal request initiated → fund transfer successful". The rule constraint expression sequence contains the atomic conditions "the user must complete real-name authentication to trigger the withdrawal request" and "the withdrawal amount must be less than the account balance". After mapping the state transition path nodes to the rule conditions, a Boolean variable set {v1: real-name authentication completed, v2: withdrawal initiated, v3: amount verification} is generated, and a CNF structure such as v1→v2 and v3=True is constructed. When the solver detects that v1 is False and v2 is True during the verification process, the Boolean flag is set to False, indicating a logical conflict. For another input scenario, if v1 is True and v3 is True, the solver returns the flag as True, and the verification result outputs the rule consistency state. In this embodiment, the comparison and judgment driven by CNF construction and Boolean solution effectively improves the robustness of matching complex business rules and state paths. The output rule compliance Boolean flag has stability and interpretability, supporting the subsequent credibility calculation in S6.4.
[0179] S6.4: Based on the Boolean flag of the rule compliance and the confidence value in the original logical consistency judgment result, perform weighted fusion calculation to generate a comprehensive verification confidence score that represents the probability of passing the double verification, quantitatively evaluate the credibility level of the current detection result and filter out potential false alarms with low confidence.
[0180] Based on the Boolean flags for rule compliance and the confidence values from the original logical consistency judgment results, the numerical input set from the dual-channel verification process is loaded, and a corresponding weight allocation matrix is established as the initial condition for fusion processing. The Boolean flags for rule compliance are numerically mapped, with true values mapped to unit values and false values mapped to zero values, forming a unified scalar format that can be used for arithmetic operations with the confidence values. Normalization is performed on the confidence value inputs, adjusting their numerical range to the [0,1] interval according to preset upper and lower limits to eliminate scale differences in the outputs of different models. The normalized confidence and rule compliance scalars are multiplied and combined according to the proportion specified by the weight matrix to obtain a product term representing the combined influence of dual-channel consistency and model confidence. A weighted summation operator is used to linearly superimpose the product term and the single-channel confidence residual term. The weights of the residual term are set according to the statistical results of samples with inconsistent dual-channel consistency but high confidence in the historical validation set to balance false alarm risk and false negative control. The comprehensive verification confidence score is calculated using the following formula: Where S is the comprehensive verification confidence score, w is the weight of the rule compliance product term, C is the normalized confidence value, R is the rule compliance scalar, and v is the residual term weight. Statistical filtering is performed on the calculated score to remove sudden increases or decreases caused by single outlier data points, thus obtaining a stable score curve for threshold determination. Through weighted fusion and filtering, the Boolean decision and model confidence from the previous step are transformed into a quantifiable comprehensive verification confidence score, enabling accurate assessment of the current detection result's credibility level and filtering out potential false alarms with low confidence.
[0181] For example, during the detection process of a certain financial transaction business module, the rule compliance flag is mapped to 1, and the normalized confidence score of the model's logical consistency inference is 0.82. Let w be 0.7 and v be 0.3, then substituting into the formula: The calculated overall verification confidence score is 0.574. After mean filtering with a sliding window length of 5, the score stabilizes at around 0.57. In this scenario, if the preset vulnerability judgment threshold is 0.55, the detection result is marked as a candidate vulnerability and enters the vulnerability analysis module. The verification output shows that high-risk unauthorized access was successfully identified and no low-confidence false alarms were generated.
[0182] S6.5: Compare the comprehensive verification confidence score with the preset vulnerability judgment threshold. If the comprehensive verification confidence score is greater than or equal to the preset vulnerability judgment threshold and the rule compliance Boolean flag is true, then generate a candidate vulnerability tag with a unique identifier and output it to the vulnerability analysis module to complete the final confirmation and transfer of high-confidence business logic vulnerabilities.
[0183] Based on the comprehensive verification confidence score and rule compliance Boolean flag generated in the previous sub-step, a preset vulnerability judgment threshold is loaded as the reference benchmark for logical judgment. The threshold comparison operation module is invoked to compare the comprehensive verification confidence score with the preset vulnerability judgment threshold, outputting a comparison result flag signal. Conditional matching processing is performed on the comparison result, detecting the truth value of the rule compliance Boolean flag, and performing a logical AND operation with the comparison result flag signal to generate a comprehensive judgment trigger signal. When the comprehensive judgment trigger signal is true, a unique identifier generator is invoked, constructing a globally unique candidate vulnerability identifier through a hash operation of the timestamp and the business module number. The unique identifier, along with the logical consistency judgment result, dynamic semantic anchor context, and comprehensive verification confidence score, is encapsulated into multiple fields to form a complete candidate vulnerability tagging data structure. This candidate vulnerability tagging data structure is output to the vulnerability analysis module through the vulnerability tagging transmission interface, achieving final confirmation and transfer of high-confidence business logic vulnerabilities. Through the logical threshold comparison and unique identifier generation processing, the result of the previous step is transformed into structured tagging data that can directly enter the vulnerability analysis stage, achieving accurate output and closed-loop verification of high-confidence business logic vulnerabilities.
[0184] For example, in the financial transaction business module, the comprehensive verification confidence score is 0.86, the rule compliance Boolean flag is true, and the vulnerability judgment threshold is set to 0.80. The threshold comparison operation module is called to perform a 0.86≥0.80 judgment, and the comparison result is true. This is compared with the true state of the rule compliance flag in the logical operation, generating a comprehensive judgment trigger signal with a true value. The unique identifier generator concatenates the current microsecond-level timestamp 1687345123456 with the business module number BKF12 and performs a SHA-256 hash operation to obtain the identifier "9a56c...e3f". This identifier, along with the logical consistency judgment result, the dynamic semantic anchor context, and the comprehensive verification confidence score, is encapsulated into a JSON-formatted candidate vulnerability tag data structure and output to the vulnerability analysis module via a secure RPC interface. In this scenario, the vulnerability analysis module, combining the tag data with business operation logs, achieves rapid confirmation of unauthorized access vulnerabilities. The output result is directly received by the subsequent remediation process, significantly improving the response speed of detection and remediation, and greatly enhancing the system's security protection capabilities.
[0185] Step S7: For high-frequency false alarm scenarios, automatically extract the hot zones of the attention weights of the large language model and the conflict points of the rule engine. Based on the conflict points, generate minimum perturbation adversarial samples to fine-tune the discrimination boundary of the business logic vulnerability detection model in a specific business semantic dimension. Specifically, this includes: S7.1: Obtain the logical consistency judgment result generated by the front-channel inference and the formal verification conclusion of the back-channel, and perform difference comparison processing on the two to identify a set of high-frequency false alarm business logic segments with inconsistent judgment conclusions.
[0186] S7.2: Based on the set of high-frequency false alarm business logic segments, extract the attention weight distribution matrix generated by the internal attention mechanism of the large language model, and perform hot zone localization calculation on the attention weight distribution matrix to lock the key code semantic feature regions that lead to misjudgment.
[0187] Based on the input of a set of high-frequency false positive business logic fragments, the attention weight distribution matrix generated by the self-attention mechanism within the large language model corresponding to the code fragment to be analyzed is loaded into the weight parsing module. Row and column normalization is performed on the attention weight distribution matrix to eliminate amplitude scale differences between different token positions, ensuring consistency in the confidence basis for subsequent feature region localization. The difference vector between each row and the global average weight is calculated according to the token sequence index, and the degree of deviation of the token in the context attention distribution is obtained through mathematical subtraction. This deviation vector is input into the hot zone candidate generation, and a sliding window scanning strategy is used to identify consecutive high-deviation segments on the token sequence. The cumulative weight and deviation intensity of each segment are calculated, and a threshold discrimination mechanism is used to filter segments whose cumulative weight and deviation intensity simultaneously meet the set conditions, outputting a high-confidence hot zone index set. The hot zone index set is mapped to specific semantic units in the source code using a code semantic mapping table, forming the key code semantic feature region localization result that led to the false positives. By using the above processing method, the difference comparison results of the previous step are transformed into precise attention hotspot location data, thereby locking the core semantic region that causes false alarms and providing a basis for target localization for the construction of subsequent perturbation samples.
[0188] For example, in a payment bypass detection task, the input set of high-frequency false alarm business logic fragments contains 12 code segments. The attention weight distribution matrix generated in the large language model for each code segment is 64×64. After normalization, the global average weight μ is 0.015, and when the weight value w of a single token position is 0.043, the deviation degree Δ is calculated to be 0.028. The sliding window size is set to 8 tokens, and the continuous high deviation segment with a starting index of 15 and an ending index of 22 is scanned and identified. Its cumulative weight is 0.385 and the average deviation intensity is 0.024, both exceeding the set thresholds of 0.3 and 0.02, respectively, and is judged as a hot zone candidate. After mapping to the source code, this segment corresponds to the semantic unit of "permission verification condition branch". The above localization process is repeated in different fragments, and finally five key code semantic feature regions are output. Subsequently, perturbations are applied to these regions in the minimum perturbation adversarial example generation stage, which greatly improves the model's ability to correctly identify payment bypass scenarios and significantly reduces the frequency of related false alarms.
[0189] S7.3: Utilize the semantic feature region of the key code and the verification conflict point of the rule engine to construct a gradient-guided perturbation mapping function, and perform a minimum norm perturbation superposition operation on the original input code sequence to generate a minimum perturbation adversarial sample that can induce the model to flip its judgment.
[0190] The system receives the key code semantic feature region from the previous sub-step and the verification conflict points output by the rule engine as input data. Based on the key code semantic feature region, the gradient calculation module is invoked to perform inverse derivative processing on the sensitivity of the output probability distribution of the large language model with respect to the input token embedding space, generating a set of gradient vectors corresponding to each token position. Using the verification conflict points, the gradient values at the corresponding conflict positions in the gradient vector set are differentially calculated with the global gradient value to construct a high-sensitivity position identifier matrix, thereby limiting the spatial range of perturbation application. Based on the high-sensitivity position identifier matrix, normalization processing and direction vector extraction are performed to map the interrelated high-sensitivity positions to a single perturbation direction vector, thereby reducing the redundancy of perturbation application. Combining the perturbation direction vector and the set upper limit of perturbation amplitude, a gradient-guided perturbation mapping function is constructed, and the minimum norm perturbation vector is calculated using the following formula: Where ε is the upper limit of the perturbation amplitude, g is the perturbation direction vector, and ||g||² is the L2 norm of g. The minimum norm perturbation vector is superimposed onto the original input token embedding vector to generate an adversarial input vector with the minimum amplitude that can guide the model to discriminate against flipping. The adversarial input vector is mapped back to the form of a code sequence while maintaining the legality of the original code syntax to ensure that the perturbation sample can be parsed normally by the model and participate in fine-tuning training. Through gradient-guided perturbation mapping and minimum norm superposition processing, the attention weight hotspots and rule conflict points from the previous step are transformed into minimum perturbation adversarial samples that can trigger model misjudgments, achieving the goal of capturing the error discrimination boundary and directional optimization of the model in a specific business semantic dimension.
[0191] S7.4: Construct a targeted fine-tuning training dataset based on the minimum perturbation adversarial sample, and use a contrastive learning loss function to perform parameter update iterations on the business logic vulnerability detection model in order to narrow the error discrimination boundary of the model in a specific business semantic dimension.
[0192] The input conditions based on minimal perturbation adversarial examples include code sequence perturbation information generated in the previous sub-step S7.3, designed to induce model discrimination flipping, and corresponding metadata of high-frequency false positive business logic fragments. These perturbation samples are combined with standard business code samples to construct a targeted fine-tuning training dataset containing positive and negative sample pairs. Data preprocessing is performed on this dataset to remove redundant fields without business logic relevance and to standardize the encoding format, ensuring complete alignment of the input data with the feature space of the business logic vulnerability detection model. Batch data generation is performed on the preprocessed dataset, employing a fixed batch size and homogeneous sampling strategy to ensure that adversarial examples participate in the gradient update process in each iteration. The batch data is input into the model's forward propagation computation path to generate prediction vectors and perform difference calculations with the corresponding label vectors. The difference measurement is accomplished using a contrastive learning loss function. This loss function, by measuring the similarity of embedding vectors between positive sample pairs and the difference of embedding vectors between negative sample pairs, prompts the model to narrow the gap between positive samples and widen the gap between negative samples in a specific business semantic dimension. The loss derivative based on adversarial example gradients is used as the driving force for backpropagation. The gradient signal is passed to the weights of each layer of the model to perform parameter update iterations. During the iteration process, momentum accumulation is applied to stabilize the parameter convergence trajectory, and overfitting is suppressed by weight decay. Through the above chained processing method, the minimum perturbation adversarial example result of the previous step is transformed into a shrunken business semantic dimension error discrimination boundary, which significantly improves the model's discrimination capability in the high-frequency false alarm domain.
[0193] S7.5: Based on the shrunken error discrimination boundary, recalibrate the confidence threshold of the model for unauthorized access and payment bypass scenarios, and output optimized business logic vulnerability discrimination model parameters with anti-interference capabilities.
[0194] Step S8: Update the parameters of the business logic vulnerability detection model based on the discriminant boundary fine-tuned by the minimum perturbation adversarial sample, completing the closed-loop optimization iteration of the multi-step business logic context modeling capability. Specifically, this includes: S8.1: Obtain the discrimination boundary gradient vector after fine-tuning with the minimum perturbation adversarial sample, and use the backpropagation algorithm to calculate the sensitivity matrix of the discrimination boundary gradient vector relative to the weights of each layer of the business logic vulnerability detection model, so as to generate a parameter update mask containing the correction direction of specific business semantic dimensions.
[0195] The business logic vulnerability detection model is the core deep neural network model used for performing front-channel inference in this invention. Based on a large language model architecture, this model enhances its semantic understanding of business state transitions by embedding dynamic semantic anchors, enabling it to generate logical consistency judgment results based on the actual business stage of the currently analyzed code snippet. The model undergoes pre-training and fine-tuning offline, and is further fine-tuned online using minimal perturbation adversarial examples in step S7 to continuously optimize its discrimination boundaries in specific business semantic dimensions. In this invention, this model works in conjunction with a rule engine to form a dual-channel verification system, and its output serves as one of the main bases for candidate vulnerability labeling.
[0196] The business logic vulnerability detection model adopts a Transformer-based large language model architecture, which mainly consists of the following modules: Input embedding layer: Converts the original code token sequence and dynamic semantic anchor enhanced prompt text into a high-dimensional vector representation, while overlaying positional encoding to preserve the relative order information of the tokens in the sequence.
[0197] Multi-head self-attention module: Stacked in multiple layers (typically 12, 24 or more), each layer contains multiple parallel attention heads. This module calculates the association weight between any two tokens in the input sequence, especially assigning higher attention weights to tokens at the location of dynamic semantic anchors, thereby focusing on code snippets relevant to business logic.
[0198] Feedforward Neural Network: Each attention layer is followed by two fully connected network layers, which enhance the feature representation ability of the model through nonlinear transformation.
[0199] Residual connection components: At the output of each sub-layer (such as a multi-head self-attention module or a feedforward neural network), the input and output of that sub-layer are added element-wise to form a direct connection across layers. Residual connections effectively alleviate the vanishing gradient problem in deep networks, enabling the model to stably stack more layers while preserving the original features of the input information, thus enhancing the model's representation learning ability.
[0200] Layer normalization component: After the output of each sub-layer passes through the residual connection, normalization is performed on each dimension of the feature vector. The mean and variance are calculated, adjusting the distribution to zero mean and unit variance. Learnable scaling and translation parameters are introduced to restore the necessary expressive power. Layer normalization can accelerate model convergence, stabilize the numerical distribution during training, and reduce the model's sensitivity to hyperparameter initialization.
[0201] Logical Discriminant Head Network: The task-specific output layer at the top of the model aggregates the business context-related parts of the last hidden state into a local context-aware vector, and then maps it into a logical consistency probability distribution through a fully connected layer and a Softmax function.
[0202] The set of trainable weight parameters includes all embedding matrices, query / key / value weight matrices of the attention layer, feedforward network weights, and output layer weights. The total number of parameters is usually in the hundreds of millions to billions.
[0203] Construction method: Offline pre-training phase: A massive amount of source code-text pairs are collected from large-scale public code repositories (such as GitHub) and corresponding documentation, covering multiple programming languages (Java, Python, Go, etc.) and business domains. Common pre-training tasks such as Masked Language Modeling (MLM) and Next Sentence Prediction (NSP) are employed to enable the model to learn the syntax, semantics, and some business logic knowledge of the code. The AdamW optimizer is used, with a cosine decay strategy for the learning rate after warm-up. The batch size is set according to hardware resources (typically tens to hundreds).
[0204] In the business logic fine-tuning phase: Numerous code snippets labeled with business logic consistency—dynamic semantic anchor pairs—are constructed from security test cases and historical vulnerability data. Positive samples represent code that conforms to business rules, while negative samples represent code with vulnerabilities such as privilege escalation or state skipping. Based on the pre-trained model, a logic discriminator network is added, and the model is supervisedly fine-tuned using the cross-entropy loss function. This enables the model to determine whether the current code behavior is consistent with the expected business state based on the dynamic semantic anchors. During fine-tuning, the enhanced prompt text of the dynamic semantic anchors generated in step S4 is inserted into the input sequence according to its position index, and attention-guided prompt engineering templates are used to strengthen the model's focus on the anchor content.
[0205] Adversarial fine-tuning phase: For scenarios with high-frequency false positives, a targeted fine-tuning training dataset is constructed using minimal perturbation adversarial examples. A contrastive learning loss function is used to update model parameters in small batches, narrowing the model's error discrimination boundary in specific business semantic dimensions. Through parameter update masks and local weight redistribution, only attention weight regions related to false positive triggers are adjusted, avoiding catastrophic forgetting.
[0206] Deployment and Inference: The trained model parameters are solidified and deployed on a security analysis server or cloud service. During online inference, the system receives the code fragment to be detected and its corresponding dynamic semantic anchors, performs forward propagation, and outputs the logical consistency judgment result (probability distribution and final label).
[0207] Through the aforementioned business logic vulnerability detection model, this invention achieves the ability to determine business logic consistency based on a large language model, and supports targeted optimization through adversarial examples, significantly improving the detection accuracy and robustness of multi-step business logic vulnerabilities such as unauthorized access and payment bypass.
[0208] S8.2: Based on the parameters, update the mask to extract the hot zone distribution of key attention weights in high-frequency false alarm scenarios, and use an adaptive learning rate optimizer to perform local weight redistribution processing on the hot zone distribution of key attention weights in order to construct a suppressive weight adjustment amount for conflict points.
[0209] The updated mask based on the parameters is input to the high-frequency false alarm scenario associated data stream analysis module to extract the key attention weight hotspot distribution adapted to the false alarm causes. The correlation calculation of the weight gradient direction is performed on the attention weight hotspot distribution, and the set of weight elements in the sensitivity matrix that are significantly correlated with the hotspots is separated into local adjustment candidate groups. These local adjustment candidate groups are input to the adaptive learning rate optimizer, which dynamically adjusts the learning rate coefficients of each candidate weight based on the gradient magnitude and historical convergence rate, forming a differentiated update step size mapping table for false alarm conflict points. Based on the differentiated update step size mapping table, weight allocation processing is performed on the hotspot weights. By increasing the gradient step size in the conflict point suppression direction and decreasing the gradient step size in the non-conflict direction, directional attenuation of false alarm source features and preservation of irrelevant features are achieved. A suppression-type weight adjustment amount containing the conflict point suppression vector is generated as input for subsequent fusion operations to enhance the model's discrimination boundary stability in high-frequency false alarm scenarios. By performing local weight redistribution, the parameter update mask from the previous step is transformed into a suppressive weight adjustment for conflict points, thereby achieving the expected technical effects of targeted attenuation of false alarm features and stabilization of the discrimination boundary.
[0210] S8.3: Utilize the suppression-type weight adjustment amount to perform element-by-element fusion operation on the original parameter matrix of the business logic vulnerability detection model, and execute the parameter smoothing update strategy with the driving amount to generate an intermediate model parameter set with enhanced business semantic discrimination capability.
[0211] S8.4: Based on the intermediate model parameter set, perform forward inference tests on the validation set, calculate the comprehensive convergence index of multi-step business logic context modeling accuracy and false alarm rate, and determine whether the model performance of the current iteration meets the preset closed-loop optimization termination condition.
[0212] Obtain the validation set input samples and their business logic vulnerability annotation information corresponding to the intermediate model parameter set, and load the set parameters into the weight space of the business logic vulnerability detection model to form a model instance to be evaluated.
[0213] For each input sample in the validation set, forward inference calculation is performed, and a dual-channel detection process integrating a large language model and a rule engine is invoked to generate a sequence of output results containing logical consistency labels and decision confidence levels.
[0214] Based on the output result record sequence, the predicted label of each sample is matched and compared with the real labeled label, the number of successfully matched samples is counted, and the accuracy of multi-step business logic context modeling is calculated.
[0215] For samples in the validation set that are marked as vulnerabilities by the model, the number of samples that are actually not vulnerabilities is calculated and normalized according to the total number of marked vulnerabilities to obtain the false positive rate.
[0216] The accuracy value and the false alarm rate value are combined according to preset weighting coefficients to construct a comprehensive convergence index.
[0217] The comprehensive convergence index is compared with the closed-loop optimization termination condition threshold to form a performance judgment signal, which is output to determine the iteration termination and parameter solidification in step S8.5.
[0218] By performing forward inference on the validation set, calculating accuracy and false positive rate, and constructing a comprehensive convergence index, the intermediate model parameter set from the previous step is transformed into a performance index that can quantify the model's ability to model business contexts, thereby determining whether the model performance meets the termination conditions for closed-loop optimization.
[0219] S8.5: Based on the determination result of the comprehensive convergence index, if the termination condition is not met, the next round of adversarial sample generation process is triggered; if the termination condition is met, the intermediate model parameter set is solidified into the final business logic vulnerability detection model parameters to complete the closed-loop optimization iteration of multi-step business logic context modeling capability.
[0220] For those skilled in the art, various other corresponding changes and modifications can be made based on the technical solutions and concepts described above, and all such changes and modifications should fall within the protection scope of the claims of this invention.
[0221] Unless otherwise defined, the technical or scientific terms used herein shall have the ordinary meaning as understood by one of ordinary skill in the art to which this application pertains. The terms "first," "second," "third," and similar terms used in this patent application specification and claims do not indicate any order, quantity, or importance, but are merely used to distinguish different components. Similarly, "an" or "a" and similar terms do not indicate a quantity limitation, but rather indicate the presence of at least one. The terms "comprising" or "including" and similar terms mean that the elements or objects preceding "comprising" or "including" encompass the elements or objects listed following "comprising" or "including" and their equivalents, and do not exclude other elements or objects. The "multiple" involved in the embodiments of this application refers to two or more. A and / or B indicate three possibilities: A; B; and A and B.
[0222] The above description is merely an exemplary embodiment of this application, but the scope of protection of this application is not limited thereto. Any person skilled in the art can easily conceive of various equivalent modifications or substitutions within the technical scope disclosed in this application, and such modifications or substitutions should all be covered within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.< / attention> < / strong>
Claims
1. A code security vulnerability intelligent detection method based on a large model, specifically including: S1: Extract business entities and state transition events from the source code and supporting documentation, and construct an initial business state graph containing nodes representing business states and directed edges representing legal state transition operations. S2: Based on the initial business state diagram, perform sandbox simulation on the target business module to capture snapshots of key state variables at the function entry and exit points in the real call chain to form a time-stamped original sequence of state trajectories. S3: Perform lossless compression processing on the original sequence of the state trajectory, retaining only the key frames of state transition permission changes or sensitive data transfers to generate a compact business state trajectory summary; S4: The compact business state trajectory summary is structured into dynamic semantic anchors containing preceding states, actions, subsequent states and constraints, and the dynamic semantic anchors are embedded into the corresponding positions of the input sequence of the large language model. S5: Utilize a large language model embedded with the dynamic semantic anchors to perform inference operations and generate a logical consistency judgment result based on the actual business stage of the current analysis code segment. S6: Call the rule engine to perform formal verification on the logical consistency judgment result, and output the candidate vulnerability label only when the two conclusions are consistent and the preset confidence threshold is met.
2. The intelligent code security vulnerability detection method based on a large model according to claim 1, characterized in that, The rule engine includes a rule base, a rule matching module, a symbolic execution instantiation module, a Boolean satisfiability solver, and a scoring fusion module.
3. The intelligent code security vulnerability detection method based on a large model according to claim 1, characterized in that, The business logic vulnerability detection model includes an input embedding layer, a multi-head self-attention module, a feedforward neural network, a residual connection component, a layer normalization component, a logic discriminant network, and a set of trainable weight parameters.
4. The intelligent code security vulnerability detection method based on a large model according to claim 1, characterized in that, Following S6, the following is also included: S7: For high-frequency false alarm scenarios, automatically extract the hot zones of attention weights of large language models and conflict points with the rule engine, and generate minimum perturbation adversarial samples based on the conflict points to fine-tune the discrimination boundary of the business logic vulnerability detection model in a specific business semantic dimension. S8: Update the parameters of the business logic vulnerability detection model based on the discriminant boundary fine-tuned by the minimum perturbation adversarial sample, and complete the closed-loop optimization iteration of the multi-step business logic context modeling capability.
5. The intelligent code security vulnerability detection method based on a large model according to claim 1, characterized in that, S3 specifically includes: Acquire a state variable snapshot event stream with microsecond-level timestamps, and segment the state variable snapshot event stream to generate an initial sliding window sequence containing state evolution features within consecutive time slices; Based on the initial sliding window sequence, a differential comparison mechanism is used to perform numerical change rate calculation and logical flag detection operations on the snapshots of adjacent state variables within the window, so as to identify the set of key state change points that characterize business state transitions, user permission changes, or sensitive data transfers. For the non-critical intervals between the set of critical state mutation points, a homogeneous state merging strategy is applied to perform redundant elimination and aggregation operations on state variable snapshots with the same business semantic identifier and no intermediate side effects, so as to generate a sparse state frame sequence that eliminates temporal noise. Lossless encoding and compression processing is performed on the sparse state frame sequence to map the retained key state mutation points and their contextual constraints into standardized binary data blocks, so as to output a compact business state trajectory summary with minimal storage overhead and complete preservation of business logic topology features.
6. The intelligent code security vulnerability detection method based on a large model according to claim 1, characterized in that, S4 specifically includes: Keyframe data from the compact business state trajectory summary is obtained, and the quadruples are processed by field extraction and semantic encapsulation to generate standardized dynamic semantic anchor raw objects. Based on the original objects of the dynamic semantic anchors, the execution sequence of the code segment to be detected in the call chain is analyzed using a business context position alignment strategy. The relative offset between each original object of the dynamic semantic anchor and the line number or function entry is calculated to generate a dynamic semantic anchor positioning sequence with precise position index. For the dynamic semantic anchor location sequence, the attention-guided prompting engineering template is applied to convert the quadruple content into natural language description instructions, and special markers are added to the keywords in the instructions to strengthen the model's attention weights, so as to generate dynamic semantic anchor enhanced prompt text with high interpretability. The system receives the enhanced prompt text from the dynamic semantic anchors, performs a dynamic injection operation into the input sequence, and inserts the prompt text into the corresponding slice position of the original input token stream of the large language model according to the position index in the dynamic semantic anchor positioning sequence, so as to construct a dynamic semantic anchor fusion input sequence.
7. The intelligent code security vulnerability detection method based on a large model according to claim 6, characterized in that, The quadruple consists of the preceding state, action, following state, and constraint.
8. The intelligent code security vulnerability detection method based on a large model according to claim 6, characterized in that, The dynamic semantic anchor fusion input sequence contains local business context information.
9. The intelligent code security vulnerability detection method based on a large model according to claim 1, characterized in that, S5 specifically includes: Obtain the model input sequence containing dynamic semantic anchors and the code fragment to be analyzed. Calculate the matching degree between the query vector and the key vector based on the self-attention mechanism of the large language model to generate an initial attention weight matrix that represents the strength of the association between the code token and the business state. The initial attention weight matrix is subjected to sparsity filtering, and low-relevance connections are filtered out according to a preset threshold in order to extract a focused attention mask that contains only high-confidence business context dependencies. The focused attention mask is used to perform weighted aggregation operations on the hidden layer states of the large language model, and the scattered context information is fused into a local context-aware vector. Based on the local context-aware vector input to the pre-trained logic discriminant head network, forward propagation inference calculation is performed to output the original logical consistency probability distribution describing the degree of conformity between the current code behavior and the business rules; The original logical consistency probability distribution is subjected to maximum likelihood estimation and confidence mapping to transform the probability values into explicit binary or multi-dimensional logical state labels, thereby generating the final business logic consistency judgment result.
10. The intelligent code security vulnerability detection method based on a large model according to claim 9, characterized in that, The local context-aware vector represents the semantic features of the current business stage.