Python byte code obfuscation method and system based on dynamic screening and random replacement

Through dynamic screening and random replacement methods, security assessment and obfuscation are performed on Python bytecode files, which solves the problems of insufficient security and performance overhead in existing technologies and achieves efficient reverse protection and low-overhead obfuscation effects.

CN120805108AActive Publication Date: 2025-10-17UNIV OF SCI & TECH BEIJING

Patent Information

Application Number
CN202510862354.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-06-25
Publication Date
2025-10-17
Estimated Expiration
2045-06-25

AI Technical Summary

Technical Problem

Existing Python bytecode obfuscation techniques are not secure enough against advanced reverse engineering methods, and the obfuscation process may cause additional runtime overhead.

Method used

A method based on dynamic screening and random replacement is adopted. By calculating multiple security indicators of bytecode files, files with high security requirements are screened out, and a random opcode mapping table is constructed for dynamic replacement to generate obfuscated bytecode files. The obfuscated bytecode is executed using a custom interpreter.

Benefits of technology

It effectively prevents obfuscated bytecode from being decompiled, improves reverse engineering protection strength, reduces time overhead, keeps space overhead unchanged, and enhances security without affecting performance.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120805108A_ABST
    Figure CN120805108A_ABST
Patent Text Reader

Abstract

The invention provides a Python bytecode obfuscation method and system based on dynamic screening and random replacement, and the method comprises the steps: calculating a plurality of safety indexes and a comprehensive safety index SDI of bytecode files, and screening out the bytecode files which have high safety requirements and need to be obfuscated; a linear congruence generator is constructed, a pseudo-random number sequence is provided for obfuscation operation of byte codes, and operation code dynamic replacement obfuscation operation is performed in byte code instructions by generating random seeds, constructing random dynamic operation code mapping tables and applying the independent operation code mapping tables to different byte code files needing to be obfuscated; and performing obfuscation state detection on the obfuscated bytecode file, if the detection result is the obfuscated bytecode file, modifying bytecode analysis and instruction scheduling logic, increasing a runtime de-obfuscation process, embedding an Opcode reflection mechanism, re-compiling to generate a customized Python interpreter supporting the execution of the obfuscated bytecode, and executing the obfuscated bytecode file. According to the invention, byte codes can be confused.
Need to check novelty before this filing date? Find Prior Art

Description

TECHNICAL FIELD

[0001] The present application relates to the technical field of Python bytecode obfuscation, and particularly to a Python bytecode obfuscation method and system based on dynamic screening and random replacement. BACKGROUND

[0002] Python adopts an interpretive execution mechanism, and its code is usually distributed in the form of a.py file. At runtime, the interpreter compiles the program into a bytecode file in the.pyc or.pyo format. Although this pre-compilation mode improves execution efficiency, the direct distribution of unencrypted source code files poses a huge security risk. To address this problem, program publishers usually take protective measures such as code obfuscation techniques to improve the security of the code and prevent unauthorized users from using or tampering with it. Common code obfuscation techniques mainly include control flow transformation, instruction replacement, string encryption, variable and function renaming, and insertion of useless code.

[0003] To further improve the anti-reverse ability of the code, researchers have proposed opcode remapping technology. This technology maps each opcode in the bytecode to a custom opcode, so that the generated bytecode file contains unrecognized or unexpected instruction sequences for the standard Python interpreter, thereby preventing attackers from cracking the code structure using traditional decompilation tools. However, this technology has obvious limitations when faced with illegal personnel using difference comparison and frequency statistics techniques for reverse engineering. Since Python code has a certain statistical distribution of the frequency of use of different opcodes during execution, such as variable loading, storage, function calling, and other operations, which usually account for a high proportion, while control flow instructions are relatively few. Therefore, attackers can collect a large number of pre- and post-obfuscated bytecode samples, compare the frequency of different opcodes before and after obfuscation, and infer the replacement relationship to recover the original instruction set. Therefore, although the opcode replacement technology can improve the anti-reverse ability of Python code to some extent, its fixed mapping relationship makes it vulnerable to frequency analysis attacks, making it difficult to effectively resist advanced reverse engineering methods, and there is a clear security deficiency in Python code protection. Moreover, existing bytecode obfuscation techniques obfuscate all bytecode files, but the obfuscated code may incur additional runtime overhead. SUMMARY

[0004] To solve the technical problems existing in the prior art, the present application provides a Python bytecode obfuscation method and system based on dynamic screening and random replacement, and the technical solution is as follows: In one aspect, a Python bytecode obfuscation method based on dynamic screening and random replacement is provided, which comprises: S1, a plurality of security indicators of the bytecode file are calculated by extracting bytecode features, including: data sensitivity indicator DSI, business logic complexity indicator BLCI, static reversibility indicator SRI, dynamic attack exposure indicator DAEI and external attack surface indicator EASI, to quantitatively evaluate the security requirements of the bytecode file from multiple dimensions, and the comprehensive security index SDI of the bytecode file is calculated by entropy weight method, based on the comprehensive security index SDI, the bytecode file with high security requirement to be obfuscated is screened out according to the threshold set by the user; S2, a linear congruential generator is constructed to provide a pseudo-random number sequence for the obfuscation operation of the bytecode, a random dynamic opcode mapping table is constructed by generating a random seed, each independent opcode mapping table is applied to different bytecode files to be obfuscated, and opcode dynamic replacement obfuscation operation is performed in the bytecode instruction to generate an obfuscated bytecode file; S3, the obfuscated bytecode file is detected for obfuscation state, if the detection result is the obfuscated bytecode file, the bytecode parsing and instruction scheduling logic is modified, the runtime de-obfuscation process is increased, the Opcode reflection mechanism is embedded, the customized Python interpreter supporting the execution of the obfuscated bytecode is recompiled, and the obfuscated bytecode file is executed using the customized Python interpreter.

[0005] In another aspect, a Python bytecode obfuscation system based on dynamic screening and random replacement is provided, which comprises: The obfuscated file dynamic screening module is used to calculate a plurality of security indicators of the bytecode file by extracting bytecode features, including: data sensitivity indicator DSI, business logic complexity indicator BLCI, static reversibility indicator SRI, dynamic attack exposure indicator DAEI and external attack surface indicator EASI, to quantitatively evaluate the security requirements of the bytecode file from multiple dimensions, and the comprehensive security index SDI of the bytecode file is calculated by entropy weight method, based on the comprehensive security index SDI, the bytecode file with high security requirement to be obfuscated is screened out according to the threshold set by the user; The obfuscation module is used to construct a linear congruential generator to provide a pseudo-random number sequence for the obfuscation operation of the bytecode, a random dynamic opcode mapping table is constructed by generating a random seed, each independent opcode mapping table is applied to different bytecode files to be obfuscated, and opcode dynamic replacement obfuscation operation is performed in the bytecode instruction to generate an obfuscated bytecode file; A custom interpreter implementation module is configured to detect the obfuscated state of the obfuscated bytecode file, modify bytecode parsing and instruction scheduling logic, add a runtime de-obfuscation process, and embed an Opcode reflection mechanism if the detection result is an obfuscated bytecode file, recompile to generate a customized Python interpreter that supports the execution of obfuscated bytecode, and execute the obfuscated bytecode file using the customized Python interpreter.

