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

Compare with Current View Page History

« Previous Version 41 Next »

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

Noncompliant Code Example

This noncompliant code example calls System.exit() 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.

public class InterceptExit {
  public static void main(String[] args) {
    // ...
    System.exit(1);  // Abrupt exit 
    System.out.println("This never executes");
  }
}	

Compliant Solution

This compliant solution installs a custom security manager PasswordSecurityManager that overrides the checkExit() method defined in the SecurityManager class. This is necessary in cases where some clean up actions must be performed prior to allowing the exit. The default checkExit() method in the SecurityManager class does not offer this facility.

class PasswordSecurityManager extends SecurityManager {
  private boolean isExitAllowedFlag; 
  
  public PasswordSecurityManager(){
    super();
    isExitAllowedFlag = false;  
  }
 
  public boolean isExitAllowed(){
    return isExitAllowedFlag;	 
  }
 
  @Override public void checkExit(int status) {
    if(!isExitAllowed()) {
      throw new SecurityException();
    }
    super.checkExit(status);
  }
 
  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.exit(1);  // Abrupt exit call
    } catch (Throwable x) {
      if (x instanceof SecurityException) {
        System.out.println("Intercepted System.exit()");
        // Log exception
      } else {
        // Forward to exception handler
      }
    }

    // ...
    secManager.setExitAllowed(true);  // Permit exit
    // System.exit() will work subsequently
    // ...
  }
}

In the overridden implementation, 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. If the flag is not set (false), a SecurityException is thrown. The System.exit() call is not allowed to execute by catching the resulting SecurityException. After intercepting and performing mandatory clean-up operations, the setExitAllowed() method is invoked. As a result, the program exits gracefully.

Noncompliant Code Example

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 noncompliant code example misses this step.

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 never executes");
  }
}

Compliant Solution

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

According to the Java API [[API 2006]] 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.

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 when accessing data and release them when done
  • They should not rely on system services as the services 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 2006]]

This compliant solution shows the standard method to install a hook.

public class Hook {
  public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        hookShutdown();
      }
    });
		
   // ...
  }

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

It is still possible for the JVM to abort 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.

Exceptions

EX1: It is permissible for a command line utility to call System.exit() or terminate prematurely, for example, when the required number of arguments are not input. [[Bloch 2008]] and [[ESA 2005]]

Risk Assessment

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC09- J

low

unlikely

medium

P2

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

[[API 2006]] method checkExit(), Class Runtime, method addShutdownHook
[[Kalinovsky 2004]] Chapter 16 Intercepting a Call to System.exit
[[Austin 2000]] Writing a Security Manager
[[Darwin 2004]] 9.5 The Finalize Method
[[Goetz 2006]] 7.4. JVM Shutdown
[[ESA 2005]] Rule 78: Restrict the use of the System.exit method
[[MITRE 2009]] CWE ID 382 "J2EE Bad Practices: Use of System.exit()"


EXC08-J. Try to gracefully recover from system errors      17. Exceptional Behavior (EXC)      EXC10-J. Do not let code throw undeclared checked exceptions

  • No labels