Link Search Menu Expand Document

Log Injection in .NET

Prevention

.NET Core provides a logging API that does not implement built-in protection against Log Injection, so it is recommended to sanitize all user-provided data before logging it.

In the code snippet below, the User-Agent HTTP request header is sanitized by removing the newline (\n) and carriage-return (\r) characters from the string before logging it.

var ua = Request.Headers["User-Agent"].ToString();
ua = ua.Replace('\n', '').Replace('\r', '');
var message = $"The visitor uses the browser {ua}";
_logger.LogInformation(message);

References

OWASP - Log Injection CWE-117: Improper Output Neutralization for Logs SANS - Log Forging