[0006] In another aspect, an electronic device is provided, which includes a processor and a memory having at least one instruction stored therein, the at least one instruction being loaded and executed by the processor to implement the above-described Python bytecode obfuscation method based on dynamic screening and random replacement.

[0007] In another aspect, a computer-readable storage medium is provided, which has at least one instruction stored therein, the at least one instruction being loaded and executed by a processor to implement the above-described Python bytecode obfuscation method based on dynamic screening and random replacement.

[0008] The technical solutions provided by the present application have at least the following beneficial effects: 1) The present application screens before obfuscation and only obfuscates bytecode files with high security requirements, so that after obfuscation using the present application, the time overhead increases by 0.79%, and the space overhead remains unchanged, indicating that the present application does not introduce significant execution overhead.

[0009] 2) The present application can effectively prevent the obfuscated bytecode from being restored by existing decompilation tools, and improve the reverse protection strength of the code. The entropy value of the opcode frequency of the Python bytecode file processed by the present application is improved by 41.7% compared with the ordinary bytecode file, and the standard deviation value is decreased by 62%, which indicates that the present application solves the problem of easy speculation of opcode mapping relationship in the difference comparison and frequency statistical attack of traditional opcode remapping technology through the random replacement mode of the dynamic opcode mapping table, thereby enhancing the security of the bytecode.

[0010] 3) The average running time change rate of the custom interpreter of the present application is 3.04% compared with the standard Python interpreter (CPython), and the file size change rate is 0%, which indicates that the custom interpreter of the present application does not bring significant performance overhead without increasing the bytecode storage overhead. BRIEF DESCRIPTION OF DRAWINGS

[0011] In order to more clearly illustrate the technical solutions in the embodiments of the present application, the drawings needed in the embodiment description will be briefly introduced as follows. Obviously, the drawings in the following description are only some embodiments of the present application, and other drawings can be obtained by those skilled in the art without creative effort on the basis of these drawings.

[0012] Figure 1 is a Python bytecode obfuscation method flowchart based on dynamic screening and random replacement provided by the embodiments of the present application. Figure 2 is a general block diagram of a cross-modal outer ear region segmentation and key point positioning method provided by the embodiments of the present application. Figure 3 is a replacement rule schematic diagram of the operation code provided by the embodiments of the present application. Figure 4 is a classification obfuscation rule schematic diagram provided by the embodiments of the present application. Figure 5 is a mapping relationship schematic diagram of the initial mapping table of various operation codes provided by the embodiments of the present application. Figure 6 is a mapping relationship schematic diagram of the mapping table of various operation codes of the bytecode file 1 provided by the embodiments of the present application. Figure 7 is a mapping relationship schematic diagram of the mapping table of various operation codes of the bytecode file 2 provided by the embodiments of the present application. Figure 8 is a Python bytecode obfuscation system block diagram based on dynamic screening and random replacement provided by the embodiments of the present application. Figure 9 is a structure schematic diagram of an electronic device provided by the embodiments of the present application. DETAILED DESCRIPTION

[0013] In order to make the technical problems, technical solutions and advantages of the present application more clear, the following will be described in detail in combination with the drawings and specific embodiments.

[0014] The embodiments of the present application provide a Python bytecode obfuscation method based on dynamic screening and random replacement, which can be implemented by an electronic device, which can be a terminal or a server. Figure 1 is a method flowchart, Figure 2 is a general block diagram of the method, and the processing flow can include the following steps: S1, a plurality of security indicators of the bytecode file are calculated by extracting bytecode features, including: a data sensitivity indicator DSI, a business logic complexity indicator BLCI, a static reversibility indicator SRI, a dynamic attack exposure indicator DAEI, and an external attack surface indicator EASI, so as to quantitatively evaluate the security requirements of the bytecode file from multiple dimensions, and the comprehensive security index SDI of the bytecode file is calculated by the entropy weight method, based on the comprehensive security index SDI, the bytecode file with high security requirements that needs to be obfuscated is screened out according to the threshold set by the user; Considering that the obfuscated code may bring additional runtime overhead, the scheme proposed in the embodiment of the application introduces a dynamic decision mechanism for bytecode files before obfuscation. Specifically, the mechanism analyzes the data sensitivity indicator (Data Sensitivity Indicator, DSI), the business logic complexity indicator (Business Logic Complexity Indicator, BLCI), the static reversibility indicator (Static Reversibility Indicator, SRI), the dynamic attack exposure indicator (Dynamic Attack Exposure Indicator, DAEI), and the external attack surface indicator (External Attack Surface Indicator, EASI) based on the characteristics of Python bytecode files. These security evaluation indicators are used to quantitatively evaluate the security requirement index (Security Demand Index, SDI) of the bytecode file from multiple dimensions. On this basis, the mechanism also supports users to set an obfuscation threshold. When obfuscation is performed, the bytecode file that meets the high security requirement and needs to be obfuscated can be screened out according to the threshold set by the user. Then, the dynamic obfuscation strategy is applied to the screened files to realize automatic code obfuscation processing. Through this method, the code can improve security while minimizing the performance overhead caused by obfuscation, making the obfuscation scheme more efficient and feasible in practical applications.

[0015] Data security has become a key factor affecting system reliability and applicability. Research shows that security risks such as data leakage, unauthorized access, and malicious attacks are currently prevalent. To address these challenges, researchers have proposed a variety of security protection strategies, such as data encryption, access control, and data integrity verification. Among them, data sensitivity assessment is an important prerequisite for determining data protection strategies. Therefore, the embodiment of the present invention introduces a data sensitivity index (DSI) to measure the degree of sensitive data involved in the bytecode, and as an important component of the calculation of the comprehensive security index. By performing a quantitative assessment of the sensitive data in the bytecode, the DSI can effectively reflect the potential risks of the code in terms of data security, thereby providing a basis for the dynamic adjustment of security policies.

