This is a command injection prevention cheat sheet by Semgrep, Inc. It contains code patterns of potential ways to run an OS command in an application. Instead of scrutinizing code for exploitable vulnerabilities, the recommendations in this cheat sheet pave a safe road for developers that mitigate the possibility of command injection in your code. By following these recommendations, you can be reasonably sure your code is free of command injection. Learn more about Command Injection vulnerability concepts.Documentation Index
Fetch the complete documentation index at: https://docs.semgrep.dev/llms.txt
Use this file to discover all available pages before exploring further.
Check your project using Semgrep
1. Running an OS command
1.A. Spawning a shell with exec function
Theexec() function executes shell commands. It spawns a shell and then executes the command within the spawned shell, buffering any generated output. Never pass unsanitized user input to this function. Any input containing shell metacharacters can be used to trigger the execution of arbitrary commands.
Example:
References
Mitigation
- Always try to use internal JavaScript APIs (if they exist) instead of running an OS command. In other words, use internal language features instead of invoking commands that can be manipulated by a malicious actor.
- Don’t pass user-controlled input or use an allowlist for inputs.
- If it is not possible, use an array with a sequence of program arguments instead of a single string.
- Avoid non-literal values for the command string. Strip everything except alphanumeric characters from an input provided for the command string and arguments.
Semgrep rule
javascript.lang.security.detect-child-process.detect-child-process
1.B. Spawning a process with spawn function
Thespawn() and spawnSync() functions spawn a new process using the command with a list of arguments. This allows spawning any programs or running shell processes with arbitrary arguments, which can result in a command injection vulnerability.
Example:
References
child_process module documentation
Mitigation
- Always try to use internal JavaScript APIs (if they exist) instead of running an OS command. In other words, use internal language features instead of invoking commands that can be manipulated by a malicious actor.
- Don’t pass user-controlled input or use an allowlist for inputs.
- Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of: - Define a list of allowed arguments.
- Avoid non-literal values for the command string. Strip everything except alphanumeric characters from an input provided for the command string and arguments.
Semgrep rule
javascript.lang.security.detect-child-process.detect-child-process