1. It is not a good practice to log and then throw the errors

2. Either log exceptions or throw exceptions; both should not be done together

Example: Log Exception

Example: Throw Exception

Vulnerabilities in Logging (Cont’d)

3. Exceptions should be thrown instead of returning null values are returned only in a normal use case

4. Null values are returned only in a normal use case

Logging: Vulnerable Code and Secure Code

  1. Group log messages regardless of the level
    – The vulnerable code below may look fine in a test case, but when it is displayed in the log file of an application server with 500 threads running parallel, the two messages may be spaced up with 1000 lines in-between in the log file

Vulnerable Code

Secure Code

Logging: Vulnerable Code and Secure Code (Cont’d)

2. Parameterized logging using SLF4J

Vulnerable Code

Secure Code

Logging: Vulnerable Code and Secure Code (Cont’d)

3. Log the exception stack trace

Vulnerable Code

Secure Code

Logging: Vulnerable Code and Secure Code (Cont’d)

4. Log exceptions in proper order

Vulnerable Code

Secure Code

Logging: Vulnerable Code and Secure Code (Cont’d)

5. Log exceptions when they are handled. Do not log messages before they are handled

Vulnerable Code

Logging: Vulnerable Code and Secure Code (Cont’d)

6. Log uncaught exceptions

Vulnerable Code

  • In web applications, uncaught exceptions can be sent to a JSP page and log it as follows:

Secure Code

  • The example code is as follows: