gpt4 book ai didi

java - Fortify 问题 - 命令注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:47 26 4
gpt4 key购买 nike

我正在尝试对我的 java 应用程序进行 hp fortify 安全扫描。我有几个问题,我已经解决了。但我无法找到以下问题的解决方案。

  1. 命令注入(inject)

    String hostname = execReadToString("hostname").split("\\.")[0];
    public static String execReadToString(String execCommand) throws IOException {
    try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) {
    return s.hasNext() ? s.next() : "";
    }

    方法 execReadToString() 调用 exec() 来执行命令。此调用可能允许攻击者注入(inject)恶意命令。

所以我也尝试过流程构建器。

private static void gethostname(String cmd1) throws IOException {
if(Pattern.matches("[A-Za-z]+", cmd1)) {
ProcessBuilder pb = new ProcessBuilder(cmd1);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String readline;
while ((readline = reader.readLine()) != null) {
System.out.println(readline);
}
}
}

即使这给我带来了安全问题此 start() 调用可能允许攻击者注入(inject)恶意命令。

此问题的理想解决方案是什么?

提前致谢

最佳答案

通常这是因为您使用用户输入来构建命令字符串,其中用户可以注入(inject)恶意代码来操纵最终运行的命令(即使您添加验证,也会有方法规避它)。

在您的情况下,您似乎对命令进行了硬编码,因此这应该不是问题,但是,请参阅 hardcoded command invocation 上的 OWASP 页面。 (强调我的):

Unlike the previous examples, the command in this example is hardcoded, so an attacker cannot control the argument passed to system(). However, since the program does not specify an absolute path for make, and does not scrub any environment variables prior to invoking the command, the attacker can modify their $PATH variable to point to a malicious binary named make and execute the CGI script from a shell prompt. And since the program has been installed setuid root, the attacker's version of make now runs with root privileges.

The environment plays a powerful role in the execution of system commands within programs. Functions like system() and exec() use the environment of the program that calls them, and therefore attackers have a potential opportunity to influence the behavior of these calls.

分辨率:

  1. 使用 native Java API/库来实现您想要的,而不是运行命令 - 这可能是最好的选择。仅在不可避免时才使用命令,例如:没有 Java 客户端库的第三方工具。这种方法的另一个优点是更便携,并且在大多数情况下也更高效。 This库可能会对您的情况有所帮助。
  2. 如果您必须运行某个命令,请确保您不使用用户提供的数据或外部数据(哪怕是间接的数据)来构建该命令。
  3. 或者,如果您对命令进行硬编码以从代码运行,请使用命令的绝对路径,并且不要使用环境变量作为其中的一部分。对于主机名(假设您使用内置命令),通常是/usr/bin/hostname,但您可以使用which hostname找到您环境的命令路径。

关于java - Fortify 问题 - 命令注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com