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;
}
}
CodePudding user response:
The correct answer is to read the documentation as your current code is not safe.
The "command to execute" should be a constant.