Command injection prevention method, apparatus, device, and medium
Patent Information
- Application Number
- CN202611328179.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-28
- Publication Date
- 2026-10-16
AI Technical Summary
[0007]本申请实施例提供了一种命令注入防御方法、装置、设备及介质,旨在解决相关技术中存在的基于字符特征的黑名单过滤因缺乏语义理解导致易被混淆绕过且误报率高,而基于语法树的语义分析虽精度较高,却面临复杂输入下的资源耗尽风险及解析器与执行环境间的语法理解偏差盲区等诸多技术问题
[0012] In the above-described scheme implemented by command injection defense methods, devices, equipment, and media, command input data input by the user is received, and it is determined whether the command input data can be parsed into a structured syntax tree. If the command input data can be parsed into a structured syntax tree, a semantic-level security check path is entered, and a semantic-level security check is performed using the syntax tree parsing result to obtain a first security check result. If the command input data cannot be parsed into a structured syntax tree, a text-level security check path is entered, and a text-level security check is performed based on character features to obtain a second security check result. Based on the first security check result or the second security check result, it is determined whether the command input data is allowed to be submitted to the corresponding command execution environment. In this invention, by distinguishing whether command input data can be parsed into a structured syntax tree, and enabling two security check paths—semantic and text-level—for collaborative verification, the invention achieves accurate semantic dimension recognition through the structured syntax tree, distinguishing syntactic fragments such as environment variables, commands, and parameters, significantly reducing false positives and false negatives caused by character matching. Furthermore, by setting a text-level character feature fallback verification path, it provides continuous basic security protection even in scenarios where syntax parsing fails, eliminating the verification interruption defects inherent in single verification paths. Simultaneously, based on the corresponding security check results output from both paths, a unified release decision is made. In scenarios with extremely high requirements for command execution security and continuity, such as finance and healthcare, this invention balances the ability to perform refined detection of complex scripts with fault tolerance protection for unparseable text, thereby comprehensively improving the scenario adaptability and security coverage completeness of the command injection defense system.
Smart Images

