Search code examples
javaunixsshjava-8veracode

CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')


I am trying to run some SSH commands on server from my application, I am getting CWE-78 Can someone help in mitigating the same Error:- CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection'): Details: This call to java.lang.Runtime.exec() contains a command injection flaw. The argument to the function is constructed using untrusted input. If an attacker is allowed to specify all or part of the command, it may be possible to execute commands on the server with the privileges of the executing process. The level of exposure depends on the effectiveness of input validation routines, if any. The first argument to exec() contains tainted data from the variable executeCommandsArray. The tainted data originated from an earlier call to AnnotationVirtualController.vc_annotation_entry. Validate all untrusted input to ensure that it conforms to the expected format, using centralized data validation routines when possible. When using blocklists, be sure that the sanitizing routine performs a sufficient number of iterations to remove all instances of disallowed characters. Most APIs that execute system commands also have a "safe" version of the method that takes an array of strings as input rather than a single string, which protects against some forms of command injection

            StringBuilder sb = new StringBuilder();
            sb.append("cat *" );
             String bashCommand= "/bin/sh";
             String optionCommand = "-c";
             String[] executeCommandsArray= new String[] 
              {bashCommand,optionCommand,sb.toString()};

            Runtime run = Runtime.getRuntime();
            Process pr = run.exec(executeCommandsArray);
            int exitcode = pr.waitFor();

Solution

  • Passed string buffer inside the Normalizer it worked

          Normalizer.normalize(sb.toString(), Normalizer.Form.NFKD));