...
This noncompliant code example uses statements that can throw exceptions when logging is in process. It attempts to log a security exception generated within main
the run
method, however, it fails to do so if the log file is renamed or a crafty attacker tampers with its name or maliciously deletes itthe original log message is not logged if an exception is thrown during the logging process. An exception is thrown 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.
- Exploiting the multi-threaded nature of the application by providing input to the application via normal input channels that results in log messages being lost due to 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.
Code Block | ||
---|---|---|
| ||
import java.io.FileOutputStream; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.io.BufferedWriter; import java.io.IOException; import java.io.FileNotFoundException; public class ExceptionLog implements Runnable { public privatevoid logMessage(String logMessage; public static void main(String[] args) { ExceptionLog log message) { FileOutputStream fo = null; FileLock lock = null; try { // This can throw an exception and prevent logging. fo = new ExceptionLog(FileOutputStream("log_file.txt", true); // Lock try { the file so only one thread can write a log //some securitymessage exceptionat occursa here time. throwlock new SecurityException= fo.getChannel().lock(); }catch(SecurityException se) { // Output the log message. log.logMessage("Security Exception has occurred!"); log.writeLog(); 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."); } } public void logMessagecatch(StringIOException messagee) { logMessage = message; ("IO Exception."); } public voidcatch writeLog(OverlappingFileLockException e) { FileWriter fw=nulllogMessage("Cannot access file."); BufferedWriter bw=null; } try finally { // Clean up Thisby canreleasing throwthe anfile exceptionlock and preventclosing logging.the fw = new FileWriter("log_file.txt", true); // file. try { bw = newif BufferedWriter(fw);(lock != null) { bw.write(logMessage + "\n"); lock.release(); } catch (FileNotFoundException fnf){ if (fo != null) { logMessage("File Not Found Exception" fo.close(); } } catch (IOException iee) { // This is unexpected. throw logMessage("IO Exception"); new RuntimeException(e); } } } public void run() { // No... log message is written to the file in// theSome eventsecurity ofexception anoccurs exceptionhere. } finally { logMessage("Security Exception has occurred!"); try { // ... } public static void fw.close(); main(String[] args) { // Start multiple bw.close(); threads logging messages. for (int x=1; x<=20; x++) { }(new catchThread(IOException ioe) { /* ignores */} new ExceptionLog())).start(); } } } } |
Compliant Solution
This compliant solution executes several statements that can possibly throw exceptions prior to performing any security critical operations and allows writeLog()
to throw an exception back to the caller in the event of a problem writing to the log fileuses the thread and exception safe Java Logger class to implement logging. As a result, exceptions do not result in the silent failure to log a message or a different message than intended being logged. 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 such phenomena.
Code Block | ||
---|---|---|
| ||
public class ExceptionLog { private static String logMessage; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.io.File; public class ExceptionLog1 implements Runnable { Logger logger; Integer id; public static void main(String[] argsExceptionLog1(Integer i, Logger l) { ExceptionLoglogger log = new ExceptionLog()l; FileWriterid fw=null i; } BufferedWriter bw=null; public void logMessage(String message) { // Note that trythe { Java Logger class does not throw exceptions fw = new FileWriter("log_file.txt", true); // while logging a message. logger.log(Level.WARNING, "From " + id //+ This": can" throw an exception, but the logging of messages is + message); } public void run() { // not silently prevented... // Some security exception bw = new BufferedWriter(fw);occurs here. } logMessage("Security Exception has occurred!"); catch (IOException e) {// ... } public static void // The logging example cannot recover from failure to openmain(String[] args) { try { // Set up the logshared file. logger for use by the multiple throw new RuntimeException(e); // threads. } Logger logger = Logger.getLogger("MyLog"); //some security exception occurs here FileHandler fh = try {new FileHandler("log_file1.txt", true); loglogger.logMessage("Security Exception has occurred!"addHandler(fh); loglogger.writeLogsetLevel(bwLevel.ALL); } SimpleFormatter formatter = new catch (IOException e) { SimpleFormatter(); fh.setFormatter(formatter); // Logging of the security exception does not silently fail. // Start multiple threads logging messages. System.err.println("Logging error failed."); for (int x=1; x<=20; x++) }{ try {(new Thread(new ExceptionLog1(x, logger))).start(); bw.close();} } catch (IOExceptionSecurityException e) { System.err.println("Closing log file failed.");// This is unexpected. } } throw new RuntimeException(e); public static void logMessage(String message)} { logMessage = message;catch (IOException e) { } public void writeLog(BufferedWriter bw) throws IOException { // This is unexpected. bw.write(logMessage + "\n"throw new RuntimeException(e); System.err.println(logMessage);} } } } |
A slightly more expensive alternative is to support recursive logging.
Note that this recommendation does not prevent a program from reopening a closed log file after it realizes that important data must be captured. While in this case an IOException
is possible, there is little that can be done when writing the data to the log file if the file itself is itself under question.
Risk Assessment
...