A structured text code generation method for PLC honey point
By constructing a set of protected variables and engineering metadata, performing equivalent structure transformation and large language model-assisted refinement, the problems of insufficient semantic awareness and insufficient structural complexity in PLC honeypot code generation are solved, generating diverse and runnable code perturbations, and enhancing the defense capability of PLC honeypots.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- GUANGZHOU UNIVERSITY
- Filing Date
- 2026-06-08
- Publication Date
- 2026-07-14
AI Technical Summary
Existing methods for generating structured text code for PLC honeypots suffer from insufficient semantic awareness, inadequate protection of key identifiers and control structures, and insufficient complexity of generated sample structures. This results in a single logical mode and insufficient diversity of expression in the generated samples, and easily leads to errors such as inconsistent types, control flow breaks, and missing key states.
By parsing the original L5X project file, a set of protected variables and project metadata are constructed. Control blocks and linear statement segments are identified and their equivalent structures are transformed. The code is then refined using a large language model to ensure that diverse code perturbations are generated without modifying the set of protected variables or introducing side effects. Loop safety checks and temporary variable declarations are also performed.
It achieves the generation of diverse code perturbations while maintaining semantic consistency, improving the runnability and semantic consistency of generated samples, and enhancing the simulation capability and deception of PLC honeypots.
Smart Images

