Sanitize/escape argument that's going into a SSH command
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 exist开发者_Go百科s(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 '\''
.
private String escape(String s) {
return "'" + s.replace("'", "'\\''") + "'";
}
You also can use '
instead of \"
for the echo
part of the command, as long as you don't need variable expansion on the server side (and there are no variables in these strings):
c.setCommand("[ -f " + escape(path) + " ] && " +
"echo 'File exists' || echo 'File does not exist'");
(Note that I also did a tiny grammar fix.)
精彩评论