如何修复 Veracode CWE 117(日志输出中和不当)

How to fix Veracode CWE 117 (Improper Output Neutralization for Logs)

有一个 Spring 全局 @ExceptionHandler(Exception.class) 方法可以像这样记录异常:

@ExceptionHandler(Exception.class)
void handleException(Exception ex) {
    logger.error("Simple error message", ex);
...

Veracode 扫描表明此日志记录有 Improper Output Neutralization for Logs 并建议使用 ESAPI 记录器。有没有办法在不将记录器更改为 ESAPI 的情况下修复此漏洞?这是我遇到此问题的代码中唯一的地方,我试图弄清楚如何以最少的更改修复它。也许ESAPI有一些我没有注意到的方法?

P.S。当前的记录器是 Log4j 而不是 slf4j

更新: 最后我使用了 ESAPI 记录器。我以为它不会使用我的默认日志记录服务,但我错了,它只是使用了我的 slf4j 记录器接口和适当的配置。

private static final Logger logger = ESAPI.getLogger(MyClass.class);
...
logger.error(null, "Simple error message", ex);

ESAPI 具有 log4j 记录器和记录器工厂的扩展。它可以配置在 ESAPI.properties 中使用什么。例如:

ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory

Is there any way how to fix this vulnerability without changing logger to ESAPI?

简而言之,是的。

TLDR:

首先了解错误的严重性。主要关注的是伪造日志声明。假设您有这样的代码:

log.error( transactionId + " for user " + username + " was unsuccessful."

如果任何一个变量都在用户控制之下,他们可以通过使用 \r\n for user foobar was successful\rn 这样的输入来注入错误的日志语句,从而允许他们伪造日志并掩盖他们的踪迹。 (好吧,在这种人为的情况下,只是让我们更难看到发生了什么。)

第二种攻击方法更像是棋步。许多日志都是 HTML 格式以便在另一个程序中查看,在这个例子中,我们假设日志是 HTML 文件以便在浏览器中查看。现在我们注入 <script src=”https://evilsite.com/hook.js” type=”text/javascript”></script> 并且您将使用最有可能作为服务器管理员执行的利用框架来连接浏览器......因为它怀疑 CEO 是否会阅读日志。现在真正的破解可以开始了。

防御:

一个简单的防御措施是确保所有带有用户输入的日志语句使用明显的东西转义字符'\n'和'\r',比如'֎'或者你可以做ESAPI所做的并用下划线转义.只要它一致就真的没关系,只要记住不要在日志中使用会使您感到困惑的字符集。类似于 userInput.replaceAll("\r", "֎").replaceAll("\n", "֎");

我还发现确保详细指定日志格式很有用...这意味着您要确保对日志语句的外观和构建格式有严格的标准,以便捕获恶意用户更容易。所有程序员都要服从党,遵守格式!

为了抵御 HTML 场景,我会使用 [OWASP 编码器项目][1]

至于为什么建议使用 ESAPI 的实现,它是一个久经考验的库,但简而言之,这就是我们所做的。见代码:

/**
 * Log the message after optionally encoding any special characters that might be dangerous when viewed
 * by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
 * injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
 * specific session ID, and the current date/time.
 *
 * It will only log the message if the current logging level is enabled, otherwise it will
 * discard the message.
 *
 * @param level defines the set of recognized logging levels (TRACE, INFO, DEBUG, WARNING, ERROR, FATAL)
 * @param type the type of the event (SECURITY SUCCESS, SECURITY FAILURE, EVENT SUCCESS, EVENT FAILURE)
 * @param message the message to be logged
 * @param throwable the {@code Throwable} from which to generate an exception stack trace.
 */
private void log(Level level, EventType type, String message, Throwable throwable) {

    // Check to see if we need to log.
    if (!isEnabledFor(level)) {
        return;
    }

    // ensure there's something to log
    if (message == null) {
        message = "";
    }

    // ensure no CRLF injection into logs for forging records
    String clean = message.replace('\n', '_').replace('\r', '_');
    if (ESAPI.securityConfiguration().getLogEncodingRequired()) {
        clean = ESAPI.encoder().encodeForHTML(message);
        if (!message.equals(clean)) {
            clean += " (Encoded)";
        }
    }

    // log server, port, app name, module name -- server:80/app/module
    StringBuilder appInfo = new StringBuilder();
    if (ESAPI.currentRequest() != null && logServerIP) {
        appInfo.append(ESAPI.currentRequest().getLocalAddr()).append(":").append(ESAPI.currentRequest().getLocalPort());
    }
    if (logAppName) {
        appInfo.append("/").append(applicationName);
    }
    appInfo.append("/").append(getName());

    //get the type text if it exists
    String typeInfo = "";
    if (type != null) {
        typeInfo += type + " ";
    }

    // log the message
    // Fix for https://code.google.com/p/owasp-esapi-java/issues/detail?id=268
    // need to pass callerFQCN so the log is not generated as if it were always generated from this wrapper class
    log(Log4JLogger.class.getName(), level, "[" + typeInfo + getUserInfo() + " -> " + appInfo + "] " + clean, throwable);
}

参见第 398-453 行。这就是 ESAPI 提供的所有转义。我建议也复制单元测试。

[免责声明]:我是 ESAPI 的项目联合负责人。

[1]: https://www.owasp.org/index.php/OWASP_Java_Encoder_Project 并确保您的输入在进入日志语句时正确编码——每一位都与您将输入发回给用户时一样多。

虽然我来晚了一点,但我认为这会帮助那些不想使用 ESAPI 库并且只面临异常处理程序问题的人 class

使用 apache 公共库

import org.apache.commons.lang3.exception.ExceptionUtils;
LOG.error(ExceptionUtils.getStackTrace(ex));

我是 Veracode 的新手,面临 CWE-117。我知道当您的记录器语句有可能通过传入的恶意请求参数值受到攻击时,Veracode 会引发此错误。因此我们需要从记录器语句中使用的变量中删除 /r 和 /n (CRLF)。

大多数新手都会想知道应该使用什么方法从logger语句中传递的变量中删除CRLF。有时 replaceAll() 也不会工作,因为它不是 Veracode 批准的方法。因此,这里是 Veracode 批准的 link 方法来处理 CWE 问题。 https://help.veracode.com/reader/4EKhlLSMHm5jC8P8j3XccQ/IiF_rOE79ANbwnZwreSPGA

在我的例子中,我使用了上面link中提到的org.springframework.web.util.HtmlUtils.htmlEscape,它解决了问题。

private static final Logger LOG = LoggerFactory.getLogger(MemberController.class);
//problematic logger statement 
LOG.info("brand {}, country {}",brand,country);
//Correct logger statement
LOG.info("brand {}, country {}",org.springframework.web.util.HtmlUtils.htmlEscape(brand),org.springframework.web.util.HtmlUtils.htmlEscape(country));

如果您正在使用 Logback,请在您的 logback 配置模式中使用 replace 函数

原始模式

<pattern>%d %level %logger : %msg%n</pattern>

替换

<pattern>%d %level %logger : %replace(%msg){'[\r\n]', '_'} %n</pattern>

如果你也想去除 <script> 标签

<pattern>%d %-5level %logger : %replace(%msg){'[\r\n]|&lt;script', '_'} %n</pattern>

这样您就不需要修改单独的日志语句。

为了避免 Veracode CWE 117 漏洞,我使用了自定义记录器 class,它使用 HtmlUtils.htmlEscape() 函数来缓解漏洞。 Veracode 针对此问题的推荐解决方案是使用 ESAPI 记录器,但如果您不想向项目添加额外的依赖项,这应该可以正常工作。 https://github.com/divyashree11/VeracodeFixesJava/blob/master/spring-annotation-logs-demo/src/main/java/com/spring/demo/util/CustomLogger.java

我已经尝试使用 org.springframework.web.util.HtmlUtilsHtmlEscape,但它无法解析[=24] =] 通过 veracode 的漏洞。尝试以下解决方案。

对于 Java 使用:

StringEscapeUtils.escapeJava(str)

Html/JSP 使用:

StringEscapeUtils.escapeHtml(str)

请使用以下包:

import org.appache.commons.lang.StringEscapeUtils;