《Java安全编码标准》一2.7 IDS06-J从格式字符串中排除用户输入

    xiaoxiao2021-04-18  191

    2.7 IDS06-J从格式字符串中排除用户输入

    对Java格式字符串的解释要比对在像C语言这样的语言中更严格[Seacord 2005]。当任何转换参数不能匹配相应的格式符时,标准类库实现会抛出一个相应的异常。这种方法降低了被恶意利用的可能性。然而,恶意用户输入可以利用格式字符串,并且造成信息泄露或者拒绝服务。因此,不能在格式字符串中使用非受信来源的字符串。

    2.7.1 不符合规则的代码示例

    这个不符合规则的代码示例展示了可能出现信息泄露的问题。它将信用卡的失效日期作为输入参数并将其用在格式字符串中。

    class Format { ??static Calendar c = ???new GregorianCalendar(1995, GregorianCalendar.MAY, 23); ??public static void main(String[] args) {?? ????// args[0] is the credit card expiration date ????// args[0] can contain either %1$tm, %1$te or %1$tY as malicious ????// arguments ????// First argument prints 05 (May), second prints 23 (day)? ????// and third prints 1995 (year) ????// Perform comparison with c, if it doesn’t match print the? ????// following line ????System.out.printf(args[0] +? ????" did not match! HINT: It was issued on %1$terd of some month", c); ??} }

    如果没有经过正确输入验证,攻击者通过在输入语句中包含以下参数之一:%1$tm、?%1$te或?%1$tY,就可以判断验证中所用来和输入相对比的日期。

    2.7.2 符合规则的方案

    该方案能够保证用户产生的输入会被排除在格式字符串之外。

    class Format { ??static Calendar c =? ????new GregorianCalendar(1995, GregorianCalendar.MAY, 23); ??public static void main(String[] args) {?? ????// args[0] is the credit card expiration date ????// Perform comparison with c,? ????// if it doesn't match print the following line ????System.out.printf ("%s did not match! " ????????+ " HINT: It was issued on %1$terd of some month", args[0], c); ??} }

    2.7.3 风险评估

    自动化检测 完成污染分析的静态分析工具可以用来判断是否违背该规则。

    2.7.4 相关规范

    2.7.5 参考书目


    最新回复(0)