java - 将用户输入的字符串用作格式控件是什么意思,为什么它是安全漏洞?

标签 java

我在 Deitel 和 Deitel 的书 Java: How to Program 中读到了这个错误预防技巧 (3.1)。我不明白这是什么意思。我只知道说的是下面这行代码:

// display the name stored in object myAccount
System.out.printf("Name in object myAccount is:%n%s%n", myAccount.getName());

该段内容如下:

Never use as a format-control a string that was input from the user. When method System.out.printf evaluates the format-control string in its first argument, the method performs tasks based on the conversion specifier(s) in that string. If the format-control string were obtained from the user, a malicious user could supply conversion specifiers that would be executed by System.out.printf, possibly causing a security breach.

最佳答案

严格来说,使用用户输入的字符串进行格式控制是这样的:

String format=getFromUser(...);
System.out.printf(format, arg1, arg2, arg3...);

这可能真的很有害,因为除了@JohnKugelman 建议的编码注入(inject)之外,我可以想到四种简单的方法,恶意用户可以通过这些方法通过 format string 来破坏安全性。 :

  • 最简单的方法是输入错误的掩码,这样就会在运行时抛出 WrongFormatConversion:
    @Test
    public void wrongMask()
    {
        String s="january";
        System.out.printf("%)/$#", s);
    }
  • 通过输入高参数索引,以便在运行时抛出 MissingFormatArgumentException:
    @Test
    public void highArgumentIndex()
    {
        String s="january";
        System.out.printf("%1000$s%n", s);
    }
  • 通过输入高字段宽度,这样会输出这么大的一行,阅读起来不切实际:
    @Test
    public void highFieldWidth()
    {
        String s="january";
        System.out.printf("%1000000s%n", s);
    }
  • 同上,但是为数字参数指定一个零填充高宽度,这样填充操作将消耗很长时间并且可能也消耗大量内存(当然是因为填充算法不是为了处理大字符串,所以,它的设计并不是最佳的)。
    @Test
    public void highArgumentWidth()
    {
        int n=12;
        System.out.printf("%01000000d%n", n);
    }

此测试延迟了将近 一分钟 在我的计算机上执行。尝试使用足够高的宽度,您可能会在延迟几分钟后收到 OutOfMemoryError

(通过对输入字符串进行简单的预处理以转义所有双引号,可以轻松避免代码注入(inject),但这些缺陷具有语义性质,因此更难发现和避免) .

但是这些都不能应用于您的行,因为您的格式字符串是硬编码的,而不是用户输入的。

更新

要了解接受来自最终用户的控制格式字符串有多危险,您最好重复上面的一组测试,但要在交互模式下进行:

    public static void main(String[] args)
    {
        String format=args[0];
        int n=12;
        System.out.printf(format, n);
    }

然后,把你自己想象成一个试图破解这个程序的黑客。使用这些建议值执行它:

  • %)/$#
  • %1000$d
  • %1000000d
  • %01000000d

结论:格式字符串必须由程序员编写,而不是由最终交互用户编写。

关于java - 将用户输入的字符串用作格式控件是什么意思,为什么它是安全漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43175926/

相关文章:

java - 如何编写一个程序来解决多个问题?

Java EE - 创建一个通过电子邮件注册的设置

java - 在java中配置mysql url

java - 当主键为 UUID 时,JPA 2 合并是插入而不是更新

Java,Person的所有实例都链接到一个对象

java - 游戏窗口闪烁

java - 在 Grails 中使用 Java 类(具有 Spring/Hibernate 依赖项的整个模块)

java - java中如何过滤mongodb中的记录

java - "If the previous activity was ... do something"

java - PDF 和 Docx 文件预览器