[0016] Optionally, the Data Sensitivity Index (DSI) is used to measure the extent of sensitive data in bytecode files. It quantitatively evaluates sensitive variables and constants in the code to identify potential security risks. During code execution, if sensitive data is leaked, it may cause serious security issues. Therefore, quantitative analysis of sensitive data helps to assess the security requirements of the code. The Data Sensitivity Index (DSI) considers the following key factors: 1) Occurrence of sensitive keywords: Calculate the frequency of sensitive keywords (such as password, secret, key, etc.) contained in the code. 2) Importance Weight of Sensitive Data: The significance of sensitive keywords is calculated using the term frequency-inverse document frequency (TF-IDF) method to measure their importance in the code. A high TF-IDF value indicates a high influence of the sensitive keyword in the current code snippet, and therefore this code segment requires more stringent security protection. 3) Sensitive Data Propagation Risk: We use the Markov prediction model to calculate the flow of sensitive data within the code execution path and further assess the probability of sensitive information leakage during variable transfer. We traverse a sequence of string constants and record the directed transition relationships between adjacent sensitive keywords. Specifically, we construct a count matrix C by counting the number of transitions between sensitive keywords and then normalize this by row to obtain a Markov transition probability matrix P, which reflects the probability of continuous exposure of sensitive information within the program execution path. The calculation formula of the data sensitivity index DSI is as follows:

[0017] in C i For the i The number of occurrences of sensitive keywords is n ; TFIDF(Ci ) For the weight of sensitive data calculated based on term frequency (TF) and inverse document frequency (IDF), TF reflects the frequency of a certain keyword in the code, and IDF measures the uniqueness of the keyword in the entire code base, and a high TF-IDF value means that the keyword has high importance in the current code segment; P ij The conditional probability of transferring from the keyword i to the keyword j ; The calculation formula combines the static feature analysis of TF-IDF calculation and the dynamic propagation modeling of Markov prediction to comprehensively measure the sensitive data risk in the code; The higher the DSI value, the more sensitive data involved in the code, and the longer the propagation chain of the data in the code execution, which means that the code has higher security requirements; if the DSI value is low, it means that the code involves less sensitive data, or the sensitive data is only used in a local range, which means that the security requirement is relatively low.

[0018] According to the research of McCabe, the core idea of the complexity metric is to calculate the number of control paths of the code, and the logical complexity of the code is calculated by analyzing the number of edges, nodes and connected components of the control flow graph, but this idea assumes that the execution probability of all paths is the same, and does not consider the unevenness of the execution path. Based on the idea of McCabe complexity metric, the embodiment of the present application further proposes a business logic complexity indicator for measuring the business logic complexity of the code, so as to make up for the deficiency of the McCabe complexity metric method in the evaluation of business logic, so as to more accurately reflect the complexity of the code execution path and its security requirements.

[0019] Optionally, the business logic complexity indicator BLCI is used to measure the business logic complexity of the bytecode, and the complexity of the code structure is calculated based on the control flow graph, and the following multiple key factors affecting the business logic complexity are comprehensively considered: 1) Control flow complexity: calculate the number of branches and loop depth of the code execution path, which is used to measure the complexity of the code structure; 2) Path entropy: used to measure the uniformity of the program execution path, reflecting the control flow complexity and predictability of the code. The program first enumerates all simple paths without repeated nodes from the starting node (number 0) to the terminating node (i.e. the last instruction) based on the control flow graph cfg; then the length of each path is counted, and all path lengths are normalized as a probability distribution. It is considered that the longer the path, the higher the probability of being executed, and the path entropy H The calculation formula is as follows:

[0020] wherein l i is the first i the length of the path; the sum of all path lengths for normalization; is considered the execution probability of the first i If the length of each path is about the same, the normalized probability distribution is relatively uniform, and the path entropy is high; if only a few paths are particularly long and the others are short, the distribution is not uniform, and the path entropy is low. The number of independent entry points: multiple execution entry points of the code are detected, and multiple entry points can lead to more complex execution logic and increase potential security risks. The calculation formula of the business logic complexity indicator BLCI is as follows:

[0021] wherein E Edges is the number of edges in the control flow graph, representing the number of branches and jumps of the code execution path; N Nodes is the number of nodes in the control flow graph, representing the number of basic blocks of the code; P is the number of independent entries in the control flow graph, used to measure whether the code has multiple execution starting points; H is the path entropy, used to measure whether the different execution paths of the code are uniformly distributed, and a high path entropy indicates that the execution path is uniform. Compared with the McCabe complexity, the BLCI of the embodiment of the application adds the calculation of the path entropy H , which can better reflect the complexity of the business logic.

[0022] The BLCI not only measures the code structure, but also considers the execution path distribution, making it more suitable for business logic complexity evaluation under modern software architecture. The higher the BLCI value is, the higher the business logic complexity contained in the code is, which means that the code contains more core business logic. Since the core business logic directly affects the functionality and security of the system, in actual application, attackers will prefer to crack or reverse analyze these high-BLCI codes to obtain key algorithms, bypass security verification, or tamper with system logic. Therefore, the higher the BLCI value of the bytecode file is, the higher the security requirement is, and the code with low BLCI value usually does not involve core business logic, so its value is low, and the security requirement is also low.

[0023] Collberg et al. proposed the concept of resilience, which focuses on the resistance of code to anti-tampering techniques. However, this concept does not provide a specific quantitative method for the impact of variable naming on program reversibility. During static analysis, variable names often carry rich semantic information. Intuitive variable naming can help analysis tools and attackers quickly understand program logic, while obfuscated variable naming can significantly increase the readability of code and increase the difficulty of reverse engineering. Therefore, the embodiment of the present application proposes a static reversibility index to quantify the security of variable naming in code and assess whether an attacker can easily infer program logic from variable names.

[0024] Optionally, the static reversibility index SRI is used to measure the difficulty of restoring the bytecode file to the original code through static analysis without or with low obfuscation. Code elements: variable names carry rich semantic information. If these elements are not effectively obfuscated, attackers can easily deduce the logic of the code through semantic information, thereby accelerating the reverse engineering process. Therefore, the SRI index quantifies the static solvability of the code by analyzing the readability of the elements in the code, providing an assessment of the security of the variable naming method of the code. The SRI measures the following aspects: 1) By analyzing the entropy value of the variable name in the program, the difficulty of identifying and restoring it in static analysis is measured. Specifically, all variable names (i.e., identifiers appearing in LOAD_NAME and STORE_NAME instructions) are extracted, the Shannon entropy of character distribution is calculated for each variable name to represent its naming complexity and unpredictability, and finally the average value of all variable name entropy values is taken as the SRI index. The higher the average value, the more random the variable name, the more difficult it is to infer, and the more difficult the static reverse is. 2) Total number of instructions: used for normalization calculation to ensure that this index is applicable to bytecode files of different sizes. The calculation formula of the static reversibility index SRI is as follows:

[0025] Wherein, Unobfuscated Element Count represents the number of variable names without obfuscation, which has strong semantic information, making it possible to infer the logical structure of the program through static analysis. Total Instruction CountThe total number of instructions in the bytecode file is represented, the character entropy of the variable name is taken as a measure of the confusion strength, an entropy threshold is set to distinguish between confused and unconfused variable names, and if the entropy value of a variable name is lower than the threshold, it indicates that the naming rule is strong and the readability is high, and it is considered to be an unconfused element. Finally, the ratio of the number of unconfused elements to the total number of instructions is taken as the static reversibility index SRI to measure the reversibility of the program under static analysis. The SRI reflects the static reversibility of the code, determines the parsing difficulty of the code under the static analysis tool, and further affects the security requirements of the code: a high SRI value indicates that the code still contains a large number of unconfused variable names and constant information, which can be used by attackers to quickly speculate the core function and business logic of the code, thereby speeding up the reverse engineering process, so the security requirement is high; a low SRI value indicates that the variable names and constant information in the code have been highly confused, and there are few recognizable elements that are not confused, and the readability of the code is low, so the security requirement is low.

