This tutorial shows how to use pro-grade policy with deny rules.
We will start a Jetty web server and use pro-grade policy file with deny rules to restrict access to the application. The access from the localhost (i.e. loopback) will not be possible. Access for remote clients comming through other network interfaces should stay working.
Download jetty and pro-grade to a test folder:
Verify the jetty works by running:
java -jar jetty-runner-9.3.14.v20161028.jar .
If you open http://localhost:8080/ in your brower, you should see directory listing of the current directory.
Create a text file named deny-localhost.policy with content:
// Grant all to everyone
grant {
permission java.security.AllPermission;
};
// Deny access to from localhost
deny {
permission java.net.SocketPermission "", "accept";
}
First rule allows everything to anyone. The second rule removes the SocketPermission (for localhost target and accept action) from the granted set.
If you want to use pro-grade security manager, you can't use -jar parameter as you did in previous step because you need to use classpath parameter which doesn't work together with -jar. You could use an uber-jar, but let's keep it simple and do it in a standard way.
The steps to do are:
META-INF/MANIFEST.MF) on the command line - without -jar we don't have it automaticallyNow the command looks like:
java -Djava.security.manager=net.sourceforge.prograde.sm.ProGradeJSM \
-Djava.security.policy==deny-localhost.policy \
-cp jetty-runner-9.3.14.v20161028.jar:pro-grade-1.1.1.jar \
org.eclipse.jetty.runner.Runner .
If you open/reload http://localhost:8080/ URL again, you should not be able to connect to the jetty server. Exception should appear in the jetty console window.
Use your public address instead of loopback (localhost) and you should be able to connect to jetty without problem. (e.g. if your public IP is 192.168.1.1, then try to open http://192.168.1.1:8080/)
If you see an exception similar to following one in the jetty output, don't worry. It's just a Jasper (JSP compiler) issue with handling custom security policies.
java.lang.SecurityException: attempt to add a Permission to a readonly Permissions object
at java.security.Permissions.add(Permissions.java:126)
at java.security.Policy$UnsupportedEmptyCollection.add(Policy.java:827)
at org.apache.jasper.compiler.JspRuntimeContext.initSecurity(JspRuntimeContext.java:477)
at org.apache.jasper.compiler.JspRuntimeContext.<init>(JspRuntimeContext.java:115)
at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:118)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:640)
...