A security risk analysis system for development process code
By constructing a closed-loop security risk analysis system, segmenting the code and combining dynamic risk assessment and interactive detection, the risk of code leakage during development and transmission is resolved. This enables real-time monitoring and efficient and secure transmission of the code, ensuring the integrity and reliability of the code during testing.
Patent Information
- Application Number
- CN202511215353.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-08-28
- Publication Date
- 2026-02-10
- Estimated Expiration
- 2045-08-28
AI Technical Summary
Existing code security technologies lack real-time risk analysis and dynamic behavior monitoring during development, making code easily leaked during transmission, especially when code is transferred from local to external servers for testing. Existing technologies are unable to effectively prevent code content leakage.
Construct a closed-loop security risk analysis system, including a local code preprocessing module, a secure transmission module, a remote isolation testing module, a leak correlation reverse engineering module, and a local image simulation module. By segmenting the code into independently runnable core segments and compensation segments, and combining dynamic risk assessment and interactive vulnerability detection, the system can monitor and verify the security of the code in real time.
It significantly reduces the risk of code leakage, identifies potential vulnerabilities through segmented transmission and dynamic monitoring, improves the overall security of the development process, ensures that only independently executable code segments are transmitted during testing, reduces the possibility of attackers obtaining complete business logic, and improves the reliability and traceability of detection results through dual verification logic.
Smart Images