[0026] In current software security research, dynamic analysis has become an important means for attackers to perform reverse engineering and vulnerability mining. Attackers can extract the execution path and key data of the program and bypass the protection of static obfuscation through tools or techniques such as debuggers, dynamic instrumentation, and memory monitoring. Therefore, the embodiment of the present application proposes a dynamic attack exposure index to quantify the degree to which the code is exposed to dynamic analysis at runtime.

[0027] Optionally, the dynamic attack exposure index DAEI is used to measure the degree to which the code is exposed to dynamic analysis tools (such as debuggers, dynamic instrumentation, and injection attacks) at runtime. In actual attack processes, attackers can use debugging tools, dynamic execution environments, or instrumentation techniques to analyze the running trajectory of the program, function call relationships, and dynamically loaded code segments, thereby bypassing the protection of static obfuscation techniques. Therefore, DAEI analyzes the important information that the code may expose during dynamic execution, including: 1) Function call risk: statistics of explicit function calls (such as CALL_FUNCTION, CALL_METHOD, LOAD_GLOBAL) in bytecode, which can be used to analyze the core logic of the program; 2) Dynamic execution risk: evaluation of instructions related to dynamic execution (such as EXEC_STMT, EVAL_CODE) in bytecode, which allows the program to generate and execute new code at runtime and is the focus of attackers; 3) Code execution depth: analysis of the complexity of the execution path to simulate potential dynamic attack paths to determine the dynamic analysis difficulty of the code; The calculation formula of the dynamic attack exposure index DAEI is as follows:

[0028] wherein Exposure Operations Count is the number of instructions in the instruction set that involve dynamic analysis; Total Operations Count is the total number of instructions in the bytecode file, used for normalization calculation, so that DAEI can be applied to code files of different scales; The calculation formula effectively measures the degree of dynamic attack exposure of the code by calculating the proportion of dynamic analysis related instructions in all instructions; The DAEI reflects the exposure degree of the code at runtime, determines the difficulty of parsing the code under dynamic analysis tools, and further affects the security requirements of the code: a high DAEI value indicates that the code contains a large number of dynamic execution related instructions, and since there are many dynamic exposure points, attackers can more easily use runtime analysis techniques to monitor critical execution paths, thereby speeding up the reverse engineering process, so the security requirement is high; a low DAEI value indicates that the code relies less on dynamic execution, function calls are limited, and the exposure degree of the code logic is low, so the security requirement is low.

[0029] In recent years, the attack surface of software systems has become an important indicator of security. Manadhata et al. proposed a systematic attack surface measurement method. This method assesses the exposure of the system based on method calls, data interactions, and channel connections. The core idea is that the larger the attack surface, the higher the security risk the system faces. Therefore, the attack surface measurement method is of great significance for evaluating software security. However, traditional attack surface measurement mainly focuses on the overall system interaction, and lacks fine-grained analysis of the specific impact of external system interaction. Therefore, the embodiment of the present application proposes an external attack surface index (EASI) to quantify the interaction risk of code and external environment, helping to evaluate the potential external threats faced by the code.

[0030] Optionally, the external attack surface index EASI is used to measure the degree of code interaction with external systems. External system interaction is a way for attackers to exploit vulnerabilities, perform unauthorized access, or perform code injection. Therefore, EASI assesses the size of the attack surface that the code may face by analyzing the interaction mode of the code and the external environment. The EASI assesses the exposure risk of the program to external systems from the following aspects: 1) External API call frequency: count the number of calls to external interaction APIs (such as socket, open, requests, etc.) in the program. These operations involve network communication, file reading and writing, or remote requests, increasing the likelihood of being attacked. 2) External dependency: the analysis of the code's dependence on third-party libraries or system APIs. If there is a known vulnerability in the external dependency, it can be exploited by attackers as an entry point; 3) API call structure analysis: use PageRank algorithm to model the calling relationship between APIs, identify key interfaces and potential attack paths; By integrating these information, EASI quantifies the interaction intensity of external APIs, evaluates the connection degree of the code and external systems, and provides quantitative basis for judging the attack surface size and security protection needs of the program; The calculation formula of the external attack surface indicator EASI is as follows:

[0031] Among them F i The first i Risk factor or weight value of the external API calling point or external dependency in the attack surface; n For different categories of external API calling types, EASI builds a calling graph of sensitive APIs and uses PageRank algorithm to evaluate the importance of each API node, and finally the influence F i Add up all the nodes to form the total value of the attack surface; The EASI directly reflects the external interaction degree of the code, determines the exposure degree of the code on the external attack surface, and further affects the security needs of the code: a high EASI value indicates that the code interacts frequently with external systems, which means that the code has multiple attack entrances, and attackers can use network communication interfaces, file operations, and external dependency vulnerabilities to launch attacks, increasing the security risk of the system, so the security needs are high; a low EASI value indicates that the code is mostly internally executed, with few external interaction points, making it difficult for attackers to attack through network, file or external library, indicating that the code is relatively secure, so the security needs are low.

[0032] The above indicators evaluate the potential risks of the code in terms of security from different dimensions. However, it is difficult to comprehensively measure the overall security needs of the bytecode file using a single indicator. Therefore, it is necessary to comprehensively calculate the above indicators to build a measurement standard that comprehensively reflects the security of the code. In view of this, the embodiment of the present application proposes a comprehensive security index (Security Demand Index, SDI) to measure the overall security demand level of the code under multi-dimensional security evaluation.

[0033] When calculating the comprehensive security index, each indicator affects overall security to varying degrees, so it's necessary to rationally determine the weights of each indicator. To ensure objectivity, automation, and adaptability in assigning weights to each indicator, the present invention employs an entropy weighting method to calculate the weights corresponding to each indicator. This eliminates computational biases that may arise from subjective weighting and ensures consistency across different bytecode files, thereby adapting the security index calculation to different bytecode files.

[0034] The entropy weight method is an objective weighting method based on information entropy. Its core idea is as follows: If the data difference of an indicator is greater, it means that the amount of information contained in the indicator is greater, and the impact on the comprehensive evaluation is greater, and it should be given a higher weight; If an indicator has little variation across all bytecode files, it means that the indicator has low discrimination for the overall security requirements assessment and its weight should be lower.

