Versions Compared

Key

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

...

Noncompliant Code Example

asdf
This noncompliant code example calls uses System.exit() to forcefully shutdown the JVM and terminate the running process. No security manager checks have been installed The program lacks a security manager; consequently, it lacks the capability to check whether the program has sufficient permissions to exitcaller 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");
  }
}	

...

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 override is required to enable invocation of cleanup code before allowing the exit. The default checkExit() method in the SecurityManager class does not offer 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
    // ...
  }
}

In the overridden This implementation , uses an internal flag is used to keep track of whether the exit is permitted or not. The method setExitAllowed() is used to set sets this flag. If The checkExit method throws a SecurityException when the flag is not set (unset (e.g., false), a SecurityException is thrown. The . Consequently, normal exception processing bypasses the initial call to System.exit() call is not allowed to execute by catching the resulting SecurityException. After intercepting and performing . The program catches the SecurityException and performs mandatory clean-up operations, including logging the exception. The setExitAllowed() method is invoked . As a resultonly after clean-up is complete. Consequently, the program exits gracefully.

Noncompliant Code Example

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

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

Compliant Solution

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

...

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 Some precautions must be taken because the JVM is in a sensitive state during this stage, some precautions must be taken:shutdown. Shutdown hook threads should:

  • Hook threads should be light-weight and simple
  • They should be thread safe
  • They should hold locks when accessing data and release them those locks when done
  • Wiki Markup
    They should not relylack 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]\].

...

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

It is still possible for the JVM to abort because of external issuesThe 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. In Shutdown hooks may fail to execute as expected in such cases, it is not guaranteed that the hooks will execute as expectedbecause 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]\].

...

Guideline

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 guideline on the CERT website.

...

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
\[[Kalinovsky 2004|AA. Bibliography#Kalinovsky 04]\] Chapter 16 Intercepting a Call to System.exit
\[[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 
\[[ESAKalinovsky 20052004|AA. Bibliography#ESABibliography#Kalinovsky 0504]\] RuleChapter 78:16 RestrictIntercepting thea useCall ofto the System.exit method 
\[[MITRE 2009|AA. Bibliography#MITRE 09]\] [CWE ID 382|http://cwe.mitre.org/data/definitions/382.html] "J2EE Bad Practices: Use of System.exit()"

...