Do apache commons CommandLine objects protect against command line injection?
I want to use the org.apache.commons.exec
Java library to call an ex开发者_开发问答ecutable. 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 around sh -c
or 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 exec
with 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.
So you control the command (pathToExe) and are worried only about the argument? How well do you know the command? Is there any chance that it could exec another program? Is there any chance it could do something damaging even without invoking a secondary command? Does the program have any other vulnerabilities (buffer overflow, etc)?
As a general answer, this approach seems iffy to me, especially if you want this to work cross platform. If you know the command to be executed and can constrain the input, then you might be able to squeak by, but personally I wouldn't use this approach unless there was a really good reason to do so.
My suggestion is to make the program err on the side of safety if possible and only issue commands itself and not dumbly execute command fragments or pass on arguments issued by an end user. There are many variations of injection. ;
is one already discussed. You can also use backticks (wrapping rm -rf ~/*
in backticks makes the shell interpret it first)The user can also accidently or intentionally invoke aliases. The list of things that can go wrong is endless.
精彩评论