Reputation: 131
I'm working on a problem where I have to execute a tar command from Java Code
tar -xcv output_file_name source_directory
This is the code
String cmd = "tar -cvzf /tmp/logs.tar.Z /home/test/log/status.*"
try {
Process p1 = Runtime.getRuntime().exec(cmd);
p1.waitFor();
} catch (IOException e) {
e.printStackTrace();
}
Above code is working but it is failing third party security test with possibility of command injection.
I have tried to sanitize my input command by adding regex but the vulnerability is still same.
Can anyone help how to deal with this scenario. Any help in this regard is greatly appreciated.
Upvotes: 0
Views: 183
Reputation: 718788
Firstly, I don't think it is going to work at all. The exec(cmd)
call will not deal with the /home/test/log/status.*
command line argument correctly ... assuming that you want the status.*
to match all files that start with "status." in that directory. The exec
method does not do understand shell syntax such as globbing.
Next, the -v
option outputs the names of files included in the tar file to standard output. But you are not consuming standard output. You should remove the option
My guess is that the security tool is complaining that you are not using the absolute path for tar
. There is the possibility that $PATH
will include (say) "." ... and you will execute a fake tar
command in the current directory.
So the command probably needs to be this:
Process p1 = Runtime.getRuntime().exec(
"/bin/sh", "-c",
"/bin/tar -czf /tmp/logs.tar.Z /home/test/log/status.*");
If that doesn't solve the problem, please tell us which security tool you are using and show us the complete message, including any error numbers. If we have more details we may be able to figure out what it is complaining about.
Upvotes: 1