[0035] Optionally, the calculation of the comprehensive security index SDI of the bytecode file by the entropy weight method in S1 specifically includes: S11. Data preprocessing Normalize the DSI, BLCI, SRI, DAEI, and EASI values ​​to ensure a consistent range of values; S12. Calculate information entropy Calculate the variability of each security indicator in different bytecode files and calculate the information entropy H j :

[0036] in q ij For the i The bytecode file is in j Normalized value of each indicator; is the standardization coefficient to ensure that the entropy value is within a reasonable range; S13. Calculate weight Calculate the weights corresponding to each indicator according to the entropy weight method w j :

[0037] in H j For the j The information entropy of the indicator, m Is the total number of indicators. If the information entropy of an indicator is small, it means that it contributes more to the overall uncertainty, that is, it contains more useful information, so its weight will be higher; S14, calculate the comprehensive security index SDI: 。

[0038] The security evaluation of bytecode is affected by various factors. For example, in the embodiment of the present application, data sensitivity mainly affects the risk of data leakage; business logic complexity affects the readability and reverse difficulty of the code; static reversibility affects the ease of analysis of static analysis of the code; dynamic attack exposure affects the exposure degree of the code when facing dynamic attack means; and external attack surface affects the dependence degree of the code on external systems and the size of the attack surface. The influence degree of these indicators varies with different program sets. The entropy weight method can automatically measure the discrimination degree of each indicator, ensure the rationality of weight distribution, avoid the influence of artificial subjective weight assignment, and be suitable for code analysis of different scales and improve the automation and adaptability of calculation.

[0039] To sum up, the comprehensive security index (SDI) calculation method proposed in the embodiment of the present application objectively measures the overall security demand of the code under multi-dimensional security evaluation. Compared with the evaluation method using only a single indicator, SDI combines data sensitivity, business logic complexity, static reversibility, dynamic attack exposure and external attack surface, and effectively quantifies the security risk of bytecode files as a whole. In addition, the introduction of the entropy weight method ensures the objectivity, automation and adaptability of weight distribution, effectively avoids the subjective bias of artificial weight assignment, and improves the applicability of the comprehensive evaluation index in different code scenarios. This method not only provides more accurate security evaluation results, but also provides a quantitative basis for the selection of code obfuscation, and provides strong support for improving the security and anti-reverse ability of the code.

[0040] S2, a linear congruential generator is constructed to provide a pseudo-random number sequence for the obfuscation operation of the bytecode, a random seed is generated, a random dynamic operation code mapping table is constructed, and each independent operation code mapping table is applied to different bytecode files to be obfuscated, and an operation code dynamic replacement obfuscation operation is performed in the bytecode instruction to generate an obfuscated bytecode file; Optionally, the random dynamic operation code mapping table in S2 is constructed, and specifically includes: In the Python 3.9.6 version, the replacement rule of the operation code is as shown in Figure 3 Therefore, the operation code replacement rule designed in the embodiment of the present application is: The classification of the operation codes that can be replaced is as follows: Category 1: no parameter operation code, operation code value < 90; Category 2: low-bit parameter operation code, 90 <= operation code value <= 130; Category 3: high-bit parameter operation code, 145 <= operation code value <= 165; The operation codes can be randomly replaced within the respective categories, but the replaced operation codes still need to maintain the original category numbering order to ensure that the Python interpreter can correctly handle the parameters and execute the logic of the instructions when parsing, as shown in Figure 4 ; Based on the operation code replacement rules, the operation code values in different bytecode files are replaced through a dynamic operation code mapping table, and the specific scheme is as follows: S21, according to the operation code replacement rules, the operation code values of different categories are extracted and defined as sets O1, O2, O3, O1: [1, 2, 3, 4, 5, 6,..., 87, 89]; O2: [90, 91, 92, 93, 94, 95,..., 126, 130]; O3: [145, 146, 147, 148, 154, 155,..., 164, 165], get the initial operation code mapping table of each category, the mapping relationship is as shown in Figure 5 ; S22, for bytecode file 1, in each category, randomly rearrange the operation codes to form new O1, O2, O3, O1: [1, 11, 12, 17, 86, 49,..., 22, 67], O2: [106, 125, 111, 94, 90, 93,..., 109, 117], O3: [160, 154, 147, 157, 164, 146,..., 148, 156], get the operation code mapping table of each category of bytecode file 1, the mapping relationship is as shown in Figure 6 ; S23, in the same way, independently map the operation codes of bytecode file 2 to generate different O1, O2, O3, O1: [77, 67, 74, 4, 26, 6,..., 51, 15], O2: [111, 114, 125, 126, 100, 107,..., 106, 118], O3: [164, 157, 163, 155, 147, 146,..., 162, 154], get the operation code mapping table of each category of bytecode file 2, the mapping relationship is as shown in Figure 7 ; S24, for other bytecode files, repeat the above process, generate independent operation code mapping table for each bytecode file, ensure that the replacement strategy of different files is independent of each other.

[0041] Then, according to the corresponding operation code mapping relationship generated for each bytecode file, that is, through the operation code replacement confusion generated by the dynamic mapping table, the operation code value in the original bytecode file is converted into the corresponding confused operation code, and the dynamic replacement process of the bytecode is completed.

[0042] In summary, the operation code random replacement scheme based on the dynamic mapping table proposed in the embodiment of the application generates an operation code mapping rule for each bytecode file on the basis of following different categories of operation code replacement rules, ensures that the replacement strategies of different bytecode files are independent of each other, and further enhances the confusion effect.

[0043] S3, the confused bytecode file is detected for a confusion state, if the detection result is a confused bytecode file, the bytecode parsing and instruction scheduling logic is modified, the runtime deconfusion process is increased, the Opcode remapping mechanism is embedded, the customized Python interpreter supporting the execution of the confused bytecode is recompiled and generated, and the customized Python interpreter is used to execute the confused bytecode file.

[0044] The code.h file of the standard Python interpreter is a header file for defining data structures, constants, flag bits and function declarations related to bytecode and code objects (PyCodeObject), therefore, the embodiment of the application defines a macro CO_MAPPED in the file and assigns a specific bit value to it as a detection identifier of the confused bytecode file.

[0045] When the Python interpreter runs, the bytecode in the.pyc file is loaded, and the marshal.c file is responsible for deserializing and converting the bytecode into a PyCodeObject object. That is, the file provides a direct interaction interface with the bytecode and is mainly responsible for the serialization and deserialization of the bytecode. In the marshal.c analysis stage, the customized interpreter implemented by the application introduces an intelligent identification strategy based on the co_flags marking mechanism. When analyzing the header of the.pyc file, the interpreter checks whether the co_flags contains the CO_MAPPED mark to determine whether the file has been subjected to operation code confusion, so as to automatically distinguish between confused files and ordinary files.

