CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')

What is CWE-78?

The product builds an operating system command from externally influenced input without correctly neutralizing special elements that can alter the intended command before it is executed.

Data statistics

OWASP TOP 10:2025 RANK5 — A05:2025 — Injection
RELATED CVES (365 DAYS)1,045
ABSTRACTIONBase
LIKELIHOOD OF EXPLOITHigh

Vulnerabilities mapped to CWE-78

1,045 vulnerabilities333.6% increase year over year

Vulnerabilities in CISA KEV for CWE-78

11 vulnerabilities83.3% increase year over year

Official definition

ByMitre CWE

The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.

This weakness can lead to a vulnerability in environments in which the attacker does not have direct access to the operating system, such as in web applications. Alternately, if the weakness occurs in a privileged program, it could allow the attacker to specify commands that normally would not be accessible, or to call alternate commands with privileges that the attacker does not have. The problem is exacerbated if the compromised process does not follow the principle of least privilege, because the attacker-controlled commands may run with special system privileges that increases the amount of damage.

There are at least two subtypes of OS command injection:

  • The application intends to execute a single, fixed program that is under its own control. It intends to use externally-supplied inputs as arguments to that program. For example, the program might use system("nslookup [HOSTNAME]") to run nslookup and allow the user to supply a HOSTNAME, which is used as an argument. Attackers cannot prevent nslookup from executing. However, if the program does not remove command separators from the HOSTNAME argument, attackers could place the separators into the arguments, which allows them to execute their own program after nslookup has finished executing.

  • The application accepts an input that it uses to fully select which program to run, as well as which commands to use. The application simply redirects this entire command to the operating system. For example, the program might use "exec([COMMAND])" to execute the [COMMAND] that was supplied by the user. If the COMMAND is under attacker control, then the attacker can execute arbitrary commands or programs. If the command is being executed using functions like exec() and CreateProcess(), the attacker might not be able to combine multiple commands together in the same line.

From a weakness standpoint, these variants represent distinct programmer errors. In the first variant, the programmer clearly intends that input from untrusted parties will be part of the arguments in the command to be executed. In the second variant, the programmer does not intend for the command to be accessible to any untrusted party, but the programmer probably has not accounted for alternate ways in which malicious attackers can provide input.

Detailed description

This weakness can affect applications that execute operating system commands on behalf of users, including web applications where the attacker has no direct operating system access. It commonly occurs in two forms: untrusted data is intended to be an argument to a fixed program but command separators or other metacharacters allow additional programs to run, or untrusted input selects and supplies an entire command, enabling arbitrary command or program execution. Privileged processes can magnify the impact, especially when they do not follow least privilege, because attacker-controlled commands may run with permissions unavailable to the attacker directly.

Characteristics

This is a base-level, simple weakness introduced during implementation. It involves mixing control syntax and externally influenced data in an operating system command, either through a fixed executable's arguments or through selection of the executable and command itself. Related terminology includes shell injection, shell metacharacters, and OS command injection; it is distinct from, but can overlap with, argument injection.

Common consequences

An attacker may execute unauthorized operating system commands, disable or crash the product, and read or modify files, directories, or application data without the intended permissions. Malicious actions may appear to originate from the application or its owner, affecting confidentiality, integrity, availability, and non-repudiation, and potentially allowing the attacker to hide activities.

ImpactScopeExplanation
Execute Unauthorized Code or Commands, DoS: Crash, Exit, or Restart, Read Files or Directories, Modify Files or Directories, Read Application Data, Modify Application Data, Hide ActivitiesConfidentiality, Integrity, Availability, Non-RepudiationAttackers could execute unauthorized operating system commands, which could then be used to disable the product, or read and modify data for which the attacker does not have permissions to access directly. Since the targeted application is directly executing the commands instead of the attacker, any malicious activities may appear to come from the application or the application's owner.

Risk mitigations

Architecture and design: Prefer library calls over external processes, keep command-generating data outside external control where possible, and map fixed input values such as numeric IDs to known filenames or URLs. Duplicate client-side security checks on the server, and use vetted libraries or frameworks that separate data from code. Where available, use structured parameterization with individual arguments instead of a single command-shell string, such as argument-array interfaces rather than system-style calls.

Implementation: Properly quote arguments and escape special characters; use an extremely strict allowlist when feasible, and quote each argument after filtering or escaping. Prefer passing arguments through an input file or standard input when the executed program supports it. Apply accept-known-good validation based on the expected type, length, syntax, allowed values, and business rules, while treating validation as defense in depth rather than a replacement for encoding, escaping, and quoting. Keep error messages minimally informative and put necessary detail in carefully protected logs.

