2

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);
Please
  • 328
  • 3
  • 17
  • Start your script without arguments and then communicate with it via stdin/out. You are never going to secure Runtime.exec. – matt Aug 17 '16 at 14:47

3 Answers3

2

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.

Community
  • 1
  • 1
SilverlightFox
  • 32,436
  • 11
  • 76
  • 145
0

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".

Piotr Wilkin
  • 3,446
  • 10
  • 18
-1

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.

Community
  • 1
  • 1
eighthrazz
  • 331
  • 1
  • 6
  • 1
    The problem is, valid path can contain characters that allow someone to prepare malicious command, how do I make sure that supplied path is just path? – Please Aug 17 '16 at 09:19
  • I modified my answer showing how to determine if the given path valid. – eighthrazz Aug 17 '16 at 14:46