[0046] If the custom interpreter detects the confusion mark, the parser will enter the dynamic seed acquisition stage, and the embodiment of the application has made deep modifications to the ceval.c file to enhance its adaptability: a seed synchronization mechanism of a remote trusted server is introduced, and the interpreter can automatically request a random seed consistent with the confusion of the file from the remote server after analyzing the.pyc file.

[0047] The embodiment of the present application uses the seed consistent with the obfuscated file obtained above, combines a linear congruential generator (LCG) and a Fisher-Yates shuffle algorithm to generate an opcode mapping table, ensures that the same.pyc file can still recover a consistent instruction set in different environments, and avoids the problem of inconsistent parsing.

[0048] The custom interpreter of the embodiment of the present application performs byte-by-byte scanning on the co_code byte sequence, and converts the bytecode object code into a PyBytesObject type so as to directly access the bytecode content (ob_sval) and the bytecode size (ob_base.ob_size), then the interpreter traverses the bytecode array and extracts each opcode in sequence, and then uses a recovery function to recover the obfuscated opcode, which ensures that the obfuscated opcode can be correctly restored and executed according to the original logic by modifying the parsing logic of the bytecode, thereby maintaining the function and execution order of the program, and all instructions have been restored to a state that can be correctly parsed by the interpreter before the.pyc file is formally loaded into the Python running environment.

[0049] Then, a recompilation process of the CPython source code is performed, thereby generating a customized interpreter, and the obfuscated bytecode file is executed using the customized Python interpreter, specifically, a compilation environment can be configured using a. / configure command to check the related settings of the system environment and ensure that the source code of the software can be successfully compiled on the current system; the source code is compiled in parallel using a sudo make -j 10 command using 10 CPU cores to speed up the compilation process; and the compiled program is installed into the system using a sudo make altinstall command, and altinstall is an alternative installation method, which is usually used to avoid covering the system's own version.

[0050] As shown in Figure 8 The embodiment of the present application also provides a Python bytecode obfuscation system based on dynamic screening and random replacement, which comprises: The obfuscated file dynamic screening module is used to calculate a plurality of security indexes of the bytecode file by extracting bytecode features, including a data sensitivity index DSI, a business logic complexity index BLCI, a static reversibility index SRI, a dynamic attack exposure index DAEI and an external attack surface index EASI, so as to quantitatively evaluate the security requirements of the bytecode file from multiple dimensions, and calculate a comprehensive security index SDI of the bytecode file through an entropy weight method, and based on the comprehensive security index SDI, the bytecode file with high security requirements that needs to be obfuscated is screened out according to a threshold set by a user; The obfuscation module is configured to construct a linear congruential generator to provide a pseudo-random number sequence for the obfuscation operation of the bytecode, to generate a random seed, to construct a random dynamic opcode mapping table, to apply each independent opcode mapping table to different bytecode files to be obfuscated, and to perform a dynamic opcode replacement obfuscation operation in the bytecode instructions to generate an obfuscated bytecode file. The custom interpreter implementation module is configured to detect the obfuscated state of the obfuscated bytecode file, to modify bytecode parsing and instruction scheduling logic if the detection result is an obfuscated bytecode file, to increase a runtime de-obfuscation process, to embed an Opcode reflection mechanism, to recompile a customized Python interpreter supporting the execution of the obfuscated bytecode, and to execute the obfuscated bytecode file using the customized Python interpreter.

[0051] The Python bytecode obfuscation system based on dynamic screening and random replacement provided by the embodiment of the present application has a function structure corresponding to the Python bytecode obfuscation method based on dynamic screening and random replacement provided by the embodiment of the present application, and will not be described here.

[0052] Figure 9 The electronic device 900 provided by the embodiment of the present application has a structure as shown in FIG. 9, and can include one or more processors (central processing units, CPUs) 901 and one or more memories 902, wherein the memory 902 stores at least one instruction, the at least one instruction is loaded and executed by the processor 901 to implement the steps of the Python bytecode obfuscation method based on dynamic screening and random replacement.

[0053] In the exemplary embodiment, a computer readable storage medium, such as a memory including instructions, is also provided, and the instructions can be executed by a processor in a terminal to complete the Python bytecode obfuscation method based on dynamic screening and random replacement. For example, the computer readable storage medium can be a ROM, a random access memory (RAM), a CD-ROM, a magnetic tape, a floppy disk, an optical data storage device, etc.

[0054] Those skilled in the art can understand that all or part of the steps of the above-mentioned embodiments can be completed by hardware, or can be instructed by a program to complete related hardware, and the program can be stored in a computer readable storage medium, and the storage medium mentioned above can be a read-only memory, a magnetic disk or an optical disk, etc.

[0055] The above merely illustrates the preferred embodiments of the present application, and is not used to limit the present application, and any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present application shall be included in the protection scope of the present application.

Claims

1. A Python bytecode obfuscation method based on dynamic screening and random replacement, characterized in that: The method comprises: S1. Calculate multiple security indicators of bytecode files by extracting bytecode features, including: data sensitivity index DSI, business logic complexity index BLCI, static reversibility index SRI, dynamic attack exposure index DAEI, and external attack surface index EASI, to quantitatively evaluate the security requirements of bytecode files from multiple dimensions, and calculate the comprehensive security index SDI of bytecode files using the entropy weight method. Based on the comprehensive security index SDI, filter out bytecode files that require obfuscation with high security requirements according to the threshold set by the user; S2. Construct a linear congruential generator to provide a pseudo-random number sequence for bytecode obfuscation operations. By generating a random seed, a random dynamic opcode mapping table is constructed. Independent opcode mapping tables are applied to different bytecode files to be obfuscated. Dynamic opcode substitution obfuscation operations are performed in bytecode instructions to generate obfuscated bytecode files. S3. Perform an obfuscation status check on the obfuscated bytecode file. If the check result indicates an obfuscated bytecode file, modify the bytecode parsing and instruction scheduling logic, add a runtime deobfuscation process, embed an Opcode demapping mechanism, recompile and generate a customized Python interpreter that supports obfuscated bytecode execution, and use the customized Python interpreter to execute the obfuscated bytecode file.

