Versions Compared

Key

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

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

Noncompliant Code Example

This noncompliant code example calls System.exit() aiming to forcefully shutdown the JVM and terminate the running process. No security manager checks have been installed to check whether the program has sufficient permissions to exit.

...

The compliant solution installs a custom security manager PasswordSecurityManager that overrides the checkExist() method defined in the 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 allowed 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 as As a result, the program exits gracefully.

Code Block
bgColor#ccccff
class PasswordSecurityManager extends SecurityManager{
  private boolean isExitAllowedFlag; 
  
  public PasswordSecurityManager(){
    super();
    isExitAllowedFlag = false;  
  }
 
 public boolean isExitAllowed(){
   return isExitAllowedFlag;	 
 }
 
 public void checkExit() {
   if(!isExitAllowed())
     throw new SecurityException();
   }
 
 public void setExitAllowed(boolean f) {
   isExitAllowedFlag = f; 	 
 }
}

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 
  }
}

...

If a user forcefully exits a program by pressing the ctrl + c key or uses the kill command, the JVM terminates abruptly. Although this event cannot be captured, the code should be able to react to it. This is missing in this non compliant noncompliant code example misses this step.

Code Block
bgColor#FFcccc
public class InterceptExit {
  public static void main(String[] args) {
    System.out.println("Regular code block");
    //abrupt exit such as ctrl + c key pressed
    System.out.println("This is never executed");
  }
}

Compliant Solution

The addShutdownHook() method of java.lang.Runtime helps to perform clean-up operations in the unusual abrupt termination scenario. When the shutdown is initiated, the hook thread starts to run concurrently with other JVM threads.

Wiki Markup
According to the Java API \[[API 06|AA. Java References#API 06]\] Class {{Runtime}}, method {{addShutdownHook}}:

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine. Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook.

Since As the JVM is in a sensitive state during this stage, some precautions must be taken:

  • Hook threads should be light-weight and simple
  • They should be thread safe
  • They should hold locks while when accessing data
  • Wiki Markup
    They should not rely on system services as they themselves may be shutting down (for example, the logger may shutdown from another hook). Instead of one service it may be better to run a series of shutdown tasks from one thread by using a single shutdown hook. \[[Goetz 06|AA. Java References#Goetz 06]\]

...

Code Block
bgColor#ccccff
public class Hook {
  public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        hookShutdown();
      }
    });
		
   //other code...
  }

  public static void hookShutdown() {
    // Log shutdown and close all resources
  }
}

It is still possibly possible for the JVM to abort due to because of external issues, such as an external SIGKILL signal (UNIX) or the TerminateProcess call (Microsoft Windows), or memory corruption caused by native methods. In such cases, it is not guaranteed that the hooks will execute as expected.

...

Allowing inadvertent calls to System.exit() may lead to denial - of - service attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC04- J

low

unlikely

medium

P2

L3

...