When Invocation of System.exit()
is invoked, all terminates the Java Virtual Machine (JVM), consequently terminating all running 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 encountering an untimely exit
(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 cleanup actions when forcibly terminated (for example, by using the Windows Task Manager, POSIX kill
command, or other mechanisms).
Noncompliant Code Example
This noncompliant code example calls uses System.exit()
aiming to forcefully shutdown shut down the JVM and terminate the running process. There is no The program lacks a security manager check which is highly inadvisable; consequently, it lacks the capability to check whether the caller is permitted to invoke System.exit()
.
Code Block | ||
---|---|---|
| ||
public class InterceptExit { public static void main(String[] args) { // System..out.println("Regular code block"); System.exit(1); //abrupt Abrupt exit call System.out.println("This is never executedexecutes"); } } |
Compliant Solution
The This compliant solution installs a custom security manager PasswordSecurityManager
that overrides the checkExist
checkExit()
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 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 a result exits gracefullyThis 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 | ||
---|---|---|
| ||
class PasswordSecurityManager extends SecurityManager { private boolean flagisExitAllowedFlag; public PasswordSecurityManager(){ super(); flagisExitAllowedFlag = false; } public boolean isExitAllowed(){ if(flag == true) return trueisExitAllowedFlag; } else return false; @Override } public void checkExit(int status) { if (!isExitAllowed()) { throw new SecurityException(); } public void setExitAllowed(boolean f) {super.checkExit(status); if(f == true)} public void setExitAllowed(boolean flag = true;f) { else isExitAllowedFlag flag = falsef; } } 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 Abrupt exit call } catch (Throwable x) { if (x instanceof SecurityException) { System.out.println("Intercepted System.exit()"); else // Log exception x.printStackTrace(); } else } { System.out.println("Executing code block..."); // secManager.setExitAllowed(true); //permit exit System.out.println("Finished block, exiting..."); //exit finally } } |
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 is missing in this non compliant code example.
Code Block | ||
---|---|---|
| ||
public class InterceptExit { public static void main(String[] args) {Forward to exception handler } } // ... SystemsecManager.out.println("Regular code block"setExitAllowed(true); //abrupt Permit exit such as ctrl + c key pressed// System.exit() will work subsequently 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 termination scenario. When the shutdown is initiated, the hook thread starts to run concurrently with other JVM threads.
Wiki Markup |
---|
According to \[[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 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 not rely on system services as they themselves may be shutting down
This compliant solution shows the method to install a hook.
Code Block | ||
---|---|---|
| ||
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 for the JVM to abort due to 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.
Risk Assessment
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 (that is, false). Because this flag is not initially set, normal exception processing bypasses the initial call to System.exit()
. The program catches the SecurityException
and performs mandatory cleanup operations, including logging the exception. The System.exit()
method 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].
Risk Assessment
Allowing unauthorized Allowing inadvertent calls to System.exit()
may lead to denial - of - service attacks.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
ERR09-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.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#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 04|AA. Java References#Kalinovsky 04]\] Chapter 16 Intercepting a Call to System.exit
\[[Austin 00|AA. Java References#Austin 00]\] [Writing a Security Manager|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed2.html]
\[[Darwin 04|AA. Java References#Darwin 04]\] 9.5 The Finalize Method |
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.DEBUG.CALL | Debug Call (Java) | ||||||
Coverity | 7.5 | DC.CODING_STYLE | Implemented | ||||||
Parasoft Jtest |
| 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 |
| S1147 | Exit methods should not be called |
Related Guidelines
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 |
Section 9.5, "The Finalize Method" | |
[ESA 2005] | Rule 78, Restrict the use of the |
Section 7.4, "JVM Shutdown" | |
Chapter 16, "Intercepting a Call to |
...
EXC03-J. Try to recover gracefully from system errors 10. Exceptional Behavior (EXC) EXC30-J. Do not exit abruptly from a finally block