Operation and hardening: Use sandboxing or jails, runtime command allowlists, and the lowest required privileges, recognizing that these measures generally limit impact rather than remove the weakness. Automatic taint propagation can prevent command execution with tainted variables, but validation must correctly remove taint. An application firewall may provide temporary or defense-in-depth protection, although it can miss input vectors, be bypassed, or reject legitimate requests. When applicable, avoid PHP register_globals and do not recreate it insecurely. Avoid weaknesses related to jail design, including CWE-243.

  1. Architecture and DesignIf at all possible, use library calls rather than external processes to recreate the desired functionality.
  2. Sandbox or Jail · Architecture and Design, Operation · Effectiveness: LimitedRun the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software. OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations. This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise. Be careful to avoid CWE-243 and other weaknesses related to jails.The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.
  3. Attack Surface Reduction · Architecture and DesignFor any data that will be used to generate a command to be executed, keep as much of that data out of external control as possible. For example, in web applications, this may require storing the data locally in the session's state instead of sending it out to the client in a hidden form field.
  4. Architecture and DesignFor any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
  5. Libraries or Frameworks · Architecture and DesignUse a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. For example, consider using the ESAPI Encoding control [REF-45] or a similar tool, library, or framework. These will help the programmer encode outputs in a manner less prone to error.
  6. Output Encoding · ImplementationWhile it is risky to use dynamically-generated query strings, code, or commands that mix control and data together, sometimes it may be unavoidable. Properly quote arguments and escape any special characters within those arguments. The most conservative approach is to escape or filter all characters that do not pass an extremely strict allowlist (such as everything that is not alphanumeric or white space). If some special characters are still needed, such as white space, wrap each argument in quotes after the escaping/filtering step. Be careful of argument injection (CWE-88).
  7. ImplementationIf the program to be executed allows arguments to be specified within an input file or from standard input, then consider using that mode to pass arguments instead of the command line.
  8. Parameterization · Architecture and DesignIf available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated. Some languages offer multiple functions that can be used to invoke commands. Where possible, identify any function that invokes a command shell using a single string, and replace it with a function that requires individual arguments. These functions typically perform appropriate quoting and filtering of arguments. For example, in C, the system() function accepts a string that contains the entire command to be executed, whereas execl(), execve(), and others require an array of strings, one for each argument. In Windows, CreateProcess() only accepts one command at a time. In Perl, if system() is provided with an array of arguments, then it will quote each of the arguments.
  9. Input Validation · ImplementationAssume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. When constructing OS command strings, use stringent allowlists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping. Note that proper output encoding, escaping, and quoting is the most effective solution for preventing OS command injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent OS command injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, when invoking a mail program, you might need to allow the subject field to contain otherwise-dangerous inputs like ";" and ">" characters, which would need to be escaped or otherwise handled. In this case, stripping the character might reduce the risk of OS command injection, but it would produce incorrect behavior because the subject field would not be recorded as the user intended. This might seem to be a minor inconvenience, but it could be more important when the program relies on well-structured subject lines in order to pass messages to other components. Even if you make a mistake in your validation (such as forgetting one out of 100 input fields), appropriate encoding is still likely to protect you from injection-based attacks. As long as it is not done in isolation, input validation is still a useful technique, since it may significantly reduce your attack surface, allow you to detect some attacks, and provide other security benefits that proper encoding does not address.
  10. Enforcement by Conversion · Architecture and DesignWhen the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
  11. Compilation or Build Hardening · OperationRun the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).
  12. Environment Hardening · OperationRun the code in an environment that performs automatic taint propagation and prevents any command execution that uses tainted variables, such as Perl's "-T" switch. This will force the program to perform validation steps that remove the taint, although you must be careful to correctly validate your inputs so that you do not accidentally mark dangerous inputs as untainted (see CWE-183 and CWE-184).
  13. ImplementationEnsure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success. If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not. In the context of OS Command Injection, error information passed back to the user might reveal whether an OS command is being executed and possibly which command is being used.
  14. Sandbox or Jail · OperationUse runtime policy enforcement to create an allowlist of allowable commands, then prevent use of any command that does not appear in the allowlist. Technologies such as AppArmor are available to do this.
  15. Firewall · Operation · Effectiveness: ModerateUse an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].An application firewall might not cover all possible input vectors. In addition, attack techniques might be available to bypass the protection mechanism, such as using malformed inputs that can still be processed by the component that receives those inputs. Depending on functionality, an application firewall might inadvertently reject or modify legitimate requests. Finally, some manual effort may be required for customization.
  16. Environment Hardening · Architecture and Design, OperationRun your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
  17. Environment Hardening · Operation, ImplementationWhen using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

