Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant code example errs by using uses statements that can throw exceptions when logging is in process. It attempts to log a security exception generated within main, however, it will end up logging no messages if a careless administrator renamed fails to do so if the log file is renamed 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 not being logged properlytampers with its name or maliciously deletes it.

Code Block
bgColor#FFcccc
public class ExceptionLog {

    private String logMessage;

    public static void main(String[] args) {
        ExceptionLog log = new ExceptionLog();
    try {
      //some security exception occurs here
      throw new SecurityException();	
    }catch(SecurityException se) {
      log.logMessage("Security Exception has occurred!");
        log.writeLog(); 
    } 
  }
  
  
  public void logMessage(String message) {
        logMessage = message;
    }
    
    public void writeLog() {
    FileWriter fw=null;
    try {BufferedWriter bw=null;
    try  {
      // This can throw an exception and prevent logging.
            FileWriter fw = new FileWriter("log_file.txt", true);
            BufferedWriter br bw = new BufferedWriter(fw);
            brbw.write(logMessage + "\n");
    } catch       br.close();
  (FileNotFoundException fnf){ 
      } catch (FileNotFoundException fnf){ logMessage("File Not Found Exception!"); }
      }  catch(IOException ie) { 
        logMessage("IO Exception!"); }          
        System.err.println(logMessage);    
        // No log message is written to the file in the event of an exception.
    } finally {
     	try {
      	  fw.close();
          bw.close();
        } catch(IOException ioe) { /* ignores */}	
    }
  }
}

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 file. 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.

...