2. The method according to claim 1, characterized in that The Data Sensitivity Index (DSI) measures the extent of sensitive data in bytecode files. It quantitatively evaluates sensitive variables and constants in the code to identify potential security risks. Leakage of sensitive data during code execution can lead to serious security issues. Therefore, quantitative analysis helps assess code security requirements. The DSI considers the following key factors: 1) Number of occurrences of sensitive keywords: Calculate the number of occurrences of sensitive keywords by counting the frequency of sensitive keywords contained in the code; 2) Importance Weight of Sensitive Data: The significance of sensitive keywords is calculated using the term frequency-inverse document frequency (TF-IDF) method to measure their importance in the code. A high TF-IDF value indicates a high influence of the sensitive keyword in the current code snippet, and therefore this code segment requires more stringent security protection. 3) Sensitive Data Propagation Risk: We use the Markov prediction model to calculate the flow of sensitive data within the code execution path and further assess the probability of sensitive information leakage during variable transfer. We traverse a sequence of string constants and record the directed transition relationships between adjacent sensitive keywords. Specifically, we construct a count matrix C by counting the number of transitions between sensitive keywords and then normalize this by row to obtain a Markov transition probability matrix P, which reflects the probability of continuous exposure of sensitive information within the program execution path. The calculation formula of the data sensitivity index DSI is as follows: in C i For the i The number of occurrences of sensitive keywords is n ; TFIDF(C i ) The weight of sensitive data is calculated based on term frequency (TF) and inverse document frequency (IDF). TF reflects the frequency of a keyword in the code, while IDF measures the uniqueness of the keyword in the entire code base. A high TF-IDF value means that the keyword is highly important in the current code snippet. P ij Indicates from keywords i Move to keywords j The conditional probability of The calculation formula combines static feature analysis of TF-IDF calculation and dynamic propagation modeling of Markov prediction to comprehensively measure the risk of sensitive data in the code; A higher DSI value indicates that a certain code segment involves more sensitive data and a longer data propagation chain during code execution, which means that the security requirements for this code segment are higher. A lower DSI value indicates that the code involves less sensitive data, or that sensitive data is only used in a local area, which indicates that the security requirements are relatively low.

3. The method according to claim 1, characterized in that The Business Logic Complexity Index (BLCI) is used to measure the complexity of business logic in bytecode. It calculates the complexity of the code structure based on the control flow graph and comprehensively considers the following key factors that affect the complexity of business logic: 1) Control flow complexity: Calculates the number of branches and loop depth in the code execution path to measure the complexity of the code structure; 2) Path entropy: It is used to measure the distribution uniformity of program execution paths and reflect the control flow complexity and predictability of the code. The program first enumerates all simple paths from the start node to the end node without repeated nodes based on the control flow graph cfg; then counts the length of each path and normalizes all path lengths into a probability distribution. It is believed that the longer the path, the higher the probability of its execution. The path entropy H The calculation formula is as follows: in l i For the i The length of each path; the sum of the lengths of all paths Used for normalization; Considered as the i The execution probability of each path is similar. If the length of each path is similar, then the normalized probability distribution is more uniform and the path entropy is high. If only a few paths are particularly long and the rest are short, then the distribution is uneven and the path entropy is low; Number of independent entry points: This function detects multiple execution entry points of the code. Multiple entry points may lead to more complex execution logic and increase potential security risks. The calculation formula of the business logic complexity index BLCI is as follows: in E is the number of edges in the control flow graph, which indicates the number of branches and jumps in the code execution path; N Nodes is the number of nodes in the control flow graph, indicating the number of basic blocks of code; P The number of independent entries in the control flow graph, used to measure whether the code has multiple execution starting points; H Path entropy is used to measure whether different execution paths of the code are evenly distributed. A high path entropy indicates that the execution path is evenly distributed. The BLCI not only measures the code structure but also considers the execution path distribution, making it more suitable for evaluating business logic complexity in modern software architectures. The higher the BLCI value, the more complex the business logic contained in a certain code segment, which means that this code segment contains more core business logic. Since the core business logic directly affects the functionality and security of the system, in actual applications, attackers will be more inclined to crack or reverse analyze these high BLCI codes to obtain key algorithms, bypass security verification, or tamper with system logic. Therefore, the higher the BLCI value of the bytecode file, the higher its security requirements. Code with a low BLCI value often does not involve core business logic, its value is low, and therefore the security requirements are also low.

4. The method according to claim 1, wherein The Static Reversibility Index (SRI) measures the difficulty of restoring a bytecode file to its original code through static analysis when it is unobfuscated or poorly obfuscated. Code elements, such as variable names, carry rich semantic information. If these elements are not effectively obfuscated, attackers can easily deduce the code's logic through this semantic information, thereby accelerating the reverse engineering process. Therefore, the SRI metric quantifies the static parsability of the code by analyzing the readability of elements in the code, providing an assessment of the security of the code variable naming method. The SRI measures the following aspects: 1) By analyzing the entropy of variable names in the program, we can measure the difficulty of identifying and restoring them in static analysis. Specifically, we extract all variable names, calculate the Shannon entropy of the character distribution for each variable name, and express its naming complexity and unpredictability. Finally, we take the average of all variable name entropy values ​​as the SRI index. The higher the average value, the more random the variable name is and the harder it is to predict, which means the static reverse engineering is more difficult. 2) Total number of instructions: used for normalization calculations to ensure that this metric is applicable to bytecode files of different sizes; The calculation formula of the static reversibility index SRI is as follows: in, Unobfuscated Element Count Indicates the number of unobfuscated variable names, which has strong semantic information and enables static analysis to infer the logical structure of the program; Total Instruction Count It represents the total number of instructions in the bytecode file. The character entropy of the variable name is used as the basis for measuring the obfuscation strength. An entropy threshold is set to distinguish obfuscated and unobfuscated variable names. If the entropy value of a variable name is lower than the threshold, it means that the naming is regular and readable, and it is considered to be an unobfuscated element. Finally, the ratio of the number of unobfuscated elements to the total number of instructions is used as the static reversibility index (SRI) to measure the reversibility of the program under static analysis. The SRI reflects the static reversibility of the code, determines the difficulty of parsing the code using static analysis tools, and further affects the security requirements of the code: a high SRI value indicates that the code still contains a large amount of unobfuscated variable names and constant information. Attackers can use this information to quickly infer the core functions and business logic of the code, thereby accelerating the reverse engineering process, so the security requirements are high; a low SRI value indicates that the variable names and constant information in the code have been highly obfuscated, with few unobfuscated identifiable elements and low code readability, so the security requirements are low.

5. The method according to claim 1, wherein The Dynamic Attack Exposure Index (DAEI) measures the extent to which code is exposed to dynamic analysis tools during runtime. In actual attacks, attackers can use debugging tools, dynamic execution environments, or instrumentation techniques to analyze program execution traces, function call relationships, and dynamically loaded code snippets, thereby bypassing static obfuscation techniques. Therefore, DAEI analyzes important information that may be exposed during dynamic code execution, including: 1) Function call risk: Counting explicit function calls in bytecode. These instructions can be used to analyze the core logic of the program. 2) Dynamic execution risk: Evaluating bytecode instructions involved in dynamic execution. These instructions allow the program to generate and execute new code at runtime and are a key focus for attackers. 3) Code execution depth: Analyze the complexity of execution paths and simulate potential dynamic attack paths to determine the difficulty of dynamic analysis of the code; The calculation formula of the dynamic attack exposure index DAEI is as follows: in Exposure Operations Count is the number of instructions involved in dynamic analysis in the instruction set; Total Operations Count is the total number of instructions in the bytecode file, which is used for normalization calculation so that DAEI can be applied to code files of different sizes; The calculation formula effectively measures the dynamic attack exposure of the code by calculating the proportion of dynamic analysis related instructions in all instructions; The DAEI reflects the degree of exposure of the code at runtime, determines the difficulty of parsing the code using dynamic analysis tools, and further affects the security requirements of the code: a high DAEI value indicates that the code contains a large number of dynamic execution-related instructions. Due to the large number of dynamic exposure points, attackers can more easily use runtime analysis technology to monitor critical execution paths, thereby accelerating the reverse engineering process, so the security requirements are high; a low DAEI value indicates that the code relies less on dynamic execution, function calls are limited, and the degree of exposure of the code logic is low, so the security requirements are low.

