Bug:Security - Potential CRLF Injection for logs

描述:When data from an untrusted source is put into a logger and not neutralized correctly, an attacker could forge log entries or include malicious content. Inserted false entries could be used to skew statistics, distract the administrator or even to implicate another party in the commission of a malicious act. If the log file is processed automatically, the attacker can render the file unusable by corrupting the format of the file or injecting unexpected characters. An attacker may also inject code or other commands into the log file and take advantage of a vulnerability in the log processing utility (e.g. command injection or XSS).

出现这个问题的大致意思就是日志没有进行对CRLF注入进行校验,存在传参时发生空格注入,具体字段是/r/n。项目中是直接使用@SLF4J这个注解进行日志打印的,这其中并没有进行防注入校验。

解决方法有两个:

方法一:针对每一条参数加上

log.info("User " + val.replaceAll("[\r\n]","") + " (" + userAgent.replaceAll("[\r\n]","") + ") was not authenticated");

查了一下资料,发现java有一个封装好的方法escapeJson,可以在每次日志打印的时候进行校验:

log.info("XXXX信息在途写入{}", StringEscapeUtils.escapeJson(logId));

上述方法过于繁琐,不如直接新建一个日志工具类,然后重写打印方法,在方法中加入注入校验,调用的时候直接调用工具类中的方法即可。

方法二:继续查找资料,发现可以在依赖中直接过滤掉/r/n,达到防止CRLF注入的效果,具体方法如下:

<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="org.apache.skywalking.apm.toolkit.log.logback.v1.x.TraceIdPatternLogbackLayout">
                <pattern>%date %-5level [%tid] [%thread] [%logger{60}] [%line] - %replace(%msg){'[\r\n]', ''}%n
                </pattern>
            </layout>
            <charset>UTF-8</charset>
</encoder>

更多推荐

Sonar问题(三)Security - Potential CRLF Injection for logs