Check your project using Semgrep
1. Running an OS command
1.A. Running OS commands with Runtime.getRuntime().exec()
Theexec call executes the specified string command in a separate process. This is dangerous if a command string is controlled by user input and could result in command injection.
Example:
References
Mitigation
- Always try to use internal Java 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.
- Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of: - If it is not possible, then strip the input of everything except alphanumeric characters provided for the command string and arguments.
- Do not use direct user input, even if it is sanitized.
- If it is not possible to avoid direct user input, do not allow running arbitrary commands. Use an allowlist for inputs.
- Strip
!@#$;&*~"'{}][-+%^characters from user input that is incorporated in the command string which is later executed.
Semgrep rule
java.lang.security.audit.command-injection-formatted-runtime-call.command-injection-formatted-runtime-call
1.B. Running OS processes with ProcessBuilder
TheProcessBuilder class is used to create operating system processes. If the command string is controlled by user input it can result in command injection.
Example:
References
ProcessBuilder documentation
Mitigation
- Try to avoid non-literal values in the command string.
- If it is not possible to prevent non-literal values in the command string, then do not allow running arbitrary commands. Use an allowlist for inputs.
- Do not include command arguments in a command string, use parameterization instead. For example:
Use:Instead of:
Semgrep rule
java.lang.security.audit.command-injection-process-builder.command-injection-process-builder