6. The method according to claim 1, characterized in that The External Attack Surface Indicator (EASI) measures the extent to which code interacts with external systems. External system interactions are a means for attackers to exploit vulnerabilities, gain unauthorized access, or perform code injection. Therefore, EASI analyzes the interaction patterns between code and the external environment to assess the potential attack surface of the code. The EASI assesses the program's exposure risk to external systems from the following aspects: 1) External API call frequency: This counts the number of calls to external interactive APIs in the program. These operations involve network communication, file reading and writing, or remote requests, increasing the likelihood of attacks. 2) External Dependencies: Analyze the code's reliance on third-party libraries or system APIs. If external dependencies contain known vulnerabilities, attackers can exploit them as intrusion points. 3) API call structure analysis: Use the PageRank algorithm to model the call relationships between APIs and identify key interfaces and potential attack paths; Combining this information, EASI quantifies the interaction intensity of external APIs and assesses the degree of connection between the code and external systems, providing a quantitative basis for determining the attack surface size and security protection needs of the program; The calculation formula of the external attack surface index EASI is as follows: in F i No. i The risk factor or weight of each external API call point or external dependency in the attack surface; n For different types of external API calls, EASI builds a call graph of sensitive APIs and uses the PageRank algorithm to evaluate the importance of each API node, ultimately ranking the influence of all nodes. F i Add them up to form the total attack surface value; The EASI directly reflects the degree of external interaction of the code, determines the code's exposure to external attack surfaces, and further affects the security requirements of the code: a high EASI value indicates that the code frequently interacts with external systems, which means that the code has many attack points. Attackers can exploit network communication interfaces, file operations, and external dependency vulnerabilities to launch attacks, increasing the security risk of the system, so the security requirements are high; A low EASI value indicates that most of the code is executed internally, with few external interaction points, making it difficult for attackers to attack through the network, files, or external libraries. This indicates that the code is relatively secure, so the security requirements are low.

7. The method according to claim 1, characterized in that The random dynamic operation code mapping table is constructed in S2, specifically including: The opcode replacement rules are: The categories of opcodes that can be replaced are as follows: Category 1: opcode without parameters, opcode value < 90; Category 2: low-order opcode with parameters, 90 <= opcode value <= 130; Category 3: high-order opcode with parameters, 145 <= opcode value <= 165; Opcodes can be randomly replaced within their respective categories, but the replaced opcodes must still maintain the order of the original category to ensure that the Python interpreter can correctly process the instruction parameters and execution logic when parsing; Based on the opcode replacement rules, the opcode values ​​in different bytecode files are replaced accordingly through the dynamic opcode mapping table. The specific solution is as follows: S21. According to the opcode replacement rule, extract the opcode values ​​of different categories respectively and define them as sets O1, O2, and O3, where O1 is [1, 2, 3, 4, 5, 6, ..., 87, 89]; O2 is [90, 91, 92, 93, 94, 95, ..., 126, 130]; and O3 is [145, 146, 147, 148, 154, 155, ..., 164, 165], thereby obtaining an initial opcode mapping table for each category. S22. For bytecode file 1, randomly rearrange the opcodes in each category to form new O1, O2, and O3. O1: [1, 11, 12, 17, 86, 49, ..., 22, 67], O2: [106, 125, 111, 94, 90, 93, ..., 109, 117], O3: [160, 154, 147, 157, 164, 146, ..., 148, 156], and obtain the opcode mapping table of bytecode file 1. S23. Using the same method, perform independent random opcode mapping on bytecode file 2 to generate different O1, O2, and O3. O1: [77, 67, 74, 4, 26, 6, ..., 51, 15], O2: [111, 114, 125, 126, 100, 107, ..., 106, 118], O3: [164, 157, 163, 155, 147, 146, ..., 162, 154], and obtain the opcode mapping table of bytecode file 2. S24. Repeat the above process for other bytecode files, and generate an independent opcode mapping table for each bytecode file to ensure that the replacement strategies between different files are independent of each other.

8. A Python bytecode obfuscation system based on dynamic screening and random replacement, characterized in that: The system comprises: The obfuscated file dynamic screening module is used to calculate multiple security indicators of bytecode files by extracting bytecode features, including: data sensitivity index DSI, business logic complexity index BLCI, static reversibility index SRI, dynamic attack exposure index DAEI and external attack surface index EASI, so as to quantitatively evaluate the security requirements of bytecode files from multiple dimensions, and calculate the comprehensive security index SDI of bytecode files through the entropy weight method. Based on the comprehensive security index SDI, bytecode files that need to be obfuscated with high security requirements are screened according to the threshold set by the user; The obfuscation module is used to construct a linear congruential generator to provide a pseudo-random number sequence for bytecode obfuscation operations. By generating a random seed, a random dynamic opcode mapping table is constructed. Each independent opcode mapping table is applied to different bytecode files to be obfuscated. The opcode dynamic substitution obfuscation operation is performed in the bytecode instructions to generate obfuscated bytecode files. A custom interpreter implementation module is used to detect the obfuscation status of the obfuscated bytecode file. If the detection result is an obfuscated bytecode file, the bytecode parsing and instruction scheduling logic is modified, a runtime deobfuscation process is added, and an Opcode demapping mechanism is embedded. The module is recompiled to generate a customized Python interpreter that supports the execution of obfuscated bytecodes, and the obfuscated bytecode file is executed using the customized Python interpreter.

9. An electronic device comprising a processor and a memory, wherein the memory stores at least one instruction, characterized in that: The at least one instruction is loaded and executed by the processor to implement the Python bytecode obfuscation method based on dynamic screening and random replacement as described in any one of claims 1-7.

10. A computer-readable storage medium, wherein at least one instruction is stored in the storage medium, characterized in that: The at least one instruction is loaded and executed by the processor to implement the Python bytecode obfuscation method based on dynamic screening and random replacement as described in any one of claims 1-7.

Citation Information

Patent Citations

  • Deep learning enhanced large language model prompting method for software vulnerability detection

    CN118607646A

  • Python byte code protection method based on operation code and control flow joint confusion

    CN119066631A

  • Method and apparatus for dynamic obfuscation of static data

    US20140165208A1

Cited By

  • Industrial control logic tamper-proofing method and device based on binary program confusion

    CN121411403A