...
Noncompliant Code Example
This noncompliant code example errs by defining statements that can throw exceptions while when logging is in process. It aims to log a security exception generated within main
, however, ends up logging the FileNotFoundException
since because a careless administrator renamed the log file or a crafty attacker caused the logging mechanism to fail through network tampering. While this code is slightly convoluted, it is easy to fall prey to similar mistakes that can result in an important security exception from not being logged properly.
...
This compliant solution declares all statements that can possibly throw exceptions prior to performing any security critical operations. As a result, other exceptions do not interfere with the exceptions that need to be 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. A slightly more expensive alternative is to support recursive logging.
Code Block | ||
---|---|---|
| ||
import java.util.logging.Logger; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.FileNotFoundException; import java.io.IOException; public class ExceptionLog { private static String logMessage; private static Logger theLogger = Logger.getLogger("ExceptionLog.class.getName()"); public static void main(String[] args) { ExceptionLog log = new ExceptionLog(); FileWriter fw=null; BufferedWriter bw=null; try { fw = new FileWriter("log_file.txt"); //this can throw an exception, but security exception is still logged bw = new BufferedWriter(fw); }catch (FileNotFoundException fne){ logMessage("File Not Found Exception!"); } catch (IOException e) { logMessage("IO Exception!"); } //some security exception occurs here log.logMessage("Security Exception has occurred!"); log.writeLog(bw); } public static void logMessage(String message) { logMessage = message; } public void writeLog(BufferedWriter bw) { theLogger.info("Starting to log"); // log to file 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 an IOException
is possible, there is little one that can do be done when writing the data to the log file is itself under question.
...