Figure CN121118062B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of information security technology, and more specifically to a security risk analysis system for development process code. Background Technology
[0002] In modern software development, code security is a crucial aspect of ensuring stable system operation and data protection. However, most existing code security technologies focus on the code execution or vulnerability scanning phases, while significant shortcomings remain in real-time risk analysis and security management during development. This is particularly true when code is transferred from local storage to an external server for testing, where the lack of effective security mechanisms can easily lead to code content leakage.
[0003] A search revealed a patent, CN107085675B, entitled "Controlled Security Code Verification," which provides a method for verifying the authorization status of code within a client device using a challenge-response mechanism. Specifically, the host device sends a request to the client, demanding verification of the nature of code stored within a specific memory address range on the client, and determines whether the code is authorized based on the received information. However, this technical solution primarily targets security verification during the code execution phase and does not address security protection mechanisms for code transmission and storage during development. Furthermore, its reliance on a specific memory address range for data verification may be insufficient to effectively prevent code content leakage in complex development environments with multiple source code transmission scenarios.
[0004] A search revealed a patent with publication number CN112560048B entitled "A Code Security Scanning Method, Code Security Scanning System, and Storage Medium." This patent proposes a code security scanning method based on a vulnerability priority table, capable of proactively detecting and prioritizing potential vulnerabilities in third-party packages. However, this technical solution is primarily used for static code security scanning, focusing on discovering known vulnerabilities, but failing to perform real-time risk analysis of the dynamic behavior of the code during development. Furthermore, its scanning process relies on existing vulnerability databases, which may prevent timely responses to emerging security threats, and it lacks targeted security protection measures during the transfer of code from local storage to external servers.
[0005] The aforementioned problems indicate that existing code security technologies still have certain shortcomings in real-time risk analysis, code transmission security, and dynamic behavior monitoring during the development process. Therefore, this invention provides a code security risk analysis system for the development process, aiming to effectively prevent code content leakage and improve overall security during development by real-time monitoring of the code development and transmission process, combined with a dynamic risk assessment mechanism, thereby meeting the demands of modern software development for efficiency and security. Summary of the Invention
[0006] To address the shortcomings of existing technologies, the present invention aims to provide a security risk analysis system for development process code. This system resolves the deep-seated contradiction between the discreteness and static nature of existing code security protection mechanisms and the continuity and dynamism of modern software development processes. Specifically, it addresses the risk of core code fragment leakage caused by incomplete code structure and dynamic interaction behavior during integration testing from the local environment to a remote server. The invention constructs a system that can be deeply embedded in the development process, analyze dynamic interaction risks in real time, and perform closed-loop verification.
[0007] To achieve the above objectives, the present invention provides the following technical solution:
[0008] A security risk analysis system for development process code includes: a local code preprocessing module, a secure transmission module, a remote isolation testing module, a leakage correlation reverse calculation module, a local image simulation module, and a closed-loop verification module; the local code preprocessing module, secure transmission module, remote isolation testing module, leakage correlation reverse calculation module, local image simulation module, and closed-loop verification module together constitute a closed-loop, self-optimizing security risk analysis and verification system.
[0009] Specifically, the local code preprocessing module is set up in the developer's local development environment. Its function is to deconstruct the complete source code to be tested into multiple independently runnable, functionally cohesive code segment packages without changing its core business logic. The local code preprocessing module integrates a code segmentation unit, a dependency analysis unit, a compensation segment generation unit, and a segmented code package encapsulation unit. The code segmentation unit has a built-in static analysis engine based on an abstract syntax tree. This engine first performs lexical and syntactic analysis on the received source code text to generate a tree-like data structure that accurately represents the code's logical structure. Based on this abstract syntax tree, the code segmentation unit automatically identifies function definition boundaries, class definition boundaries, or module boundaries according to preset segmentation rules based on the principle of "minimum functionally independent unit," and cuts the source code into multiple initial code segments along these boundaries.
[0010] Furthermore, the segmentation rules include configurable segmentation granularity parameters, allowing developers to set a code line threshold, such as 50 to 200 lines, through a configuration file, or specify specific logical nodes, such as the start and end statements of database transaction operations, as mandatory segmentation points. The code segmentation unit calculates a unique segment identifier for each generated code segment. This identifier is formed by concatenating a 256-bit hash value calculated using a secure hash algorithm for the binary content of the segment with a 32-bit unsigned integer representing its logical order in the original code. Simultaneously, the unit records the precise position index of each code segment in the original source code file, including the start and end line numbers, and stores the mapping relationship between this identifier and the position index in a local segmentation mapping table. Next, the dependency analysis unit processes each initial code segment to identify the external dependencies required for its operation.
[0011] The dependency analysis unit traverses the abstract syntax tree of the code segment to find all symbolic references that are not defined in the current segment. These symbolic references constitute the missing dependencies of the segment. The missing dependencies are classified into three types: undefined variable references, undefined function or method calls, and import statements of external libraries or modules.
[0012] The compensation segment generation unit automatically generates a corresponding compensation segment for each initial code segment based on the missing dependency list output by the dependency analysis unit. The compensation segment is an auxiliary code whose sole purpose is to satisfy the running conditions of the initial code segment without introducing any new business logic. Specifically, for undefined variable references, the compensation segment generation unit automatically inserts a variable declaration statement and assigns it a default value based on the variable type. For example, an integer variable is assigned the value 0, a string variable is assigned the value of an empty string, and an object type is assigned the value null. For undefined function or method calls, the compensation segment generation unit obtains the signature of the called function, including its parameter list and return type, through static type information or reflection mechanism, and generates a simulated function with the same signature. The function body of this simulated function is set to return only a preset static value that conforms to its declared return type, and a specific comment is added inside the function body for subsequent identification.
[0013] Regarding dependencies on external libraries, the compensation segment generation unit generates a lightweight simulation library that contains only simulated implementations of the same name as the called interface. Its behavior is strictly limited. For example, when simulating the "get" method of a network request library, its implementation is set to immediately return a fixed and preset HTTP response object.
[0014] Finally, the segmented code package encapsulation unit concatenates each initial code segment (i.e., the core segment) with its corresponding compensation segment to form a syntactically complete combined code segment that can be independently compiled or interpreted and executed. This unit performs a pre-run verification of the combined code segment by calling the local compiler or interpreter to ensure that it has no syntax errors and can be executed smoothly to the end. After the verification is passed, the unit encapsulates the combined code segment, the unique segment identifier, and a cyclic redundancy check code calculated from the combined code segment into a structured segmented code package. The data format of the segmented code package is JSON, which contains the identifier, check code, and Base64 encoded code content.
[0015] The secure transmission module is responsible for securely transmitting the segmented code packets generated by the local code preprocessing module from the local development environment to the remote test server. The secure transmission module includes an encrypted channel establishment unit, a digital signature unit, and a transmission integrity verification unit. The encrypted channel establishment unit establishes an encrypted, two-way authenticated communication session between the local client and the remote server by executing a complete TLS protocol handshake process. During this process, the client and the server negotiate the session key and use their respective digital certificates based on the RSA algorithm for authentication. All subsequent segmented code packets are transmitted within this encrypted channel.
[0016] Before sending each segmented code packet, the digital signature unit uses the developer's local private key to sign the SHA-256 hash value of the code packet and appends the generated digital signature to the code packet. The transmission integrity verification unit ensures that during transmission, after decrypting the data packet, the receiver recalculates the CRC checksum of its content and compares it with the original checksum carried in the packet. If the two do not match, the data packet is immediately discarded and a retransmission is requested from the sender.
[0017] The remote isolation testing module is deployed on a remote testing server. Its core function is to execute the received segmented code in a controlled environment isolated from the main server system and to perform in-depth monitoring of its dynamic behavior to detect potential code leakage vulnerabilities. The module includes a sandbox environment deployment unit, an interactive test execution unit, and a vulnerability event logging unit. After receiving and verifying each segmented code package, the sandbox environment deployment unit calls an API interface of a containerization engine to dynamically instantiate a container image. The instantiation parameters of the container are strictly set: its network mode is configured as "network_mode:none" and it is connected to a specific monitoring port of the host machine only through a virtual bridge; its root file system is mounted as read-only "--read-only", and only one memory-based file system "tmpfs" is mounted to the " / tmp" directory to store the segmented code to be tested and temporary files generated during runtime. This configuration fundamentally prevents the test code from persistently writing to the server file system and arbitrarily accessing the external network.
[0018] The interactive test execution unit executes segmented code in the sandbox environment and actively applies a series of test inputs to induce potential leakage behaviors. The workflow of this unit is precisely divided into four sub-steps: expected output baseline establishment, dynamic interactive testing, output anomaly detection, and interactive feedback and vulnerability confirmation.
[0019] First, in the expected output baseline establishment phase, this unit performs static analysis on the core segments of the segmented code. By parsing its AST, it identifies the syntactic structure of all output statements, such as "print", "return", and "log.info", and extracts the format, data type, and length range of the expected output content to form a static baseline. At the same time, by inputting a set of predefined normal use cases that conform to the parameter specifications, the segmented code is run to capture all its outputs. These normal outputs are then classified using a clustering analysis algorithm to generate a dynamic baseline output feature library containing normal output samples and their hash values. All simulated outputs generated by the compensation segment are identified by their built-in specific tags and included in the baseline to prevent misjudgment.
[0020] Secondly, in the dynamic interactive testing phase, this unit adopts a layered input strategy. The first layer is basic functional testing, using the same normal test cases as in the baseline establishment phase to verify whether the code output matches the baseline. The second layer is boundary value testing, which uses critical values of input parameters, such as null, empty strings, and maximum / minimum values, to detect whether exception handling logic will incorrectly append debugging information or code snippets. The third layer is attack-oriented input testing, which selects test cases from a built-in attack vector library. This library contains special strings for triggering SQL injection, such as "'OR'1'='1", and HTML tags for triggering cross-site scripting, such as " <script>alert(1)< / script> ", and an extremely long random byte sequence used to trigger a buffer overflow.
[0021] Secondly, in the output anomaly detection phase, this unit deploys output monitoring hooks. Specifically, in the Python environment, this is done by redirecting the "sys.stdout" and "sys.stderr" objects, and in the Java environment, by setting a custom "PrintStream" proxy. This captures all standard output, error output, and network packets sent through the virtual bridge during the execution of the segmented code. For each captured output event, the unit first attempts to match it with the expected output baseline. If the output content exceeds the baseline in terms of structure and content, the excess part is marked as "Extra Content B".
[0022] Subsequently, the leakage feature identification subunit performs in-depth analysis of the "extra content B". This subunit uses a pre-set sensitive feature library, which contains function names, variable names, and unique algorithm constants specific to the core segment extracted from the original complete code. The analysis process uses regular expressions to match code syntax keywords, such as "def", "class", and "SELECT*FROM", and combines it with a pre-trained bidirectional encoder representation language model based on the Transformer architecture to calculate the cosine similarity between the semantic vector of "extra content B" and the semantic vector of the core segment code. If the regular expression matches successfully or the semantic similarity is higher than a preset threshold, then "extra content B" is determined to be a code fragment leakage event.
[0023] Finally, in the interactive feedback and vulnerability confirmation phase, after a leakage event is detected, the unit will keep the input that triggered the event unchanged and repeat the test three times. If the leaked content is stably reproduced, it is confirmed as a deterministic vulnerability. Furthermore, the unit will try to construct a new and targeted input, namely "user='admin'", based on the leaked code snippet, namely a function name "check_permission", to detect whether it can trigger a deeper leakage, thereby constructing a complete leakage chain.
[0024] After each confirmed disclosure event, the vulnerability event recording unit generates a structured vulnerability report. The report is in JSON format and strictly defines the following fields: the complete input data that triggered the vulnerability, the captured original output containing the disclosed content, i.e., the complete text of A+B, the precise location information of the disclosed content B, such as the output stream type, the line number in the output, and the feature tags that initially match the content of B with the core section or compensation section.
[0025] The leakage correlation reverse inference module receives the vulnerability report generated by the remote isolation test module. Its core task is to accurately determine whether the detected code leakage is caused by an inherent defect in the original core segment or by improper implementation of the automatically generated compensation segment. The module consists of a leakage content feature extraction unit, a correlation matching algorithm unit, and a source tracing clue generation unit.
[0026] The leaked content feature extraction unit performs multi-dimensional feature engineering on leaked segment B in the vulnerability report. In terms of syntax, it extracts keywords, variable naming styles (such as the prefix "_private_var" in the core segment and "mock_" in the compensation segment) and code structure (such as the comment marker " / / AUTO-GENERATED COMPENSATION") using lexical analysis tools. In terms of logic, it identifies specific calculation formulas or business logic in the leaked content by constructing control flow graphs and data flow graphs, and compares them with the logical fingerprints of the original core and compensation segments. In terms of context, it records the runtime environment in which the leak occurred, such as which function was called. This unit further employs the TF-IDF (Term Frequency and Inverse Document Frequency) algorithm to assign a weight to each extracted feature, reflecting the importance of that feature in distinguishing between the core and compensation segments.
[0027] For example, a core business function name has a very high weight, while a general "if" keyword has a lower weight. Ultimately, each leaked segment B is represented as a high-dimensional, weighted feature vector. The relevance matching algorithm unit performs the final attribution judgment. It adopts a two-channel matching model. In the first channel, it uses the Levinstein distance algorithm to calculate the edit distance between the text content of the leaked segment B and the text content of the original core segment and the compensation segment, and obtains a text similarity score. In the second channel, it calculates the cosine similarity between the feature vector of the leaked segment B and the feature vectors of the core segment and the compensation segment, which are pre-calculated and stored for each segment code, and obtains a feature similarity score.
[0028] The pre-defined decision logic merges these two scores: if the feature similarity is higher than the judgment threshold, the attribution is made directly based on the feature similarity; if the feature similarity is in the fuzzy range, a comprehensive judgment is made by combining the text similarity and the context information in the vulnerability report; if the leak occurs within 100 milliseconds after a function call marked "mock_", the confidence level associated with the compensation segment is increased. The algorithm uses a conflict resolution mechanism to prioritize the feature similarity result at the logical level when the text similarity and feature similarity results contradict each other.
[0029] The source tracing clue generation unit generates a highly structured JSON-formatted clue report based on the output of the relevance matching algorithm. The core fields of this report include: "leak_type", "segment_id", "matched_core_features", "matched_compensation_features", "trigger_condition", "confidence", and "location_in_source". Among them, "leak_type" is either "core_segment" or "compensation_segment", "segment_id" is the unique SHA-256 identifier of the associated segment, "matched_core_features" is the list of matched core segment features, "matched_compensation_features" is the list of matched compensation segment features, "trigger_condition" is the complete test case that triggered the leak, "confidence" is the attribution confidence score, and "location_in_source" is the start and end line numbers of the original complete code that are mapped back to the leak location by querying the local segment mapping table.
[0030] The local mirror simulation module works together with the closed-loop verification module to form a feedback loop for final confirmation of remote test results and system optimization. The local mirror simulation module builds a simulation environment in the local development environment that is completely consistent with the configuration of the real production environment. The module contains a mirror database construction unit and an attack simulation execution unit. The mirror database construction unit is responsible for storing the complete source code without any segmentation, the exact versions of all dependent libraries of the project, and a complete environment configuration description file including the operating system type, database service version, and network topology. This unit adopts an incremental synchronization mechanism, which automatically synchronizes the latest version of the code and configuration each time the developer submits a code change, and records a detailed version change log.
[0031] The attack simulation execution unit deploys the software system to be tested in a highly isolated virtual machine according to the configuration of the image database. Then, the unit selects an attack script from a continuously updated attack vector library that matches the vulnerability type discovered in the remote test, such as a vulnerability exploit payload generated by the Metasploit framework, and launches a real attack simulation on the complete system in the simulation environment. It records all successful attack events, including their attack paths and the actual leaked content obtained. The closed-loop verification module receives the source clues from the leak correlation reverse inference module and the real attack results from the local image simulation module, and performs cross-comparison to determine the reliability of the remote segmented test. This module contains a result comparison unit, a reliability determination unit, and a strategy optimization triggering unit.
[0032] The result comparison unit performs consistency verification from three dimensions: First, consistency of leaked content, which is determined by calculating the cosine similarity of feature vectors between the leaked features described in the server clues and the actual leaked fragments obtained from the simulated attack. If the similarity is higher than a high confidence threshold, the content is determined to be consistent. Second, consistency of triggering conditions, which is determined by analyzing the payload of the simulated attack and the test cases in the server clues to determine whether they belong to the same attack type, such as both being SQL injection or both being path traversal. Third, consistency of associated segments, which checks whether the line number range of the code fragments leaked by the simulated attack in the original code matches the "location_in_source" field marked in the server clues.
[0033] The reliability determination unit outputs a final conclusion based on the comparison results. If all three dimensions are determined to be consistent, a "verification matching instruction" is output, indicating that the current code segmentation and compensation strategy are reliable. If any dimension is inconsistent, a "verification mismatch instruction" is output. This instruction activates the strategy optimization trigger unit, which automatically issues adjustment instructions to the local code preprocessing module based on the specific inconsistency. If it finds that the segmentation granularity is too large, causing ambiguity in the core logic, it instructs the module to reduce the code line count threshold of the segment. If it finds that the simulated implementation of the compensation segment is too similar to the core segment features, leading to attribution errors, it instructs the module to adopt more distinctive naming and commenting specifications when generating the compensation segment. Through this closed-loop feedback, the system of the present invention achieves continuous learning and self-optimization of its own detection strategy.
[0034] The beneficial effects of this invention are as follows: 1. By using a code segmentation and compensation segment generation mechanism, only independently runnable segmented code, including core segments and compensation segments, is transmitted to external servers, rather than complete code. Although the core segment contains key logic, it is restricted to the smallest functional unit, and the compensation segment avoids calling other core logic by simulating dependencies. This solves the overall leakage risk caused by the transmission of complete code. Even if a segment of code is leaked during testing, attackers cannot obtain the complete business logic or core algorithm, which significantly reduces the cost of code leakage during the development phase.
[0035] 2. Interactive vulnerability detection does not passively wait for leaks to occur, but actively triggers potential vulnerabilities by dynamically generating test cases. For scenarios where "output A but leaks A+B", the system can accurately identify the additional leaked B content by setting a baseline of expected output and monitoring the output content in real time. At the same time, combined with tools such as system call tracing and memory scanning in the sandbox environment, the complete context of vulnerability triggering can be recorded, providing detailed evidence for subsequent correlation back-inference, avoiding the problems of high false negative or false positive rates in traditional static detection.
[0036] 3. Through a dual verification logic of server segment testing and local mirror database simulation, the server side uses a reverse algorithm to determine the correlation between the leak and the core segment or compensation segment, and outputs preliminary clues. The local mirror database simulates real attack scenarios based on complete code, and cross-verifies the attack results with the clues. That is, by comparing the segment detection results with the real attack scenarios, the reliability of the detection is quantified, which solves the problem of strong subjectivity in vulnerability judgment under a single test environment, and makes the detection results repeatable and traceable. Attached Figure Description
[0037] Figure 1 This is a system framework diagram of the present invention;
[0038] Figure 2 This is a flowchart of the local code preprocessing module in this invention;
[0039] Figure 3 This is a flowchart of the remote isolation testing module in this invention;
[0040] Figure 4 This is a flowchart of the closed-loop verification and strategy optimization process in this invention. Detailed Implementation
[0041] The present invention will be further described in detail below with reference to the accompanying drawings and embodiments. Identical components are denoted by the same reference numerals. It should be noted that the terms "front," "rear," "left," "right," "upper," and "lower" used in the following description refer to directions in the accompanying drawings, and the terms "bottom surface," "top surface," "inner," and "outer" refer to directions toward or away from the geometric center of a specific component, respectively.
[0042] like Figure 1 As shown, the present invention provides a security risk analysis system for development process code. The core of its technical solution lies in building a full-process security assurance system covering code development, secure transmission, isolation testing, leakage tracing, and closed-loop verification. This system decomposes the code under test into small, cohesive functional units, performs dynamic interactive testing in a highly isolated remote environment, and combines it with local full-mirror simulation verification, thereby achieving accurate identification and root cause location of the risk of leakage of core code segments caused by incomplete code form or dynamic interactive behavior during the development process.
[0043] The system includes a local code preprocessing module, a secure transmission module, a remote isolation testing module, a leak correlation reverse engineering module, a local image simulation module, and a closed-loop verification module. These six modules work together to form a data-driven, continuously self-optimizing closed-loop system.
[0044] When developers complete the initial coding of a functional module and plan to submit it to the continuous integration server for integration testing, this system intervenes. First, the local code preprocessing module is activated, such as... Figure 2 As shown, this module processes the complete source code file or directory specified by the developer. The core goal of this module is to transform a large source code with complex dependencies into a series of lightweight, independently executable, and logically decoupled code segments. Specifically, the code segmentation unit integrated within the local code preprocessing module first undertakes the task of code destructuring. This unit has a built-in static analysis engine based on an abstract syntax tree. Taking a piece of Python source code as an example, the engine first calls the "ast" module in the Python standard library and executes the "ast.parse()" function to convert the source code text into a tree-like node structure. This structure accurately reflects the code hierarchy, call relationships, and logical blocks.
[0045] Based on this abstract syntax tree, code segmentation units are cut along the natural logical boundaries of the code according to a set of preset segmentation rules. As a preferred implementation, the segmentation rules are configurable, and their configuration information is stored in a local file named "segmenter_config.yml". This configuration file allows setting a "max_lines" parameter, for example, setting it to 150, which means that any function or class with more than 150 lines will be regarded as an independent segmentation unit.
[0046] After the segmentation is performed, the code segmentation unit calculates a unique segment identifier for each generated initial code segment. The generation process of this identifier is extremely rigorous: First, the secure hash algorithm SHA-256 is used to calculate a 256-bit hash value from the UTF-8 encoded binary stream of the segment content; second, the logical order index of the segment in the original complete code is obtained, which is a 32-bit unsigned integer counting from 0; finally, the 32-bit integer is converted into a byte string in big-endian byte order and concatenated with the aforementioned 256-bit hash value to form the final unique segment identifier with a length of 36 bytes; at the same time, the physical location of the segment in the original file, including the filename, start line number and end line number, is recorded along with this identifier in a local SQLite database named "segment_map.db", establishing a precise reverse mapping from the segment to the source code.
[0047] Next, the dependency analysis unit processes each initial code segment generated by the code segmentation unit. It works by performing a depth-first traversal of the segment's abstract syntax tree. During this traversal, for each encountered identifier node, such as the "ast.Name" node, the unit checks if the identifier is defined in the current scope and the known global scope. If no definition is found, the identifier is identified as an external dependency. These external dependencies are further categorized: if the identifier appears on the right-hand side of an assignment statement or as a function parameter, it is classified as an "undefined variable reference"; if the identifier is followed by parentheses, it is classified as an "undefined function or method call"; if it appears in an "import" or "from...import" statement, it is classified as an "external library or module import". All identified missing dependencies and their types are compiled into a structured list and passed to the next processing unit.
[0048] The compensation segment generation unit generates a corresponding compensation code segment, or compensation segment, for each initial code segment based on the list of missing dependencies output by the dependency analysis unit. The generation of compensation segments follows the principle of "minimizing simulation," and its purpose is only to meet the compilation and execution conditions of the initial code segment without introducing any real business logic or external connections. Specifically, for an undefined variable reference "db_config," the compensation segment generation unit will infer its type based on the context or type annotation. If it cannot infer, it will default to "None" and generate the code line "db_config=None#AUTO-GENERATED COMPENSATION." For an undefined function or method call "get_user_profile(user_id)," the unit will analyze its call signature. If it can obtain its return type through static information such as type hints, such as "UserObject," it will generate a mock function with the same name. Its function body only contains "return MockUserObject()#AUTO-GENERATED COMPENSATION," where "MockUserObject" is a mock class containing only default values. If the type information cannot be obtained, it will return "None."
[0049] For importing external libraries or modules ("import requests"), the compensation segment generation unit generates a lightweight mock module file "mock_requests.py", which contains a mock implementation of the methods actually called in the original code (such as "get"), for example: "def get(url,params=None):return MockResponse()", where "MockResponse" is a predefined mock response class containing a fixed status code and a fixed response body "'{"status":"ok"}'". All lines of code generated by this unit are required to include a comment mark "#AUTO-GENERATED COMPENSATION" that can be recognized by subsequent modules. Finally, the segmented code package encapsulation unit concatenates the initial code segment (core segment) and its corresponding compensation segment at the text level to form a syntactically closed and independently executable combined code segment. This unit calculates the CRC32 cyclic redundancy check code of the combined code segment and combines it with the previously generated unique segment identifier and Base64 (RFC) encoded data. The combined code segments encoded using the 4648 standard are encapsulated together into a structured JSON object. The structure of this JSON object is strictly defined as: "{"segment_id":"...","crc32":"...","payload":"..."}". At this point, a segmented code package is generated and awaits to be sent to the remote server.
[0050] The secure transmission module is responsible for securely and reliably transmitting these segmented code packets from the local development environment to the server where the remote isolation testing module resides. This module operates collaboratively by three units. First, the encrypted channel establishment unit initiates a TLS 1.3 handshake process between the local client and the remote server. During this process, both parties use the Elliptic Curve Diffie-Hellman key exchange algorithm to negotiate a one-time session key and exchange and verify their respective X.509 digital certificates. These certificates are issued by an internal private certificate authority, ensuring that the trust chain of the certificates is closed and controllable. All subsequent data transmissions, including segmented code packets, will use the negotiated symmetric key within this encrypted channel. Before data transmission, the digital signature unit locally calculates the SHA-256 hash value of the complete text content of each JSON-formatted segmented code packet to be sent.
[0051] Then, the hash value is RSA signed using the developer's local private key. The generated digital signature is appended to the JSON object, forming a new field "signature". During transmission, the transmission integrity verification unit plays a key role at the receiving end. Whenever a data packet is received, the receiving end first decrypts the data at the TLS layer. Then, it reads the "crc32" field in the packet and independently recalculates the CRC32 checksum after decoding the content of the "payload" field. If the two checksums do not match, it indicates that the data may have been corrupted during transmission. The data packet will be immediately discarded, and the sender will be notified to retransmit the segmented code packet through a non-acknowledgment (NACK) mechanism. Only after the CRC32 verification passes will the data packet be delivered to the remote isolation test module for further processing.
[0052] The remote isolation testing module is the core execution engine of this system. Deployed on a dedicated test server cluster, its function is to perform dynamic interactive testing on received code segments in an environment completely isolated from the server operating system and other applications, in order to discover potential code leakage vulnerabilities, such as... Figure 3 As shown, this module consists of a sandbox environment deployment unit, an interactive test execution unit, and a vulnerability event logging unit. When a segmented code package that has undergone integrity verification and digital signature verification arrives, the sandbox environment deployment unit immediately starts working. This unit dynamically instantiates a pre-built Alpine-based sandbox environment by sending an API request to the Docker daemon running on the server. This is a minimal Linux container image with strictly limited creation parameters for the highest level of isolation: the network mode is set to "network_mode:none", completely prohibiting the container from accessing any external or internal network; the root filesystem is mounted in read-only mode with "--read-only", preventing any persistent modifications to the container image; only a limited-size memory filesystem "tmpfs" is mounted in the " / tmp" directory to store the combined code segments to be tested and temporary files that may be generated during runtime; at the same time, all Linux kernel privileges are removed by the "--cap-drop=ALL" parameter, and "--security-optseccomp=unconfined" is replaced with a path to a strict seccomp configuration file, which only allows the minimum set of system calls necessary for the execution of the code; this configuration fundamentally eliminates the possibility of test code escaping the sandbox, accessing the server filesystem, or initiating network connections.
[0053] Subsequently, the interactive test execution unit executes the combined code segments within a prepared sandbox container and proactively applies a series of carefully designed test inputs to induce potential leakage behaviors. The execution process of this unit is precisely divided into four phases. The first phase is the establishment of the expected output baseline. In this phase, the unit first performs static analysis on the core segments of the combined code segments. By parsing their ASTs, it identifies all explicit output statements, such as "print()", "logging.info()", and "return" statements in Python, and extracts the static characteristics of the expected output content of these statements. For example, a "print(f"Use The static signature of the statement "r:{name}")" is the regular expression "^User:\w+$". Simultaneously, by inputting a set of predefined "golden" test cases conforming to function parameter specifications, the segmented code is run, and all its output on standard output (stdout) and standard error (stderr) is captured. The SHA-256 hashes of these normal outputs are stored, forming a dynamic baseline output signature library. All outputs generated by the compensation segment and marked with "#AUTO-GENERATEDCOMPENSATION" are automatically identified and added to a whitelist to avoid being misjudged as leaks in subsequent stages.
[0054] The second phase is dynamic interactive testing. This unit employs a layered, progressive input strategy. The first layer uses the same "golden" test cases as the baseline establishment phase to quickly verify whether the code's basic functionality and output fully match the baseline. The second layer performs boundary value analysis, inputting various boundary condition values into the code, such as "None," empty strings """, the maximum and minimum values of integers, and strings containing special characters. This detects whether the code's exception handling paths inappropriately print debugging information, stack traces, or internal variable values. The third layer is offensive input testing. This unit selects test cases from a built-in, continuously updated attack vector database containing payloads for common vulnerability types.
[0055] The third stage is output anomaly detection. This unit captures all runtime output by redirecting its standard output and standard error streams to a memory buffer when executing code within the sandbox. For each captured output text, the unit first compares it with the expected output baseline established in the first stage. If the output content does not match the baseline in terms of format or hash value, the output is marked as "abnormal output." Subsequently, a leakage feature identification subunit performs in-depth analysis on this "abnormal output." This subunit employs a dual detection mechanism: first, it uses a rule set containing hundreds of regular expressions to match code syntax keywords, namely "def," "class," and "private." The system uses common sensitive data patterns such as "SELECT", "FROM", and "UPDATE", including IP addresses and password variable names, as well as highly recognizable function and variable names derived from the original complete code. Secondly, it utilizes a pre-trained language model based on the Transformer architecture to encode the "abnormal output" text and the original core code text into high-dimensional semantic vectors, and calculates the cosine similarity between these two vectors. If the regular expression matches successfully, or the semantic similarity exceeds a configurable threshold, the system determines that a "code snippet leakage event" has occurred and precisely locates the portion of the abnormal output that matches the core segment features as the leaked content B.
[0056] The fourth stage is interactive feedback and vulnerability confirmation. After a potential disclosure event is detected, in order to eliminate random factors, the unit will repeat the test at least three times using the same trigger input. If the disclosed content is reproduced stably, the vulnerability is confirmed as a deterministic vulnerability. Whenever a deterministic vulnerability is confirmed, the vulnerability event recording unit will generate a detailed, structured vulnerability report. The report is in JSON format, and its fields are strictly defined and must include: UUID, ISO 8601 format, segment identifier that triggered the vulnerability, complete input data that led to the disclosure, Base64 encoded, captured complete raw output containing the disclosed content, Base64 encoded, code snippet that was precisely located as the leak, start and end indices of the leaked content in "raw_output", and a list containing all matching leak feature tags.
[0057] The leak correlation and reverse engineering module receives vulnerability reports, and its core task is to perform accurate responsibility attribution: determining whether the discovered code leak stems from inherent logical flaws in the original core code written by the developer, or from an illusion introduced by improper implementation of the compensation section automatically generated by the system. This module consists of a leak content feature extraction unit, a relevance matching algorithm unit, and a source tracing clue generation unit. The leak content feature extraction unit first performs in-depth feature engineering on the "leaked_content_B" field in the vulnerability report. It extracts features from multiple dimensions: in terms of syntax features, it uses a lexical analyzer to identify keywords and operators, and pays special attention to naming conventions that can distinguish between core sections and compensation sections. For example, core sections may use variable names like "_internal_data", while compensation sections follow the naming convention of the "mock_" prefix. At the same time, it also checks for the existence of "#AUTO-GENERATED". Specific annotations such as "COMPENSATION" are used; in the logical feature dimension, it attempts to parse the leaked code fragment into a miniature AST and perform subgraph isomorphic matching with the ASTs of the original core segment and compensation segment to find similarities in logical structure; in the context feature dimension, it analyzes the "trigger_input" and call sequence information in the vulnerability report to determine whether the leak occurred immediately after the call of a simulated function. This unit further uses the TF-IDF (Term Frequency-Inverse Document Frequency) algorithm to weight all extracted features. In a pre-built corpus containing a large number of core segment and compensation segment samples, a feature that appears frequently only in the core segment will receive high weight, such as a specific business function name, while a general feature will receive low weight, such as the "if" keyword. Finally, each leaked fragment B is represented as a high-dimensional, weighted feature vector.
[0058] The relevance matching algorithm unit performs the final attribution decision. It employs a dual-channel fusion decision model. The first channel is text-level matching, which uses the Levinstein distance algorithm to calculate the edit distance between the leaked fragment B and the original core segment and the compensation segment, respectively, and normalizes it to a text similarity score between 0 and 1. The second channel is feature-level matching, which calculates the cosine similarity between the weighted feature vector of the leaked fragment B and the feature vectors of the core segment and the compensation segment, which are pre-calculated and stored for this segment of code, to obtain a feature similarity score. These two scores are fused through a pre-defined decision tree logic: if the feature similarity is highly specific to the core segment, the leak is directly determined to originate from the core segment; if the feature similarity is in an ambiguous range, text similarity is introduced as an auxiliary judgment criterion; if the two conclusions conflict, the feature similarity result that reflects the internal logic of the code is given priority. In addition, contextual information is also used as a weighting factor in the decision. For example, if the leak occurs within 5 milliseconds after a function call with the prefix "mock_", the confidence of attributing it to the compensation segment will be increased by 20%. The output is based on the relevance matching algorithm.
[0059] The source tracing clue generation unit generates a highly structured JSON-formatted clue report and sends it back to the local development environment. The report's core fields include: a value of "core_segment_flaw" or "compensation_segment_artifact"; a unique SHA-256 identifier for the associated segment; an attribution confidence score (an integer from 0 to 100); a list of objects; detailed matching features supporting the conclusion and their weights; complete test cases that triggered the leak; and, crucially, the "source_code_location". The "source_code_location" field is obtained by querying the local database to map the "segment_id" back to the specific file path, start line number, and end line number in the original complete code, providing developers with direct and actionable location information.
[0060] Finally, the local mirror simulation module and the closed-loop verification module work together in the local development environment to form the final confirmation link for the remote test conclusions and the system's self-optimization feedback loop. The local mirror simulation module aims to create a local simulation environment that is completely consistent with the configuration of the real production environment or the final integration environment. Its internal mirror database construction unit is responsible for maintaining a "digital twin" information library for a project. This information library is linked to the project's version control system and stores various versions of the complete source code without any segmentation, the precise version of the project dependency list file, and configuration files describing the infrastructure. This unit ensures that the versions of all environmental elements are exactly corresponding. When a traceability report attributable to "core_segment_flaw" is received from a remote location, the attack simulation execution unit is activated. This unit automatically deploys a complete software system to be tested in a highly isolated virtual machine using the configuration information provided by the mirror database construction unit.
[0061] Subsequently, the unit parses the complete test cases that trigger the leak in the source tracing report and transforms them into a real attack script. For example, if the trigger condition is an SQL injection payload, the unit will generate a Python script that uses the "requests" library to send an HTTP request containing the malicious payload to the web application running in the simulation environment. The unit will closely monitor the logs and network traffic of the simulation system to record whether the attack was successfully reproduced and what the leaked content was actually obtained.
[0062] The closed-loop verification module receives tracing clues from the leak correlation reverse engineering module and real attack simulation results from the local mirror simulation module, and performs cross-comparison to ultimately determine the accuracy and reliability of the remote segmentation test. Figure 4As shown, its internal result comparison unit performs strict consistency checks from three dimensions: First, leaked content consistency: calculate the cosine similarity between the feature vector of "leaked_content_B" in the remote clue report and the feature vector of the actual leaked fragment obtained by the local simulation attack. If the similarity is higher than a high confidence threshold, the content is determined to be consistent. Second, triggering condition consistency: compare whether the vulnerability principles used by the remote test case and the local attack script belong to the same category, i.e., both are path traversal vulnerabilities. Third, associated segment consistency: check the code execution path triggered by the local simulation attack to confirm whether it has indeed passed through the source code line number range marked by the "source_code_location" field in the remote clue report. The reliability judgment unit outputs the final conclusion based on the comparison results. If all three dimensions are determined to be consistent, the system outputs a "verification matched" final report to the developer, confirming that the vulnerability is a real, high-priority security flaw. If any dimension is inconsistent, a "verification mismatch instruction" is output. This instruction will directly activate the strategy optimization triggering unit, which will automatically issue an adjustment instruction to the local code preprocessing module according to the specific reason for the inconsistency.
[0063] For example, if an attribution error is found—that is, the remote attribution is to the core segment, but the local simulation cannot reproduce it—it may be because the simulated behavior of the compensation segment is too similar to that of the core segment. In this case, the optimization instruction might be "{"action":"refine_compensation_logic","segment_id":"...",
[0064] If the segmentation granularity is found to be too large, causing multiple unrelated logics to be coupled together, the optimization instruction might be "{"action":"decrease_segment_size","params":{"max_lines":80}}". Through this closed-loop feedback mechanism, the system described in this invention can learn from each test and verification, continuously and automatically optimizing its code segmentation strategy, compensation segment generation logic, and vulnerability detection algorithm, thereby maintaining a high level of detection accuracy and reliability in the ever-evolving software development process.
[0065] The above are merely preferred embodiments of the present invention. The scope of protection of the present invention is not limited to the above embodiments. All technical solutions falling within the scope of the present invention's concept are within the scope of protection of the present invention. It should be noted that for those skilled in the art, any improvements and modifications made without departing from the principle of the present invention should also be considered within the scope of protection of the present invention.
Claims
1. A security risk analysis system for development process code, characterized in that: include: The local code preprocessing module, set up in the local development environment, deconstructs the complete source code to be tested into multiple segmented code packages encapsulated with unique segment identifiers; The secure transmission module securely transmits the segmented code package from the local development environment to the remote test server; The remote isolation testing module includes a sandbox environment deployment unit and an interactive test execution unit. The interactive test execution unit executes the combined code segments in the segmented code package in the sandbox environment deployment unit and actively applies a series of test inputs to induce potential leakage behavior. The interactive test execution unit includes an execution strategy, which includes: The expected output baseline establishment steps involve statically analyzing the core segments of the segmented code and combining this with the dynamic execution of normal use cases to establish a baseline output feature library containing normal output samples and their characteristics. The dynamic interactive testing process involves testing segmented code by sequentially using basic functional test cases, boundary value test cases, and attack-type input test cases selected from the built-in attack vector library through layered input. The output anomaly detection step involves deploying an output monitoring hook to capture all outputs during the execution of segmented code. When the captured output does not match the baseline output feature library, the excess portion is marked as extra content, and the extra content is analyzed in depth to determine whether it constitutes a code fragment leakage event. The remote isolation testing module is deployed on the remote testing server. It executes the received segmented code package in a controlled isolation environment and monitors its dynamic interactive behavior to detect potential code leakage events and generate a vulnerability report containing the leaked content. The leakage correlation and reverse inference module receives the vulnerability report and analyzes and determines whether the code leakage event is caused by the original core segment in the segmented code package or by the compensation segment automatically generated to meet the running conditions, and generates a source tracing clue containing attribution conclusions and source code location. The local mirror simulation module builds a simulation environment locally based on the complete, unsegmented source code and environment configuration, and simulates real attacks based on the tracing clues to verify the reproducibility of the code leakage event; The closed-loop verification module cross-compares the source tracing clues with the actual attack results. If the verification matches, the vulnerability is confirmed. If the verification does not match, the strategy optimization of the local code preprocessing module is triggered.
2. The security risk analysis system for development process code according to claim 1, characterized in that: The local code preprocessing module includes: The code segmentation unit, based on abstract syntax tree analysis, cuts the complete source code into multiple initial code segments according to preset segmentation rules, and generates a unique segment identifier for each initial code segment; The dependency analysis unit processes each initial code segment to identify and classify missing dependencies that are not defined within the current segment and are required for its execution. The compensation generation unit automatically generates a corresponding compensation segment for each initial code segment based on the missing dependencies. The compensation segment reflects auxiliary code that satisfies the running conditions of the initial code segment. The segmented code package encapsulation unit combines each initial code segment with its corresponding compensation segment, performs pre-run verification, and then encapsulates the combined code segment, a unique segment identifier, and a transmission check code together into a segmented code package.
3. The security risk analysis system for development process code according to claim 2, characterized in that: The code segmentation unit uses a built-in, abstract syntax tree-based static analysis engine to cut the source code along function, class, or module boundaries according to segmentation rules including segmentation granularity parameters or specific logical nodes. The unique segment identifier is formed by concatenating the hash value of the segment content calculated by a secure hash algorithm with an integer representing its logical order in the original code. The compensation segment generation unit generates compensation content for different types of missing dependencies. The generation methods include: for undefined variable references, inserting a declaration statement that assigns a default value to the variable type; for undefined function or method calls, generating a simulated function with the same signature but whose function body only returns a preset static value; and for external library dependencies, generating a lightweight simulated library that only contains a simulated implementation of the called interface with the same name.
4. A security risk analysis system for development process code according to any one of claims 1-3, characterized in that: In the remote isolation test module: It also includes a vulnerability event recording unit, which generates a structured vulnerability report after each confirmed disclosure event occurs. The report includes the input data that triggered the vulnerability, the captured raw output containing the disclosed content, and the precise location information of the disclosed content. Specifically, the sandbox environment deployment unit receives and verifies each segmented code package, and then dynamically instantiates a predefined container with strict isolation configuration as a sandbox environment by calling the interface of the containerization engine. The isolation configuration includes network access prohibition, root file system read-only, and restricted system call permissions.
5. The security risk analysis system for development process code according to claim 4, characterized in that: The output anomaly detection step determines code snippet leakage events through a dual detection mechanism, which includes: The first detection mechanism uses a preset sensitive feature library to perform pattern matching on the additional content. The sensitive feature library contains unique function names, variable names, unique algorithm constants, and code syntax keywords extracted from the core segment of the original complete code. The pattern matching is implemented using regular expressions. The second detection mechanism uses a pre-trained bidirectional encoder to represent the language model, calculates the semantic vector of the additional content and the semantic vector of the core segment of the segmented code, and calculates the cosine similarity between the two. When the regular expression matches successfully in the first detection mechanism, or when the semantic similarity in the second detection mechanism is higher than a preset threshold, the additional content is determined to be a code snippet leakage event.
6. The security risk analysis system for development process code according to claim 1, characterized in that: The leakage correlation reverse inference module includes: The leaked content feature extraction unit extracts information on syntactic features, logical features, and contextual features from the leaked fragments in the vulnerability report, and uses the term frequency-inverse document frequency algorithm to weight the extracted features, ultimately representing the leaked fragment as a high-dimensional weighted feature vector; The relevance matching algorithm unit performs the final attribution judgment, calculates the similarity between the feature vector of the leaked segment and the pre-calculated feature vector of the core segment and the feature vector of the compensation segment, and combines the text edit distance to determine the source of the leak; The source tracing clue generation unit generates source tracing clues based on the source of the leak, including attribution type, associated segment identifier, confidence score, and original code location information obtained by reverse mapping through querying the local segment mapping table.
7. The security risk analysis system for development process code according to claim 6, characterized in that: The relevance matching algorithm unit performs attribution judgment through a dual-channel matching model. The dual-channel matching model includes a first channel, which calculates the text content edit distance between the leaked fragment and the original core segment and compensation segment in the segmented code package to obtain a text similarity score. The second channel calculates the cosine similarity between the weighted feature vector of the leaked fragment and the feature vectors of the core segment and compensation segment pre-stored in the segmented code, and obtains the feature similarity score.
8. The security risk analysis system for development process code according to claim 1, characterized in that: The local mirror simulation module includes: The mirror database building unit stores the complete, unsegmented source code, precise versions of project dependency libraries, and a complete environment configuration description file including the operating system, and records changes synchronously with the version control system. The attack simulation execution form fully deploys the software system to be tested in an isolated virtual machine according to the complete environment configuration description file, initiates a real attack simulation based on the triggering conditions in the source tracing clues, and records successful attack events and the leaked content obtained.
9. The security risk analysis system for development process code according to claim 1, characterized in that: The closed-loop verification module includes: The result comparison unit verifies the consistency between the source tracing clues and the actual attack simulation results of the local mirror simulation module from three dimensions: leaked content, triggering conditions, and associated segments. The reliability judgment unit outputs a verification compliance instruction when all three dimensions are consistent, and outputs a verification non-compliance instruction when any dimension is inconsistent. The strategy optimization trigger unit is activated when it receives a verification mismatch instruction and outputs code segmentation granularity or compensation segment generation adjustment instructions to the local code preprocessing module.
Citation Information
Patent Citations
Controlled security code verification
CN107085675B
Code security scanning method, code security scanning system and storage medium
CN112560048B
Automatic construction method and system for cloud native application vulnerability reproduction environment
CN111259406A
Security analysis system
CN118802230A