Before going further lets talk about Log Forging or JVM Log Forging.
Log Forging
According to OWASP , writing invalidated logs can allow attackers to forge log or inject malicious content in log file. Log forging is when attackers tries to add/modify the log content by exploring the security loopholes of application.
Lets understand the log forging by an example.
private void printLog(String amount) {
logger.info("Amount credited in account Rs. {}" + amount);
}
above code will print the logs like:
Amount credited in account Rs. 500
Now suppose attacker provide the input \n\n Amount debited in account Rs.500
Amount credited in account Rs. 500
Amount debited in account Rs.500
So, attacker forged the logs by making a fake or forge entry in log.
Avoid directly embedding user input in log files when possible. Sanitize untrusted data used to construct log entries by using safe logging mechanism such as OWASP ESAPI logger, which will automatically remove unexpected carriage returns. So, to prevent this, we use use ESAPI Logger mechanism.
Here is the dependency of ESAPI:
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>2.2.2.0</version>
</dependency>
We can encode the logs using ESAPI‘s Encoder method and interface:
public String encode(String message) { message = message.replace( '\n' , '_' ).replace( '\r' , '_' ) .replace( '\t' , '_' ); message = ESAPI.encoder().encodeForHTML( message ); return message; }