You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

When System.exit() is invoked, all programs and threads running on the JVM terminate. This can lead to denial of service attacks, for example, a web server can stop servicing users on encountering an untimely exit.

Non-Compliant Code Example

This non-compliant example calls System.exit() aiming to forcefully shutdown the JVM and terminate the running process. There is no security manager check which is highly inadvisable.

public class InterceptExit {
  public static void main(String[] args) {
    System.out.println("Regular code block");
    System.exit(1);  //abrupt exit call
    System.out.println("This is never executed");
  }
}	

Compliant Solution

The compliant solution installs a custom security manager PasswordSecurityManager that overrides the checkExist method defined in SecurityManager class. An internal flag is used to keep track of whether the exit is permitted or not. The method setExitAllowed is used to set this flag to true. If the flag is false, a SecurityException is thrown. The System.exit call is not permitted to execute by catching the SecurityException in a try-catch block. After intercepting and performing mandatory clean-up operations, the setExitAllowed method is invoked. The program thus exits gracefully.

public class PasswordSecurityManager extends SecurityManager{
  private boolean flag; 
  
  public PasswordSecurityManager(){
    super();
    flag = false;  
  }
 
 public boolean isExitAllowed(){
   if(flag == true)
     return true;
   else
     return false;	 
 }
 
 public void checkExit(int status) {
   if(!isExitAllowed())
     throw new SecurityException();
   }
 
 public void setExitAllowed(boolean f) {
   if(f == true)
     flag = true;
   else
     flag = false; 	 
 }
}

public class InterceptExit {
  public static void main(String[] args) {
    PasswordSecurityManager secManager = new PasswordSecurityManager();
    System.setSecurityManager(secManager);
    try {
      System.out.println("Regular code block");
      System.exit(1);  //abrupt exit call
    }
    catch (Throwable x) {
      if (x instanceof SecurityException)
        System.out.println("Intercepted System.exit()");
      else
        x.printStackTrace();
    }

    System.out.println("Executing code block...");
    secManager.setExitAllowed(true);  //permit exit
    System.out.println("Finished block, exiting...");  //exit finally 
  }
}

References

Covert Java, Chapter 16 Intercepting a Call to System.exit
Java Documentation http://java.sun.com/j2se/1.4.2/docs/api/java/lang/SecurityManager.html#checkExit(int)
Custom security managers, http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed2.html

  • No labels