Runtime.getRuntime().exec(String[]) safety
I'm using Runtime.getRuntime().exec(Stri开发者_开发问答ng[]) to run processes where some of the elements of the String array are defined by the user.
Is this safe? Or will it allow to inject code into the terminal?
If it isn't safe what can i do to avoid code injection? (it has to be platform independent)
As i mentioned in a comment on another answer (might as well add my own answer), this should be safe as long as you control the first argument.
Generally this isn't safe since it should be possible to execute shell scripts (which might be malicious).
I'd allow a predefined set of commands which you know and let the user select one of those (with optional parameters that might be escaped somehow) instead of allowing to enter the commands completely.
Assuming your user is supplying arguments, ProcessStarter is your friend. A small tutorial on how to use it can be found at https://www.java-tips.org/java-se-tips-100019/88888889-java-util/426-from-runtimeexec-to-processbuilder.html
I think the safety in this case is defined by the underlying operating system access control. If you are using unix and running your script as a limited user, then you should be fine. So as long as the access control is defined correctly and the script is run as a user with correct permission, then it is fine. (but what use case made you write a program like this. )
All of these comments seem to be missing one important fact. Command injection is only ONE of the dangers of using user defined arguments with exec. Another possible attack is argument injection. You need to be aware of all possible arguments to a command you are letting a user call.
An example of a dangerous command is find. A user could add the option -exec as an argument to gain arbitrary command execution.
精彩评论