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. Using the subprocess module
Thesubprocess module allows you to start new processes, connect to their input/output/error pipes, and obtain their return codes. Methods such as Popen, run, call, check_call, check_output are intended for running commands provided as an argument. Allowing user input in a command that is passed as an argument to one of these methods can create an opportunity for a command injection vulnerability.
Example:
References
- subprocess module documentation
- shlex.split documentation
- shlex.quote documentation
- CVE-2020-7698: Gerapy Command Injection
- CVE-2020-11981: Apache Airflow Command Injection
Mitigation
Do not let a user input intosubprocess methods. Alternatively:
- Always try to use internal Python API (if it exists) instead of running an OS command. In other words, use internal language features instead of invoking commands that can be exploited.
- Don’t pass user-controlled input.
- If it is not possible, use an array with a sequence of program arguments instead of a single string.
- Use
shlex.splitto correctly parse a command string into an array andshlex.quoteto correctly sanitize input as a command-line parameter. - Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of: - If it is not possible, strip everything except alphanumeric characters from an input provided for the command string and arguments.
Semgrep rule
python.lang.security.audit.dangerous-subprocess-use
1.B. shell=True
Functions from thesubprocess module have the shell argument for specifying if the command should be executed through the shell.
Using shell=True is dangerous because it propagates current shell settings and variables.
This means that variables, glob patterns, and other special shell features in the command string are processed before the command is run,
making it much easier for a malicious actor to execute commands. The subprocess module allows you to start new processes, connect to their input/output/error pipes, and obtain their return codes. Methods such as Popen, run, call, check_call, check_output are intended for running commands provided as an argument (‘args’). Allowing user input in a command that is passed as an argument to one of these methods can create an opportunity for a command injection vulnerability.
Example:
References
Mitigation
Avoid usingshell=True. Alternatively, use shell=False instead.
Semgrep rule
python.lang.security.audit.subprocess-shell-true
1.C. Using os module to execute commands
Theos module provides a portable way of using operating system dependent functionality. Methods such as system, popen and deprecated popen2, popen3 and popen4 are intended for running commands provided as a string. Letting user supplied data into a command that is passed as an argument to one of these methods can create an opportunity for a command injection vulnerability.
Example:
References
Mitigation
Do not let a user input intoos methods. Alternatively:
- Always try to use an internal Python API (if it exists) instead of running an OS command.
- Consider using
subprocessfunctions with array of program arguments. - Don’t pass user-controlled input.
- If it is not possible, then don’t let running arbitrary commands. Use an allowlist for inputs.
Semgrep rule
python.lang.security.audit.dangerous-system-call
1.D. Using os module to spawn a process
Theos module allows executing the program path in a new process. Variations of spawn method including spawnl, spawnle, spawnlp, spawnlpe, spawnv, spawnve, spawnvp, spawnvpe, posix_spawn and posix_spawnp are intended for spawning a process with a program passed as a string argument. Allowing spawning of arbitrary programs or running shell processes with arbitrary arguments may result in a command injection vulnerability.
Example:
References
Mitigation
Do not let a user input intospawn methods. Alternatively:
- Always try to use an internal Python API (if it exists) instead of running an OS command.
- Don’t pass user-controlled input.
- Use
shlex.splitto correctly parse a command string into an array andshlex.quoteto correctly sanitize input as a command-line parameter. - Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of: - If it’s not possible to avoid, strip everything except alphanumeric characters from an input provided for the command string and arguments.
Semgrep rule
python.lang.security.audit.dangerous-spawn-process.dangerous-spawn-process
1.E. Replacing current process with exec
Execution methods of theos module are intended to execute a new program, replacing the current process. The available methods are execl, execle, execlp, execlpe, execv, execve, execvp, and execvpe. Allowing running of arbitrary programs or running shell processes with arbitrary arguments may result in a command injection vulnerability.
Example:
References
Mitigation
Do not let a user input intoexec methods. Alternatively:
- Always try to use internal an Python API (if it exists) instead of running an OS command.
- Don’t pass user-controlled input.
- Use
shlex.splitto correctly parse a command string into an array andshlex.quoteto correctly sanitize input as a command-line parameter. - Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of: - If it’s not possible to avoid, strip everything except alphanumeric characters from an input provided for the command string and arguments.
Semgrep rule
python.lang.security.audit.dangerous-spawn-process.dangerous-spawn-process
1.F. Wildcard character in a system call that spawns a shell
Spawning a shell or executing a Unix shell command with a wildcard leads to normal shell expansion, which can have unintended consequences if there exist any non-standard file names. Consider a file named ‘-e sh script.sh’ — this will execute a script when ‘rsync’ is called. Example:References
Mitigation
Avoid wildcards in Unix shell commands.Semgrep rule
python.lang.security.audit.system-wildcard-detected
1.G. Running shell commands asynchronously
Theasyncio.subprocess is an async or await API to create and manage subprocesses. Such methods as create_subprocess_shell and Event Loop’s subprocess_shell are intended for running shell commands provided as an argument ‘cmd’. Allowing user input into a command that is passed as an argument to one of these methods can create an opportunity for a command injection vulnerability.
Example:
References
Mitigation
Do not let a user input intoasyncio.subprocess methods. Alternatively:
- Always try to use an internal Python API (if it exists) instead of running an OS command.
- Consider using
asyncio.subprocessfunctions with array of program arguments (for example:create_subprocess_exec). - Don’t pass user-controlled input.
- If it’s not possible, then don’t let running arbitrary commands. Use an allowlist for inputs.
Semgrep rule
python.lang.security.audit.dangerous-asyncio-shell.dangerous-asyncio-shell
1.H. Creating subprocesses asynchronously
Theasyncio.subprocess also allows asynchronous creation of subprocesses. Such methods as create_subprocess_exec and Event Loop’s subprocess_exec are intended for creating a subprocess from one or more string arguments specified by args. Allowing user input into a command that is passed as an argument to one of these methods can create an opportunity for a command injection vulnerability.
Example:
References
Mitigation
Do not let a user input intoasyncio subprocess methods. Alternatively:
- Always try to use an internal Python API (if it exists) instead of running an OS command.
- Don’t pass user-controlled input.
- Use
shlex.splitto correctly parse a command string into an array andshlex.quoteto correctly sanitize input as a command-line parameter. - Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of: - If it’s not possible to avoid, strip everything except alphanumeric characters from an input provided for the command string and arguments.
Semgrep rule
python.lang.security.audit.dangerous-asyncio-exec.dangerous-asyncio-execpython.lang.security.audit.dangerous-asyncio-create-exec.dangerous-asyncio-create-exec