问题
I need to call a custom script via command line, the scripts takes few arguments and is called on Linux machine. Current version is prone to all kinds of shell injection, how to sanitize arguments given by user? Arguments include login and path (Unix or Windows path) and user should be able to type in any possible path (the path refers to remote path on user server).
The code right now simply looks like this:
Process process = Runtime.getRuntime().exec("myscript " + login + " " + path);
回答1:
From this answer, use ProcessBuilder instead:
ProcessBuilder pb = new ProcessBuilder("myscript", login, path);
This should secure it against shell injection.
Path injection should not be an issue if path only refers to a path on their own system as you say:
the path refers to remote path on user server
The risk is if the server contacts the "path" somehow, which is not clear from your question. What type of path is it? A URL path, a Samba share?
You may need to secure it against Server Side Request Forgery. This involves validating the user input to check it refers to an external server, and not one inside of your own network.
回答2:
One way to validate the path is to use the FileSystem method getPath() to construct a Path object, then get the string representation back by toString() (or toAbsolutePath().toString()). That way, you can be sure that only valid paths are processed. However, this will not save you from typical path injection attachs using for example "../../../../somecriticalsystemfolder".
回答3:
Verify the login and path using simple rules defined by regular expressions.
Validate Username: Regular Expression in Java for validating username
Validate Path: java regular expression to match file path
The regular expression will determine if the path is formatted correctly. To determine if the path is actually a directory on the file system, use the isDirectory method of the File object.
来源:https://stackoverflow.com/questions/38972123/how-to-sanitize-user-input-used-in-runtime-exec