Skip to content
Advertisement

Command Injection In Java

I am new in java, a self learner. I came accross the following issue and was stuck. In fact I am trying to sanitize this code against command injection but failed to understand how. I know how to sanitize user input but this specific has to do with command executed in the OS and I am not sure how anyone help please. here is the code:

public class CommandProcessor {

    public CommandProcessor() {
        // TODO Auto-generated constructor stub
    }
    
    public int invokeCommand(String command) throws  IOException{
        int exitCode =0;
        
        if(command !=null && !command.isEmpty()) {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(command);
                process.waitFor();
                exitCode = process.exitValue();
                
            }catch(InterruptedException e) {
                
            }
        }
        return exitCode;
        
    }
}

Advertisement

Answer

The correct answer is to read the documentation as your current code is not safe.

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Runtime.html#exec(java.lang.String%5B%5D)

The “command to execute” should be a constant.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement