Versions Compared

Key

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

...

This example demonstrates code that accepts a file name as an input argument on which operations are to be performed. An attacker can gain insights on the underlying filesystem file system structure by repeatedly passing different paths to fictitious files. When a file is not found, the FileInputStream constructor throws a FileNotFoundException. Other risks such as revelation of the user's home directory and thus the user name also manifest themselves.

Code Block
bgColor#FFcccc

import java.io.FileInputStream;
import java.io.FileNotFoundException;

class exception {
	  public static void main(String[] args) throws FileNotFoundException
	 {
		    FileInputStream dis = new FileInputStream("c:\\" + args[1]);
		
	  }
}

Compliant Solution

Information leakage can result from both the exception message text and the type of exception. With FileNotFoundException, the message reveals the filesystem file system layout while the type conveys the absence of the file. The same exception must be caught while taking special care to sanitize the message before propagating it to the caller. In cases where the exception type itself can reveal too much, consider throwing a different exception (with a different message) altogether.

Code Block
bgColor#ccccff

import java.io.FileInputStream;
import java.io.FileNotFoundException;

class exception {
	  public static void main(String[] args) 
	{
		try
		{
		    try {
      FileInputStream dis = new FileInputStream("c:\\" + args[1]);
		    }
		    catch(FileNotFoundException fnf) { 
      System.out.println("Error: Operation could not be performed"); 
    } //sanitized message
	  }
}

References

Secure coding in Java http://java.sun.com/security/seccodeguide.html