We have a Spring project using Logback with SLF4J. I have been working on building Log Forging prevention in our project. I have used owasp.security-logging-logback to replace CRLF characters in the log.
pattern: %d ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%15.15t] %-40.40logger{39} : %crlf(%m%ex) %n
Along with this we also want to add XSS protection by escaping the HTML that is present in the messages being logged. I have not been able to find any method to introduce escape HTML in the pattern.
log4j has the %encode{} conversion pattern. Is there something similar in SLF4J? If not, can you guide me on how to build a solution for this?
I wasn't able to find an existing library or tool that could integrate with logback and encode the HTML characters. So I created a custom logback MessageConverter.
import org.apache.commons.text.StringEscapeUtils;
import ch.qos.logback.classic.pattern.MessageConverter;
public class HtmlContentEncoderMessageConverter extends MessageConverter {
@Override
public String convert(ILoggingEvent event) {
return StringEscapeUtils.escapeHtml4(super.convert(event));
}
}
I added this converter to the logback configuration in logback-spring.xml,
<conversionRule conversionWord="htmlEncode" converterClass="<path_to_class>.HtmlContentEncoderMessageConverter">
And finally used this conversionWord in the logging pattern in application.properties,
logging.pattern.console: %d ${LOG_LEVEL_PATTERN:-5%p} ... %crlf(%htmlEncode{%m%ex})
Logs without message converters,
This is a
test quote with HTML
< testTag >.
Logs with the crlf and htmlEncode message converters,
This is a_test quote with HTML_< testTag >
Other tried methods,