CodeByAkram: Log4j
Showing posts with label Log4j. Show all posts
Showing posts with label Log4j. Show all posts

How to use / implement OWASP ESAPI Logger in Java

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;
}
How to use / implement OWASP ESAPI Logger in Java





How to create multiple log file using same log4j property file?

You can create multiple logs file by using same log4j properties file or you can send logs to multiple files by using same log4j file.

How to create multiple log file using same log4j property file?
Add this below to your log4j properties file.

log4j.rootLogger=TRACE, stdout
log4j.appender.dataLogs=org.apache.log4j.FileAppender
log4j.appender.dataLogs.File=logs/logFile1.log
log4j.appender.dataLogs.layout=org.apache.log4j.PatternLayout
log4j.appender.dataLogs.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/logFile2.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.dataLogger=TRACE, dataLogs
log4j.additivity.debugLogger=false
log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false
Then configure the loggers in the code accordingly as shown below:

static final Logger debugLog = Logger.getLogger("dataLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");