Skip to content

Instantly share code, notes, and snippets.

@bdelacretaz
Created February 21, 2018 15:14
Show Gist options
  • Select an option

  • Save bdelacretaz/8a4949274e44225fbcdb3a5fd36c2175 to your computer and use it in GitHub Desktop.

Select an option

Save bdelacretaz/8a4949274e44225fbcdb3a5fd36c2175 to your computer and use it in GitHub Desktop.
Java: block System.exit() using a SecurityManager
<%--
JSP page that demonstrates blocking System.exit()
with a SecurityManager.
Do NOT use on production systems unless you know
EXACTLY what you are doing!
--%>
<%@page
contentType="text/plain"
pageEncoding="UTF-8"
import="
java.lang.SecurityManager,
java.lang.SecurityException,
java.security.Permission,
java.util.Date
"
%>
<%!
private static class ExitBlocker extends SecurityManager {
static void activate() {
System.setSecurityManager(new ExitBlocker());
}
/** Block System.exit */
public void checkExit(int status) {
throw new SecurityException("Blocking System.exit at " + new Date()
+ ", check stack trace to find out where it was called");
}
/** Allow everything else */
public void checkPermission(Permission perm) {
}
}
/** Use a named class so it shows in the stack trace for our demo */
private static class ExitCommand {
ExitCommand() {
System.exit(42);
}
}
%>
<%
if(request.getParameter("exit") != null) {
%>Attempting System.exit()!<%
new ExitCommand();
} else {
ExitBlocker.activate();
}
%>
All good, <%= System.getSecurityManager() %> is active!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment