A python bytecode obfuscation method and system based on dynamic screening and random replacement
By using a bytecode obfuscation method with dynamic filtering and random replacement, this method obfuscates files with high security requirements, solving the problems of insufficient security and runtime overhead in existing technologies, and achieving more efficient reverse protection and performance maintenance.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-25
- Publication Date
- 2026-04-07
AI Technical Summary
Existing Python bytecode obfuscation techniques are not secure enough against advanced reverse engineering techniques, and the obfuscation process may cause additional runtime overhead.
A method based on dynamic filtering and random replacement is adopted. By calculating multiple security indicators of bytecode files, files with high security requirements are filtered out. A linear congruence generator is used to build a random opcode mapping table for dynamic replacement, and a custom interpreter is used for obfuscation processing.
It effectively improves the reverse engineering protection strength of bytecode, reduces the time overhead caused by obfuscation, keeps the file size unchanged, increases the opcode frequency entropy value and reduces the standard deviation, thus enhancing the security of bytecode.
Smart Images

Figure CN120805108B_ABST
Abstract
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. During the execution of Python code, the frequency of use of different opcodes has a certain statistical distribution. For example, variable loading, storage, and function calling operations 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 posing a significant 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:
[0005] On the one hand, a Python bytecode obfuscation method based on dynamic filtering and random replacement is provided, which includes:
[0006] S1. Calculate multiple security indicators for 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. Calculate the comprehensive security index (SDI) of bytecode files using the entropy weight method. Based on the comprehensive security index (SDI), select bytecode files with high security requirements that need to be obfuscated according to the threshold set by the user.
[0007] S2. Construct a linear congruential generator to provide a pseudo-random number sequence for bytecode obfuscation operations. By generating a random seed, construct a random dynamic opcode mapping table. Apply each independent opcode mapping table to different bytecode files to be obfuscated. Perform dynamic opcode replacement obfuscation operations in bytecode instructions to generate obfuscated bytecode files.
[0008] S3. Perform obfuscation status detection on the obfuscated bytecode file. If the detection result is an obfuscated bytecode file, modify the bytecode parsing and instruction scheduling logic, add a runtime deobfuscation process, embed the Opcode anti-mapping mechanism, recompile to generate a customized Python interpreter that supports the execution of obfuscated bytecode, and use the customized Python interpreter to execute the obfuscated bytecode file.
[0009] On the other hand, a Python bytecode obfuscation system based on dynamic filtering and random replacement is provided, the system comprising:
[0010] The obfuscated file dynamic filtering 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. It also calculates the comprehensive security index (SDI) of bytecode files using the entropy weight method. Based on the comprehensive security index (SDI), bytecode files with high security requirements that need to be obfuscated are filtered out according to the threshold set by the user.
[0011] 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, it constructs a random dynamic opcode mapping table, applies each independent opcode mapping table to different bytecode files to be obfuscated, performs dynamic opcode replacement obfuscation operations in bytecode instructions, and generates obfuscated bytecode files.
[0012] A custom interpreter implementation module is used to perform obfuscation status detection on 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 anti-mapping mechanism is embedded. The module is then recompiled to generate a customized Python interpreter that supports the execution of obfuscated bytecode, and the obfuscated bytecode file is executed using the customized Python interpreter.
[0013] On the other hand, an electronic device is provided, comprising a processor and a memory, wherein the memory stores at least one instruction, which is loaded and executed by the processor to implement the above-described Python bytecode obfuscation method based on dynamic filtering and random replacement.
[0014] On the other hand, a computer-readable storage medium is provided, wherein at least one instruction is stored in the storage medium, the at least one instruction being loaded and executed by a processor to implement the above-described Python bytecode obfuscation method based on dynamic filtering and random replacement.
[0015] The beneficial effects of the technical solution provided by this invention include at least the following:
[0016] 1) Because the present invention performs screening before obfuscation, it only obfuscates bytecode files with high security requirements. After using the bytecode obfuscation of the present invention, the time overhead increased by 0.79%, while the space overhead remained unchanged. This shows that the present invention does not introduce significant execution overhead.
[0017] 2) This invention can effectively prevent obfuscated bytecode from being restored by existing decompilation tools, thereby improving the reverse engineering protection of the code. Compared with ordinary bytecode files, Python bytecode files obfuscated by this invention have a 41.7% higher entropy value in opcode frequency and a 62% lower standard deviation. This indicates that this invention solves the problem of easy speculation of opcode mapping relationships in difference comparison and frequency statistics attacks by randomly replacing the dynamic opcode mapping table, thereby enhancing the security of bytecode.
[0018] 3) Compared with the standard Python interpreter (CPython), the custom interpreter of the present invention has a change rate of 3.04% in average runtime and 0% in file size. This shows that the custom interpreter of the present invention does not bring significant performance overhead without increasing bytecode storage overhead. Attached Figure Description
[0019] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0020] Figure 1 This is a flowchart of a Python bytecode obfuscation method based on dynamic filtering and random replacement provided in an embodiment of the present invention;
[0021] Figure 2 This is a general block diagram of a cross-modal external ear region segmentation and key point localization method provided in an embodiment of the present invention;
[0022] Figure 3 This is a schematic diagram illustrating the opcode replacement rules provided in an embodiment of the present invention;
[0023] Figure 4 This is a schematic diagram of the classification confusion rules provided in an embodiment of the present invention;
[0024] Figure 5 This is a schematic diagram of the mapping relationship of the initial various opcode mapping tables provided in the embodiments of the present invention;
[0025] Figure 6 This is a schematic diagram of the mapping relationship of various opcode mapping tables of bytecode file 1 provided in the embodiment of the present invention;
[0026] Figure 7 This is a schematic diagram of the mapping relationship of various opcode mapping tables of bytecode file 2 provided in the embodiments of the present invention;
[0027] Figure 8 This is a block diagram of a Python bytecode obfuscation system based on dynamic filtering and random replacement provided in an embodiment of the present invention;
[0028] Figure 9 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present invention. Detailed Implementation
[0029] To make the technical problems, technical solutions and advantages of the present invention clearer, a detailed description will be given below in conjunction with the accompanying drawings and specific embodiments.
[0030] This invention provides a Python bytecode obfuscation method based on dynamic filtering and random replacement. This method can be implemented by an electronic device, which can be a terminal or a server. Figure 1 The flowchart of this method is shown below. Figure 2 The diagram shown is an overall block diagram of the method. The processing flow may include the following steps:
[0031] S1. Calculate multiple security indicators for 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. Calculate the comprehensive security index (SDI) of bytecode files using the entropy weight method. Based on the comprehensive security index (SDI), select bytecode files with high security requirements that need to be obfuscated according to the threshold set by the user.
[0032] Considering that obfuscated code may incur additional runtime overhead, the solution proposed in this invention introduces a dynamic decision-making mechanism for bytecode files before obfuscation. Specifically, this mechanism, based on the relevant characteristics of Python bytecode files, comprehensively analyzes several security assessment indicators, including the 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 demand index of bytecode files from multiple dimensions. Based on this, the mechanism also supports users to set obfuscation thresholds. During obfuscation, bytecode files that meet high security requirements can be filtered out according to the user-defined thresholds. Then, dynamic obfuscation strategies are applied to these filtered files to achieve automated code obfuscation. Through this method, code can improve security while minimizing the performance overhead caused by obfuscation, which makes this obfuscation scheme more efficient and feasible in practical applications.
[0033] Data security has become a key factor affecting system trustworthiness and applicability. Research indicates that security risks such as data leakage, unauthorized access, and malicious attacks are prevalent. To address these challenges, researchers have proposed various security protection strategies, such as data encryption, access control, and data integrity verification. Among these, data sensitivity assessment is a crucial prerequisite for determining data protection strategies. Therefore, this invention introduces a Data Sensitivity Index (DSI) to measure the degree of sensitivity of data contained in bytecode and serves as an important component in the calculation of a comprehensive security index. By quantitatively assessing sensitive data in bytecode, DSI can effectively reflect the potential data security risks of the code, thereby providing a basis for the dynamic adjustment of security strategies.
[0034] Optionally, the Data Sensitivity Index (DSI) is used to measure the degree of sensitive data involved in bytecode files. It quantitatively assesses and identifies potential security risks for sensitive variables and constants in the code. If sensitive data is leaked during code execution, it may lead to serious security problems. Therefore, quantitative analysis helps to assess the security requirements of the code. The DSI considers the following key factors:
[0035] 1) Number of occurrences of sensitive keywords: The number of occurrences of sensitive keywords (such as password, secret, key, etc.) contained in the code is calculated by counting the frequency of these keywords.
[0036] 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 the importance of sensitive keywords in the code. A high TF-IDF value means that the sensitive keywords have a great influence in the current code segment, and this code needs more stringent security protection.
[0037] 3) Risk of sensitive data propagation: Based on the Markov prediction model, the fluidity of sensitive data in the code execution path is calculated, and the probability of leakage of sensitive information in the variable transmission process is further evaluated. By traversing the string constant sequence, the directed transition relationship between adjacent sensitive keywords is recorded. Specifically, the counting matrix C is constructed by counting the number of transitions between sensitive keywords, and the Markov transition probability matrix P is obtained by row normalization, which reflects the possibility of sensitive information being continuously exposed in the program execution path.
[0038] The formula for calculating the Data Sensitivity Index (DSI) is as follows:
[0039]
[0040] in C i For the firsti The number of times each sensitive keyword appears, and the total number of sensitive keywords is... n ; TFIDF(C i ) The weights of sensitive data are 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 codebase. A high TF-IDF value means that the keyword has high importance in the current code snippet. P ij Indicates from keywords i Shift to keywords j The conditional probability;
[0041] The calculation formula combines static feature analysis of TF-IDF calculation with dynamic propagation modeling of Markov prediction to comprehensively measure the risk of sensitive data in the code.
[0042] A higher DSI value indicates that a certain piece of code involves more sensitive data and that the data propagation chain during code execution is longer, meaning that this piece of code has a higher security requirement; a low DSI value indicates that the code involves less sensitive data, or that the sensitive data is only used in a local area, indicating that the security requirement is relatively low.
[0043] Based on McCabe's research, the core idea of complexity measurement is to calculate the number of control paths in the code. The logical complexity of the code is calculated by analyzing the number of edges, nodes, and connected components of the control flow graph. However, this idea assumes that all paths have the same execution probability and does not take into account the unevenness of execution paths. Based on the idea of McCabe's complexity measurement, this invention further proposes a business logic complexity index to measure the business logic complexity of the code, so as to make up for the shortcomings of McCabe's complexity measurement method in business logic evaluation, thereby enabling it to more accurately reflect the complexity of code execution paths and its security requirements.
[0044] Optionally, 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 affecting the complexity of business logic:
[0045] 1) Control flow complexity: Calculates the number of branches and the depth of loops in the code execution path, used to measure the complexity of the code structure;
[0046] 2) Path Entropy: Used to measure the uniformity of program execution path distribution, reflecting the control flow complexity and predictability of the code. The program first enumerates all simple paths without repeating nodes from the starting node (number 0) to the ending node (i.e., the last instruction) based on the control flow graph (cfg). Then, the length of each path is calculated, and all path lengths are normalized to a probability distribution. It is assumed that the longer the path, the higher its probability of execution. Path entropy... H The calculation formula is as follows:
[0047]
[0048] in l i For the first i The length of the path; the sum of the lengths of all paths. Used for normalization; regarded as the first i The execution probability of each path is determined by the following: if the length of each path is roughly the same, the normalized probability distribution will be relatively uniform, and the path entropy will be high; if only a few paths are particularly long and the others are short, the distribution will be uneven, and the path entropy will be low.
[0049] Number of independent entry points: This detects multiple execution entry points in the code. Multiple entry points may lead to more complex execution logic and increase potential security risks.
[0050] The Business Logic Complexity Index (BLCI) is calculated using the following formula:
[0051]
[0052] in E To control the number of edges in the flow graph, Edges represents the number of branches and jumps in the code execution path; N Nodes, used to control the number of nodes in the flow graph, represents the number of basic blocks of code. P To control the number of independent entry points in the flow graph, used to measure whether the code has multiple execution start points; H Path entropy is used to measure whether different execution paths of code are evenly distributed; a high path entropy indicates that the execution paths are evenly distributed.
[0053] Compared to McCabe complexity, the BLCI implementation in this invention incorporates path entropy. H The calculations make it more reflective of the complexity of business logic.
[0054] The BLCI not only measures code structure but also considers execution path distribution, making it more suitable for evaluating business logic complexity in modern software architectures.
[0055] The higher the BLCI value, the higher the complexity of the business logic contained in a certain code segment. This means that the code contains more core business logic. Since core business logic directly affects the functionality and security of the system, in practical applications, attackers are more likely to target these high BLCI codes for cracking or reverse engineering to obtain key algorithms, bypass security verification, or tamper with system logic. Therefore, bytecode files with higher BLCI values have higher security requirements, while code with low BLCI values often does not involve core business logic and has low value, so its security requirements are also low.
[0056] The resistance to deobfuscation proposed by Collberg et al. focuses on the ability of code to resist deobfuscation techniques. However, this concept does not provide a specific quantitative method for the impact of variable naming conventions on program reversibility. In static analysis, variable names often carry rich semantic information. Intuitive variable naming helps analysis tools and attackers quickly understand program logic, while obfuscated variable names can significantly increase code unreadability, thereby increasing the difficulty of reverse engineering. Therefore, this invention proposes a static reversibility index to quantify the security of variable naming conventions in code, assessing whether attackers can easily infer program logic through variable names.
[0057] Optionally, the Static Reversibility Index (SRI) is used to measure the ease with which a bytecode file can be restored to its original code through static analysis without obfuscation or with low obfuscation levels. Code elements, such as 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 metric quantifies the static reversibility of code by analyzing the readability of elements in the code, and provides an assessment of the security of code variable naming methods.
[0058] The SRI measures the following aspects:
[0059] 1) By analyzing the entropy values of variable names in the program, the difficulty of identifying and reconstructing them in static analysis is measured. Specifically, all variable names (i.e., identifiers appearing in the LOAD_NAME and STORE_NAME instructions) are extracted, and the Shannon entropy of the character distribution is calculated for each variable name to represent its naming complexity and unpredictability. Finally, the average of the entropy values of all variable names is taken as the SRI index. The higher the average value, the more random and difficult to predict the variable names are, and the greater the difficulty of static reverse engineering.
[0060] 2) Total number of instructions: Used for normalization calculations to ensure that this metric applies to bytecode files of different sizes;
[0061] The static reversibility index (SRI) is calculated using the following formula:
[0062]
[0063] in, Unobfuscated Element Count It represents the number of variable names that have not been obfuscated, and has strong semantic information, which allows the logical structure of the program to be inferred through static analysis; Total Instruction Count This represents the total number of instructions in the bytecode file. The character entropy of variable names is used as a measure of obfuscation strength. An entropy threshold is set to distinguish between obfuscated and unobfuscated variable names. If the entropy value of a variable name is lower than the threshold, it indicates that the naming rules are strong and the readability is high. It is considered 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 program's reversibility under static analysis.
[0064] The SRI reflects the static reversibility of the code, determines the difficulty of parsing the code under static analysis tools, and further affects the security requirements of the code: a high SRI value indicates that the code still contains a large number 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, there are few unobfuscated identifiable elements, the code readability is low, so the security requirements are low.
[0065] In current software security research, dynamic analysis has become an important tool for attackers to perform reverse engineering and vulnerability discovery. Attackers can use tools or techniques such as debuggers, dynamic instrumentation, and memory monitoring to extract the execution path and key data of a program and bypass static obfuscation protection. Therefore, this invention proposes a dynamic attack exposure index to quantify the degree to which code is exposed to dynamic analysis at runtime.
[0066] Optionally, the Dynamic Attack Exposure Index (DAEI) measures the extent to which code is exposed to dynamic analysis tools (such as debuggers, dynamic instrumentation, and injection attacks) during runtime. In actual attacks, attackers can utilize debugging tools, dynamic execution environments, or instrumentation techniques to analyze the program's execution trajectory, function call relationships, and dynamically loaded code snippets, thereby bypassing static obfuscation protection. Therefore, DAEI analyzes important information that code may expose during dynamic execution, including:
[0067] 1) Function call risk: Analyze explicit function calls in bytecode (such as CALL_FUNCTION, CALL_METHOD, LOAD_GLOBAL). These instructions can be used to analyze the core logic of the program.
[0068] 2) Dynamic execution risk: Evaluate instructions in the bytecode that involve dynamic execution (such as EXEC_STMT, EVAL_CODE). These instructions allow the program to generate and execute new code at runtime, which is a key focus for attackers.
[0069] 3) Code execution depth: Analyze the complexity of the execution path and simulate potential dynamic attack paths to determine the difficulty of dynamic code analysis;
[0070] The formula for calculating the Dynamic Attack Exposure Index (DAEI) is as follows:
[0071]
[0072] in Exposure Operations Count The number of instructions in the instruction set that involve dynamic analysis; Total Operations Count This represents the total number of instructions in the bytecode file, used for normalization calculations to enable DAEI to be applicable to code files of different sizes.
[0073] The calculation formula effectively measures the degree of dynamic attack exposure of the code by calculating the proportion of relevant instructions in all instructions through dynamic analysis.
[0074] The DAEI reflects the degree of code exposure at runtime, determines the difficulty of code parsing under dynamic analysis tools, and further affects the code's security requirements: a high DAEI value indicates that the code contains a large number of dynamically executed instructions. Due to the many dynamic exposure points, attackers can more easily use runtime analysis techniques to monitor critical execution paths, thereby accelerating the reverse engineering process, hence the high security requirements; a low DAEI value indicates that the code relies less on dynamic execution, function calls are restricted, and the degree of exposure of code logic is low, hence the low security requirements.
[0075] In recent years, the attack surface of software systems has become an important indicator for measuring security. Manadhata et al. proposed a systematic attack surface measurement method. This method assesses the system's exposure based on method calls, data interactions, and channel connections. Its core idea is that the larger the attack surface, the higher the security risk the system faces. Therefore, attack surface measurement methods are of great significance for evaluating software security. However, traditional attack surface measurements mainly focus on overall system interactions, lacking fine-grained analysis of the specific impact of external system interactions. Therefore, this invention proposes the External Attack Surface Index (EASI) to quantify the interaction risks between code and the external environment, helping to assess the potential external threats faced by the code.
[0076] Optionally, the External Attack Surface Index (EASI) is used to measure the degree of interaction between code and external systems. External system interaction is a way for attackers to exploit vulnerabilities, make unauthorized access, or execute code injection. Therefore, EASI assesses the size of the attack surface that the code may face by analyzing the interaction patterns between the code and the external environment.
[0077] The EASI assesses the program's risk of exposure to external systems from the following aspects:
[0078] 1) External API call frequency: Count the number of times the program calls external interactive APIs (such as socket, open, requests, etc.). These operations involve network communication, file reading and writing, or remote requests, which increases the possibility of being attacked.
[0079] 2) Degree of external dependency: Analyze the code's dependency on third-party libraries or system APIs. If there are known vulnerabilities in external dependencies, attackers can exploit them as entry points.
[0080] 3) API call structure analysis: The PageRank algorithm is used to model the call relationships between APIs and identify key interfaces and potential attack paths;
[0081] By combining this information, EASI assesses the degree of connection between the code and external systems by quantifying the interaction strength of external APIs, providing a quantitative basis for determining the attack surface size and security protection requirements of the program;
[0082] The formula for calculating the External Attack Surface Index (EASI) is as follows:
[0083]
[0084] in F i No. i The risk factor or weight value of an external API call point or external dependency in the attack surface; n For different categories of external API call types, EASI constructs a call graph of sensitive APIs and uses the PageRank algorithm to evaluate the importance of each API node, ultimately determining the influence of all nodes. F i Accumulate them to form the total attack surface value;
[0085] The EASI directly reflects the degree of external interaction of the code, determines the extent to which the code is exposed to external attack surfaces, and further affects the security requirements of the code: a high EASI value indicates that the code interacts frequently with external systems, which means that there are many attack entry points for the code. Attackers can launch attacks by exploiting network communication interfaces, file operations, and external dependency vulnerabilities, increasing the security risk of the system, hence the high security requirements; a low EASI value indicates that most of the code is executed internally, with few external interaction points. Attackers find it difficult to attack through networks, files, or external libraries, indicating that the code is relatively secure, hence the low security requirements.
[0086] The aforementioned metrics assess potential security risks in code from different dimensions. However, using only a single metric is insufficient to comprehensively measure the overall security requirements of bytecode files. Therefore, it is necessary to comprehensively calculate these metrics to construct a metric that fully reflects code security. To address this, this invention proposes the Security Demand Index (SDI) to measure the overall security requirement level of code under multi-dimensional security assessment.
[0087] When calculating the overall security index, each indicator has a different impact on overall security, so it is necessary to reasonably determine the weight of each indicator. To ensure the objectivity, automation, and adaptability of the weight allocation for each indicator, this embodiment of the invention uses the entropy weight method to calculate the weight corresponding to each indicator. This eliminates the calculation deviation that may be caused by subjective human weighting and ensures that the calculation method for the relevant weights is consistent across different bytecode files, thereby adapting to the security index calculation of different bytecode files.
[0088] Entropy weighting is an objective weighting method based on information entropy, and its core idea is as follows:
[0089] The greater the data difference of an indicator, the greater the amount of information contained in that indicator and the greater its impact on the overall evaluation; therefore, it should be given a higher weight.
[0090] If a metric shows little variation across all bytecode files, it indicates that the metric has low discriminative power in assessing overall security requirements, and therefore its weight should be low.
[0091] Optionally, the calculation of the comprehensive security index SDI of the bytecode file using the entropy weight method in step S1 specifically includes:
[0092] S11, Data Preprocessing
[0093] The DSI, BLCI, SRI, DAEI, and EASI values were normalized to ensure consistent numerical ranges.
[0094] S12, Calculate information entropy
[0095] Calculate the variability of each security metric across different bytecode files and determine the information entropy. H j :
[0096]
[0097] in q ij For the first i The bytecode file in the first j Normalized values for each indicator; The coefficients are standardized to ensure that the entropy value is within a reasonable range;
[0098] S13, Calculate weights
[0099] The weights of each indicator are calculated using the entropy weight method. w j :
[0100]
[0101] in H j For the first j Information entropy of each indicator m It is the total number of indicators. If the information entropy of a certain indicator is low, it means that it contributes more to the uncertainty of the whole, that is, it contains more useful information, so its weight will also be higher.
[0102] S14. Calculate the Comprehensive Security Index (SDI):
[0103] .
[0104] Security assessments of bytecode are influenced by a variety of factors. For example, in this embodiment of the invention, data sensitivity primarily affects the risk of data leakage; business logic complexity affects code readability and reverse engineering difficulty; static reversibility affects the ease of static analysis of the code; dynamic attack exposure affects the degree of exposure of the code to dynamic attack methods; and external attack surface affects the degree of dependence of the code on external systems and the size of the attack surface. The degree of influence of these indicators varies depending on the assembly. The entropy weighting method can automatically measure the distinguishing degree of each indicator, ensure the rationality of weight allocation, avoid the influence of subjective human weighting, and is applicable to code analysis of different scales, as well as improve the automation and adaptability of the calculation.
[0105] In summary, the Comprehensive Security Index (SDI) calculation method proposed in this invention objectively measures the overall security requirements of code under multi-dimensional security assessment using the entropy weight method. Compared to assessments using only a single indicator, SDI combines multiple key dimensions, including data sensitivity, business logic complexity, static reversibility, dynamic attack exposure, and external attack surface, effectively quantifying the security risks of bytecode files holistically. Furthermore, the introduction of the entropy weight method ensures the objectivity, automation, and adaptability of weight allocation, effectively avoiding subjective biases from manual weighting while improving the applicability of the comprehensive assessment index in different code scenarios. This method not only provides more accurate security assessment results but also provides a quantitative basis for code obfuscation selection and offers strong support for improving code security and reverse engineering capabilities.
[0106] S2. Construct a linear congruential generator to provide a pseudo-random number sequence for bytecode obfuscation operations. By generating a random seed, construct a random dynamic opcode mapping table. Apply each independent opcode mapping table to different bytecode files to be obfuscated. Perform dynamic opcode replacement obfuscation operations in bytecode instructions to generate obfuscated bytecode files.
[0107] Optionally, the construction of a random dynamic opcode mapping table in step S2 specifically includes:
[0108] In Python 3.9.6, the opcode replacement rules are as follows: Figure 3 As shown, the opcode replacement rule in this embodiment of the invention is as follows:
[0109] The categories of replaceable opcodes are as follows:
[0110] Category 1: No-parameter opcode, opcode value < 90; Category 2: Opcode with low-order parameter, 90 <= opcode value <= 130; Category 3: Opcode with high-order parameter, 145 <= opcode value <= 165;
[0111] Opcodes can be randomly replaced within their respective categories, but the replaced opcodes must still maintain the original category numbering order to ensure that the Python interpreter can correctly process the instruction's parameters and execution logic during parsing. Figure 4 As shown;
[0112] Based on the aforementioned opcode replacement rules, opcode values in different bytecode files are replaced accordingly using a dynamic opcode mapping table. The specific scheme is as follows:
[0113] S21. According to the opcode replacement rules, extract the opcode values of different categories and define them as sets O1, O2, and 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]. This yields the initial opcode mapping table for each category, with the mapping relationships as follows: Figure 5 As shown;
[0114] S22. For bytecode file 1, within each category, randomly rearrange the opcodes 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]. This yields the opcode mapping table for each category of bytecode file 1, with the mapping relationships as follows: Figure 6 As shown;
[0115] S23. Using the same method, perform independent opcode random 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]. This yields the opcode mapping table for bytecode file 2, and its mapping relationship is as follows: Figure 7 As shown;
[0116] S24. For other bytecode files, repeat the above process to generate an independent opcode mapping table for each bytecode file, ensuring that the replacement strategies between different files are independent of each other.
[0117] Then, based on the corresponding opcode mapping relationship generated for each bytecode file, that is, by generating a dynamic mapping table, opcode replacement obfuscation is performed to convert the opcode values in the original bytecode file into the corresponding obfuscated opcodes, thus completing the dynamic replacement process of bytecode.
[0118] In summary, the opcode random replacement scheme based on dynamic mapping table proposed in this embodiment of the invention generates opcode mapping rules independently for each bytecode file while following the opcode replacement rules for different categories. This ensures that the replacement strategies between different bytecode files are independent of each other, thereby further enhancing the obfuscation effect.
[0119] S3. Perform obfuscation status detection on the obfuscated bytecode file. If the detection result is an obfuscated bytecode file, modify the bytecode parsing and instruction scheduling logic, add a runtime deobfuscation process, embed the Opcode anti-mapping mechanism, recompile to generate a customized Python interpreter that supports the execution of obfuscated bytecode, and use the customized Python interpreter to execute the obfuscated bytecode file.
[0120] The code.h file of the standard Python interpreter is a header file used to define data structures, constants, flags, and function declarations related to bytecode and code objects (PyCodeObject). Therefore, this embodiment of the invention defines the macro CO_MAPPED in this file and assigns a specific bit value as a detection identifier for obfuscated bytecode files.
[0121] When the Python interpreter runs, it loads the bytecode from .pyc files. The marshal.c file is responsible for deserializing this bytecode and converting it into PyCodeObject objects. In other words, this file provides a direct interface for interacting with the bytecode, primarily handling bytecode serialization and deserialization. During the marshal.c parsing phase, the customized interpreter implemented in this invention introduces an intelligent identification strategy based on the co_flags flag mechanism. When parsing the header of a .pyc file, this interpreter checks whether the co_flags contain the CO_MAPPED flag to determine if the file has been obfuscated, thus automatically distinguishing between obfuscated and ordinary files.
[0122] If the custom interpreter detects an obfuscation flag, the parser will enter the dynamic seed acquisition stage. In this embodiment of the invention, the ceval.c file has been deeply modified to enhance its adaptability: a seed synchronization mechanism of a remote trusted server has been introduced. After parsing the .pyc file, the interpreter can automatically request a random seed consistent with the one used when obfuscating the file from the remote server.
[0123] This invention utilizes the seed obtained above, which is consistent with the obfuscated file, and combines a linear congruential generator (LCG) with the Fisher-Yates shuffle algorithm to generate an opcode mapping table. This ensures that the same .pyc file can still recover a consistent instruction set in different environments, avoiding the problem of inconsistent parsing.
[0124] When the custom interpreter in this embodiment of the invention performs a byte-by-byte scan of the co_code byte sequence, it forcibly casts the bytecode object code to PyBytesObject. The type is specified so that the bytecode content (ob_sval) and bytecode size (ob_base.ob_size) can be directly accessed. Then, the interpreter traverses the bytecode array and extracts each opcode in order. Then, it uses a recovery function to restore the obfuscated opcodes. This process ensures that the obfuscated opcodes can be correctly restored and executed according to the original logic by modifying the bytecode parsing logic. This maintains the functionality and execution order of the program. All instructions are restored to a state that can be correctly parsed by the interpreter before the .pyc file is officially loaded into the Python runtime environment.
[0125] Then, the CPython source code is recompiled to generate a customized interpreter. This customized Python interpreter is used to execute the obfuscated bytecode file. Specifically, the `. / configure` command can be used to configure the compilation environment and check the relevant system environment settings to ensure that the software source code can be successfully compiled on the current system. The `sudo make -j 10` command is used to compile the source code in parallel, using 10 CPU cores to accelerate the compilation process. The `sudo make altinstall` command is used to install the compiled program into the system. `altinstall` is an alternative installation method, usually used to avoid overwriting the system's default version.
[0126] like Figure 8 As shown, this embodiment of the invention also provides a Python bytecode obfuscation system based on dynamic filtering and random replacement, the system comprising:
[0127] The obfuscated file dynamic filtering 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. It also calculates the comprehensive security index (SDI) of bytecode files using the entropy weight method. Based on the comprehensive security index (SDI), bytecode files with high security requirements that need to be obfuscated are filtered out according to the threshold set by the user.
[0128] 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, it constructs a random dynamic opcode mapping table, applies each independent opcode mapping table to different bytecode files to be obfuscated, performs dynamic opcode replacement obfuscation operations in bytecode instructions, and generates obfuscated bytecode files.
[0129] A custom interpreter implementation module is used to perform obfuscation status detection on 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 anti-mapping mechanism is embedded. The module is then recompiled to generate a customized Python interpreter that supports the execution of obfuscated bytecode, and the obfuscated bytecode file is executed using the customized Python interpreter.
[0130] The Python bytecode obfuscation system based on dynamic filtering and random replacement provided in this embodiment of the invention has a functional structure that corresponds to the Python bytecode obfuscation method based on dynamic filtering and random replacement provided in this embodiment of the invention, and will not be described again here.
[0131] Figure 9 This is a schematic diagram of the structure of an electronic device 900 provided in an embodiment of the present invention. The electronic device 900 may vary greatly due to different configurations or performance. It may include one or more central processing units (CPUs) 901 and one or more memories 902. The memory 902 stores at least one instruction, which is loaded and executed by the processor 901 to implement the steps of the Python bytecode obfuscation method based on dynamic filtering and random replacement described above.
[0132] In an exemplary embodiment, a computer-readable storage medium is also provided, such as a memory including instructions that can be executed by a processor in a terminal to perform the Python bytecode obfuscation method based on dynamic filtering and random replacement. For example, the computer-readable storage medium may be a ROM, random access memory (RAM), CD-ROM, magnetic tape, floppy disk, or optical data storage device.
[0133] Those skilled in the art will understand that all or part of the steps of the above embodiments can be implemented by hardware or by a program instructing related hardware. The program can be stored in a computer-readable storage medium, such as a read-only memory, a disk, or an optical disk.
[0134] The above description is merely a preferred embodiment of the present invention and is not intended to limit the present invention. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.
Claims
1. A Python bytecode obfuscation method based on dynamic filtering and random replacement, characterized in that, The method includes: S1. Calculate multiple security indicators for 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). This quantitatively evaluates the security requirements of bytecode files from multiple dimensions. Based on the five security indicators (DSI, BLCI, SRI, DAEI, and EASI), calculate the comprehensive security index (SDI) of the bytecode files using the entropy weight method. Based on the comprehensive security index (SDI), select bytecode files with high security requirements that need to be obfuscated according to the user-defined threshold. S2. Construct a linear congruential generator to provide a pseudo-random number sequence for bytecode obfuscation operations. By generating a random seed, construct a random dynamic opcode mapping table. Apply each independent opcode mapping table to different bytecode files to be obfuscated. Perform dynamic opcode replacement obfuscation operations in bytecode instructions to generate obfuscated bytecode files. S3. Perform obfuscation status detection on the obfuscated bytecode file. If the detection result is an obfuscated bytecode file, modify the bytecode parsing and instruction scheduling logic, add a runtime deobfuscation process, embed the Opcode anti-mapping mechanism, recompile and generate a customized Python interpreter that supports the execution of obfuscated bytecode, and use the customized Python interpreter to execute the obfuscated bytecode file. The formula for calculating the Data Sensitivity Index (DSI) is as follows: ; Where C i Let be the number of occurrences of the i-th sensitive keyword, and let n be the total number of sensitive keywords; TFIDF(C i The TF-IDF values represent the weights of sensitive data 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 within the entire codebase. A high TF-IDF value indicates that the keyword has high importance in the current code snippet. ij This represents the conditional probability of transitioning from keyword i to keyword j; The Business Logic Complexity Index (BLCI) is calculated using the following formula: ; Where E is the number of edges in the control flow graph, representing the number of branches and jumps in the code execution path; N is the number of nodes in the control flow graph, representing the number of basic blocks of code; P is the number of independent entries in the control flow graph, used to measure whether there are multiple execution starting points in the code; H is the path entropy, used to measure whether the different execution paths of the code are uniformly distributed. A high path entropy indicates that the execution paths are uniform. The formula for calculating H is as follows: ; Among them l i The length of the i-th path; the sum of the lengths of all paths. Used for normalization; The execution probability of being considered as the i-th path; The static reversibility index (SRI) is calculated using the following formula: ; Here, Unobfuscated Element Count represents the number of unobfuscated variable names, which has strong semantic information, enabling the logical structure of the program to be inferred through static analysis; Total Instruction Count represents the total number of instructions in the bytecode file. The character entropy of variable names is used as a measure of obfuscation strength. An entropy threshold is set to distinguish between obfuscated and unobfuscated variable names. If the entropy value of a variable name is lower than the threshold, it indicates that the naming regularity is strong and the readability is high, and it is considered 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 program's reversibility under static analysis. The formula for calculating the Dynamic Attack Exposure Index (DAEI) is as follows: ; Exposure Operations Count is the number of instructions in the instruction set involved in dynamic analysis; Total Operations Count is the total number of instructions in the bytecode file, used for normalization calculations to enable DAEI to be applicable to code files of different sizes. The formula for calculating the External Attack Surface Index (EASI) is as follows: ; Where F i Let be the risk factor or weight value of the i-th external API call point or external dependency in the attack surface; n represents the different categories of external API call types. EASI constructs a call graph of sensitive APIs and uses the PageRank algorithm to evaluate the importance of each API node, ultimately assigning an F-value to all nodes. i The total attack surface value is accumulated.
2. The method according to claim 1, characterized in that, The Data Sensitivity Index (DSI) measures the degree of sensitive data involved in bytecode files. It quantitatively assesses and identifies potential security risks by analyzing sensitive variables and constants in the code. If sensitive data is leaked during code execution, it can lead to serious security problems. Therefore, quantitative analysis helps assess the security requirements of the code. The DSI considers the following key factors: 1) Frequency of occurrence of sensitive keywords: The frequency of occurrence of sensitive keywords is calculated 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 the importance of sensitive keywords in the code. A high TF-IDF value means that the sensitive keywords have a great influence in the current code segment, and this code needs more stringent security protection. 3) Risk of sensitive data propagation: Based on the Markov prediction model, the fluidity of sensitive data in the code execution path is calculated, and the probability of leakage of sensitive information in the variable transmission process is further evaluated. By traversing the string constant sequence, the directed transition relationship between adjacent sensitive keywords is recorded. Specifically, the counting matrix C is constructed by counting the number of transitions between sensitive keywords, and the Markov transition probability matrix P is obtained by row normalization, which reflects the possibility of sensitive information being continuously exposed in the program execution path. The calculation formula of the Data Sensitivity Index (DSI) 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 piece of code involves more sensitive data and that the data propagation chain during code execution is longer, meaning that this piece of code has a higher security requirement; a low DSI value indicates that the code involves less sensitive data, or that the sensitive data is only used in a local area, indicating that the security requirement is relatively low.
3. The method according to claim 1, characterized in that, The Business Logic Complexity (BLCI) metric measures the complexity of business logic in bytecode. It calculates the complexity of the code structure based on the control flow graph, taking into account several key factors that influence business logic complexity: 1) Control flow complexity: Calculates the number of branches and the depth of loops in the code execution path, used to measure the complexity of the code structure; 2) Path entropy: Used to measure the uniformity of the distribution of program execution paths, reflecting the control flow complexity and predictability of the code. The program first enumerates all simple paths without repeating nodes from the start node to the end node based on the control flow graph cfg; then it counts the length of each path and normalizes all path lengths into a probability distribution, assuming that the longer the path, the higher the probability of it being executed. Number of independent entry points: This detects multiple execution entry points in the code. Multiple entry points may lead to more complex execution logic and increase potential security risks. The BLCI not only measures code structure but also considers execution path distribution, making it more suitable for evaluating business logic complexity in modern software architectures. The higher the BLCI value, the higher the complexity of the business logic contained in a certain code segment. This means that the code contains more core business logic. Since core business logic directly affects the functionality and security of the system, in practical applications, attackers are more likely to target these high BLCI codes for cracking or reverse engineering to obtain key algorithms, bypass security verification, or tamper with system logic. Therefore, bytecode files with higher BLCI values have higher security requirements, while code with low BLCI values often does not involve core business logic and has low value, so its security requirements are also low.
4. The method according to claim 1, characterized in that, The Static Reversibility Index (SRI) measures the ease with which a bytecode file can be restored to its original form through static analysis, provided 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, thus accelerating the reverse engineering process. Therefore, the SRI metric quantifies the static reversibility of code by analyzing the readability of its elements, providing an assessment of the security of the code's variable naming conventions. The SRI measures the following aspects: 1) By analyzing the entropy values of variable names in the program, the difficulty of identifying and reconstructing them in static analysis is measured. Specifically, all variable names are extracted, and the Shannon entropy of the character distribution is calculated for each variable name to represent its naming complexity and unpredictability. Finally, the average of the entropy values of all variable names is taken as the SRI index. The higher the average value, the more random and difficult to predict the variable names are, and the greater the difficulty of static reverse engineering. 2) Total number of instructions: Used for normalization calculations to ensure that this metric applies to bytecode files of different sizes; The SRI reflects the static reversibility of the code, determines the difficulty of parsing the code under static analysis tools, and further affects the security requirements of the code: a high SRI value indicates that the code still contains a large number 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 speeding up the reverse engineering process, so the security requirements are high. A low SRI value indicates that variable names and constant information in the code have been highly obfuscated, with few unobfuscated identifiable elements, resulting in low code readability and therefore low security requirements.
5. The method according to claim 1, characterized in that, 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 utilize debugging tools, dynamic execution environments, or instrumentation techniques to analyze the program's execution trajectory, function call relationships, and dynamically loaded code snippets, thereby bypassing static obfuscation protection. Therefore, DAEI analyzes important information that code may expose during dynamic execution, including: 1) Function call risk: Analyze explicit function calls in bytecode, as these instructions can be used to analyze the core logic of a program; 2) Dynamic execution risk: Evaluate the instructions in the bytecode that involve dynamic execution. These instructions allow the program to generate and execute new code at runtime, which is a key focus for attackers. 3) Code execution depth: Analyze the complexity of the execution path and simulate potential dynamic attack paths to determine the difficulty of dynamic code analysis; The Dynamic Attack Exposure Index (DAEI) is calculated by calculating the proportion of related instructions in all instructions, effectively measuring the degree of dynamic attack exposure of the code. The DAEI reflects the degree of code exposure at runtime, determines the difficulty of code parsing under dynamic analysis tools, and further affects the code's security requirements: a high DAEI value indicates that the code contains a large number of dynamically executed instructions. Due to the many dynamic exposure points, attackers can more easily use runtime analysis techniques to monitor critical execution paths, thereby accelerating the reverse engineering process, hence the high security requirements; a low DAEI value indicates that the code relies less on dynamic execution, function calls are restricted, and the degree of exposure of code logic is low, hence the low security requirements.
6. The method according to claim 1, characterized in that, The External Attack Surface Index (EASI) measures the extent to which code interacts with external systems. External system interaction is a means for attackers to exploit vulnerabilities, gain unauthorized access, or inject code. Therefore, EASI assesses the size of the attack surface that code may face by analyzing the interaction patterns between code and the external environment. The EASI assesses the program's risk of exposure to external systems from the following aspects: 1) External API call frequency: Count the number of times the program calls external interactive APIs. These operations involve network communication, file reading and writing, or remote requests, which increases the possibility of being attacked. 2) Degree of external dependency: Analyze the code's dependency on third-party libraries or system APIs. If there are known vulnerabilities in external dependencies, attackers can exploit them as entry points. 3) API call structure analysis: The PageRank algorithm is used to model the call relationships between APIs and identify key interfaces and potential attack paths; By combining this information, EASI assesses the degree of connection between the code and external systems by quantifying the interaction strength of external APIs, providing a quantitative basis for determining the attack surface size and security protection requirements of the program; The EASI directly reflects the degree of external interaction of the code, determines the degree of exposure of the code to external attack surfaces, and further affects the security requirements of the code: a high EASI value indicates that the code interacts frequently with external systems, which means that there are many attack entry points for the code. Attackers can launch attacks by using network communication interfaces, file operations, and external dependency vulnerabilities, which increases the security risk of the system. Therefore, 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 launch attacks through networks, files, or external libraries. This suggests that the code is relatively secure and therefore has low security requirements.
7. The method according to claim 1, characterized in that, The construction of a random dynamic opcode mapping table in S2 specifically includes: The opcode replacement rules are as follows: The categories of replaceable opcodes are as follows: Category 1: No-parameter opcode, opcode value < 90; Category 2: Opcode with low-order parameter, 90 <= opcode value <= 130; Category 3: Opcode with high-order parameter, 145 <= opcode value <= 165; Opcodes can be randomly replaced within their respective categories, but the replaced opcodes must still maintain the original category numbering order to ensure that the Python interpreter can correctly process the instruction parameters and execution logic during parsing; Based on the aforementioned opcode replacement rules, opcode values in different bytecode files are replaced accordingly using a dynamic opcode mapping table. The specific scheme is as follows: S21. According to the opcode replacement rules, extract the opcode values of different categories and define them as sets O1, O2, and 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], thus obtaining the initial opcode mapping table for each category. S22. For bytecode file 1, within each category, the opcodes are randomly rearranged 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], thus obtaining the opcode mapping table for each category of bytecode file 1; S23. Using the same method, perform independent opcode random 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], thus obtaining the various opcode mapping tables for bytecode file 2; S24. For other bytecode files, repeat the above process to generate an independent opcode mapping table for each bytecode file, ensuring that the replacement strategies between different files are independent of each other.
8. A Python bytecode obfuscation system based on dynamic filtering and random replacement, characterized in that, The system includes: The obfuscated file dynamic filtering 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). This allows for a quantitative assessment of the security requirements of bytecode files from multiple dimensions. Based on the five security indicators (DSI, BLCI, SRI, DAEI, and EASI), the module calculates the comprehensive security index (SDI) of the bytecode files using the entropy weight method. Based on the comprehensive security index (SDI), bytecode files with high security requirements that need to be obfuscated are filtered out according to a user-defined threshold. 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, it constructs a random dynamic opcode mapping table, applies each independent opcode mapping table to different bytecode files to be obfuscated, performs dynamic opcode replacement obfuscation operations in bytecode instructions, and generates obfuscated bytecode files. A custom interpreter implementation module is used to perform obfuscation status detection on 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 anti-mapping mechanism is embedded. The module is then recompiled to generate a customized Python interpreter that supports the execution of obfuscated bytecode, and the obfuscated bytecode file is executed using the customized Python interpreter. The formula for calculating the Data Sensitivity Index (DSI) is as follows: ; Where C i Let be the number of occurrences of the i-th sensitive keyword, and let n be the total number of sensitive keywords; TFIDF(C i The TF-IDF values represent the weights of sensitive data 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 within the entire codebase. A high TF-IDF value indicates that the keyword has high importance in the current code snippet. ij This represents the conditional probability of transitioning from keyword i to keyword j; The Business Logic Complexity Index (BLCI) is calculated using the following formula: ; Where E is the number of edges in the control flow graph, representing the number of branches and jumps in the code execution path; N is the number of nodes in the control flow graph, representing the number of basic blocks of code; P is the number of independent entries in the control flow graph, used to measure whether there are multiple execution starting points in the code; H is the path entropy, used to measure whether the different execution paths of the code are uniformly distributed. A high path entropy indicates that the execution paths are uniform. The formula for calculating H is as follows: ; Among them l i The length of the i-th path; the sum of the lengths of all paths. Used for normalization; The execution probability of being considered as the i-th path; The static reversibility index (SRI) is calculated using the following formula: ; Here, Unobfuscated Element Count represents the number of unobfuscated variable names, which has strong semantic information, enabling the logical structure of the program to be inferred through static analysis; Total Instruction Count represents the total number of instructions in the bytecode file. The character entropy of variable names is used as a measure of obfuscation strength. An entropy threshold is set to distinguish between obfuscated and unobfuscated variable names. If the entropy value of a variable name is lower than the threshold, it indicates that the naming regularity is strong and the readability is high, and it is considered 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 program's reversibility under static analysis. The formula for calculating the Dynamic Attack Exposure Index (DAEI) is as follows: ; Exposure Operations Count is the number of instructions in the instruction set involved in dynamic analysis; Total Operations Count is the total number of instructions in the bytecode file, used for normalization calculations to enable DAEI to be applicable to code files of different sizes. The formula for calculating the External Attack Surface Index (EASI) is as follows: ; Where F i Let be the risk factor or weight value of the i-th external API call point or external dependency in the attack surface; n represents the different categories of external API call types. EASI constructs a call graph of sensitive APIs and uses the PageRank algorithm to evaluate the importance of each API node, ultimately assigning an F-value to all nodes. i The total attack surface value is accumulated.
9. An electronic device comprising a processor and a memory, wherein the memory stores at least one instruction, characterized in that, The processor loads and executes at least one instruction to implement the Python bytecode obfuscation method based on dynamic filtering and random replacement as described in any one of claims 1-7.
10. A computer-readable storage medium storing 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 filtering and random replacement as described in any one of claims 1-7.
Citation Information
Patent Citations
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