如何避免以下代码的“This use of java/lang/ProcessBuilder.([Ljava/lang/String;)V can be eager to Command Injection”声纳消息?
更新
void assign(String path, File jarFile) {
File cert = new File(path, "Cert");
String password = "123";
File script = new File(path, "assign.bat");
String command = "\"" + script.getAbsolutePath() + "\" " + password
+ " \"" + cert.getAbsolutePath() + "\""
+ " \"" + jarFile.getAbsolutePath() + "\"";
Process proc = new ProcessBuilder(command).start();
}
Run Code Online (Sandbox Code Playgroud)
您可能可以在当前的测试代码中推断出这里实际上不存在滥用的可能性,但我怀疑这是给出硬编码密码“123”的生产代码。像这样的代码往往会变形,如果您留下注入的可能性,您必须非常了解所有参数的来源才能排除注入。如果你的方法正确,你就不必对参数那么小心。
而且,漏洞扫描器不可能这么聪明。谁知道 Sonar 正在寻找什么,但它正在抱怨 ProcessBuilder 构造函数的这个特定变体。也许它可以识别输入字符串中的空格并知道那里有参数。谁知道。无论如何,确实没有理由不使用更强大的构造函数版本。我希望这样做可以避免出现此消息。
就像 SQL 一样,答案是将各个参数传递给 ProcessBuilder,如下所示:
void assign(String path, File jarFile) throws IOException {
File cert = new File(path, "Cert");
String password = "123";
File script = new File(path, "assign.bat");
String[] command = {
script.getAbsolutePath(),
password,
cert.getAbsolutePath(),
jarFile.getAbsolutePath()
};
Process proc = new ProcessBuilder(command).start();
}
Run Code Online (Sandbox Code Playgroud)
这确保了代码知道可执行文件本身和参数之间的区别,因此可执行文件不会那么容易被操纵。这也使得这个特定的代码更干净、更容易阅读。
请注意,即使在这种情况下,为了确保此代码是安全的,您需要密切了解File.getAbsolutePath()的行为和/或确切地了解“path”和“jarFile”的来源。File可能会被操纵以从getAbsolutePath返回错误的内容。我并不是说它可以,但事实上我不知道这两种方式正是我想要使用 ProcessBuilder 构造函数的多字符串变体的原因。
更新:所以声纳仍在抱怨这种形式。事实证明,这个新版本仍然使用相同的构造函数,因为构造函数是一个可变参数构造函数,可以接受“一个或多个”字符串。我认为我提供的原始解决方案实际上确实解决了注入问题,但 Sonar 无法识别我们已经分离出命令参数的事实。
有一个 ProcessBuilder 构造函数采用列表而不是数组。我的示例的这个版本使用该构造函数。
void assign(String path, File jarFile) throws IOException {
File cert = new File(path, "Cert");
String password = "123";
File script = new File(path, "assign.bat");
String[] command = {
script.getAbsolutePath(),
password,
cert.getAbsolutePath(),
jarFile.getAbsolutePath()
};
List<String> commandList = Arrays.asList(command);
Process proc = new ProcessBuilder(commandList).start();
}
Run Code Online (Sandbox Code Playgroud)
我希望这能让声纳满意。我猜想这种构建 ProcessBuilder 的方式正是它所寻找的。
归档时间: |
|
查看次数: |
1664 次 |
最近记录: |