Sand-box based source code protection method and device and storage medium
Patent Information
- Application Number
- CN202610908941.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-23
- Publication Date
- 2026-09-04
AI Technical Summary
然而,该类技术存在明显的性能瓶颈和兼容性问题:由于加解密操作发生在每次文件I/O过程中,对于大规模代码库的增量编译、分布式编译等场景,加解密开销会显著降低编译效率;同时,部分集成开发环境(IDE)和构建工具链对文件访问方式较为特殊(如内存映射文件、异步I/O),透明加解密技术容易出现兼容性故障,导致编译失败或调试异常
通过在内核态创建沙盒实例,并基于进程身份识别动态切换透明模式与污染模式。对于白名单进程,沙盒实例工作于透明模式:在沙盒内存空间中对磁盘加密的源代码文件进行实时解密,以明文形式供白名单进程读写,落盘时自动加密。由于加解密操作在内存中进行且采用硬件加速指令,白名单进程的编译、调试、版本控制等操作完全不受影响,性能损耗明显降低,且不再是每次I/O操作时都需要解密,提升了响应速率,实现了与传统明文开发环境一致的使用体验。
Smart Images

Figure CN122692986A_ABST
Abstract
Description
Technical Field
[0001] This disclosure relates to the field of information technology, and in particular to a sandbox-based source code protection method, apparatus, and storage medium. Background Technology
[0002] With the widespread adoption of digital R&D and collaboration models in enterprises, the security of source code, as a core form of intellectual property, faces increasingly severe challenges. Once source code is leaked, it can lead to the outflow of core technologies, a decline in business competitiveness, and even serious economic losses and legal risks.
[0003] Existing technologies for source code protection include intercepting process read and write operations on files through file system filter drivers (such as WindowsMiniFilter and Linux FUSE), automatically encrypting files when they are written to disk, and automatically decrypting them when they are read into memory. This type of technology ensures that source code is always stored in encrypted form on disk, effectively preventing unauthorized file copying and external theft. However, this technology has significant performance bottlenecks and compatibility issues: since encryption and decryption operations occur during each file I / O operation, the overhead of encryption and decryption significantly reduces compilation efficiency in scenarios such as incremental compilation and distributed compilation of large-scale codebases; at the same time, some integrated development environments (IDEs) and build toolchains have special file access methods (such as memory-mapped files and asynchronous I / O), making transparent encryption and decryption technologies prone to compatibility issues, leading to compilation failures or debugging anomalies. Summary of the Invention
[0004] This disclosure provides a sandbox-based source code protection method, apparatus, and storage medium.
[0005] Firstly, this disclosure provides a sandbox-based source code protection method, comprising: creating a sandbox instance in the operating system kernel mode, the sandbox instance being used to isolate protected source code files; the sandbox instance being communicatively connected to a zero-trust security gateway; intercepting a first process performing read / write operations on a first source code file within the sandbox instance and identifying the identity of the first process: if the first process is a whitelisted process included in a whitelist set, setting the working mode of the sandbox instance to transparent mode, receiving a session key issued by the zero-trust security gateway in transparent mode, and using the session key in the memory space of the sandbox instance to decrypt the encrypted first source code file on the disk into plaintext, and allowing the first process to perform read / write operations on the plaintext; if the first process is not a whitelisted process, setting the working mode of the sandbox instance to pollution mode, generating a pollution-enhanced second source code based on a copy of the first source code file in pollution mode, and allowing the first process to perform read / write operations on the second source code; the second source code having at least additional tracing code compared to the first source code; wherein, different pollution treatment methods are used for the importance levels of each function body in the first source code; and receiving tracing data returned based on the tracing code.
[0006] Secondly, this disclosure provides a sandbox-based source code protection device, comprising: a creation module for creating a sandbox instance in the operating system kernel mode, the sandbox instance being used to isolate protected source code files; the sandbox instance being communicatively connected to a zero-trust security gateway; an interception and identification module for intercepting a first process performing read / write operations on a first source code file within the sandbox instance and identifying the identity of the first process; and a transparent mode module for setting the working mode of the sandbox instance to transparent mode if the first process is included in a whitelist set of whitelisted processes, receiving a session key issued by the zero-trust security gateway in the transparent mode, and using the session key in the memory space of the sandbox instance. The key decrypts the encrypted first source code file on the disk into plaintext and allows the first process to perform read and write operations on the plaintext; the pollution mode module is used to set the working mode of the sandbox instance to pollution mode if the first process is not a whitelisted process. In the pollution mode, a pollution-inducing second source code is generated based on a copy of the first source code file, and the first process is allowed to perform read and write operations on the second source code; the second source code has at least additional tracing code compared to the first source code; wherein, the importance level of each function body in the first source code adopts different pollution processing methods; the receiving module is used to receive tracing data returned based on the tracing code.
[0007] Thirdly, this disclosure provides a computer storage medium storing a computer program, wherein the computer program, when executed by a processor, implements the sandbox-based source code protection method provided in any embodiment of this disclosure.
[0008] The sandbox-based source code protection method, apparatus, and storage medium disclosed herein have the following technical advantages: By creating sandbox instances in kernel mode and dynamically switching between transparent and polluted modes based on process identity, the sandbox instance operates in transparent mode for whitelisted processes: encrypted source code files on disk are decrypted in real-time within the sandbox memory space, providing them to whitelisted processes in plaintext for reading and writing, and automatically encrypted upon disk write. Since encryption and decryption operations are performed in memory using hardware-accelerated instructions, compilation, debugging, and version control operations of whitelisted processes are completely unaffected, significantly reducing performance overhead. Furthermore, decryption is no longer required for every I / O operation, improving response speed and achieving a user experience consistent with traditional plaintext development environments.
[0009] For non-whitelisted processes, the sandbox instance operates in pollution mode: it generates polluted code carrying tracing code based on a copy of the source code, which is then read and written by non-whitelisted processes. The polluted code remains syntactically correct and compileable, but its core logic is deleted, obfuscated, or replaced with fake logic. Even if an attacker obtains the polluted code, they cannot obtain usable source code. This invention is the first to introduce the proactive defense concept of providing attackers with polluted code into the field of source code protection, completely changing the traditional binary protection approach of either blocking or allowing.
[0010] Based on the importance level of each function body in the source code, different pollution treatment methods are adopted. Compared with the traditional approach of treating all code the same way, the differentiated pollution strategy of this invention reduces the impact of pollution treatment on the compilation process while ensuring the security of core assets, and achieves precise protection.
[0011] Embedded in the contaminated secondary source code is tracking code. When this contaminated code is copied, compiled, or executed, it returns tracking data (such as the IP address of the execution environment, device fingerprint, timestamp, etc.). Security teams can use this data to quickly locate the source of the leak, identify the attacker, and reconstruct the leak path. Traditional solutions can only provide passive defense and cannot effectively trace the source of a leak; this invention achieves a leap from simply preventing the leak to being able to trace it back to its origin.
[0012] In this embodiment of the invention, the sandbox instance maintains a communication connection with the zero-trust security gateway and dynamically obtains the session key from the gateway in transparent mode. The key is not persistently stored locally; instead, it is issued in real-time by the gateway based on multi-factor authentication results, device fingerprints, behavioral risks, etc., thus implementing the zero-trust principle of never trusting and always verifying. Compared to traditional solutions that use static keys or store keys locally, this invention significantly reduces the risk of key leakage.
[0013] This invention does not modify the compiler, does not damage the project structure, and does not change the version control process. Developers can obtain transparent and seamless security protection without having to learn new operating habits.
[0014] In summary, this invention, through sandbox instances, dual-mode switching of sandbox instances, differentiated pollution, and closed-loop technology for tracing and tracking, achieves proactive protection of source code throughout its entire lifecycle while ensuring normal development efficiency. It solves long-standing technical problems in existing technologies, such as the trade-off between security and efficiency, the single dimension of protection, and the difficulty in tracing leaks, and has achieved significant technological progress. Attached Figure Description
[0015] Figure 1 A schematic flowchart illustrating a sandbox-based source code protection method provided in an embodiment of this disclosure; Figure 2A This is a simulation diagram of a network sandbox system provided in an embodiment of the present disclosure; Figure 2B A simulation diagram of a network sandbox system provided in yet another embodiment of this disclosure; Figure 2C A schematic flowchart illustrating a sandbox-based source code protection method provided in an embodiment of this disclosure; Figure 3 A schematic diagram of the structure of a sandbox-based source code protection device provided in an embodiment of this disclosure; Figure 4 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present disclosure. Detailed Implementation
[0016] The present disclosure will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative of the present disclosure and are not intended to limit the scope of the disclosure.
[0017] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this disclosure belongs. The terminology used herein is for the purpose of describing particular embodiments only and is not intended to be limiting of this disclosure. The term "and / or" as used herein includes any and all combinations of one or more of the associated listed items.
[0018] Reference Figure 1 The diagram illustrates a flowchart of a sandbox-based source code protection method provided in an embodiment of the present invention, which may specifically include the following steps: Step S101: Create a sandbox instance in the operating system kernel mode. The sandbox instance is used to isolate protected source code files. The sandbox instance is communicatively connected to the zero-trust security gateway.
[0019] In this embodiment of the invention, the sandbox instance is an isolated execution environment created based on operating system kernel technologies (such as namespaces and cgroups in Linux, and Job Objects and Filter Manager in Windows). An encrypted communication channel is established between the sandbox instance and the zero-trust security gateway to receive policies, keys, and configuration information issued by the gateway.
[0020] Understandably, sandbox instance creation can be triggered after successful user login authentication or pre-created during system startup. Sandbox instances have independent process spaces, file system views, and network views, ensuring that operations within the sandbox do not affect the host machine or other applications. Figure 2A and Figure 2B The image shown is a simulation diagram of the sandbox system provided in this disclosure.
[0021] Step S102: Intercept the first process that performs read / write operations on the first source code file within the sandbox instance and identify the identity of the first process.
[0022] In this embodiment of the invention, all access requests to source code files within the sandbox directory are intercepted by a kernel file system filter driver (such as FUSE in Linux or MiniFilter in Windows). For each process initiating access, its process name, process path, digital signature, process hash, and other identity information are extracted.
[0023] For example, when a user opens the main.c file in the sandbox directory through Visual Studio Code, the kernel interception module will capture the CreateFile operation of the devenv.exe or code.exe process and identify the identity information of the process.
[0024] Step S103: If the first process is a whitelist process included in the whitelist set, the working mode of the sandbox instance is set to transparent mode. In the transparent mode, the session key issued by the zero-trust security gateway is received, and the first source code file encrypted on the disk is decrypted into plaintext in the memory space of the sandbox instance using the session key, and the first process is allowed to perform read and write operations on the plaintext.
[0025] In some embodiments, the whitelist set may be a pre-defined list of trusted processes. Further, the whitelist set is dynamically distributed by the zero-trust security gateway and supports real-time updates, and includes at least one or more of the following processes: compiler processes, integrated development environment processes, and version control processes; process identification is based on a combination of verification using process path, digital signature, and process hash value.
[0026] In some embodiments, the whitelist set includes a pre-defined list of trusted processes, such as gcc, clang, java, python, idea64.exe, code.exe, devenv.exe, git.exe, svn.exe, etc.
[0027] When the first process is identified as belonging to the whitelist set, the sandbox instance switches to transparent mode. In transparent mode, the sandbox instance first requests the session key for the current session from the zero-trust security gateway. The gateway dynamically issues the key based on the multi-factor authentication result and the device fingerprint.
[0028] In some embodiments, the transparent mode refers to: the sandbox instance shielding the whitelisted process from the encrypted storage state of the first source code file on the disk; the read operation initiated by the whitelisted process is decrypted in memory by the sandbox instance in real time and returned as plaintext; the write operation initiated by the whitelisted process is encrypted in real time by the sandbox instance and written to the disk, so that the whitelisted process can complete the reading and writing of the encrypted source code file in the same way as operating on plaintext files, without modifying the code or configuration of the whitelisted process.
[0029] Specifically, the sandbox instance allocates protected memory pages in memory (with hardware-level memory encryption implemented via Intel SGX or AMD SEV technology), and uses a session key within this memory region to decrypt encrypted source code files on disk. The decrypted plaintext code exists only within this protected memory region; it remains encrypted on disk at all times.
[0030] Taking a Linux system as an example, assume that ` / sandbox / project / main.c` is a source code file stored in encryption. When the whitelisted process `gcc` reads this file, the sandbox instance captures the read operation through the FUSE file system hook, obtains the session key `K_session` from the zero-trust security gateway, decrypts the file content in the sandbox memory using an encryption algorithm (such as AES-256-GCM), and returns the plaintext to the `gcc` process. The `gcc` process sees all normal plaintext code and can complete the compilation normally. When the `gcc` process writes the compiled output back to disk, the sandbox instance automatically encrypts the data before writing it to disk.
[0031] Step S104: If the first process is not a whitelisted process, the working mode of the sandbox instance is set to pollution mode. In the pollution mode, a pollution-induced second source code is generated based on a copy of the first source code file, and the first process is allowed to perform read and write operations on the second source code. The second source code has at least additional tracing code compared to the first source code. The importance level of each function body in the first source code is determined by different pollution treatment methods.
[0032] In this disclosure, read and write operations performed on the second source code by a non-whitelisted process are a means by which the second source code is removed from the sandbox instance. Specifically: When a non-whitelisted process reads the second source code, the sandbox instance returns the contents of the second source code to that process. The process can then store the contents in its own memory or write them to a disk outside the sandbox, thereby allowing the second source code to be retrieved from the sandbox instance. When a non-whitelisted process writes the second source code, the process can save the second source code to a storage path outside the sandbox instance, thus achieving the same retrieval effect.
[0033] Once the second source code is retrieved from the memory of the sandbox instance, it is removed from the control boundary of the sandbox instance. At this point, it can be... Figure 2C As shown, if the second source code is compiled or interpreted, the embedded executable tracing code will be activated at runtime and actively send tracing data (such as IP address, device fingerprint, timestamp) to the preset tracing server; if the second source code is copied and spread, the embedded digital watermark (such as zero-width Unicode characters, steganographic information) can be extracted afterward for source tracing analysis.
[0034] In this embodiment of the invention, when it is detected that the first process does not belong to the whitelist set, the sandbox instance switches to pollution mode. In pollution mode, instead of simply denying access to non-whitelisted processes (which would alert attackers), it provides attackers with seemingly normal but actually polluted code.
[0035] In some embodiments, pollution mode is an active defense working mode of a sandbox instance. In this mode, the sandbox instance does not provide the real plaintext source code to non-whitelisted processes. Instead, it generates a second source code file based on a decrypted copy of the original source code file. This second source code file is syntactically correct, compileable, but has modified core logic, and is available for non-whitelisted processes to read and write.
[0036] Specifically, the sandbox instance first decrypts the first source code file into a plaintext copy, and then uses differentiated pollution treatment methods for different function bodies according to the importance level of each function body in the first source code.
[0037] In some embodiments, the contamination methods include, but are not limited to, at least one of the following: Insert redundant characters. Insert blank characters, comment lines, or empty statements into the first source code that do not affect the syntax correctness and compilation results. This includes inserting at least one of the following: inserting meaningless single-line or multi-line comments, inserting blank lines that do not change the semantics of the code, and inserting constant declarations that do not participate in logical operations.
[0038] Obfuscation is a technique that alters the representation of the first source code without changing its original semantics, including at least one of renaming local variables to meaningless characters, shuffling declaration positions that are not dependent on order, inserting conditional branches that will not be executed, and expanding simple conditional expressions into equivalent but complex logical expressions. Complete obfuscation further reconstructs the control flow of the function body into an equivalent but difficult-to-analyze complex structure, including control flow flattening, opaque predicate insertion, expanding loop structures into equivalent recursive calls, and replacing conditional branches with at least one of the following indirect jump tables.
[0039] Forged values are data of the same type as the original return value but with incorrect business meaning or randomness. They are generated by a deterministic algorithm based on the identity of non-whitelisted processes, which allows the same process to obtain the same forged value multiple times and different processes to obtain different forged values.
[0040] Hardware fingerprint is a fixed-length string generated by hashing one or more of the following hardware identifiers of the device where the sandbox instance resides: central processing unit serial number, trusted platform module metric, network interface card media access control address, hard drive serial number, and motherboard identifier.
[0041] For example, the first source code, payment_service.py, contains three functions: calculate_price(): core business logic involving price calculation, with an importance level of first; validate_user(): user validation logic, with an importance level of second; and log_access(): logging, with an importance level of third.
[0042] For the first-level function `calculate_price()`, the approach is to delete or completely obfuscate it, for example, by replacing the function body with `raise NotImplementedError` or replacing the algorithm logic with returning a random number. For the second-level function `validate_user()`, the approach is to insert redundant characters or forged values, for example, by inserting meaningless comments like `# FIXME: optimize later` into the function, or by changing the return value from `True` to `True if random()>0.5else False`. For the third-level function `log_access()`, only tracing code is inserted without affecting its normal functionality.
[0043] Meanwhile, the second source code contains embedded tracing code. This tracing code can be an invisible digital watermark (such as a zero-width Unicode character or an invisible sequence of comments), or a callback function that actively sends tracing data when the code is executed.
[0044] Step S105: Receive tracking data returned based on the tracking code.
[0045] In this embodiment of the invention, when the contaminated second source code is copied, pasted, compiled, or executed, the embedded tracing code triggers data return. The tracing data may include: the IP address of the execution environment, device fingerprint, timestamp, and / or the identity of the user performing the operation, etc.
[0046] For example, when an attacker copies the compromised `payment_service.py` to their development environment and executes it, the network regression function in the tracing code sends an HTTP request to a pre-defined tracing server, carrying information such as the attacker's public IP address, hostname, and / or username. The security team can then use this information to pinpoint the source of the leak and take further action.
[0047] Through the above steps, this invention achieves transparent and seamless protection for whitelisted processes (transparent mode) while providing contaminated code for non-whitelisted processes (contaminated mode). This ensures normal development efficiency while providing proactive protection and source code tracing capabilities against leaks. The present invention also provides a flowchart of a method for dynamically adjusting the degree of pollution, which may specifically include the following steps: obtaining the behavioral risk assessment score of the first process.
[0048] In this embodiment of the invention, the behavioral risk assessment score is used to quantify the degree of abnormality of the access behavior of the first process. The risk assessment score can be calculated based on one or more of the following factors: Time modal data, the deviation between the timestamp of process access and the preset normal working time window; Spatial modal data, the degree of matching between the geographical region of the process access source IP address and the preset authorized region; Sequence modal data, the edit distance between the process's access order to a file and a preset typical access sequence; Relational modal data, which is the structural similarity between the co-occurrence relationships of files accessed simultaneously by processes and the predefined dependency graph.
[0049] In some embodiments, the first process's time modality data (e.g., whether the access time is outside of working hours), spatial modality data (e.g., whether the access source IP is outside of a regular region), sequence modality data (e.g., whether the file access order is abnormal), relational modality data (e.g., whether there is a relationship between files accessed at the same time), the number of files accessed by the first process, and whether the command line parameters of the first process contain predetermined sensitive keywords (e.g., dump, export, copy).
[0050] For example, when the whitelisted process git.exe executes the command git clone --bare at 3 a.m., its command line parameters contain the sensitive keyword --bare (usually used for copying a complete repository). At this time, the behavior risk assessment score will be calculated as a higher value (such as 85 points out of 100).
[0051] Determine the threshold range in which the behavioral risk assessment score falls. When the behavioral risk assessment score is lower than the first threshold, insert redundant characters into the second function body in the first source code.
[0052] The first threshold can be set to 30 points, but is not limited to 30 points; it can also be 25 points, 35 points, or 40 points, etc. When the risk assessment score is lower than the first specified score, the current access behavior is considered basically normal, requiring only the minimum level of contamination. In this case, redundant characters (such as meaningless comments, blank lines, and whitespace characters that do not change the semantics) are inserted only into the function bodies of the second level, while no contamination processing is performed on the function bodies of the first level.
[0053] When the behavioral risk assessment score is between the first threshold and the second threshold, the second function body is processed by inserting redundant characters or forged values, and the first function body is processed by obfuscation.
[0054] The second threshold can be set to a second specified score, such as 70, 75, or 65. When the risk assessment score falls between the first and second thresholds, the current access behavior is considered to pose a certain risk. In this case, redundant characters or forged values are inserted into the function bodies of the second level (e.g., changing the return value from True to True if user.is_admin else False), and obfuscation is applied to the function bodies of the first level (e.g., renaming local variables, scrambling code order, inserting dead code).
[0055] When the behavioral risk assessment score is higher than the second threshold, the first function body is deleted and the second function body is completely obfuscated.
[0056] When the risk assessment score is higher than the second threshold, the current access behavior is considered highly suspicious and is very likely to be malicious. At this time, the function body of the first level is directly deleted (replaced with pass or return None), and the function body of the second level is completely obfuscated (for example, the entire function body is replaced with a complex but meaningless control flow structure).
[0057] Taking the example of git.exe executing git clone --bare at 3 AM, when the risk assessment score is 85 (higher than 70), the sandbox instance will perform the following operations: Delete the body of the `calculate_price()` function and replace it with `pass`; Completely obfuscate the validate_user() function; Thus, although the code obtained by the attacker is syntactically correct and compileable, the core business logic has been deleted or obfuscated, making it unusable.
[0058] This invention achieves a progressive protection strategy by dynamically linking the degree of contamination with the behavioral risk assessment score, where higher risks result in heavier contamination. This avoids excessive interference with normal users while effectively countering high-risk attacks.
[0059] The method for determining the importance level of a function body provided in this embodiment of the invention may specifically include the following steps: The first source code is structurally analyzed based on the abstract syntax tree, control flow graph, and / or data dependency graph, and the function body parameters of each function body are extracted. The function body parameters include loop complexity, call depth, global variable dependency, cross-module application programming interface (API) exposure surface, and / or sensitive operation call chain.
[0060] In this embodiment of the invention, static analysis is first performed on the first source code. Taking C language code as an example, an abstract syntax tree (AST) and a control flow graph (CFG) are generated using static code analysis tools. Then, each function node is traversed to extract the following parameters: Cyclomatic Complexity: Calculates the number of independent paths in a function. The higher the complexity, the more complex the function's logic, and the higher its importance level may be.
[0061] Call Depth: The depth of a function in the call graph. The deeper the depth, the more upper-level functions the function depends on.
[0062] Global Variable Dependency: The number of global variables accessed by a function. A higher dependency rate indicates that the function is more difficult to replace.
[0063] Cross-module API exposure (Exported API Count): The number of interfaces that a function exports for use by other modules. A larger exposure count indicates that the function is more important.
[0064] Sensitive Operation Chain: Whether a function calls functions that involve sensitive operations such as encryption / decryption, permission verification, or database access.
[0065] The results of the structural analysis and the function body parameters are input into a pre-trained code semantic understanding model, which outputs the semantic sensitivity score of each function body.
[0066] In this embodiment of the invention, the code semantic understanding model can be a neural network model pre-trained based on a transformer architecture (such as Code BERT or Graph Code BERT). This model is pre-trained on a large number of open-source code libraries and learns the correlation between code semantics and security sensitivity.
[0067] Specifically, the AST serialization and CFG features of the function body are used as model inputs, and the model outputs a semantic sensitivity score between 0 and 1. The higher the score, the greater the impact on the overall system security if the function body is leaked. For example, the semantic sensitivity score of the function `process_payment`, which processes user payment information, is 0.95; and the score of the function `format_log`, which formats logs, is 0.12.
[0068] Based on the semantic sensitivity scores, the function bodies are divided into the first level of the first function body, the second level of the second function body, and the third level of the third function body.
[0069] For example, the semantic sensitivity score can be set as follows: a score ≥ 0.7 is the first level, 0.3 ≤ score < 0.7 is the second level, and a score < 0.3 is the third level. Using the example above, process_payment (0.95) is classified as the first level, validate_user (0.55) as the second level, and format_log (0.12) as the third level.
[0070] Different pollution treatment methods may be used depending on the level of the function body, including but not limited to at least one of the following: For the first function body, pseudocode generated based on a generative adversarial network is used to replace it. The pseudocode retains the original function signature, interface contract, and exception handling path, and the algorithm logic of the first function body is reconstructed to generate erroneous output or leak preset honeypot data under specified input domain or boundary conditions.
[0071] Specifically, using a Conditional GAN network, pseudocode with the same signature as the original function but containing internal logical errors is generated, based on the function signature. For example, the original function `int add(int a, int b) { return a + b;}` might be replaced with `int add(int a, int b) { return a;}`. b;}, but the function signature and exception handling remain unchanged, making it impossible for the caller to detect the exception.
[0072] For the second function body, a control flow preservation and data flow injection obfuscation method is adopted. The forged value is dynamically generated based on the identity of the first process, making the forged value received by different non-whitelisted processes distinguishable.
[0073] For example, for the function `bool is_admin(user_id)`, different forged return values can be generated based on the process ID: process A receives `True`, process B receives `False`, and process C receives `random.choice([True, False])`. In this way, even if multiple attackers obtain the code simultaneously, they cannot verify the authenticity of the code against each other.
[0074] For the third function body, redundant characters and meaningless control flow branches are inserted. This method has minimal impact on the function's functionality and is mainly used to embed tracing code and increase code size.
[0075] This invention uses a code semantic understanding model to intelligently classify function bodies and adopts differentiated pollution treatment methods according to the level, achieving precise protection by replacing core functions, obfuscating secondary functions, and only marking irrelevant functions.
[0076] A flowchart of a whitelist behavior drift detection method provided in this embodiment of the invention may specifically include the following steps: Monitor the behavioral characteristics of each whitelisted process in the whitelist set and establish a baseline for the normal behavior of each process.
[0077] In this embodiment of the invention, the normal behavioral baseline may include statistical characteristics of one or more of the following dimensions: File access mode: the directory, file type, and number of files typically accessed; Network access mode: typically the IP address, port, and protocol used for connection; System call sequence: The types and order of system calls typically executed; Command-line argument mode: Commonly used parameter combinations; Time pattern: During which time periods do you usually participate in activities?
[0078] For example, the normal behavior baseline for the gcc compiler process might be: it is invoked during normal working hours (9:00-18:00), typically accesses .c and .h files in the / sandbox / src / directory, outputs to the / sandbox / build / directory, and command-line arguments usually include options such as -c, -o, and -I.
[0079] When the behavior of the whitelisted process deviates from the baseline of normal behavior by more than a preset deviation threshold, the whitelisted process is marked as a suspicious process.
[0080] For example, if the gcc process is invoked at 2:00 AM and attempts to access the / etc / passwd and / home / user / .ssh / directories, and its behavior deviates significantly from the normal baseline, exceeding a threshold, then the gcc process is marked as a suspicious process.
[0081] For the suspicious process, perform at least one of the following actions: temporarily remove the suspicious process from the whitelist set; add audit operations to the suspicious process; send an alarm to the management terminal and wait for alarm confirmation.
[0082] Specifically, a tiered approach can be adopted: Slight deviation: Increase the frequency of audit operations, log all file accesses and system calls, but do not immediately block them.
[0083] Moderate deviation: Temporarily remove the process from the whitelist set, causing subsequent accesses to switch to pollution mode.
[0084] Severe deviation: Immediately send an alert to the administrator and wait for manual confirmation before taking action.
[0085] Once the behavior of a suspicious process returns to the normal behavior baseline and remains within a preset duration, the flag of the suspicious process is removed.
[0086] For example, if the suspicious gcc process behaves in accordance with the normal behavior baseline for 30 consecutive minutes during subsequent monitoring, the suspicious flag will be automatically removed and its whitelist status will be restored.
[0087] This invention effectively addresses the attack scenario where legitimate processes (e.g., whitelisted processes) abuse privileges after being compromised by continuously monitoring the behavior drift of whitelisted processes, thus achieving an upgrade from static whitelists to dynamic trust assessment.
[0088] The sandbox online / offline mode switching method provided in this embodiment of the invention may specifically include the following steps: Detect network connectivity status to determine whether the sandbox instance is in online or offline mode.
[0089] In the online mode, the sandbox instance maintains an encrypted connection with the zero-trust security gateway to obtain a real-time updated whitelist set, session keys, and control policies. These control policies may include at least offline policies.
[0090] In online mode, the sandbox instance maintains a heartbeat with the gateway via a WebSocket or gRPC streaming connection. Each time a user accesses the service, the sandbox instance can request the latest session key and policy from the gateway in real time to ensure dynamic authorization.
[0091] In the offline mode, the sandbox instance runs independently in a network-free environment and performs operations based on an offline policy pre-obtained from the zero-trust security gateway.
[0092] Developers can request offline authorization from the gateway in advance when in network-free environments such as business trips or on-site debugging. The gateway issues an offline policy package, which includes at least one or more of the following: offline validity period: for example, 72 hours; set of operation permissions: for example, read-only, editable but not exportable; offline decryption key: encrypted and stored in the TEE of the sandbox instance; when any of the following conditions are detected, the sandbox instance is locked to prohibit any read and write operations based on the sandbox instance, and the plaintext data in the sandbox instance's memory is cleared: the offline duration exceeds the offline validity period; the offline decryption key is attempted to be exported or tampered with; the hardware fingerprint of the sandbox instance does not match the hardware fingerprint bound to the offline policy.
[0093] For example, a developer applies for a 72-hour offline license, but still tries to access the code in the 73rd hour. The sandbox instance detects the offline timeout, automatically locks itself, clears all plaintext code in memory, and prompts the developer to re-authenticate.
[0094] For example, if an attacker copies the sandbox instance directory from the hard drive to another device and attempts to access it offline, the sandbox instance will be immediately locked and the key destroyed because the hardware fingerprint does not match (the CPU serial number, network card MAC address, and the fingerprint bound to the policy are inconsistent).
[0095] The sandbox instance is unlocked after the encrypted connection between the locked sandbox instance and the zero-trust security gateway is restored.
[0096] Once the device reconnects to the network, the sandbox instance automatically establishes an encrypted connection with the gateway. After authentication and policy synchronization are completed, the connection can be unlocked and normal use can resume.
[0097] The embodiments of the present invention achieve controllable security protection in offline scenarios, filling the security gap in traditional solutions where offline means loss of control.
[0098] An escape prevention mechanism for a sandbox provided in this embodiment of the invention may specifically include the following escape prevention components: (1) Intercepting the calling program. For example, the intercepting calling program is implemented based on eBPF technology and deployed in the network driver layer (XDP hook) and system call layer (tracepoint hook) of the Linux kernel. This program is used to intercept and audit all system calls of processes within the sandbox instance. When an abnormal system call sequence is detected (such as ptrace, process_vm_readv, etc., which are commonly used for process injection), the call is immediately blocked and reported.
[0099] (2) Namespace isolation. For example, sandbox instances achieve isolation through Linux namespace technology: Mountnamespace: isolates the file system view, and processes in the sandbox can only see files in the sandbox directory; PID namespace: isolates the process view, and processes in the sandbox cannot see other processes on the host machine; Net namespace: isolates the network view, and network traffic of processes in the sandbox can be controlled by independent rules. (3) Filter, which can be a seccomp filter. The filter is used to restrict the whitelist of system calls that processes within the sandbox instance can use. Taking the compiler process as an example, it only needs about 50 system calls such as read, write, open, close, mmap, munmap, and exit. The seccomp filter will reject any system calls that are not on the whitelist (such as kexec, reboot, and swapon).
[0100] (4) The process capability set stripper can be used to remove unauthorized operation capabilities of processes within a sandbox instance. Specifically, it will remove one or more of the following permissions: system management permissions; permissions to debug other processes; permissions to load kernel modules; network configuration permissions; and permissions to bypass file permission checks.
[0101] The self-protection process of the sandbox instance is triggered when any of the following conditions are met: The interceptor program detected an abnormal system call sequence (such as consecutive calls to ptrace and process_vm_writev). The namespace isolation detects cross-namespace access attempts (such as attempts to access / proc / 1 / root). The filter detects system calls not on the whitelist; The process capability set stripping program detected unauthorized operations (such as attempts to modify the system time). An attempt was detected to connect to a hardware debug interface (such as JTAG / SWD) or to attempt to dump physical memory.
[0102] Perform self-protection procedures, including at least one of the following: This invention, through the coordinated operation of multiple anti-escape mechanisms, achieves a defense-in-depth system of detection, response, and self-destruction, effectively preventing sandbox escape attacks.
[0103] like Figure 3 As shown, this disclosure provides a sandbox-based source code protection device, including: Module 301 is used to create a sandbox instance in the operating system kernel mode. The sandbox instance is used to isolate protected source code files. The sandbox instance is communicatively connected to the zero-trust security gateway. The interception and identification module 302 is used to intercept the first process performing read and write operations on the first source code file within the sandbox instance and to identify the identity of the first process. The transparent mode module 303 is used to set the working mode of the sandbox instance to transparent mode if the first process is included in the whitelist set of whitelist processes, receive the session key issued by the zero trust security gateway in the transparent mode, and use the session key to decrypt the first source code file encrypted on the disk into plaintext in the memory space of the sandbox instance, and allow the first process to perform read and write operations on the plaintext. The pollution mode module 304 is used to set the working mode of the sandbox instance to pollution mode if the first process is not a whitelisted process. In the pollution mode, a pollution-induced second source code is generated based on a copy of the first source code file, and the first process is allowed to perform read and write operations on the second source code. The second source code has at least additional tracing code compared to the first source code. The importance level of each function body in the first source code is determined by different pollution treatment methods. The receiving module 305 is used to receive tracking data returned based on the tracking code.
[0104] The sandbox-based source code protection device provided in this disclosure can be used to execute the sandbox-based source code protection method provided in any of the foregoing embodiments.
[0105] To achieve the above objectives, this disclosure also provides an electronic device, such as... Figure 4 As shown, the electronic device may include a processor 501 and a memory 503 connected to the processor 501 via a communication bus 502; wherein, the memory 503 is used for an executable program; the processor 501 can implement the sandbox-based source code protection method provided in any of the foregoing embodiments by executing the executable program.
[0106] Optionally, the processor 501 may be a general-purpose processor, a digital signal processor (DSP), an application-specific integrated circuit (ASIC), a field-programmable gate array (FPGA), or other programmable logic devices, discrete gate or transistor logic devices, or discrete hardware components. Here, the program executed by the processor 501 may be stored in a memory 503 connected to the processor 501 via a communication bus 502. The memory 503 may be volatile memory or non-volatile memory, or may include both. Non-volatile memory can be read-only memory (ROM), programmable read-only memory (PROM), erasable programmable read-only memory (EPROM), electrically erasable programmable read-only memory (EEPROM), ferromagnetic random access memory (FRAM), flash memory, magnetic surface memory, optical disc, or compact disc read-only memory (CD-ROM); magnetic surface memory can be disk storage or magnetic tape storage. Volatile memory can be random access memory (RAM), which is used as an external cache.By way of example, but not limitation, many forms of RAM are available, such as Static Random Access Memory (SRAM), Synchronous Static Random Access Memory (SSRAM), Dynamic Random Access Memory (DRAM), Synchronous Dynamic Random Access Memory (SDRAM), Double Data Rate Synchronous Dynamic Random Access Memory (DDRSDRAM), Enhanced Synchronous Dynamic Random Access Memory (ESDRAM), Sync Link Dynamic Random Access Memory (SLDRAM), and Direct Rambus Random Access Memory (DRRAM). The memory 503 described in this disclosure is intended to include, but is not limited to, these and any other suitable types of memory 503. The memory 503 in this disclosure is used to store various types of data to support the operation of the processor 501. Examples of this data include: any computer programs operated by the processor 501, such as operating systems and applications; contact data; phonebook data; messages; pictures; videos, etc. The operating system contains various system programs, such as the framework layer, core library layer, and driver layer, used to implement various basic business functions and handle hardware-based tasks.
[0107] In some embodiments, the memory 503 in this disclosure may be volatile memory or non-volatile memory, or may include both volatile and non-volatile memory. The non-volatile memory may be read-only memory (ROM), programmable read-only memory (PROM), erasable programmable read-only memory (EPROM), electrically erasable programmable read-only memory (EEPROM), or flash memory. The volatile memory may be random access memory (RAM), which serves as an external cache. By way of example, but not limitation, many forms of RAM are available, such as Static Random Access Memory (SRAM), Dynamic Random Access Memory (DRAM), Synchronous DRAM (SDRAM), Double Data Rate SDRAM (DDRSDRAM), Enhanced SDRAM (ESDRAM), Synchlink DRAM (SLDRAM), and Direct Rambus RAM (DRRAM). The memory 503 of the systems and methods described herein is intended to include, but is not limited to, these and any other suitable types of memory.
[0108] The processor 501 may be an integrated circuit chip with signal processing capabilities. In implementation, each step of the above method can be completed by the integrated logic circuitry in the hardware of the processor 501 or by instructions in software form. The processor 501 can be a general-purpose processor, a digital signal processor (DSP), an application-specific integrated circuit (ASIC), a field-programmable gate array (FPGA), or other programmable logic devices, discrete gate or transistor logic devices, or discrete hardware components. It can implement or execute the methods, steps, and logic block diagrams disclosed in this disclosure. The general-purpose processor can be a microprocessor or any conventional processor. The steps of the methods disclosed in this disclosure can be directly implemented by a hardware decoding processor, or implemented by a combination of hardware and software modules in the decoding processor. The software modules can be located in random access memory, flash memory, read-only memory, programmable read-only memory, electrically erasable programmable memory, registers, or other mature storage media in the art. This storage medium is located in memory 503, and the processor 501 reads the information in memory 503 and, in conjunction with its hardware, completes the steps of the above method. In some embodiments, the embodiments described herein can be implemented using hardware, software, firmware, middleware, microcode, or a combination thereof. For hardware implementation, the processing unit can be implemented in one or more application-specific integrated circuits (ASICs), digital signal processors (DSPs), digital signal processing devices (DSPDs), programmable logic devices (PLDs), field-programmable gate arrays (FPGAs), general-purpose processors, controllers, microcontrollers, microprocessors, other electronic units for performing the functions described herein, or combinations thereof.
[0109] For software implementation, the techniques described herein can be achieved through modules (e.g., procedures, functions, etc.) that perform the functions described herein. The software code can be stored in memory and executed by a processor. The memory can be implemented within the processor or externally.
[0110] Another embodiment of this disclosure provides a computer storage medium storing an executable program that, when executed by a processor 501, can implement the steps of a sandbox-based source code protection method applied to the computing device. For example, as... Figures 1-3 One or more of the methods shown.
[0111] In some embodiments, the computer storage medium may include various media capable of storing program code, such as a USB flash drive, a portable hard drive, a read-only memory (ROM), a random access memory (RAM), a magnetic disk, or an optical disk.
[0112] It should be noted that the technical solutions described in this disclosure can be combined arbitrarily as long as they do not conflict.
[0113] The above description is merely a preferred embodiment of this disclosure and is not intended to limit the scope of protection of this disclosure.
Claims
1. A sandbox-based source code protection method, characterized in that, include: A sandbox instance is created in the operating system kernel mode. The sandbox instance is used to isolate protected source code files. The sandbox instance communicates with the zero-trust security gateway. Intercept the first process that performs read / write operations on the first source code file within the sandbox instance and identify the identity of the first process: If the first process is a whitelist process included in the whitelist set, the working mode of the sandbox instance is set to transparent mode. In the transparent mode, the session key issued by the zero-trust security gateway is received, and the first source code file encrypted on the disk is decrypted into plaintext in the memory space of the sandbox instance using the session key, and the first process is allowed to perform read and write operations on the plaintext. If the first process is not a whitelisted process, the working mode of the sandbox instance is set to pollution mode. In pollution mode, a pollution-induced second source code is generated based on a copy of the first source code file, and the first process is allowed to perform read and write operations on the second source code. The second source code has at least additional tracing code compared to the first source code. The importance level of each function body in the first source code is determined by different pollution treatment methods. Receive tracking data returned based on the tracking code.
2. The method according to claim 1, characterized in that, The function body includes at least a first function body of the first level and a second function body of the second level; the method further includes: the degree of pollution under the pollution mode is positively correlated with the behavioral risk assessment score of the first process. When the behavioral risk assessment score is lower than the first threshold, redundant characters are inserted into the second function body in the first source code. When the behavioral risk assessment score is between the first threshold and the second threshold, the second function body is processed by inserting redundant characters or forged values, and the first function body is processed by obfuscation. When the behavioral risk assessment score is higher than the second threshold, the first function body is deleted and the second function body is completely obfuscated.
3. The method according to claim 2, characterized in that, The behavioral risk assessment score is calculated based on one or more of the following factors: the temporal modality data, spatial modality data, sequence modality data, relational modality data of the first process, the number of files accessed by the first process, and whether the command line parameters of the first process contain predetermined sensitive keywords.
4. The method according to claim 2, characterized in that, The importance level of each function body in the first source code is determined in the following way: The first source code is structurally analyzed based on the abstract syntax tree, control flow graph, and / or data dependency graph, and the function body parameters of each function body are extracted; the function body parameters include loop complexity, call depth, global variable dependency, cross-module application programming interface (API) exposure surface, and / or sensitive operation call chain. The results of the structural analysis and the function body parameters are input into a pre-trained code semantic understanding model, which outputs the semantic sensitivity score of each function body, wherein the semantic sensitivity score represents the degree of impact on the overall system security after the corresponding function body is leaked. Based on the semantic sensitivity scores, the function bodies are divided into a first-level first function body, a second-level second function body, and a third-level third function body; The importance levels of each function body in the first source code are determined using different pollution treatment methods, including: For the first function body, pseudocode generated by adversarial generative network is used to replace it. The pseudocode keeps the original function signature, interface contract and exception handling path unchanged, and the algorithm logic of the first function body is reconstructed to generate error output or leak preset honeypot data under specified input domain or boundary conditions. For the second function body, a control flow preservation and data flow injection obfuscation method is adopted. The forged value is dynamically generated based on the identity of the first process, so that the forged value received by different non-whitelisted processes is distinguishable. For the third function body, a method of inserting redundant characters and meaningless control flow branches is adopted.
5. The method according to any one of claims 1 to 3, characterized in that, The method further includes: Monitor the behavioral characteristics of each whitelisted process in the whitelist set and establish a normal behavior baseline for each process; When the behavior of the whitelisted process deviates from the baseline of normal behavior by more than a preset deviation threshold, the whitelisted process is marked as a suspicious process. For the suspicious process, perform at least one of the following actions: Temporarily remove the suspicious process from the whitelist set; Add an audit operation to the suspicious process, and respond to the suspicious process when the audit result corresponding to the audit operation is qualified; Send an alarm to the management console and wait for alarm confirmation; Once the behavior of a suspicious process returns to the normal behavior baseline and remains within a preset duration, the flag of the suspicious process is removed.
6. The method according to any one of claims 1 to 3, characterized in that, The sandbox instance supports both online and offline modes: In the online mode, the sandbox instance maintains an encrypted connection with the zero-trust security gateway. The encrypted connection is used to obtain a real-time updated whitelist set, session key, and control policy. The control policy includes at least an offline policy. In the offline mode, the sandbox instance runs independently in a network-free environment, based on the offline policy obtained in advance from the zero-trust security gateway. The offline policy includes at least one of the following: offline validity period, set of operation permissions, and offline decryption key. When any of the following conditions are detected, the sandbox instance is locked to prevent any read or write operations based on the sandbox instance, and the plaintext data in the sandbox instance's memory is cleared: The offline duration exceeds the stated offline validity period; The offline decryption key was attempted to be exported or tampered with; The hardware fingerprint of the sandbox instance does not match the hardware fingerprint bound to the offline policy; Once the encrypted connection between the locked sandbox instance and the zero-trust security gateway is restored, the sandbox instance is unlocked.
7. The method according to any one of claims 1 to 3, characterized in that, An anti-escape mechanism is deployed at the boundary of the sandbox instance. The anti-escape mechanism includes at least one of the following: intercepting the calling program, which is used to intercept and audit the system calls of the processes within the sandbox instance and block abnormal system calls; Namespace isolation is used to isolate the file system view, process view, and / or network view of processes within the sandbox instance, and to prohibit processes within the sandbox instance from accessing host resources. A filter is used to restrict the whitelist set of system calls that processes within the sandbox instance can use; a process capability set stripping procedure is used to restrict unauthorized operations by processes within the sandbox instance.
8. The method according to claim 7, characterized in that, The method further includes: The self-protection process of the sandbox instance is triggered when any of the following conditions are met: The intercepting program detected an abnormal system call sequence; The namespace isolation detected a cross-namespace access attempt; The filter detects system calls outside of whitelisted processes; The process capability set stripping procedure detected an unauthorized operation. An attempt was detected to connect to the hardware debug interface or to attempt to dump physical memory. The self-protection process includes at least one of the following: freezing all processes within the sandbox instance, clearing the memory pages associated with the sandbox instance, reporting an escape alarm to the zero-trust security gateway, and locking the sandbox instance; different self-protection processes correspond to different degrees of escape operations.
9. A sandbox-based source code protection device, characterized in that, include: A module is created to create sandbox instances in the operating system kernel mode, which are used to isolate protected source code files; The sandbox instance communicates with the zero-trust security gateway. The interception and identification module is used to intercept the first process performing read and write operations on the first source code file within the sandbox instance and to identify the identity of the first process. The transparent mode module is used to set the working mode of the sandbox instance to transparent mode if the first process is included in the whitelist set of whitelist processes. In the transparent mode, the first process receives the session key issued by the zero trust security gateway, and uses the session key to decrypt the first source code file encrypted on the disk into plaintext in the memory space of the sandbox instance, and allows the first process to perform read and write operations on the plaintext. The pollution mode module is used to set the working mode of the sandbox instance to pollution mode if the first process is not a whitelisted process. In the pollution mode, a pollution-induced second source code is generated based on a copy of the first source code file, and the first process is allowed to perform read and write operations on the second source code. The second source code has at least additional tracing code compared to the first source code. The importance level of each function body in the first source code adopts different pollution treatment methods. A receiving module is used to receive tracking data returned based on the tracking code.
10. A computer storage medium, characterized in that, The computer storage medium stores a computer program, characterized in that, when the computer program is executed by a processor, it implements the sandbox-based source code protection method according to any one of claims 1 to 8.