Figure CN122386884A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of computer technology, and in particular to a method for generating structured text code for PLC honeypots. Background Technology
[0002] In the field of industrial manufacturing automation, programmable logic controllers (PLCs) are the core of industrial control systems, widely used in critical scenarios such as power, chemical, metallurgy, and automated assembly. Structured text (ST), a high-level language supported by the IEC 61131-3 standard, has become the primary means of expressing and implementing complex control logic. With the continuous evolution of advanced persistent threat (APT) attacks targeting PLCs, such as tampering and logic injection, PLC honeypots serve as crucial defense mechanisms. They simulate real PLCs to induce attackers to interact and collect attack behavior data, thereby enhancing the proactive defense capabilities of industrial control systems. To enhance the deceptiveness and realism of honeypots, there is an urgent need for automated batch generation of ST code variant samples with high semantic consistency, diverse presentation formats, and the ability to simulate real control logic. In practical engineering, PLC programs are often encapsulated in project files such as L5X format. These files contain not only ST source code but also project metadata such as tags and register mappings. Therefore, when perturbing ST code, it is essential to protect critical identifiers and the project context to ensure that the generated variant files can be correctly backfilled, imported, and run in the target environment.
[0003] Existing ST code generation and perturbation technologies still suffer from the following shortcomings: First, their semantically aware perturbation capabilities are insufficient. Existing methods largely rely on text-level processing such as regular expression replacement and code block rearrangement, failing to identify control flow nesting and data dependencies. Perturbations may disrupt control boundaries or introduce semantic errors, resulting in a single logical pattern and insufficient diversity in the generated samples. Second, the protection of key identifiers and control structures is inadequate. Existing solutions lack a systematic mechanism for protecting variables and control block constraints. The perturbation process may directly modify key engineering variables such as registers, timers, and state variables, easily leading to errors such as type inconsistencies, control flow breaks, and missing key states, reducing the runnability and semantic consistency of the generated samples. Third, the richness of sample perturbations is insufficient. Existing perturbation methods are mostly limited to simple copying, partial replacement, or single-condition transformations, lacking transformations such as state machine injection, multi-branch condition construction, and expression-level equivalent rewriting. The structural complexity of the generated samples is insufficient, limiting their application in PLC honeypots and other practical scenarios. Therefore, it is urgent to develop a solution to address these problems. Summary of the Invention
[0004] The purpose of this invention is to provide a structured text code generation method for PLC honeypots, which improves the problems of insufficient semantic awareness, insufficient protection of key identifiers and control structures, and insufficient complexity of generated sample structures in the prior art.
[0005] The structured text code generation method for PLC honeypots provided by this invention adopts the following technical solution:
[0006] A structured text code generation method for PLC honeypots, specifically including:
[0007] Parse the original L5X project file to obtain the structured text source code; based on the structured text source code and the original L5X project file, construct a set of protection variables and project metadata;
[0008] The structured text source code is segmented to identify control blocks and linear statement segments; without modifying the set of protected variables or introducing side effects, equivalent structural transformations are performed on control blocks whose number of lines of code does not exceed a preset threshold, and equivalent transformations are performed on expressions.
[0009] Based on engineering metadata, data flow analysis is performed on the transformed code, which is then re-divided into control blocks and linear statement segments. Based on data dependency analysis, the re-divided linear statement segments are rearranged, and the values of initial variable values and constant items in assignment statements are modified. Temporary variables introduced in expression transformation are renamed to avoid conflict with protected variables. A loop safety check is then performed on the code after the above processing.
[0010] The checked code is input into the large language model and refined under the constraints of protected variables. If the refinement is successful, the refined result is used as the final code; otherwise, the input code is used as the final code.
[0011] Based on the project metadata, declaration information is added to the newly added temporary variables in the final code, which is then filled back into the original L5X project file and output.
[0012] The beneficial effects of the structured text code generation method for PLC honeypots provided by this invention are that by constructing a set of protected variables and performing equivalent structure transformation, expression equivalence transformation, and statement rearrangement based on data dependency analysis on control blocks, expressions, and linear statement segments respectively, diverse code perturbations are achieved while maintaining semantic consistency. Furthermore, the transformation space is expanded through cyclic safety checks and Large Language Model (LLM)-assisted refinement, which improves the problems of insufficient semantic awareness, insufficient protection of key identifiers and control structures, and insufficient complexity of generated sample structures in the prior art.
[0013] Optionally, when parsing the original L5X project file to obtain the structured text source code, the following is included:
[0014] The original L5X project file is parsed using the Document Object Model (DOM) to locate the structured text routine nodes, extract the source code text, and restore the XML entity characters. After purification, the structured text source code is obtained.
[0015] Optionally, when constructing the set of protection variables and project metadata based on the structured text source code and the original L5X project files, the following are included:
[0016] The structured text source code is scanned for identifiers, and core business variables are identified by combining preset key variable rules and system address features. Unprotected objects are then filtered out based on a reserved word list to obtain the set of protected variables. The core business variables include key status variables, device-related variables, and timer and counter-related variables.
[0017] Traverse the tag nodes and variable declarations in the original L5X project file, extract variable names, data types, dimension information and array boundaries to form the project metadata.
[0018] Optionally, the side effect operations include reading and writing hardware input / output registers, calling timer function blocks, calling external function blocks, state advancement, or counter updates; the linear statement segment consists of adjacent non-control statements.
[0019] Optionally, equivalent structural transformations are performed on control blocks whose number of lines of code does not exceed a preset threshold, including:
[0020] For an IF control block, when it contains one main branch and no less than two ELSIF branches, and the conditions of each branch can be classified as equality judgments on the same decision object, the IF control block is converted into a CASE structure; for a CASE control block, when it contains no less than three branch items, the CASE control block is converted into an IF-ELSIF-ELSE structure.
[0021] After completing the above structural transformation, perform local transformation on control blocks that begin with IF, WHILE, FOR, CASE, or REPEAT; the local transformation includes rewriting FOR loops into WHILE loops, rewriting WHILE loops into FOR loops, performing condition reverse reorganization or protective pre-judgment on nested IF structures, and performing condition boosting and branch splitting on scenarios where local inner conditions depend only on outer conditions.
[0022] When performing equivalent transformations on expressions, the process includes: performing equivalent transformations on logical expressions based on De Morgan's laws, identifying subexpressions in the expression that consist of constants and replacing them with calculation results, and splitting the expression into multi-step calculations that introduce temporary variables with a preset probability.
[0023] Optionally, when rearranging statements on newly segmented linear statement blocks based on data dependency analysis, the following may be included:
[0024] For each statement in the linear statement segment, record its variable definition set and variable usage set; when the intersection of the variable definition set of each of the two statements with the variable usage set of the other is empty, and the variable definition sets of the two statements have no intersection, and neither statement introduces the side effect operation, it is determined that there is no data dependency between the two statements, and statement rearrangement is performed.
[0025] When modifying the values of initial values of variables and constant items in assignment statements, the following steps are taken: modifying the values of initial values of non-critical temporary variables that do not involve the set of protected variables and do not introduce the side effect operation, as well as constant items in candidate assignment statements, according to a preset probability.
[0026] When renaming temporary variables introduced in expression transformations in a way that does not conflict with protected variables, the process includes: generating replacement names based on a preset template, establishing a correspondence between the original name and the new name after conflict detection, and simultaneously replacing the declaration location and all reference locations.
[0027] Optionally, when performing loop safety checks on the code after the above processing, the checks include: checking the loop structure, and inserting exit logic or a counter protection statement when it is detected that the loop condition variable has not been effectively updated within the loop body.
[0028] Optionally, it also includes: when the preset trigger probability is met and there are no state variables in the current code that conflict with the set of protected variables, generating state variables and a set of state values, and injecting state transition judgments and action statements into the local control area.
[0029] Optionally, when inputting the checked code into a large language model for refinement under protection variable constraints, the following may be included:
[0030] A constrained request containing the set of protected variables, the engineering metadata, and the transformation intent is constructed and sent to the large language model. The result is refined by reusing the least recently used algorithm, and the call is retried using an exponential backoff mechanism.
[0031] The transformation intent includes equivalent rewriting of control structures, equivalent expansion of expressions, reorganization of local statements, introduction of redundant steps, and complication of code representation.
[0032] Optionally, based on project metadata, declaration information is added to newly added temporary variables in the final code, and this information is then populated back into the original L5X project file and output, including:
[0033] Based on the existing declarations recorded in the engineering metadata, name conflict detection is performed on newly added temporary variables. If a conflict exists, a new name is generated by adding a serial number or a random suffix until it is unique. The newly added temporary variable with a unique name and its data type are written into the declaration position.
[0034] Based on the relationship between the routine identifiers and the location of the structured text content nodes preserved during the parsing phase, the final code is written line by line to the corresponding location, and a variant L5X file is output. Attached Figure Description
[0035] Figure 1 This is a flowchart illustrating a structured text code generation method for PLC honeypots, provided in an embodiment of the present invention. Detailed Implementation
[0036] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions in the embodiments of the present invention will be clearly and completely described below. Obviously, the described embodiments are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention. Unless otherwise defined, the technical or scientific terms used herein should have the ordinary meaning understood by those skilled in the art. The terms "comprising" and similar expressions used herein mean that the element or object preceding the word covers the element or object listed after the word and its equivalents, but does not exclude other elements or objects.
[0037] See Figure 1 This invention provides a structured text code generation method for PLC honeypots, comprising the following steps:
[0038] S1. Parse the original L5X project file to obtain the structured text source code; based on the structured text source code and the original L5X project file, construct a set of protection variables and project metadata;
[0039] S2. Segment the structured text source code and identify control blocks and linear statement segments; without modifying the set of protected variables and without introducing side effects, perform equivalent structure transformation on control blocks whose number of lines of code does not exceed a preset threshold, and perform equivalent transformation on expressions;
[0040] S3. Based on the engineering metadata, perform data flow analysis on the transformed code and re-segment it into control blocks and linear statement sections; based on data dependency analysis, rearrange the statements in the re-segmented linear statement sections, modify the values of constant items in variable initial values and assignment statements, and rename the temporary variables introduced in the expression transformation to avoid conflict with protected variables; perform loop safety checks on the code after the above processing.
[0041] S4. Input the checked code into the large language model and refine it under the protection variable constraint. If the refinement is successful, the refined result is used as the final code; otherwise, the input code is used as the final code.
[0042] S5. Based on the project metadata, add declaration information for newly added temporary variables in the final code, fill it back into the original L5X project file, and output it.
[0043] In some embodiments, when parsing the original L5X project file and obtaining the structured text source code in step S1, document object model parsing is performed on the original L5X project file to locate the structured text routine nodes, extract the source code text, and restore the XML entity characters. After purification processing, the structured text source code is obtained. The specific process is as follows:
[0044] S101. Load the original L5X project file using the Document Object Model Parser, retaining the contents of the file. <controller> 、 <programs> 、 <tags>The project's metadata and structure are preserved so that the project's metadata and layout are not altered during write-back.
[0045] S102, Traverse each program node ( <program>) and routine set nodes ( <routines>), locate routine nodes whose routine type attribute is structured text ( <routine type="ST">Extract the structured text content nodes ( <stcontent>Extracting text content from structured text content nodes: When structured text content consists of multiple nodes... <line>When storing child nodes row by row, by <line>The line number attribute of the child node reads the code text of each line in sequence and concatenates them into a complete structured text source code; when the structured text content is stored as a whole CDATA block, the text content within the CDATA block is directly extracted as the structured text source code.
[0046] S103. Perform XML entity character unescapement processing on the extracted text content, and restore <, >, &, etc. to the corresponding characters in the source code to obtain the unescaped structured text source code.
[0047] S104. Clean up the structured text source code after the escape sequence, including deleting residual XML tags, unifying the format of block comments and line comments, and standardizing newline characters and blank lines to obtain the cleaned structured text source code, while retaining the routine identifiers and the location information of the structured text content nodes corresponding to each cleaned structured text source code.
[0048] In some embodiments, when constructing the set of protected variables and project metadata based on the structured text source code and the original L5X project file in step S1, the structured text source code is scanned for identifiers. Core business variables are identified by combining preset key variable rules and system address features. Unprotected objects are then filtered out based on a reserved word list to obtain the set of protected variables. The core business variables include key status variables, device-related variables, and timer and counter-related variables. The tag nodes and variable declarations in the original L5X project file are traversed to extract variable names, data types, dimension information, and array boundaries to form the project metadata. The specific process is as follows:
[0049] S111. Perform identifier scanning on the cleaned structured text source code, extract candidate identifiers according to the IEC 61131-3 structured text naming rules, and remove comment residues, numerical constants, string constants and invalid symbol fragments from the candidate identifiers.
[0050] S112. Based on a preset key variable rule base, identify core business variables through a combination of precise matching and pattern matching; identify PLC system address variables based on features such as preset address prefixes, hierarchical separators, and input / output mapping address formats.
[0051] S113. Merge core business variables, PLC system address variables, structured text reserved keyword dictionary and built-in function dictionary to obtain the initial set of protected variables;
[0052] S114. Read the new protection list and the unprotected protection list in the project configuration. After removing blanks, deduplication and name normalization, merge the variables in the new protection list into the initial protection variable set, and remove the corresponding variables from the initial protection variable set according to the unprotected protection list to obtain the protection variable set.
[0053] S115, Traverse the tag nodes in the original L5X project file ( <tags>The system extracts variable names, data types, and dimension information from the declaration nodes and related declaration nodes. When the declaration contains array dimensions, it further parses the array boundaries to form the first engineering metadata.
[0054] S116. Perform pattern matching on the explicit declaration segments in the structured text source code to extract variable names, data types, and array definition information to form the second engineering metadata.
[0055] S117. Merge the first engineering metadata and the second engineering metadata. When the same variable is declared in both, the declaration result in the first engineering metadata shall be used first, and the second engineering metadata shall be used to supplement the missing items to form engineering metadata. The engineering metadata includes variable name, data type, dimension information, array boundary, declaration source and existing declaration status.
[0056] In the above embodiments, the set of protected variables can be formally represented as: ,in, For the core business variable set, For the set of system address variables, To preserve the set of keywords and built-in functions, This is a set of variables extracted from the engineering declaration information. PLC system address variables, structured text reserved keyword lists, and built-in function lists are included in the protected variable set and will not be considered as perturbation objects in subsequent perturbations. The protected variable set is used for operations such as renaming, deleting, injecting, and rewriting control flow of constraint variables; the engineering metadata is used to support subsequent variable analysis, array boundary checks, supplementation of temporary variable declarations, and refinement of constrained code.
[0057] In some embodiments, when segmenting the structured text source code and identifying control blocks and linear statement segments in step S2, firstly, the purified structured text source code is traversed at the statement level, and each statement is marked as a control block statement or a non-control statement according to its type. Control block statements include IF, WHILE, FOR, CASE, REPEAT, and state machine-related statements, while non-control statements are statements other than control block statements. Then, based on the start and end markers of the control block statements, the boundaries of each control block are identified, and a nested block structure is constructed according to the hierarchical inclusion relationship of the control blocks. Adjacent non-control statements are aggregated into linear statement segments according to their order in the source code, and each linear statement segment consists of a continuous non-control statement. Finally, the identified control blocks and linear statement segments are organized into a nested list structure that can be used for subsequent semantic analysis and perturbation processing. In the above embodiments, by preserving the control structure boundary information, perturbations can be performed on local code blocks without destroying the original control logic.
[0058] In some embodiments, when performing equivalent structure transformation on control blocks with no more than a preset threshold number of lines of code in step S2, the specific process is as follows:
[0059] S201. Traverse each control block in the nested block structure, obtain the type, start position, end position, number of branches, conditional expression and branch body content of the control block, and filter control blocks whose code lines and nesting complexity do not exceed the preset threshold and do not involve protected variable sets and side effect operations as candidate control blocks;
[0060] S202. For the IF control block in the candidate control block, when it contains a main branch and no less than two ELSIF branches, and the conditions of each branch can be classified as equal judgments on the same decision object, extract the common decision expression, branch value items, branch body and default branch, and rewrite the IF control block into a CASE structure.
[0061] S203. For the CASE control block in the candidate control block, when it contains no less than three branch items, extract the value items of each branch and the corresponding branch body content, expand each branch value into an equal value judgment condition, and reconstruct it into an IF-ELSIF-ELSE structure.
[0062] S204. For the candidate control blocks that have completed the above structural conversion, further perform diversified equivalent control flow rewriting to enrich the code structure representation and maintain functional logic consistency. The triggering conditions for diversified equivalent control flow rewriting are: the target control block starts with IF, WHILE, FOR, CASE or REPEAT, does not involve hardware input / output mapping register variables, timer function blocks and external function block calls, does not introduce the side effect operations, the number of lines of code does not exceed the preset threshold, and no variables are added or deleted from the set of protected variables before and after rewriting.
[0063] S205. The local transformations supported by diversified equivalent control flow rewriting can be: loop structure conversion, including rewriting a FOR loop with clear boundaries and a fixed step size into a semantically equivalent WHILE loop, and rewriting a WHILE loop that satisfies initialization, boundary comparison, and fixed step size update conditions into a FOR loop; nested condition flattening, including reducing the nesting level of nested IF structures without side effects through condition reversal, protective pre-judgment, or early termination rewriting; and local nesting compression, including compressing the control flow depth through condition lifting and branch splitting for scenarios where the local inner condition only depends on the outer condition.
[0064] Example 1: Equivalent conversion between FOR and WHILE loops
[0065] Original FOR loop control block (ST):
[0066] "FOR i := 0 TO 9 BY 1 DO
[0067] sum := sum + arr[i];
[0068] END_FOR;
[0069] The equivalent rewritten WHILE loop:
[0070] i := 0;
[0071] WHILE i <= 9 DO
[0072] sum := sum + arr[i];
[0073] i := i + 1;
[0074] END_WHILE;
[0075] In this example, the initial value of the loop variable, the termination boundary, and the step size can all be explicitly extracted. Furthermore, the loop body does not contain a FOR control block that includes hardware input / output writes, timer function blocks, external function block calls, or other side-effect operations. This is rewritten as a semantically equivalent WHILE control block: first, the loop variable, initial value, termination value, and step size parameters are extracted from the FOR statement; the loop variable initialization statement is moved to the beginning; then, a WHILE loop condition expression is constructed based on the termination condition; and finally, a step size update statement is added at the end of the loop body. This transformation achieves diverse expressions of the control flow structure without changing the number of iterations, execution order, or loop body logic.
[0076] Example 2: Protective front rewriting of nested IF structures
[0077] Original ST code segment:
[0078] "IF motor_ready THEN
[0079] IF safety_ok THEN
[0080] start_cmd := TRUE;
[0081] END_IF;
[0082] END_IF;
[0083] After equivalent rewriting:
[0084] "IF NOT motor_ready THEN
[0085]
[0086] ELSIF NOT safety_ok THEN
[0087]
[0088] ELSE
[0089] start_cmd := TRUE;
[0090] END_IF;
[0091] In this example, for nested conditional structures without side-effect operations, they are rewritten as protective pre-conditions. The original layer-by-layer nested execution conditions are rewritten as pre-interception conditions. This reduces the nesting depth of the control structure while maintaining the semantics of executing start_cmd := TRUE only when both motor_ready and safety_ok are satisfied.
[0092] In the above embodiments, by performing diversified equivalent control flow rewriting after completing specific structural conversions, the diversity of generated variants and structural complexity can be improved while maintaining the original control semantics, execution path constraints and the stability of key variables.
[0093] In some embodiments, the process of performing an equivalent transformation on the expression in step S2 is as follows:
[0094] S211. Apply De Morgan's Law to perform equivalent transformations on negation operations in logical expressions: Identify logical expressions wrapped by negation operations through regular expression matching, and split and reconstruct them according to operator type. For example, convert NOT(x AND y) to (NOT x)OR(NOT y), and convert NOT(x OR y) to (NOT x)AND(NOT y).
[0095] S212. Identify subexpressions in an expression that consist entirely of constants (such as 5+6, 3×2-1), directly calculate the constant result of the subexpression and replace the original expression, and maintain the consistency of integer and floating-point types during calculation; constant folding covers the four basic arithmetic operations: addition (+), subtraction (-), multiplication (×), and division ( / );
[0096] S213. For complex assignment expressions that satisfy safety constraints, trigger expression splitting with a preset probability: Identify candidate assignment statements whose rvalues contain compound arithmetic operations, Boolean combination operations, or multiple operands. When a randomly sampled value satisfies the preset splitting probability, decompose the complex rvalue expression into multiple intermediate calculations and introduce temporary variables to cache the intermediate values. For example, split the original expression "a := b + c × d;" into "temp_1234 := c × d; a := b + temp_1234;". Safety constraints include not involving protected variable sets, not involving hardware input / output references, and not involving timer function blocks or external function block calls. This probability-triggered mechanism can control the disturbance intensity and engineering compatibility while avoiding the uniform rewriting of all candidate expressions, thereby improving the structural differences and formal diversity among generated variants.
[0097] In some embodiments, during step S3, when performing data flow analysis on the transformed code based on engineering metadata and re-segmenting it into control blocks and linear statement segments, static analysis is performed on the code transformed in step S2 to extract the definition location, usage location, and information on used but undeclared variables. Simultaneously, combining the variable types, dimension information, and array boundaries recorded in the engineering metadata, state variables, count variables, and used but undeclared variables are identified, forming variable analysis results. Based on the variable analysis results, the current code is re-segmented into statements, dividing it into control blocks and linear statement segments according to the start and end markers of IF, WHILE, FOR, CASE, and REPEAT control structures.
[0098] In some embodiments, when rearranging the re-segmented linear statement segments based on data dependency analysis in step S3, the variable definition set and variable usage set are recorded for each statement in the linear statement segment. When the intersection of the variable definition set of each of the two statements and the variable usage set of the other is empty, and the variable definition sets of the two statements have no intersection, and neither statement introduces any side effects, it is determined that there is no data dependency between the two statements, and statement rearrangement is performed. The specific process is as follows:
[0099] S301. For each linear statement segment, record the variable definition set and variable usage set for each statement within it;
[0100] S302. Determine the data dependency relationship between each pair of statements within the same linear statement segment: When the intersection of the variable definition set of each statement with the variable set of the other statement is empty, and the intersection of the variable definition sets of the two statements is empty, it is determined that the two statements have no direct data dependency.
[0101] S303. For two statements that are determined to have no direct data dependency, further check whether they involve identifiers in the protected variable set, hardware input / output references, timer function block calls, external function block calls, and other side-effect operations; determine the two statements that do not involve the above items as reorderable candidate statements;
[0102] S304. Perform random rearrangement on rearrangeable candidate statements.
[0103] In some embodiments, when modifying the initial values of variables and constant items in assignment statements in step S3, each statement in the newly segmented linear statement block is traversed. Non-critical temporary variable initial values and constant items in candidate assignment statements that do not affect the main control semantics, do not involve the protection variable set, and do not introduce side-effect operations are selected as the objects for value modification, and their values are modified according to a preset probability. Furthermore, for redundant statements or intermediate value cache statements without side effects that are determined by constraints to be unaffected by repeated execution, restricted copying is performed according to a configured probability to increase the redundancy of segments and code performance differences.
[0104] In some embodiments, when renaming the temporary variables introduced in the expression transformation in step S3 to avoid conflict with protected variables, replacement names are generated according to a preset template. After conflict detection, a correspondence between the original name and the new name is established, and the declaration location and all reference locations are replaced simultaneously. The specific process is as follows:
[0105] S311. Temporary variables introduced in expression transformation, as well as auxiliary index variables, cache variables, and intermediate variables that do not belong to the protected variable set within the local scope, are included in the candidate variable set.
[0106] S312. Generate replacement names for each variable in the candidate variable set according to the preset naming template, and verify one by one whether the replacement names conflict with the identifiers in the protected variable set, the existing declarations in the project file, and the existing variable names in the current scope.
[0107] S313. After the verification is passed, establish a one-to-one mapping relationship between the original name and the replacement name to ensure that different original variables are mapped to different replacement names;
[0108] S314. Based on the mapping relationship, perform synchronous replacement at the variable declaration location and all reference locations. After replacement, the variable mapping remains consistent and the scope relationship remains unchanged.
[0109] In the above embodiments, the renaming relationship can be represented as a mapping. ,in Represents the set of candidate original variable names; This represents the set of new variable names after the replacement. Represents the original variable Replaced with new variable ;when When, satisfy This is to avoid name merging conflicts between different variables after replacement.
[0110] In some embodiments, during the loop safety check of the processed code in step S3, the loop structures in the processed code are traversed, including WHILE loops and REPEAT loops. For each loop structure, it is checked whether its loop condition variable is effectively updated within the loop body, and whether there is a control flow gap that could lead to an infinite loop. When it is detected that the loop condition variable has not been effectively updated within the loop body, or that a control flow gap exists, exit logic or a counter protection statement is inserted.
[0111] In some preferred embodiments, state machine fragments can also be injected according to a preset probability: when the preset trigger probability is met and there are no state variables in the current code that conflict with the set of protected variables, state variables and a set of state values are generated, and state transition judgments and action statements are injected into the local control area to increase the complexity of the control flow representation while maintaining the overall logic's resolvability and rewritability.
[0112] The code perturbation refinement assisted by the large language model is a configurable feature, enabled by default and can be disabled; when using it, the corresponding API credentials and calling parameters need to be configured.
[0113] In some embodiments, in step S4, the checked code is input into the large language model and refined under the constraint of protected variables. When the refinement is successful, the refined result is used as the final code; otherwise, the input code is used as the final code. The specific process is as follows:
[0114] S401. Construct a constrained request, which includes a set of protected variables, project name, file name, program name, routine name, and tag declaration information and project meta-information related to the current structured text code snippet, the ST code to be refined, and the transformation intent matching the current code snippet. The transformation intent is used to limit the target direction of this refinement and the types of perturbations allowed, so that the large language model performs constrained rewriting according to predetermined transformation requirements, rather than freely generating the original code without constraints. This includes equivalent rewriting of control structures, equivalent expansion of expressions, local statement reorganization, introduction of redundant intermediate steps, and increasing the complexity of code representation.
[0115] S402. Send the constrained request to the large language model. The constrained request also includes output constraints and prohibitions, which are used to limit the return of only ST code, prohibit the addition of explanatory text, comply with IEC 61131-3 syntax, and prohibit the modification of the identifiers in the set of protected variables, and prohibit the addition of hardware register writes and external function block calls.
[0116] S403, the Least Recently Used algorithm reuses existing refined results and implements exponential backoff (delay increases exponentially with the base) and maximum retry limit for large language model calls to cope with rate limiting or temporary failures;
[0117] S404. When the large language model returns refined code that meets the constraints, the refined code shall be used as the final code; when the call fails or the return result does not meet the constraints, the code before inputting the large language model shall be used as the final code, and an audit log shall be recorded for traceability.
[0118] In some embodiments, during step S5, based on project metadata, declaration information is added to the newly added temporary variables in the final code. When this information is backfilled into the original L5X project file and output, name conflict detection is performed on the newly added temporary variables based on the existing declarations recorded in the project metadata. If a conflict exists, a new name is generated by appending a serial number or a random suffix until it is unique. The newly added temporary variable with a unique name and its data type are written to the declaration location. According to the location relationship between the routine identifier and the structured text content node retained during the parsing phase, the final code is written line by line to the corresponding location, and a variant L5X file is output. The specific process is as follows:
[0119] S501, Based on the document object model tree preserved during the parsing phase, maintain... <controller> 、 <programs> 、 <routine>and <tags>The original project nodes and their hierarchical structure remain unchanged, serving as the basic framework for subsequent declaration writing and code backfilling; this step does not change the version number, device model, comments, or other meta-attributes in the original project files;
[0120] S502. Traverse the existing variable declaration names in the original L5X project file, and combine them with the temporary variable names that have been added but not yet written back during the current generation process to construct a set of occupied names.
[0121] S503. For newly added temporary variables, generate candidate names according to the preset naming template, and check whether the candidate names already exist in the set of occupied names; if there is a conflict, generate new candidate names by adding an incrementing sequence number, a random number suffix, or regenerating the name, until a unique name that is not occupied is obtained; after the name is determined, register it in the set of occupied names.
[0122] S504. Write the newly added temporary variable with a unique name and its data type to the declaration location; by default, write it to the tag collection node, and in scenarios where it is necessary to preserve the local declaration structure, write it to the local declaration location of the corresponding routine.
[0123] S505. Based on the location relationship between the routine identifiers and structured text content nodes retained during the parsing phase, locate the original code position corresponding to each routine, and organize the final code line by line. <line number="i"><![CDATA[...]]>< / line> The code is written back to the original code location;
[0124] S506. Generate an XML declaration header for the completed L5X document, perform indentation, line breaks and node format standardization processing, retain the version number, device model and comments and other meta-attributes in the original project file, export the variant L5X file according to the preset output path and naming rules, and record the output result log.
[0125] In the above embodiments, by constructing a set of occupied names and performing conflict detection, the names of newly added temporary variables are ensured to be unique within the project scope, avoiding name conflicts, reference ambiguities, and project import conflicts. By backfilling the code according to the positioning relationship retained in the parsing stage and keeping the original project meta-attributes unchanged, the generated variant L5X file is ensured to have compatibility and importability in the target project environment. In batch generation scenarios, multiple L5X variant files with consistent structure but different perturbation results can be generated, and output result logs are recorded for auditing and traceability. The finally generated variant file can be deployed on PLC honeypots, thereby enhancing the simulation capabilities and deception of PLC honeypots.
[0126] Example 3: Expression splitting, introduction of temporary variables, reorganization of equivalent condition expressions, and writing back added declaration information.
[0127] Original ST code snippet:
[0128] "IF State = 2 & input_1 THEN
[0129] gear_ratio := gear_ratio + 0.5;
[0130] State := 3;
[0131] ELSIF State = 2 & input_2 THEN
[0132] gear_ratio := gear_ratio - 0.5;
[0133] State := 3;
[0134] ELSIF State = 2 & input_0 THEN
[0135] State := 5;
[0136] END_IF;
[0137] This invention is based on a variant of the above-mentioned code snippet after perturbation:
[0138] "IF State = 2 & input_1 THEN
[0139] temp_gear_ratio_2679 := gear_ratio;
[0140] gear_ratio := temp_gear_ratio_2679 + 0.5;
[0141] State := 3;
[0142] ELSIF State = 2 & input_2 THEN
[0143] gear_ratio := gear_ratio - 0.5;
[0144] State := 3;
[0145] ELSIF NOT ((NOT (State = 2)) OR (NOT (input_0))) THEN
[0146] State := 5;
[0147] END_IF;
[0148] The following shows an example of writing back the declaration of one of the temporary variables:
[0149] " <tag name="temp_gear_ratio_2679" tagtype="Base" datatype="REAL" externalaccess="Read / Write">
[0150] <data format="L5K">0.0< / data>
[0151] <data format="Decorated">
[0152] <datavalue DataType="REAL" Radix="Float" Value="0.0" / >
[0153] < / data>
[0154] < / tag> "
[0155] While maintaining the original control semantics, the above ST code snippet undergoes structured perturbation processing, including expression splitting, the introduction of temporary variables, and the reorganization of equivalent conditional expressions. In this example, by introducing a temporary variable temp_gear_ratio_2679 to cache intermediate values of the variable gear_ratio before performing the addition of 0.5, the original single-step assignment expression is reconstructed into a multi-step calculation process. At the same time, the branch corresponding to "State = 2 & input_0" is rewritten into a logical expression with semantically equivalent meaning to enhance the difference in code presentation.
[0156] Meanwhile, for temporary variables newly added during the disturbance process, the system further generates corresponding declaration information and writes it to the corresponding declaration location in the project file during the output stage. This reduces the risk of import errors and runtime errors in the generated sample within the original project environment and PLC honeypot scenario. In this example, the temporary variable declaration is written... <tags>The process is presented in a node-based manner to illustrate the process of writing back the newly added declaration information and the corresponding code after the disturbance.
[0157] While embodiments of the present invention have been described in detail above, it will be apparent to those skilled in the art that various modifications and variations can be made to these embodiments. However, it should be understood that such modifications and variations fall within the scope and spirit of the invention as set forth in the claims. Furthermore, the invention described herein may have other embodiments and can be implemented or carried out in various ways.< / tags> < / tags> < / routine> < / programs> < / controller> < / tags> < / line> < / line> < / stcontent> < / routine> < / routines> < / program> < / tags> < / programs> < / controller>
Claims
1. A structured text code generation method for PLC honeypots, characterized in that, include: Parse the original L5X project file to obtain the structured text source code; Based on the structured text source code and the original L5X project file, a set of protection variables and project metadata are constructed. The system segments structured text source code, identifying control blocks and linear statement sections. Without modifying the set of protected variables or introducing side effects, equivalent structural transformations are performed on control blocks whose number of lines of code does not exceed a preset threshold, and equivalent transformations are performed on expressions. Based on engineering metadata, data flow analysis is performed on the transformed code, and it is re-divided into control blocks and linear statement segments. Based on data dependency analysis, the re-segmented linear statement blocks are rearranged, and the initial values of variables and constant items in assignment statements are modified. Temporary variables introduced in expression transformations are renamed to avoid conflict with protected variables. The code after the above processing is then subjected to loop safety checks. The checked code is input into the large language model and refined under the constraints of protected variables. If the refinement is successful, the refined result is used as the final code; otherwise, the input code is used as the final code. Based on the project metadata, declaration information is added to the newly added temporary variables in the final code, which is then filled back into the original L5X project file and output.
2. The method as described in claim 1, characterized in that, When parsing the original L5X project file to obtain the structured text source code, the following is included: The original L5X project file is parsed using the Document Object Model (DOM) to locate the structured text routine nodes, extract the source code text, and restore the XML entity characters. After purification, the structured text source code is obtained.
3. The method as described in claim 1, characterized in that, When constructing the protection variable set and project metadata based on structured text source code and original L5X project files, the following are included: The structured text source code is scanned for identifiers, and core business variables are identified by combining preset key variable rules and system address features. Unprotected objects are then filtered out based on a reserved word list to obtain the set of protected variables. The core business variables include key status variables, device-related variables, and timer and counter-related variables. Traverse the tag nodes and variable declarations in the original L5X project file, extract variable names, data types, dimension information and array boundaries to form the project metadata.
4. The method as described in claim 1, characterized in that, The side effect operations include reading and writing hardware input / output registers, calling timer function blocks, calling external function blocks, state advancement, or counter updates; the linear statement segment consists of adjacent non-control statements.
5. The method as described in claim 1, characterized in that, Perform equivalent structure transformations on control blocks whose number of lines of code does not exceed a preset threshold, including: For an IF control block, when it contains one main branch and no less than two ELSIF branches, and the conditions of each branch can be classified as equality judgments on the same decision object, the IF control block is converted into a CASE structure; for a CASE control block, when it contains no less than three branch items, the CASE control block is converted into an IF-ELSIF-ELSE structure. After completing the above structural transformation, perform local transformation on control blocks that begin with IF, WHILE, FOR, CASE, or REPEAT; the local transformation includes rewriting FOR loops into WHILE loops, rewriting WHILE loops into FOR loops, performing condition reverse reorganization or protective pre-judgment on nested IF structures, and performing condition boosting and branch splitting on scenarios where local inner conditions depend only on outer conditions. When performing equivalent transformations on expressions, the process includes: performing equivalent transformations on logical expressions based on De Morgan's laws, identifying subexpressions in the expression that consist of constants and replacing them with calculation results, and splitting the expression into multi-step calculations that introduce temporary variables with a preset probability.
6. The method as described in claim 1, characterized in that, Based on data dependency analysis, when reordering statements from newly segmented linear statement blocks, the following is included: For each statement in the linear statement segment, record its variable definition set and variable usage set; when the intersection of the variable definition set of each of the two statements with the variable usage set of the other is empty, and the variable definition sets of the two statements have no intersection, and neither statement introduces the side effect operation, it is determined that there is no data dependency between the two statements, and statement rearrangement is performed. When modifying the values of initial values of variables and constant items in assignment statements, the following steps are taken: modifying the values of initial values of non-critical temporary variables that do not involve the set of protected variables and do not introduce the side effect operation, as well as constant items in candidate assignment statements, according to a preset probability. When renaming temporary variables introduced in expression transformations in a way that does not conflict with protected variables, the process includes: generating replacement names based on a preset template, establishing a correspondence between the original name and the new name after conflict detection, and simultaneously replacing the declaration location and all reference locations.
7. The method as described in claim 1, characterized in that, When performing loop safety checks on the code after the above processing, the following steps are taken: check the loop structure, and insert exit logic or counter protection statements when it is detected that the loop condition variable has not been effectively updated within the loop body.
8. The method as described in claim 7, characterized in that, Also includes: When the preset trigger probability is met and there are no state variables in the current code that conflict with the set of protected variables, a set of state variables and state values is generated, and the state transition judgment and action statement are injected into the local control area.
9. The method as described in claim 1, characterized in that, The checked code is then input into the large language model for refinement under protected variable constraints, including: A constrained request containing the set of protected variables, the engineering metadata, and the transformation intent is constructed and sent to the large language model. The result is refined by reusing the least recently used algorithm, and the call is retried using an exponential backoff mechanism. The transformation intent includes equivalent rewriting of control structures, equivalent expansion of expressions, reorganization of local statements, introduction of redundant steps, and complication of code representation.
10. The method as described in claim 1, characterized in that, Based on project metadata, declaration information is added to newly added temporary variables in the final code. This information is then populated back into the original L5X project file and output, including: Based on the existing declarations recorded in the engineering metadata, name conflict detection is performed on newly added temporary variables. If a conflict exists, a new name is generated by adding a serial number or a random suffix until it is unique. The newly added temporary variable with a unique name and its data type are written into the declaration position. Based on the relationship between the routine identifiers and the location of the structured text content nodes preserved during the parsing phase, the final code is written line by line to the corresponding location, and a variant L5X file is output.