OS Command Injection (CWE ID 78) (1 flaw) Java code

1.4k views Asked by At

The flaw is at Runtime.getRuntime().exec(cmd, env) method. We have validated the input using OWASP ESAPI.

But Veracode still reports OS command injection flaw.

Old Code:

public Process exec(String[] cmd, String[] env) throws IOException {

  return Runtime.getRuntime().exec(cmd, env);

}

New Code:

public Process exec(String[] cmd, String[] env) throws IOException {

  String[] newCmdArr = new String[cmd.length];

  String[] newEnvArr = new String[env.length];

  for(int i=0;i<env.length;i++)

  {

  newEnvArr[i] = CSSecurity.getValidInput(ESAPIContext.OSCommand, env[i], ESAPIType.OSCommand);               

  }       

  for ( int i = 0; i < cmd.length; i++ ) 

  {

   newCmdArr[i] = CSSecurity.getValidInput(ESAPIContext.OSCommand, cmd[i], ESAPIType.OSCommand);

  }

  return Runtime.getRuntime().exec(newCmdArr, newEnvArr);   

 }
1

There are 1 answers

0
securecodeninja On

Try using the encodeForOS ESAPI method instead:

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.codecs.WindowsCodec;

public Process exec(String[] cmd, String[] env) throws IOException {

   String[] newCmdArr = new String[cmd.length];
   String[] newEnvArr = new String[env.length];

   for(int i=0; i<env.length; i++){
      newEnvArr[i] = ESAPI.encoder().encodeForOS(new WindowsCodec(),env[i]);
   }

   for (int i=0; i<cmd.length; i++){
      newCmdArr[i] = ESAPI.encoder().encodeForOS(new WindowsCodec(),cmd[i]);
   }
 
 return Runtime.getRuntime().exec(newCmdArr, newEnvArr);
}