What do I need to do to properly sanitize/escape a parameter that is being entered into a programmatic SSH command?
For example, the path parameter –
public boolean exists(String path) {
try {
ChannelExec c = (ChannelExec) session.openChannel("exec");
//Here *** would like to be sure that the path is completely valid
c.setCommand("[ -f " + path + " ] && echo \"File exists\" || echo \"File does not exists\"");
InputStream in = c.getInputStream();
c.connect();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(in, out);
in.close();
out.close();
System.out.println(out.toString("UTF-8"));
c.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
The reason it is unsafe is that the path parameter can come from a user uploaded file. A malicious user could technically upload a file w/ an invalid filename. Although I can check for this beforehand (which I’m doing) I’d also like to check for it here too.
I think a good idea here would be to make sure it is passed as a single parameter to
[, and not multiple ones (or even multiple commands). So simply wrap it in', and replace any'inside the string by'\''.You also can use
'instead of\"for theechopart of the command, as long as you don’t need variable expansion on the server side (and there are no variables in these strings):(Note that I also did a tiny grammar fix.)