How to resolve CWE 117 Issue

7.7k views Asked by At

I have a CWE 117 issue reported in my Product.

CWE 117 issue is that the software does not properly sanitize or incorrectly sanitizes output that is written to logs and one possible solution i got was to add the following while logging.

String clean = args[1].replace('\n', '_').replace('\r', '_');

log.info(clean);

My question is whether there is any central place in log4j where a single change can solve this issue?

1

There are 1 answers

11
aioobe On BEST ANSWER

It is the Layout that is responsible for serializing the log message, and it is here the newline-transformation code belongs.

I suggest creating your own (trivial) subclass of PatternLayout that does the transformation. This has also been discussed on the Log4j mailing list here. Here's a slightly modified version of the solution suggested in that thread:

import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

public class NewLinePatternLayout extends PatternLayout {

    public NewLinePatternLayout() { }

    public NewLinePatternLayout(String pattern) {
        super(pattern);
    }

    public boolean ignoresThrowable() {
        return false;
    }

    public String format(LoggingEvent event) {
        String original = super.format(event);

        // Here your code comes into play
        String clean = original.replace('\n', '_').replace('\r', '_');

        StringBuilder sb = new StringBuilder(clean);

        String[] s = event.getThrowableStrRep();
        if (s != null) {
            for (int i = 0; i < s.length; i++) {
                sb.append(s[i]);
                sb.append('_');
            }
        }
        return sb.toString();
    }
}

Related question (with a potentially useful answer):