清理/转义进入 SSH 命令的参数
我需要做什么才能正确清理/转义正在输入到编程 SSH 命令中的参数?
例如,路径参数 -
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;
}
不安全的原因是路径参数可能来自用户上传的文件。从技术上讲,恶意用户可以上传带有无效文件名的文件。虽然我可以事先检查这一点(我正在这样做),但我也想在这里检查一下。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这里的一个好主意是确保它作为单个参数传递给
[
,而不是多个参数(甚至多个命令)。因此,只需将其包装在'
中,并将字符串内的任何'
替换为'\''
即可。您还可以使用
'
而不是\"
作为命令的echo
部分,只要您不需要变量扩展即可服务器端(并且这些字符串中没有变量):(请注意,我还做了一个小小的语法修复。)
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 theecho
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):(Note that I also did a tiny grammar fix.)