MStirling820357 (Community Member) asked a question.

Fix for OS Command Injection (CWE ID 78) Java

My old code:

// Build the params

String[] sCommandAndParam = new String[vcctParams.size () + 1];

 

// Set the commands

sCommandAndParam[0] = scriptName;

for (int iP = 0; iP < vcctParams.size (); iP++)

sCommandAndParams[iP + 1] = NPSCommon.safeVectorGetString(vctParams, iP);

 

// Execute the script

pUs = rt.exec (sCommandAndParams); //flaw shows here

 

NewCode:

// Build the params

String[] sCommandAndParam = new String[vcctParams.size () + 1];

 

// Set the commands

sCommandAndParam[0] = scriptName;

for (int iP = 0; iP < vcctParams.size (); iP++)

sCommandAndParams[iP + 1] = ESAPI.encoder().encodeForOS(new WindowsCodec(),NPSCommon.safeVectorGetString (vctParams, iP));

 

 

// Execute the script

pUs = rt.exec (sCommandAndParams); /flaw still shows here

 

But scan still showing flaw in the execute line could you please suggest another way


  • Hello @MStirling820357 (Community Member)​ ,

     

    Veracode Static Analysis will report CWE 78 Improper Neutralization of Special Elements used in an OS Command (OS Command Injection) if it can detect that there is data from outside the scope of the application (eg. HTTP Request, Database, webservice, Configuration files etc.) being used in a command or it's arguments.

     

    The general recommendation is as follows:

    1. When possible hardcode the allowed inputs and use only hardcoded data in OS commands executed by the application. This would automatically resolve and close the vulnerabilities in the Veracode Platform.
    2. Use ProcessBuilder instead of Runtime.exec() and separate the command from the arguments. Also validate external input against a whitelist of known allowed characters, for instance letters and numbers which will avoid shell meta-characters and spaces. 

     

    Please note custom input validation would require proposing a mitigation (https://docs.veracode.com/r/Propose_Mitigating_Factors_for_a_Flaw ) on this flaw from the Veracode Platform or IDE plugin describing the controls you have in place to prevent an attacker from abusing this functionality and contacting your security team to have these proposals reviewed.

     

    Reference: https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html#java

     

    Regards,

    Sounderya Ramesh Babu

     

    Expand Post

Topics (5)

No articles found
Loading

Ask the Community

Get answers, share a use case, discuss your favorite features, or get input from the community.