I have this line of code in my ASP.NET Core 8 Web API. When I ran SAST scan I am getting a "Log Fing" warning.
_logger.LogDebug(string.Concat(HttpStatusCode.NotFound,Convert.ToString(SanitizeLogMessage(Expression.UserInput))));
I have tried below code to sanitize user input before logging in logs. But still the scan is throwing a warning.
private static string SanitizeLogMessage(string message)
{
if (message == null)
{
return string.Empty;
}
// Replace newline characters to prevent log fing
message = message.Replace("\r", string.Empty).Replace("\n", string.Empty);
// Regex to remove other unwanted characters
message = Regex.Replace(message, @"[^\u0020-\u007E]", string.Empty);
return message;
}
I have this line of code in my ASP.NET Core 8 Web API. When I ran SAST scan I am getting a "Log Fing" warning.
_logger.LogDebug(string.Concat(HttpStatusCode.NotFound,Convert.ToString(SanitizeLogMessage(Expression.UserInput))));
I have tried below code to sanitize user input before logging in logs. But still the scan is throwing a warning.
private static string SanitizeLogMessage(string message)
{
if (message == null)
{
return string.Empty;
}
// Replace newline characters to prevent log fing
message = message.Replace("\r", string.Empty).Replace("\n", string.Empty);
// Regex to remove other unwanted characters
message = Regex.Replace(message, @"[^\u0020-\u007E]", string.Empty);
return message;
}
Share
Improve this question
edited Mar 20 at 7:59
Tiny Wang
16.5k2 gold badges18 silver badges38 bronze badges
asked Mar 20 at 6:56
CoderCoder
1
1
|
1 Answer
Reset to default 0With the proposed sanitizer it looks about ok for log injection, you can dismiss / ignore / mark as mitigated by design (terminology depends on the scanner you use :) ), if your threat model allows that.
With that you are accepting the fact that log messages may indeed contain user input, which in certain cases might be deceiving for readers. A slightly better version would be to explicitly mark user input with boundaries, for example status: '<status>', message: '<message>'
, and of course then escape / sanitize for the boundary character ('
in this example) as well. This makes it explicit which part is potential user input.
This can also be supported by structured logging (ie. json), which also makes processing / SIEM easier.
_logger.LogDebug("HTTP Status: {StatusCode}, User Input: {UserInput}", HttpStatusCode.NotFound, SanitizeLogMessage(Expression.UserInput));
. I didn't test the SAST scan, I could only say I always see such kind of log format in Microsoft document. – Tiny Wang Commented Mar 20 at 7:45