General Idea
The general idea of Java Security Manager is to restrict what an application can do. This is important as it provides a separate environment for programs to do whatever they do without affecting the host system or other applications.
[wp_ad_camp_1]
For instance, we only allow application MyApp to read and write files in some directory.
Here are some useful links:
- https://docs.oracle.com/javase/tutorial/essential/environment/security.html
- http://docs.oracle.com/javase/7/docs/technotes/guides/security/smPortGuide.html
- https://tomcat.apache.org/tomcat-8.5-doc/security-manager-howto.html
Through the Security Manager, the applications are controlled with security policies ( .policy files).
Consider this source code file.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 | package com.turreta.securitymanager; import java.io.File; public class SecurityManagerDemo { public static void main(String[] args) { File file = new File("c:/where-ever-file.txt"); System.out.println("Does file exist? " + file.exists()); } } |
Running Java without Security Manager
Run your application from the command line prompt as follows.
1 | java com.turreta.securityManager.SecurityManagerDemo |
Outputs
1 | Does file exist? false |
Running Java with Security Manager
Now run it with -D option.
1 | java -Djava.security.manager com.turreta.securityManager.SecurityManagerDemo |
Outputs
1 2 3 4 5 6 7 | Exception in thread "main" java.security.AccessControlException: access denied ("java.io.FilePermission" "c:\where-ever-file.txt" "read") at java.security.AccessControlContext.checkPermission(AccessControlContext.java:472) at java.security.AccessController.checkPermission(AccessController.java:884) at java.lang.SecurityManager.checkPermission(SecurityManager.java:549) at java.lang.SecurityManager.checkRead(SecurityManager.java:888) at java.io.File.exists(File.java:814) at com.turreta.securitymanager.SecurityManagerDemo.main(SecurityManagerDemo.java:9) |
[wp_ad_camp_3]
Since we did not specify a .policy file, Java uses a default .policy file.