
Jesse C (Community Member) asked a question.
We are using the .NET ILogger API to handle all of our logging. We route all of our logging calls through helper methods that eventually make this call on the ILogger, which is the line that gets reported as having the CWE-117 flaw in the static scan:
logger?.Log(level, eventId, logEvent, exception, LogEvent.Formatter);
Those first 4 parameters are all variables, but I tried testing with hard-coded values for them (LogLevel.Debug, 0, null, null), and the CWE-117 flaw was still reported. It is definitely something in the LogEvent.Formatter that is causing the flaw to be reported.
That formatter gets called for every message that is logged, and its output is what ultimately gets written to the log. So I put the sanitization code inside of it. At first I thought that maybe the static scan doesn't recognize that this is always called, but if I have the formatter just always return an empty string, then the flaw is no longer reported. So it must know that the output of the formatter is what is ultimately logged.
I've simplified that formatter down to where it's just a single line:
return System.Web.HttpUtility.HtmlEncode(logEvent.Message.Replace("\r", "").Replace("\n", ""));
This HtmlEncode method is on the list of supported .NET cleansing functions, and then I'm also stripping all carriage returns and linefeeds. However, even with the formatter just being this one line, CWE-117 is still getting reported.
What do I need to change with the code to keep this flaw from being reported on the scan?
.png)
Remember that proper input validation and output sanitization are crucial for preventing CWE-117 vulnerabilities. Review your entire logging process, including input handling, formatter behavior, and log output, to ensure a robust solution.
public class CustomLogFormatter : ILogFormatter
{
public string Format(LogEvent logEvent)
{
// Sanitize log message: encode CRLF sequences
var sanitizedMessage = System.Web.HttpUtility.HtmlEncode(logEvent.Message)
.Replace("\r", "")
.Replace("\n", "");
// Construct the final log entry
return $"{logEvent.Level}: {sanitizedMessage}";
}
}