Figure CN122933245A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of cybersecurity technology, and is applicable to the financial or medical fields, particularly to a command injection defense method, device, equipment, and medium. Background Technology
[0002] In the field of cybersecurity, command injection has long been one of the core threats to web application security and system operation and maintenance security due to its extremely high harm and wide attack surface. Attackers can penetrate the boundaries of applications and directly execute malicious instructions on the underlying operating system by implanting specific syntactic structures (such as command separators, redirection characters, or subcommand substitution characters) into controlled input, leading to serious consequences such as data leakage and server compromise.
[0003] To address the aforementioned threats, there are two main defensive technology approaches currently available: Firstly, there's the character-feature-based blacklist filtering mechanism. This technology scans user-submitted strings using predefined regular expression rules, attempting to block input containing high-risk characters (such as semicolons, pipes, and backticks). However, this text-matching mechanism inherently suffers from semantic fragmentation. Because regular expressions cannot understand the execution logic and context of commands, attackers can easily exploit encoding conversions, quotation mark wrapping, variable concatenation, or wildcard manipulation to construct semantically valid but malicious instructions, thus easily penetrating a single layer of regular expression defense. Furthermore, overly strict regular expression rules often mistakenly flag legitimate business input, leading to a high false positive rate.
[0004] Secondly, there's the semantic analysis mechanism based on syntax tree parsing. This technology attempts to transform the input string into an abstract syntax tree (AST) and identify dangerous semantic structures (such as command substitution, process substitution, etc.) by traversing syntax nodes. Although this method theoretically has higher detection accuracy, it faces severe resource consumption and compatibility issues in engineering practice. On the one hand, when faced with extremely long inputs, deep recursion, or complex dynamic syntax of specific interpreters (such as zsh and bash), the syntax tree parsing process is prone to exhausting computing resources or causing the parser to crash, resulting in service unavailability (DoS). On the other hand, there are often subtle grammatical understanding discrepancies between the parsing model used for security checks and the target command interpreter. These discrepancies may cause certain control characters or escape sequences to be ignored during detection but take effect during execution, creating a blind spot in defense.
[0005] Furthermore, existing technologies typically use these two mechanisms in isolation, lacking the ability to adaptively handle different input data types. For example, for simple parameter inputs and complex script inputs, the same rigid detection logic is often used, failing to ensure both detection accuracy and system robustness.
[0006] For example, in the end-of-day batch processing scenario of the core financial accounting system, the system often needs to call the underlying Shell command to compress and archive the transaction records of the entire bank. If it encounters complex injection instructions constructed by attackers, including nested redirects and specific control characters, traditional regular expression filtering is easily bypassed because it cannot understand the semantics. On the other hand, single AST parsing often leads to service paralysis due to the exhaustion of parser resources caused by the excessive complexity of the script. Summary of the Invention
[0007] This application provides a command injection defense method, apparatus, device, and medium, aiming to solve many technical problems in related technologies, such as blacklist filtering based on character features being easily confused and bypassed due to a lack of semantic understanding and having a high false positive rate, while semantic analysis based on syntax trees, although more accurate, faces the risk of resource exhaustion under complex inputs and blind spots in the syntax understanding between the parser and the execution environment.
[0008] In a first aspect, embodiments of this application provide a command injection defense method, the method comprising: Receive command input data from the user and determine whether the command input data can be parsed into a structured syntax tree; In response to the command input data being parsed into a structured syntax tree, the system enters the semantic-level security check path, performs a semantic-level security check using the syntax tree parsing result, and obtains the first security check result. In response to the fact that the command input data cannot be parsed into a structured syntax tree, the text-level security check path is entered, and a text-level security check is performed based on character features to obtain a second security check result; Based on the first security check result or the second security check result, determine whether it is permissible to submit the command input data to the corresponding command execution environment.
[0009] Secondly, embodiments of this application provide a command injection defense device, the device comprising: The receiving module is used to receive command input data input by the user and determine whether the command input data can be parsed into a structured syntax tree; The first inspection module is used to respond to the command input data being parsed into a structured syntax tree, enter the semantic-level security inspection path, perform semantic-level security inspection using the syntax tree parsing result, and obtain the first security inspection result; The second inspection module is used to respond to the fact that the command input data cannot be parsed into a structured syntax tree, enter the text-level security inspection path, perform text-level security inspection based on character features, and obtain the second security inspection result; The determination module is used to determine, based on the first security check result or the second security check result, whether it is permissible to submit the command input data to the corresponding command execution environment.
[0010] Thirdly, a computer device is provided, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the steps of the command injection defense method described above.
[0011] Fourthly, a computer-readable storage medium is provided, which stores a computer program that, when executed by a processor, implements the steps of the command injection defense method described above.
[0012] In the above-described scheme implemented by command injection defense methods, devices, equipment, and media, command input data input by the user is received, and it is determined whether the command input data can be parsed into a structured syntax tree. If the command input data can be parsed into a structured syntax tree, a semantic-level security check path is entered, and a semantic-level security check is performed using the syntax tree parsing result to obtain a first security check result. If the command input data cannot be parsed into a structured syntax tree, a text-level security check path is entered, and a text-level security check is performed based on character features to obtain a second security check result. Based on the first security check result or the second security check result, it is determined whether the command input data is allowed to be submitted to the corresponding command execution environment. In this invention, by distinguishing whether command input data can be parsed into a structured syntax tree, and enabling two security check paths—semantic and text-level—for collaborative verification, the invention achieves accurate semantic dimension recognition through the structured syntax tree, distinguishing syntactic fragments such as environment variables, commands, and parameters, significantly reducing false positives and false negatives caused by character matching. Furthermore, by setting a text-level character feature fallback verification path, it provides continuous basic security protection even in scenarios where syntax parsing fails, eliminating the verification interruption defects inherent in single verification paths. Simultaneously, based on the corresponding security check results output from both paths, a unified release decision is made. In scenarios with extremely high requirements for command execution security and continuity, such as finance and healthcare, this invention balances the ability to perform refined detection of complex scripts with fault tolerance protection for unparseable text, thereby comprehensively improving the scenario adaptability and security coverage completeness of the command injection defense system. Attached Figure Description
[0013] To more clearly illustrate the technical solutions of the embodiments of this application, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0014] Figure 1 This is a schematic diagram of an application environment for a command injection defense method according to an embodiment of the present invention.
[0015] Figure 2 A schematic flowchart of a command injection defense method according to an embodiment of this application is shown.
[0016] Figure 3 A schematic flowchart of step S202 in a command injection defense method according to an embodiment of this application is shown.
[0017] Figure 4A A schematic diagram illustrating the correspondence between attack vectors and verifiers in a command injection defense method according to an embodiment of this application is shown.
[0018] Figure 4B A schematic flowchart of step S203 in a command injection defense method according to an embodiment of this application is shown.
[0019] Figure 5 A detailed flowchart of a command injection defense method according to yet another embodiment of this application is shown.
[0020] Figure 6 A schematic diagram of the verifier chain execution and priority classification mechanism in a command injection defense method according to an embodiment of this application is shown.
[0021] Figure 7 A block diagram of a command injection defense device according to an embodiment of this application is shown.
[0022] Figure 8 A schematic diagram of the structure of a computer device according to an embodiment of this application is shown.
[0023] Figure 9 Another structural schematic diagram of a computer device according to an embodiment of this application is shown. Detailed Implementation
[0024] To better understand the technical solution of this application, the embodiments of this application will be described in detail below with reference to the accompanying drawings.
[0025] It should be understood that the described embodiments are merely some, not all, of the embodiments in this application. All other embodiments obtained by those skilled in the art based on the embodiments in this application without inventive effort are within the scope of protection of this application.
[0026] The terminology used in the embodiments of this application is for the purpose of describing particular embodiments only and is not intended to be limiting of this application. The singular forms “a,” “the,” and “the” used in the embodiments of this application and the appended claims are also intended to include the plural forms unless the context clearly indicates otherwise.
[0027] The following detailed description of some embodiments of this application is provided in conjunction with the accompanying drawings. Unless otherwise specified, the following embodiments and features can be combined with each other.
[0028] It should be noted that the embodiments of this application can acquire and process relevant data based on artificial intelligence technology. Artificial intelligence is the theory, method, technology, and application system that uses digital computers or machines controlled by digital computers to simulate, extend, and expand human intelligence, perceive the environment, acquire knowledge, and use that knowledge to obtain optimal results.
[0029] The fundamental technologies of artificial intelligence generally include sensors, dedicated AI chips, cloud computing, distributed storage, big data server processing technology, operating / interactive systems, and mechatronics. Artificial intelligence software technologies mainly include computer vision, robotics, biometrics, speech processing, natural language processing, and machine learning / deep learning.
[0030] The command injection defense method provided in this embodiment of the invention can be applied to, for example, Figure 1In this application environment, the client communicates with the server via a network. The server can receive command input data from the user through the client and determine whether the command input data can be parsed into a structured syntax tree (SLP). If the command input data can be parsed into a SLP, the server enters a semantic-level security check path, performs a semantic-level security check using the syntax tree parsing result, and obtains a first security check result. If the command input data cannot be parsed into a SLP, the server enters a text-level security check path, performs a text-level security check based on character features, and obtains a second security check result. Based on the first security check result or the second security check result, the server determines whether to allow the command input data to be submitted to the corresponding command execution environment. In this invention, by distinguishing whether command input data can be parsed into a structured syntax tree and enabling semantic-level and text-level security check paths for collaborative verification, the invention achieves accurate semantic dimension recognition through the structured syntax tree, distinguishing syntactic fragments such as environment variables, commands, and parameters, significantly reducing false positives and false negatives caused by character matching. Furthermore, a text-level character feature fallback verification path provides continuous basic security protection even in scenarios where syntax parsing fails, eliminating the verification interruption defects inherent in single verification paths. Simultaneously, the invention outputs corresponding security check results from both paths to uniformly complete the approval decision, balancing sophisticated detection of complex scripts with fault tolerance for unparseable text, thus comprehensively improving the scenario adaptability and security coverage of the command injection defense system. The client can include, but is not limited to, various personal computers, laptops, smartphones, tablets, and portable wearable devices. The server can be implemented using a standalone server or a server cluster consisting of multiple servers. The invention will be described in detail below through specific embodiments.
[0031] Please see Figure 2 , Figure 2 A schematic flowchart of a command injection defense method according to an embodiment of this application is shown.
[0032] like Figure 2 As shown, a command injection defense method according to an embodiment of this application includes: Step S201: Receive command input data from the user and determine whether the command input data can be parsed into a structured syntax tree; Command input data refers to various instruction texts that are to be verified and delivered for execution, including system commands manually entered by humans, Shell, Bash, and Zsh script commands automatically generated by large language models / AI agents, dynamic command strings concatenated by programs, and batch execution statements assembled by operation and maintenance automation tools; A structured syntax tree is a tree-like syntax data structure obtained by segmenting instruction text and constructing hierarchical relationships between nodes through a syntax parsing engine. It can distinguish syntax units such as environment variables, operators, parameters, and subcommands.
[0033] Step S202: In response to the command input data being parsed into a structured syntax tree, the semantic-level security check path is entered, and the semantic-level security check is performed using the syntax tree parsing result to obtain the first security check result; The semantic-level security check path is a refined verification link that conducts layered and segmented risk detection based on complete syntax tree node information; The first security check result is structured risk assessment information based on semantic analysis of syntax structure, including the compliance status of environmental variables, risk markers for each validator, and the hit status of blocking rules.
[0034] In this step, when the instruction text has a complete grammatical structure and can generate a syntax tree, the process switches to the semantic verification link. Layered verification is carried out based on the various grammatical segments split from the syntax tree. Environment variable whitelist verification and multi-verifier syntax risk traversal detection are completed in sequence. All verification outputs are integrated to form a structured first security check result.
[0035] In this way, by leveraging the complete semantic context information of the syntax tree, accurate segmented verification can be achieved, which can distinguish between quotation marks, escape characters, and variable boundaries to eliminate false positives generated by plain text matching. At the same time, it can achieve fine-grained control of environment variables, greatly improving the ability to identify advanced obfuscation injection attacks and reducing the probability of false negatives.
[0036] Step S203: In response to the command input data not being parsed into a structured syntax tree, the text-level security check path is entered, and a text-level security check is performed based on character features to obtain the second security check result; The text-level security check path is a fallback verification link that does not rely on syntax structure and only performs character matching on the entire original text. The character signature features include preset high-risk special symbols, injection keywords, and malicious identifier strings; The second security check result is a coarse-grained risk assessment information output after full-text character matching and text validator traversal.
[0037] In this step, if the command text fails to build a syntax tree due to incomplete syntax, overly complex structure, or incompatible parsing engines, the process switches to a fallback text verification chain. First, blacklisted character matching is performed on the entire text. Then, the validator is invoked to complete text-level risk screening, and all matching results are aggregated to generate a second security check result. This independent fallback text verification branch addresses the lack of protection after a single syntax tree verification path fails, achieving full-scenario fault tolerance and ensuring basic security interception can be completed regardless of whether the command text has a complete syntax structure, eliminating the risk of single-point failure in the verification process.
[0038] Step S204: Based on the first security check result or the second security check result, determine whether it is allowed to submit the command input data to the corresponding command execution environment.
[0039] The command execution environment is an instance of an interpreter such as Shell that carries out the execution of scripts and system commands; submitting a command means forwarding the verified command data to the execution engine to start running.
[0040] In this step, the first security check results from the semantic path output or the second security check results from the text path output are uniformly summarized and judged according to preset blocking rules. If the verification result matches the blocking rule, the instruction is blocked; otherwise, the instruction is allowed to enter the execution environment. In this way, the judgment exit of the two verification branches is unified, realizing standardized risk handling logic, compatible with both fine-grained semantic verification and coarse-grained text fallback verification outputs, ensuring that the judgment logic of the entire defense process is unified, closed-loop and controllable, and stably realizing differentiated handling of command injection risk interception and legitimate instruction release.
[0041] The above-mentioned technical solution of the present invention distinguishes whether command input data can be parsed into a structured syntax tree and enables two security check paths, semantic level and text level, to perform collaborative verification. On the one hand, it uses the structured syntax tree to achieve accurate semantic dimension recognition, which can distinguish syntax fragments such as environment variables, commands, and parameters, and significantly reduce false positives and false negatives caused by character matching. On the other hand, it sets a text-level character feature fallback verification path, which can continuously provide basic security protection in scenarios where syntax parsing fails, and eliminate the verification interruption defects of a single verification path. At the same time, it outputs the corresponding security check results based on the two paths to complete the release decision in a unified manner, taking into account the fine-grained detection of complex scripts and the fault tolerance protection capability of unparseable text, and improving the scenario adaptability and security coverage of the command injection defense system as a whole.
[0042] In one embodiment, optionally, the method further includes: In response to the command input data being parsed into a structured syntax tree, it is determined whether the complexity of the command input data exceeds a preset threshold; Complexity refers to a quantitative indicator that measures the cumbersomeness of the syntax structure of the input command and the difficulty of parsing; preset threshold refers to a pre-set upper limit of system resource consumption or structural constraints, used to define the boundary between secure parsing and high-risk parsing.
[0043] In this step, after successfully constructing the abstract syntax tree, deep semantic detection is not performed immediately; instead, a complexity evaluation mechanism is initiated first. This mechanism comprehensively considers multiple metrics: first, scale metrics, including the total number of nodes in the syntax tree (Node Count) and the total length of the input string, to prevent buffer overflow or memory exhaustion attacks caused by excessively long inputs; second, structural metrics, focusing on detecting the presence of deep recursive nesting, multiple command substitutions, or uncommon control flow structures; and third, characteristic metrics, scanning for complex syntactic features that are prone to causing parsing ambiguity, such as control characters, Unicode whitespace characters, zsh dynamic syntax (e.g., globbing), curly brace expansion within quotation marks, and untraceable variables.
[0044] The complexity exceeding the preset threshold includes at least one of the following: the number of syntax tree nodes is greater than the preset number, the length of command input data is greater than the preset length, the parsing time is greater than the preset duration, or the presence of preset characters. For example, the following situations can be judged as complexity exceeding the preset threshold: hard budget: number of nodes > 50,000, length > 10,000, timeout > 50ms; pre-check: such as the presence of control characters, Unicode whitespace, escaped whitespace, zsh dynamic syntax, curly braces within quotation marks, etc.; fallback traversal: untraceable variable values, unknown nodes, unsupported structures, curly brace expansion, dangerous heredoc, etc.
[0045] By establishing a circuit breaker mechanism before semantic analysis, it effectively avoids parser dead loops, stack overflows, or CPU resource exhaustion (DoS attacks) caused by processing malformed or overly complex malicious scripts. This ensures the high availability of the security protection mechanism itself, preventing it from collapsing first due to malicious attacks.
[0046] If the complexity of the command input data exceeds a preset threshold, the security check path will be forcibly switched from the semantic-level security check to the text-level security check.
[0047] In this step, if the system determines that the complexity exceeds the limit—for example, if the number of nodes exceeds 50,000, the parsing time exceeds 50ms, or a specific complex grammatical feature is hit—the system will immediately suspend the current AST parsing and semantic analysis process, discard the generated syntax tree, and forcibly redirect the input data to a text-level security check path based on regular expressions. Under this path, the system no longer attempts to understand the logical structure of the command but directly performs blacklist matching and basic rule scanning on the raw string.
[0048] This achieves adaptive degradation and fallback in the defense strategy. It resolves the conflict between high-precision detection (AST) and high-performance requirements, ensuring that even in extremely complex situations, the system can still provide basic injection protection through regular expression paths, preventing high-risk instructions from being executed directly without monitoring, thus achieving the best balance between system stability and security.
[0049] like Figure 3 As shown, in one embodiment, optionally, step S202 includes: Step S301: Identify the corresponding target environment variable from the parsing result of the syntax tree; The syntax tree parsing result refers to the hierarchical data structure composed of an abstract syntax tree. The target environment variable refers to the dynamically named value defined in the syntax tree node that is used to configure the software runtime environment, such as PATH, HOME, or LD_LIBRARY_PATH.
[0050] The system traverses the constructed syntax tree, focusing on analyzing assignment nodes. Unlike ordinary command parameters, environment variables typically appear in specific syntax structures, such as `export KEY=value` or `KEY=value command`. By recognizing these specific syntax patterns, the system extracts the identifier on the left-hand side of the equals sign as candidate environment variables and identifies them as target environment variables for subsequent security assessments.
[0051] Step S302: Determine whether the target environment variable matches the preset safe environment variable set; The preset security environment variable set refers to a predefined whitelist of environment variables that are allowed to be modified or used in the system; a hit means that the name of the target environment variable is exactly the same as an entry in the set or conforms to a specific matching rule.
[0052] The system compares the identified target environment variables with the built-in security library. This security set typically includes about 45 known safe variables (such as GOOS, NODE_ENV, TEMP, etc.). Only environment variables on the whitelist are allowed to be stripped during permission matching, and critical system variables such as PATH, LD_PRELOAD, PYTHONPATH, and HOME are explicitly excluded. The comparison process not only checks the variable names but also whether their values point to illegal paths or contain malicious code snippets, such as path traversal.
[0053] In this way, by classifying environment variables into safe and dangerous categories, the system can effectively prevent attackers from using environment variable hijacking, such as modifying LD_PRELOAD to load malicious libraries, to carry out privilege escalation or code injection attacks, thus filling the logical vulnerabilities that may exist in the simple detection command itself.
[0054] Step S303: In response to the target environment variable matching the preset set of security environment variables, the command input data is allowed to be submitted to the corresponding command execution environment.
[0055] Hitting the preset security environment variable set means passing the above whitelist verification. Allowing submission means removing the security block status and transferring the command to the execution stage.
[0056] When the system confirms that the target environment variable belongs to the preset security set, it determines that the operation is a normal business configuration behavior and does not have an attack intent. At this time, the system will skip the subsequent cumbersome general validator detection and directly make a permission decision, without performing deeper blocking rule matching on the input.
[0057] In this way, for clearly harmless environmental variable operations, the fast-track mechanism of whitelisting significantly reduces unnecessary computational overhead, lowers the false alarm rate of the system, and ensures that legitimate business instructions, such as normal compilation environment configurations, can be executed with low latency and without obstacles.
[0058] In one embodiment, optionally, the method further includes; Step S304: In response to the target environment variable not matching the preset security environment variable set, a semantic-level security check is performed on the syntax tree parsing result using multiple validators to determine whether the syntax tree parsing result matches the corresponding first preset blocking rule, and a first security check result is generated.
[0059] Multiple validators are detection units used to distinguish different injection attack vectors and identify risks by traversing syntax tree nodes; the syntax tree parsing result is a complete structured syntax tree and various syntax fragments obtained by splitting it; the first preset blocking rule is a risk interception standard set to adapt to semantic-level fine-grained verification, for parser differences, and various script injection behaviors; the first security check result is a structured comprehensive risk judgment information formed by integrating the environmental variable verification conclusions and the detection outputs of each validator.
[0060] After completing the environment variable matching and verification, if the current target environment variable does not exist in the preset security environment variable set, the multi-verifier joint detection process is started. All verifiers are called to traverse the nodes and syntax fragments of each level of the syntax tree one by one, match various first preset blocking rules, summarize all detection output content, and uniformly generate the first security check result carrying complete risk information.
[0061] In one specific embodiment, an ordered validator chain can be implemented using more than 20 dedicated security validators, including the following key validators: 1) Command substitution detection: Detects command substitution syntax such as $(...), backticks, ${...}, $[...], and Zsh parameter expansion ~[...]; 2) Process replacement detection: Detects process replacement syntax such as <(...), >(...), =() (Zsh process replacement); 3) Zsh dangerous command interception: Maintain a set of Zsh-specific dangerous commands (such as zmodload, emulate, sysopen, syswrite, zpty, ztcp, etc.) to intercept attacks that bypass security checks by loading Zsh modules; 4) IFS Injection Defense: Detects the use of IFS variables such as $IFS and ${...IFS...} to prevent bypassing space-based command parsing by modifying field separators; 5) jq system() call detection: Intercepts system() function calls in jq commands and dangerous flags such as -f and --from-file that can load external code; 6) git commit message injection defense: Verify the content of the -m parameter of git commit to prevent the embedding of command substitution patterns such as $(), backticks, and ${} in the commit message; 7) Unicode whitespace character deception defense: Detects invisible Unicode whitespace characters (such as U+00A0, U+2000-U+200A, U+FEFF, etc.) to prevent the use of the visual deception of whitespace characters to hide malicious content; 8) Detection of Comment-Quote Asynchrony Attack: Detects quote characters included in # comments to prevent subsequent validators from misjudging the quote context due to quote state out-of-sync. 9) Backslash escape operator detection: Detects Shell operators such as \;, \|, \& that are escaped with backslashes to prevent misjudgment of command segmentation due to parser differences; 10) Heredoc Injection Defense: Perform security verification on heredoc documents, distinguishing between delimiters with quotes (variables not expanded) and delimiters without quotes (variables expanded), and only allow access when the $(cat<<'DELIM'...DELIM) pattern is confirmed to be safe; 11) / proc / / environ access interception: detects attacks that read other processes' environment variables through the / proc file system; 12) Bracket expansion attack defense: Detect Bash brace expansion syntax (such as {a,b,c}) to prevent the parser from bypassing parameter checks by exploiting the parser's lack of support for brace expansion; 13) Obfuscation Flag Detection: Detects attacks that obfuscate dangerous command flags by using ANSI-C references $'...', empty quotes concatenated with ''--flag, or flag name splitting between quotes "-"exec.
[0062] In one specific embodiment, taking shell commands as the input data as an example, such as... Figure 4A As shown, this invention divides the attack vector of Shell command injection into four key defense layers: Syntax layer: Deeply analyzes and blocks Shell-specific syntax structures such as command substitution, process substitution, heredoc, and curly brace expansion; Encoding layer: Detects encoding bypass techniques such as Unicode whitespace characters, backslash escaping, comment quotation marks, and flag obfuscation; Tool layer: Intercepting abuse of specific high-risk tools (such as jq, git) and function calls (such as system()); Environment layer: Defends against malicious manipulation of environment variables and system environment, such as IFS tampering and / proc access.
[0063] like Figure 4B As shown, in one embodiment, optionally, step S203 includes: Step S401: Perform character-level blacklist matching on the command input data to determine whether preset feature characters exist; Character features are special symbols, keywords, escape characters, and other text identifiers that pose an attack risk in script injection scenarios; the character-level blacklist is a pre-collected interception list of all high-risk characteristic characters and malicious keywords; the preset characteristic characters are high-risk text symbols recorded in the blacklist that can be directly identified as having injection risk, including pipe characters, command separators, backticks, redirection symbols, escape ambiguity characters, and other commonly used command injection attack symbols.
[0064] In this step, after the text-level security check is initiated, it does not rely on any syntactic structure or semantic information, but directly performs a character-by-character comparison of the complete original command input, matching the text content with the built-in blacklist item by item, and screening whether the original command natively carries high-risk malicious character features.
[0065] Step S402: In response to the presence of the preset feature character, the submission of the command input data to the corresponding command execution environment is blocked. The blocking is a rejection command issued by the security verification module; the command execution environment is a backend container that runs scripts such as Shell and is responsible for parsing and executing system commands.
[0066] In this step, once the full-text blacklist matches any of the preset high-risk characteristic characters, there is no need to start the subsequent verifier detection process. Instead, an interception command is generated directly, refusing to forward the current command input data to the backend command execution environment and directly terminating the current security verification process.
[0067] In this way, high-risk commands that are clearly malicious can be quickly intercepted by circuit breakers, eliminating the need for subsequent redundant verification steps, further saving security verification computing resources, and at the same time quickly blocking blatant injection attacks, improving the defense response efficiency in basic attack scenarios.
[0068] In step S403, in response to the absence of the preset feature character, multiple verifiers are used to perform a text-level security check on the command input data to determine whether the corresponding second preset blocking rule is hit, and a second security check result is generated.
[0069] Multiple validators are standardized risk detection components that are uniformly deployed in the entire defense solution and share semantic-level security check paths and text-level security check paths. The two verification paths reuse the same set of validators. The text-level security check is a coarse-grained risk verification logic without syntax fragmentation and based on the full-text dimension. The second preset blocking rule is a text-level risk judgment standard specifically adapted to the text fallback verification scenario and formulated for obfuscated and deformed injection attacks. The second security check result is the final output of the text path standardized risk judgment receipt after integrating the blacklist first-round matching result and the validator full-text detection result.
[0070] In this step, if the entire command text is clean and does not match any high-risk blacklist feature characters, a shared set of validators that is exactly the same as the semantic-level security check path is invoked to perform a full-text indiscriminate risk scan on the original command text, determine whether the text matches various text-level obfuscation injection blocking rules, and finally integrate all detection information to generate a complete second security check result that can be used for final decision-making.
[0071] In this way, the two verification paths reuse the same set of validator components, eliminating the need to maintain independent detection units for each path, thus reducing development, iteration, and operation and maintenance costs. At the same time, it makes up for the shortcomings of static blacklists in not being able to identify character obfuscation, encoding bypass, and implicit injection attacks, and supplements the standardized validator detection capabilities in the lightweight text fallback path, taking into account the low computing power advantage of text verification and attack coverage capabilities, and avoiding the problem of missed detections caused by relying solely on a simple blacklist after syntax parsing failure.
[0072] like Figure 5 As shown, in one embodiment, optionally, when performing semantic-level security checks on the syntax tree parsing results using multiple validators, or performing text-level security checks on the command input data using multiple validators, the process includes: Step S501: Divide the plurality of verifiers into a first subset of verifiers and a second subset of verifiers; The first subset of validators is a set of parser-differentiated validators, mainly used to identify high-risk injection risks caused by interpreter syntax divergence; the second subset of validators is a set of non-parser-differentiated validators, mainly used to identify regular explicit command injection risks.
[0073] In this step, before calling the shared validator to carry out risk detection, all validators that are uniformly reused globally are classified in advance. Based on the attack risk level and whether there are ambiguities in the parser syntax, all validators are divided into two independent subsets of high and low levels. The detection objects, risk levels and subsequent handling logic of the two types of validators are defined in advance, providing a preliminary classification basis for subsequent differentiated risk scheduling and graded blocking judgment.
[0074] Step S502: Detect the structural semantic conflict risk in the syntax tree parsing result or command input data through the first validator subset, and mark the obtained first detection result as the highest priority blocking signal, and the highest priority blocking signal is not covered or downgraded by subsequent permission policies; Structural semantic conflict risk refers to high-risk injection risks caused by mismatch between command content and the inherent syntax rules of the script interpreter, and grammatical understanding deviations between different interpreters, including risks such as backslash escaping exceptions, illegal control characters, and grammatical ambiguity of carriage returns; the highest priority blocking signal is the system's preset non-exempt risk identifier; the permission policy is the risk exemption and permission granting policy configured on the business side.
[0075] In this step, the first subset of validators is invoked to detect various parser structural semantic conflict risks in the parsing results of the syntax tree under the semantic path and the original command input data under the text path. Once the corresponding risk is detected, the first detection result is generated and fixed as the highest priority blocking signal. This type of high-risk result is immutable, and no subsequent business permission relaxation policy can exempt, revoke or downgrade the blocking signal.
[0076] Step S503: Detect explicit high-risk instruction calls in the syntax tree parsing results or the command input data through the second validator subset, and mark the obtained second detection results as allowing the pre-configured permission relaxation policy adjustment; Explicit high-risk command invocation refers to conventional injection risk behaviors that are intuitively visible in the command and have no syntactic ambiguity, including common attack behaviors such as command redirection, pipeline splicing, and ordinary malicious keyword invocation; pre-configured permission relaxation policies are risk exemption whitelist policies that are pre-configured for legitimate business scenarios to allow high-risk commands required for normal business operations.
[0077] In this step, a subset of the second validators is invoked to traverse the parsed results of the syntax tree or the full text of the original command input, identify common explicit high-risk instructions that are visible in plain text and have no interpreter syntax bias; generate the corresponding second detection result, and mark the detection result as adjustable, supporting the exemption and release of such risks through preset permission relaxation policies according to the actual business operation needs.
[0078] In this way, we can distinguish between high-risk hard-blocking risks and exemptable regular risks, balance security defense capabilities with business compatibility, avoid a one-size-fits-all approach that would prevent normal operation and maintenance services and legitimate script commands from being executed, and adapt to the personalized release requirements of special business scenarios such as enterprise finance and medical operation and maintenance, balancing the stringency of security protection with business availability.
[0079] Step S504: When the second validator subset is triggered before the first validator subset, the second detection result is temporarily stored and the remaining validators are traversed. The triggering mechanism detects corresponding risks and outputs valid detection results during the verifier traversal process; it temporarily stores low-priority risk results as a temporary cache and does not output interception or approval conclusions in advance; when traversing the remaining verifiers, it does not interrupt the overall verification process and continues to execute the detection logic of the first subset of verifiers that have not yet run.
[0080] In this step, since the serial traversal process of the validators has a sequential order, if the second subset of validators with lower risk detects the risk first and outputs the second detection result, the system will not immediately return the low-risk result, nor will it terminate the overall verification process prematurely; instead, it will temporarily cache the low-priority detection result and continue to execute the detection process of all subsequent validators until the first subset of validators has finished running.
[0081] This avoids bypass vulnerabilities caused by low-priority risks being hit prematurely or the verification process exiting early, which could lead to the omission of high-risk semantic conflicts in the backend parsing; it ensures the complete execution of the entire set of verifiers, eliminates security weaknesses caused by sequential verification, and improves the overall defense system's ability to prevent bypasses.
[0082] Step S505: In response to the completion of all validators or the triggering of the first subset of validators, determine whether to allow the submission of the command input data to the corresponding command execution environment based on the highest priority blocking signal.
[0083] The command execution environment is a backend script command interpreter such as Shell or Bash; the highest priority blocking signal is the non-exempt high-risk flag output by the first subset of verifiers; the final decision is based on the logic of prioritizing the acceptance of high-risk results and then determining the handling logic of low-priority exemptable risks.
[0084] In this step, there are two triggering conditions for ending the verification and executing the decision: one is that all validators have completed the traversal detection, and the other is that the high-priority first validator subset detects the high-risk blocking signal in advance. Regardless of the triggering condition, the highest priority blocking signal is given priority as the core judgment basis. Then, combined with the cached second detection result and the permission relaxation policy, a unified judgment is made on whether to allow the command input data to be sent to the command execution environment.
[0085] Specifically, such as Figure 6As shown, after receiving command input data, it flows sequentially through three verifier groups: syntax structure detection, injection and encoding detection, and file and obfuscation detection, totaling 13 specific detection nodes. After completing all technical feature matching, the system does not simply output a binary result, but enters a decision branch based on parsing characteristics. Depending on whether the command involves parser differences, it ultimately decides whether to execute a forced blocking or let the permission policy make a flexible decision, thus constructing a complete closed loop from feature identification to risk assessment. Among them, verifier group 1 mainly identifies basic syntax structure risks unique to the shell interpreter. This level focuses on detecting V1 command substitution (such as the $() structure), V2 process substitution (such as the <() structure), and V3 proprietary high-risk commands in the Zsh environment, aiming to intercept the most direct and common injection attempts. At the same time, V4 IFS injection detection specifically monitors the tampering behavior of internal field delimiters to prevent privilege escalation or logic bypass due to environment variable manipulation, ensuring that the basic syntax skeleton of the command meets security expectations. Verifier group 2 identifies the exploitation of vulnerabilities in specific tools and obfuscation at the character encoding level. V5 and V6 respectively block specific scenarios such as the `system()` function call of the jq tool and parameter injection via `git commit -m`, while V7 to V9 focus on general bypass techniques, including detecting Unicode whitespace characters (zero-width spaces), asynchronous matching of comments and quotation marks, and abuse of backslash escape operators. This layer effectively compensates for the blind spots of simple regular expression matching in handling complex encoding and specific toolchain attacks. Validator group 3 mainly involves file operations and syntax obfuscation. V10 to V13 cover comprehensive monitoring from multi-line text injection (heredoc), sensitive file system access ( / proc) to curly brace expansion and obfuscation flag detection. Through these detection points, the system can identify malicious commands that attempt to exploit advanced shell features or file operation permissions, ensuring that even if attackers bypass basic syntax checks, they will find it difficult to escape detection at this level. After completing the scan of all validators, the system enters the critical decision-making and triage stage based on the summarized results. The system first classifies risks into parser-differentiated and non-parser-differentiated types: the former refers to commands that may produce different execution results in different shell environments (such as those involving specific escaping or dynamic syntax). These risks are judged as extremely high-risk and directly trigger the highest priority forced blocking, without allowing any permission policy to override them; the latter are regular risks with consistent performance. The system allows them to enter the permission policy module, and decides on the final execution permission based on specific business rules and allowance policies, thereby maximizing business flexibility while ensuring security.
[0086] In one embodiment, optionally, step S204 includes: In response to the syntax tree parsing result matching the corresponding first preset blocking rule, the submission of the command input data to the corresponding command execution environment is prohibited; After the semantic-level security check path verification is completed, if the first security check result shows that the parsed content of the syntax tree matches the first preset blocking rule, it indicates that the current command has a high risk of deep structured injection. The system will directly issue an interception command to block the subsequent execution link of the input data of the command.
[0087] In response to the syntax tree parsing result not matching the corresponding first preset blocking rule, the command input data is allowed to be submitted to the corresponding command execution environment; If no semantic layer blocking rules are matched after the full-dimensional semantic verification of the syntax tree is completed, it proves that the structured command does not pose a security risk of injection. The system will then allow the input data of the command to be passed directly, ensuring the normal execution of normal compliant operation and maintenance scripts and business automation commands.
[0088] In response to the command input data hitting the corresponding second preset blocking rule, the submission of the command input data to the corresponding command execution environment is prohibited; After the text-level fallback security check path verification is completed, if the second security check result shows that the original command text hits the second preset blocking rule of the text layer, it indicates that the text has explicit malicious injection characteristics, and the system directly intercepts the abnormal command that cannot be parsed.
[0089] In response to the command input data not matching the corresponding second preset blocking rule, the command input data is allowed to be submitted to the corresponding command execution environment.
[0090] For unconventional commands with abnormal syntax structure and inability to construct a syntax tree, but whose text content does not pose a hard high-risk blocking risk, they will not be allowed to pass unconditionally. Instead, a second policy review will be conducted on the low-risk commands detected by the subset of the second verifier, which can be exempted. Only after the review is passed can the input data of such commands be allowed. If the review fails, the blocking operation will still be performed.
[0091] The above steps strictly match the risk level and permission policy rules of the validator subset to form a fixed decision priority: First, the high-risk structural semantic conflict detected by the first validator subset corresponds to a hard block result under both paths, with the highest priority, completely unaffected by the pre-configured permission relaxation policy adjustment, and cannot be exempted from passage; Second, the explicit low-risk command risk detected by the second validator subset supports calling the preset permission relaxation policy for secondary adjustment, and legitimate business scenarios can be exempted from interception, while malicious scenarios are still intercepted; Third, compliant commands with no risk hits are directly allowed to the command execution environment.
[0092] In this way, on the one hand, the exit judgment criteria of the two differentiated verification paths are unified, avoiding the logical confusion caused by independent decision-making of the two paths; on the other hand, it breaks the traditional one-size-fits-all judgment mode of security detection, distinguishes between high-risk risks that cannot be exempted and low-risk risks that can be exempted by policy, and fully links the end decision-making with the front-end verifier classification mechanism. This not only safeguards the security bottom line of absolutely blocking high-risk attacks, but also adapts to normal business scenarios through permission relaxation policies, balancing the strength of security protection and business compatibility, and completing the decision-making closed loop of the entire defense solution.
[0093] The technical solutions of the present invention will be described in detail below with reference to specific embodiments.
[0094] Scenario 1: Normal business input (efficiently allowing access via regular expression paths) In this embodiment, the system receives an archiving instruction from the end-of-day scheduling center, such as the file path / data / trans / logs / 20240115 / . The system first determines that this input cannot be parsed into a structured syntax tree because it does not contain any command delimiters or logical operators, and is therefore a simple text parameter. Accordingly, the system enters a text-level security check path, performing a rapid scan using character features. After character-level blacklist matching and path traversal detection using a dedicated regular expression validator, it is confirmed that the input does not match any blocking rules. Finally, based on the second security check result, the system determines that the input is safe and allows it to be submitted to the execution environment. This process demonstrates the efficient processing capability of this invention for non-script input, significantly reducing system resource consumption by avoiding high-overhead syntax parsing.
[0095] Scenario 2: Complex Injection Attack (Complexity Determination and Forced Downgrade) When the system encounters malicious input crafted by an attacker, such as complex scripts containing extremely long nested structures, zsh dynamic syntax, and control characters, the system first determines that it can be parsed into a structured syntax tree. However, in further complexity assessment, the system detects that the number of nodes in the input's syntax tree far exceeds a preset threshold, and the parsing time is excessive, posing a risk of exhausting parser resources. At this point, the system triggers a forced degradation mechanism, ceasing to perform deep semantic-level checks and instead forcibly switching the security check path from semantic-level to text-level. In the text-level path, the system quickly identifies high-risk injection characteristic characters (such as && and backticks) through character-level blacklist matching, directly blocking execution. This scenario verifies the effectiveness of this invention in defending against denial-of-service (DoS) attacks, ensuring the continuity of core business operations.
[0096] Scenario 3: Legitimate Operation and Maintenance (AST Path and Environment Variable Whitelist) For legitimate operations by internal operations personnel, such as inputting `export NODE_ENV=production&&node / opt / app / server.js`, the system determines that it is a parsable script-like input with normal complexity, and then proceeds to the semantic-level security check path. The system first identifies the target environment variable `NODE_ENV` from the syntax tree parsing results. Next, the system determines that this variable matches a preset set of secure environment variables (including approximately 45 secure variables such as `NODE_ENV` and `GOOS`, and explicitly excludes high-risk variables such as `PATH` and `LD_PRELOAD`). In response, the system determines that the operation is safe, allows the command to be submitted to the execution environment, and skips subsequent general validator checks. This demonstrates the invention's ability to allow low-latency passage of legitimate business logic while ensuring security through a whitelist mechanism.
[0097] Scenario 4: High-risk escape attack (verifier priority and delayed return mechanism) When the system detects an attempt to escalate privileges through environment variable hijacking, such as `export LD_PRELOAD= / tmp / hack.so&&rm -rf / data / backup`, it enters a semantic-level security check path. After identifying that `LD_PRELOAD` does not match the security whitelist, the system calls multiple validators for detection. During this process, the second subset of validators (detecting explicit high-risk commands) is triggered first, identifying the `rm -rf` command and temporarily storing the result; however, the system does not immediately return but continues to iterate until the first subset of validators (detecting structural semantic conflict risks) is triggered, identifying the escape risk of modifying `LD_PRELOAD`. Based on the validator priority classification mechanism, this first detection result is marked as the highest priority blocking signal and is not overridden by subsequent permission policies. Ultimately, the system blocks execution based on this highest priority signal, effectively preventing defense failures that might result from relaxed permission policies.
[0098] like Figure 7 As shown, in a second aspect, embodiments of this application provide a command injection defense device 70, the device comprising: The receiving module 71 is used to receive command input data input by the user and determine whether the command input data can be parsed into a structured syntax tree; The first inspection module 72 is used to respond to the command input data being parsed into a structured syntax tree, enter the semantic-level security inspection path, perform semantic-level security inspection using the syntax tree parsing result, and obtain the first security inspection result; The second inspection module 73 is used to respond to the command input data not being parsed into a structured syntax tree, enter the text-level security inspection path, perform text-level security inspection based on character features, and obtain the second security inspection result; The determination module 74 is used to determine, based on the first security check result or the second security check result, whether it is permissible to submit the command input data to the corresponding command execution environment.
[0099] In one embodiment, optionally, the apparatus further includes: The judgment module is used to determine whether the complexity of the command input data exceeds a preset threshold in response to the fact that the command input data can be parsed into a structured syntax tree; The switching module is used to forcibly switch the security check path from the semantic-level security check to the text-level security check in response to the complexity of the command input data exceeding a preset threshold.
[0100] In one embodiment, optionally, the first inspection module includes: The identification unit is used to identify the corresponding target environment variable from the parsing result of the syntax tree; The first determining unit is used to determine whether the target environment variable matches a preset set of safe environment variables. The first processing unit is configured to, in response to the target environment variable matching the preset set of security environment variables, allow the submission of the command input data to the corresponding command execution environment.
[0101] In one embodiment, optionally, the apparatus further includes; The second processing unit is configured to, in response to the target environment variable not matching the preset security environment variable set, perform a semantic-level security check on the syntax tree parsing result using multiple validators to determine whether the syntax tree parsing result matches the corresponding first preset blocking rule, and generate a first security check result.
[0102] In one embodiment, optionally, the second inspection module includes: The matching unit is used to perform character-level blacklist matching on the command input data to determine whether preset feature characters exist; The third processing unit is used to block the submission of the command input data to the corresponding command execution environment in response to the presence of the preset feature character; The fourth processing unit is used to perform a text-level security check on the command input data using multiple verifiers if the preset feature character is not present, in order to determine whether the corresponding second preset blocking rule is hit and generate a second security check result.
[0103] In one embodiment, the determining module optionally includes: The fifth processing unit is used to prevent the submission of the command input data to the corresponding command execution environment in response to the syntax tree parsing result hitting the corresponding first preset blocking rule; The sixth processing unit is configured to, in response to the syntax tree parsing result not matching the corresponding first preset blocking rule, allow the command input data to be submitted to the corresponding command execution environment; The seventh processing unit is configured to prevent the submission of the command input data to the corresponding command execution environment in response to the command input data hitting the corresponding second preset blocking rule; The eighth processing unit is configured to, in response to the command input data not matching the corresponding second preset blocking rule, allow the command input data to be submitted to the corresponding command execution environment.
[0104] In one embodiment, optionally, when performing semantic-level security checks on the syntax tree parsing results using multiple validators, or when performing text-level security checks on the command input data using multiple validators, the following may be included: The multiple validators are divided into a first validator subset and a second validator subset; The first validator subset detects structural semantic conflict risks in the syntax tree parsing results or command input data, and marks the obtained first detection result as the highest priority blocking signal, and the highest priority blocking signal is not covered or downgraded by subsequent permission policies; The second validator subset detects explicit high-risk instruction calls in the syntax tree parsing results or the command input data, and marks the obtained second detection results as allowing adjustments to the pre-configured permission relaxation policy; When the second validator subset is triggered before the first validator subset, the second detection result is temporarily stored and the remaining validators are traversed. In response to the completion of all validators or the triggering of the first subset of validators, a decision is made based on the highest priority blocking signal as to whether to allow the submission of the command input data to the corresponding command execution environment.
[0105] Thirdly, a computer device is provided, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the steps of the command injection defense method described above.
[0106] Fourthly, a computer-readable storage medium is provided, which stores a computer program that, when executed by a processor, implements the steps of the command injection defense method described above.
[0107] For specific limitations regarding command injection defense devices, please refer to the limitations on command injection defense methods above, which will not be repeated here. Each module in the aforementioned command injection defense device can be implemented entirely or partially through software, hardware, or a combination thereof. These modules can be embedded in hardware or independently of the processor in the computer device, or stored in software in the memory of the computer device, so that the processor can call and execute the operations corresponding to each module.
[0108] In one embodiment, a computer device is provided, which may be a server, and its internal structure diagram may be as follows: Figure 8 As shown, the computer device includes a processor, memory, network interface, and database connected via a system bus. The processor provides computing and control capabilities. The memory includes non-volatile and / or volatile storage media and internal memory. The non-volatile storage media stores the operating system, computer programs, and database. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used to communicate with external clients via a network connection. When the computer program is executed by the processor, it implements the functions or steps of a command injection defense method on the server side.
[0109] In one embodiment, a computer device is provided, which may be a client, and its internal structure diagram may be as follows: Figure 9 As shown, the computer device includes a processor, memory, network interface, display screen, and input devices connected via a system bus. The processor provides computing and control capabilities. The memory includes non-volatile storage media and internal memory. The non-volatile storage media stores the operating system and computer programs. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used to communicate with an external server via a network connection. When the computer program is executed by the processor, it implements the functions or steps of a command injection defense method on the client side.
[0110] It should be understood that the processor can be a Central Processing Unit (CPU), but it can also be other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. Among these, a general-purpose processor can be a microprocessor or any conventional processor.
[0111] In one embodiment, a computer device is provided, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the method described in any one of the first aspect embodiments.
[0112] It should be noted that the functions or steps that can be implemented by the computer-readable storage medium or electronic device described above can be referred to the relevant descriptions in the foregoing method embodiments. To avoid repetition, they will not be described one by one here.
[0113] It should be understood that the term "and / or" used in this article is merely a description of the relationship between related objects, indicating that three relationships can exist. For example, A and / or B can represent: A existing alone, A and B existing simultaneously, and B existing alone. Additionally, the character " / " in this article generally indicates that the preceding and following related objects have an "or" relationship.
[0114] It should be understood that although the terms "first," "second," etc., may be used to describe the setting units in the embodiments of this application, these setting units should not be limited to these terms. These terms are only used to distinguish the setting units from each other. For example, without departing from the scope of the embodiments of this application, the first setting unit may also be referred to as the second setting unit, and similarly, the second setting unit may also be referred to as the first setting unit.
[0115] Depending on the context, the word "if" as used here can be interpreted as "when," "when," "in response to determination," or "in response to detection." Similarly, depending on the context, the phrase "if determination" or "if detection (of the stated condition or event)" can be interpreted as "when determination," "in response to determination," "when detection (of the stated condition or event)," or "in response to detection (of the stated condition or event)."
[0116] In the several embodiments provided in this application, it should be understood that the disclosed systems, apparatuses, and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces; the indirect coupling or communication connection between apparatuses or units may be electrical, mechanical, or other forms.
[0117] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or in a combination of hardware and software functional units.
[0118] Those skilled in the art will understand that all or part of the processes in the methods of the above embodiments can be implemented by a computer program instructing related hardware. The computer program can be stored in a non-volatile computer-readable storage medium. When executed, the computer program can include the processes of the embodiments of the above methods. Any references to memory, storage, databases, or other media used in the embodiments provided in this application can include non-volatile and / or volatile memory. Non-volatile memory may include read-only memory (ROM), programmable ROM (PROM), electrically programmable ROM (EPROM), electrically erasable programmable ROM (EEPROM), or flash memory. Volatile memory may include random access memory (RAM) or external cache memory. By way of illustration and not limitation, RAM is available in a variety of forms, such as static RAM (SRAM), dynamic RAM (DRAM), synchronous DRAM (SDRAM), dual data rate SDRAM (DDRSDRAM), enhanced SDRAM (ESDRAM), synchronous link DRAM (SLDRAM), RAMbus direct RAM (RDRAM), direct memory bus dynamic RAM (DRDRAM), and memory bus dynamic RAM (RDRAM), etc.
[0119] It should be noted that any AI models, software tools, or components not belonging to this company appearing in the embodiments of this application are merely illustrative examples and do not represent actual use. All user personal information involved in the embodiments of this application has been authorized (with the knowledge and consent) by the relevant parties or has been fully authorized by all parties, and the executing entity may obtain it through various legal and compliant means. The collection, storage, use, processing, transmission, provision, and disclosure of the information, data, and signals involved all comply with relevant laws and regulations and do not violate public order and good morals.
[0120] The above-described embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention, and should all be included within the protection scope of the present invention.
Claims
1. A command injection defense method, characterized in that, The method includes: Receive command input data from the user and determine whether the command input data can be parsed into a structured syntax tree; In response to the command input data being parsed into a structured syntax tree, the system enters the semantic-level security check path, performs a semantic-level security check using the syntax tree parsing result, and obtains the first security check result. In response to the fact that the command input data cannot be parsed into a structured syntax tree, the text-level security check path is entered, and a text-level security check is performed based on character features to obtain a second security check result; Based on the first security check result or the second security check result, determine whether it is permissible to submit the command input data to the corresponding command execution environment.
2. The method according to claim 1, characterized in that, The method further includes: In response to the command input data being parsed into a structured syntax tree, it is determined whether the complexity of the command input data exceeds a preset threshold; If the complexity of the command input data exceeds a preset threshold, the security check path will be forcibly switched from the semantic-level security check to the text-level security check.
3. The method according to claim 1, characterized in that, The semantic-level security check performed using the syntax tree parsing results includes: Identify the corresponding target environment variables from the parsing results of the syntax tree; Determine whether the target environment variable matches the preset set of safe environment variables; In response to the target environment variable matching the preset set of security environment variables, the command input data is allowed to be submitted to the corresponding command execution environment.
4. The method according to claim 3, characterized in that, The method further includes; In response to the target environment variable not matching the preset safe environment variable set, multiple validators are used to perform semantic-level security checks on the syntax tree parsing result to determine whether the syntax tree parsing result matches the corresponding first preset blocking rule, and a first security check result is generated.
5. The method according to claim 1, characterized in that, The text-level security check based on character features includes: The command input data is subjected to character-level blacklist matching to determine whether preset characteristic characters exist; In response to the presence of the preset characteristic character, the submission of the command input data to the corresponding command execution environment is blocked; In response to the absence of the preset feature character, multiple verifiers are used to perform text-level security checks on the command input data to determine whether the corresponding second preset blocking rule is hit, and a second security check result is generated.
6. The method according to claim 1, characterized in that, Based on the first security check result or the second security check result, determining whether to allow the submission of the command input data to the corresponding command execution environment includes: In response to the syntax tree parsing result matching the corresponding first preset blocking rule, the submission of the command input data to the corresponding command execution environment is prohibited; In response to the syntax tree parsing result not matching the corresponding first preset blocking rule, the command input data is allowed to be submitted to the corresponding command execution environment; In response to the command input data hitting the corresponding second preset blocking rule, the submission of the command input data to the corresponding command execution environment is prohibited; In response to the command input data not matching the corresponding second preset blocking rule, the command input data is allowed to be submitted to the corresponding command execution environment.
7. The method according to claim 4 or 5, characterized in that, When performing semantic-level security checks on the parsed syntax tree results using multiple validators, or when performing text-level security checks on the command input data using multiple validators, the following methods are employed: The multiple validators are divided into a first validator subset and a second validator subset; The first validator subset detects structural semantic conflict risks in the syntax tree parsing results or command input data, and marks the obtained first detection result as the highest priority blocking signal, and the highest priority blocking signal is not covered or downgraded by subsequent permission policies; The second validator subset detects explicit high-risk instruction calls in the syntax tree parsing results or the command input data, and marks the obtained second detection results as allowing adjustments to the pre-configured permission relaxation policy; When the second validator subset is triggered before the first validator subset, the second detection result is temporarily stored and the remaining validators are traversed. In response to the completion of all validators or the triggering of the first subset of validators, a decision is made based on the highest priority blocking signal as to whether to allow the submission of the command input data to the corresponding command execution environment.
8. A command injection defense device, characterized in that, The device includes: The receiving module is used to receive command input data input by the user and determine whether the command input data can be parsed into a structured syntax tree; The first inspection module is used to respond to the command input data being parsed into a structured syntax tree, enter the semantic-level security inspection path, perform semantic-level security inspection using the syntax tree parsing result, and obtain the first security inspection result; The second inspection module is used to respond to the fact that the command input data cannot be parsed into a structured syntax tree, enter the text-level security inspection path, perform text-level security inspection based on character features, and obtain the second security inspection result; The determination module is used to determine, based on the first security check result or the second security check result, whether it is permissible to submit the command input data to the corresponding command execution environment.
9. A computer device, characterized in that, include: At least one processor; And, a memory communicatively connected to the at least one processor; The memory stores instructions that can be executed by the at least one processor; The instructions are configured to perform the method described in any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that, The device stores computer-executable instructions for performing the method as described in any one of claims 1 to 7.