Detection methods

Detection can combine manual and automated approaches. Manual source review, focused spot checks, architecture or design review, and formal methods can provide high or highly cost-effective coverage when all command-execution paths can be assessed. Automated source, binary, or bytecode static analysis can identify data flows into command execution, but may produce false positives when validation is not recognized and false negatives for custom APIs or unavailable third-party code; complete accuracy and coverage are not feasible.

Dynamic testing can use fuzzing, robustness testing, fault injection, web application and web service scanners, and database scanners. These approaches provide moderate or partial coverage and may slow operation, so the product should not become unstable, crash, or produce incorrect results during testing.

MethodApproachEffectiveness
Automated Static AnalysisThis weakness can often be detected using automated static analysis tools. Many modern tools use data flow analysis or constraint-based techniques to minimize the number of false positives. Automated static analysis might not be able to recognize when proper input validation is being performed, leading to false positives - i.e., warnings that do not have any security consequences or require any code changes. Automated static analysis might not be able to detect the usage of custom API functions or third-party libraries that indirectly invoke OS commands, leading to false negatives - especially if the API/library code is not available for analysis.This is not a perfect solution, since 100% accuracy and coverage are not feasible.—
Automated Dynamic AnalysisThis weakness can be detected using dynamic tools and techniques that interact with the product using large test suites with many diverse inputs, such as fuzz testing (fuzzing), robustness testing, and fault injection. The product's operation may slow down, but it should not become unstable, crash, or generate incorrect results.Moderate
Manual Static AnalysisSince this weakness does not typically appear frequently within a single software package, manual white box techniques may be able to provide sufficient code coverage and reduction of false positives if all potentially-vulnerable operations can be assessed within limited time constraints.High
Automated Static Analysis - Binary or BytecodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Bytecode Weakness Analysis - including disassembler + source code weakness analysis Binary Weakness Analysis - including disassembler + source code weakness analysisHigh
Dynamic Analysis with Automated Results InterpretationAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Web Application Scanner Web Services Scanner Database ScannersSOAR Partial
Dynamic Analysis with Manual Results InterpretationAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Fuzz Tester Framework-based FuzzerSOAR Partial
Manual Static Analysis - Source CodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Manual Source Code Review (not inspections) ``` Cost effective for partial coverage: ``` Focused Manual Spotcheck - Focused manual analysis of sourceHigh
Automated Static Analysis - Source CodeAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Source code Weakness Analyzer Context-configured Source Code Weakness AnalyzerHigh
Architecture or Design ReviewAccording to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Formal Methods / Correct-By-Construction ``` Cost effective for partial coverage: ``` Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)High

Representative vulnerabilities

The official record lists these as representative examples, not an exhaustive list: CVE-2024-53899 involved unquoted template strings and shell metacharacters in a directory name; CVE-2025-44844 involved a wireless access point file upload path using a filename from a Content-Disposition header; CVE-2024-6091 and CVE-2024-44335 illustrate chains involving incomplete path or character denylists; CVE-2024-41316 involved os.execute in a Lua network-device application; and CVE-2024-52803 involved insecure use of Popen during LLM training. Earlier examples include command injection in Wi-Fi routers, network configuration and web-server functionality, FTP and telnet link handling, ZIP filenames, environment variables, HTTPS URLs, and files or parameters containing shell metacharacters, including CVE-2020-10987, CVE-2020-9054, CVE-1999-0067, CVE-2002-0061, CVE-2003-0041, CVE-2008-2575, CVE-2002-1898, CVE-2008-4304, CVE-2008-4796, CVE-2007-3572, and CVE-2012-1988. CVE-2001-1246 additionally demonstrates that OS command injection can coexist with argument injection.

Below are representative vulnerabilities related to this CWE, prioritized by severity.

Sources (14)

CWE™ Program, operated by The MITRE Corporation. Copyright © 2006–2026, The MITRE Corporation. The MITRE Corporation hereby grants you a non-exclusive, royalty-free license to use CWE for research, development, and commercial purposes. CWE Terms of Use.

Learn more

Run an in-depth assessment with complete web risk management

CyStack VulnScan continuously discovers assets, validates vulnerabilities, and helps security teams prioritize remediation across the organization.

Explore CyStack VulnScan