I want to use the org.apache.commons.exec Java library to call an executable. Does the CommandLine object protect against command line injection? For example, if I call:
String singleStringArgument = "-whatever;rm -rf ~/*"; // evil looking argument!
CommandLine cl = new CommandLine(new File(pathToExe,exeName));
cl.addArgument(singleStringArgument); // oh no!
Executor exe = new DefaultExecutor();
exe.execute(cl);
would rm -rf ~/* also run in addition to the intended command? If it does, what is the best way to protect against this?
The API says addArgument() “handles quoting” but I’m not sure what that means in this context. I could whip up a test case to see what happens on my linux box, but I want to be sure that it’s safe on other platforms too.
;is a feature of the shell. If you don’t create a command line aroundsh -cor something like it, you can’t get injected into. It’s not that commons is safe, its that you aren’t even running the program with the vunerability.Commons CLI is wrapping the Process class. The Process class is not documented to fire up the shell. It is documented to do an
execwith specified arguments of what you tell it to.As per a comment, one of the wonders of open source is that you can read the source. If version X of commons-CLI does what you like, depend on it, and don’t upgrade without rechecking.