Versions Compared

Key

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

Invocation of System.exit() terminates the Java Virtual Machine (JVM), consequently terminating all running programs and threads running thereon. This can result in denial-of-service (DoS) attacks. For example, a call to System.exit() that is embedded in Java Server Pages (JSP) code can cause a web server to terminate, preventing further service for users. Programs must prevent both inadvertent and malicious calls to System.exit(). Additionally, programs should perform necessary clean-up cleanup actions when forcibly terminated (via ctrl + c or the for example, by using the Windows Task Manager, POSIX kill command, for exampleor other mechanisms).

Noncompliant Code Example

This noncompliant code example uses System.exit() to forcefully shutdown shut down the JVM and terminate the running process. The program lacks a security manager; consequently, it lacks the capability to check whether the caller is permitted to invoke System.exit().

Code Block
bgColor#FFcccc

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 override is required to enable invocation of cleanup code before allowing the exit. The default checkExit() method in the SecurityManager class lacks this facility.

Code Block
bgColor#ccccff

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

This implementation uses an internal flag to track whether the exit is permitted. The method setExitAllowed() sets this flag. The checkExit() method throws a SecurityException when the flag is unset (e.g.that is, false). ConsequentlyBecause this flag is not initially set, normal exception processing bypasses the initial call to System.exit(). The program catches the SecurityException and performs mandatory clean-up cleanup operations, including logging the exception. The setExitAllowed() method is invoked only after clean-up is complete. Consequently, the program exits gracefully.

Noncompliant Code Example

When a user forcefully exits a program by pressing the ctrl + c key or by using the kill command, the JVM terminates abruptly. Although this event cannot be captured, the program should nevertheless perform any mandatory clean-up operations before exiting. This noncompliant code example fails to do so.

...

bgColor#FFcccc

...

System.

...

exit

...

(

...

Compliant Solution

Use the addShutdownHook() method of java.lang.Runtime to assist with performing clean-up operations in the event of abrupt termination. The JVM starts the shutdown hook thread when abrupt termination is initiated; the shutdown hook runs concurrently with other JVM threads. Wiki MarkupAccording to the Java API \[[API 2006|AA. Bibliography#API 06]\] Class {{Runtime}}, method {{addShutdownHook}}

...

is

...

enabled

...

only after cleanup is complete.

Exceptions

ERR09-J-EX0: It is permissible for a command-line utility to call System.exit(), for example, when the required number of arguments are not input [Bloch 2008], [ESA 2005

Some precautions must be taken because the JVM is in a sensitive state during shutdown. Shutdown hook threads should:

  • be light-weight and simple
  • be thread safe
  • hold locks when accessing data and release those locks when done
  • Wiki Markup
    lack reliance 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|AA. Bibliography#Goetz 06]\].

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

Code Block
bgColor#ccccff

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

The JVM can abort for external reasons, such as an external SIGKILL signal (UNIX) or the TerminateProcess call (Microsoft Windows), or memory corruption caused by native methods. Shutdown hooks may fail to execute as expected in such cases, because the JVM cannot guarantee that they will be executed as intended.

Exceptions

Wiki Markup*EXC09-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|AA. Bibliography#Bloch 08]\] and \[[ESA 2005|AA. Bibliography#ESA 05]\].

Risk Assessment

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

Guideline

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXC09

ERR09-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Related Vulnerabilities

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

Bibliography

Wiki Markup
\[[API 2006|AA. Bibliography#API 06]\] [method checkExit()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/SecurityManager.html#checkExit(int)], Class Runtime, method addShutdownHook
\[[Austin 2000|AA. Bibliography#Austin 00]\] [Writing a Security Manager|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed2.html]
\[[Darwin 2004|AA. Bibliography#Darwin 04]\] 9.5 The Finalize Method
\[[ESA 2005|AA. Bibliography#ESA 05]\] Rule 78: Restrict the use of the System.exit method 
\[[Goetz 2006|AA. Bibliography#Goetz 06]\] 7.4. JVM Shutdown 
\[[Kalinovsky 2004|AA. Bibliography#Kalinovsky 04]\] Chapter 16 Intercepting a Call to System.exit
\[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE ID 382|http://cwe.mitre.org/data/definitions/382.html] "J2EE Bad Practices: Use of System.exit()"

Automated Detection

Tool
Version
Checker
Description
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.DEBUG.CALL

Debug Call (Java)

Coverity7.5

DC.CODING_STYLE
FB.DM_EXIT

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.ERR09.JVM
CERT.ERR09.EXIT
Do not stop the JVM in a web component
Do not call methods which terminates Java Virtual Machine
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1147Exit methods should not be called

Related Guidelines

MITRE CWE

CWE-382, J2EE Bad Practices: Use of System.exit()

Android Implementation Details

On Android, System.exit() should not be used because it will terminate the virtual machine abruptly, ignoring the activity life cycle, which may prevent proper garbage collection.

Bibliography

[API 2014]

Method checkExit()
Class Runtime: Method addShutdownHook

[Austin 2000]

"Writing a Security Manager"

[Darwin 2004]

Section 9.5, "The Finalize Method"

[ESA 2005]

Rule 78, Restrict the use of the System.exit method

[Goetz 2006]

Section 7.4, "JVM Shutdown"

[Kalinovsky 2004]

Chapter 16, "Intercepting a Call to System.exit"


...

Image Added Image Added Image AddedERR07-J. Prevent exceptions while logging data      06. Exceptional Behavior (EXC)      EXC10-J. Do not let code throw undeclared checked exceptions