If an exception is Exceptions that are thrown while logging is in progress , data may not be logged can prevent successful logging unless special care is taken. Failing Failure to account for exceptions during the logging process can result in a multitude of cause security vulnerabilities, such as denial of service or vulnerabilities that allow the allowing an attacker to conceal critical security exceptions by preventing them from being logged. Consequently, programs must ensure that data logging continues to operate correctly even when exceptions are thrown during the logging process.
Noncompliant Code Example
This noncompliant code example uses statements that can throw exceptions when logging is in progress. It attempts to log a SecurityException
generated within the run()
method, however, the original log message is not logged if an exception is thrown while logging is underway.writes a critical security exception to the standard error stream:
Code Block | ||
---|---|---|
| ||
public class ExceptionLog implements Runnable { public void logMessage(String message) { FileOutputStream fo = null; FileLock lock = null; try { // This can throw an exception and prevent logging. fo = new FileOutputStream("log_file.txt", true); // Lock the file so only one thread can write a log message at a time. lock = fo.getChannel().lock(); // Output the log message. System.err.println(message); fo.write((message + "\n").getBytes()); } // If an exception is caught, the original message to log is lost catch (FileNotFoundException e){ logMessage("File Not Found Exception."); } catch(IOException eSecurityException se) { logMessage("IO Exception."); } catch (OverlappingFileLockException e) { logMessage("Cannot access file."); } finally { // Clean up by releasing the file lock and closing the file. try { if (lock != null) { lock.release(); } if (fo != null) { fo.close(); } } catch (IOException e) { // This is unexpected. throw new RuntimeException(e); } } } public void run() { try { // Some security exception occurs here. } catch(SecurityException se) { logMessage("Security Exception has occurred!"); } } public static void main(String[] args) { // Start multiple threads logging messages. for (int x = 1; x <= 20; x++) { (new Thread(new ExceptionLog())).start(); } } } |
This noncompliant code example throws an exception if there is a problem with the application's file system or if a thread attempts to write to the log file when the file is locked by another thread. An attacker can exploit these problems by:
- Gaining access to the application's file system and deleting or changing the permissions of the log file so that a runtime exception results. While this appears to be inconceivable, it is possible that an attacker has access to the physical media from which the application reads data. If the application's code depends on such functionality, an attacker may induce runtime exceptions at the appropriate moment to circumvent logging. This vulnerability can particularly manifest in multi-threaded applications.
- Exploiting the multi-threaded nature of the application by providing input to the application via normal input channels so that log messages are lost as a result of an
OverlappingFileLockException
. Because this attack vector makes use of standard input channels to perform the attack, it is much simpler to implement than the previous attack, which requires access to the application's file system.
Compliant Solution
System.err.println(se);
// Recover from exception
}
|
Writing such exceptions to the standard error stream is inadequate for logging purposes. First, the standard error stream may be exhausted or closed, preventing recording of subsequent exceptions. Second, the trust level of the standard error stream may be insufficient for recording certain security-critical exceptions or errors without leaking sensitive information. If an I/O error were to occur while writing the security exception, the catch
block would throw an IOException
and the critical security exception would be lost. Finally, an attacker may disguise the exception so that it occurs with several other innocuous exceptions.
Using Console.printf()
, System.out.print*()
, or Throwable.printStackTrace()
to output a security exception also constitutes a violation of this rule.
Compliant Solution
This compliant solution uses java.util.logging.Logger
, the default logging API provided by JDK 1.4 and later. Use of other compliant logging mechanisms, such as log4j, is also permittedThis compliant solution executes several statements that can possibly throw exceptions prior to performing any security critical operations and uses the thread and exception safe java.util.logging.Logger
class to implement logging (see EXC03-J. Use a logging API to log critical security exceptions for more information on the use of logging libraries).
Code Block | ||
---|---|---|
| ||
public class ExceptionLog implements Runnable { Logger logger; Integer id; public ExceptionLog(Integer i, Logger log) { logger = log; id = i; } public void logMessage(String message) { // Note that the Java Logger class does not throw exceptions // while logging a message. logger.log(Level.WARNING, "From " + id + ": " + message); } public void run() { try { // Some security exception occurs here. try { // ... } catch(SecurityException se) { logMessage("Security Exception has occurred!"); } } public static void main(String[] args) { try { // Set up the shared logger for use by the multiple threads Logger logger = Logger.getLogger("MyLog"); FileHandler fh = new FileHandler("log_file.txt", true); logger.addHandler(fh); logger.setLevel(Level.ALL); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); // Start multiple threads for logging messages for (int x = 1; x <= 20; x++) { (new Thread(new ExceptionLog(x, logger))).start(); } } catch (SecurityException e) { // This is unexpected. throw new RuntimeException(e); } catch (IOException e) { // This is unexpected. throw new RuntimeException(e); } } } |
As a result, exceptions do not result in failure to log a message or logging a different message than the intended one. While this is a stringent requirement, it is necessary in cases where an exception can be deliberately thrown to conceal an attacker's tracks. The logging mechanism must be robust and should be able to detect and handle all such cases. A slightly more expensive alternative is to support recursive logging.
While in this compliant solution an IOException
is still possible, there is little that can be done when writing the data to the log file if the existence of the file itself is under question. Consequently, this recommendation does not prevent a program from reopening a closed log file. If an IOException
results when doing so, it is likely that the log file was not properly protected using operating system level permissions.
Risk Assessment
(Level.SEVERE, se);
// Recover from exception
}
|
Typically, only one logger is required for the entire program.
Risk Assessment
Exceptions thrown during data logging can cause loss of data and can conceal security problemsIf an exception is thrown while data is being logged, the data may be lost or security problems may be concealed.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
ERR02-J |
Medium |
Likely |
High | P6 | L2 |
Automated Detection
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.DEBUG.LOG | Debug Warning (Java) | ||||||
SonarQube |
| S106 | Standard outputs should not be used directly to log anything |
Related Vulnerabilities
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] [Class Logger|http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html]
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 11, Exceptions|http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html] |
describes a vulnerability in the HARMONY implementation of Java. In this implementation, the FileHandler
class can receive log messages, but if one thread closes the associated file, a second thread will throw an exception when it tries to log a message.
Bibliography
...
EXC06-J. Do not allow exceptions to transmit sensitive information 13. Exceptional Behavior (EXC) EXC08-J. Try to gracefully recover from system errors