Using Java SecurityManager to grant/deny access to system functions
In Java it is possible to restrict access to specific functions like reading/writing files and system properties, thread control, networking, object serialization and much more for the running application. Such restrictions may be crucial(重要的;决定性的;定局的;决断的) for guaranteeing security of the system and are implemented for example in Applets, Java Web Start or Java EE Servers.
Class witch takes care of all that security is SecurityManager whose currently registered instance can be accessed through System.getSecurityManager() method. Normally for stand-alone Java applications there is no SecurityManager registered, which means a call to getSecurityManager() would return null. In such case, all the system functions are allowed.
We will show here a simple example of how security in Java works. Take a look at the class below:
import java.io.FileInputStream;
import java.io.FileNotFoundException; public class SecurityTest {
public static void main(String[] args)
throws FileNotFoundException {
//Is there a SecurityManger registered?
System.out.println("SecurityManager: " +
System.getSecurityManager()); //Checking if we can open a file for reading
FileInputStream fis = new FileInputStream("test.txt");
System.out.println("File successfully opened"); //Checking if we can access a vm property
System.out.println(System.getProperty("file.encoding"));
}
}
The class first gets the SecurityManager’s instance and prints it out. Note that this step has no influence on two proceeding steps. It’s purpose is just to show clearly if SecurityManager is there or not. Next step is opening a file called ‘test.txt’ for reading. For this step you should create a file ‘text.txt’ (it may be empty) and put it in the application’s directory. Last step reads a system property “file.encoding” which on most systems should be set by default to “UTF-8″.
Now run the program! If you got any exceptions, check if you copied everything well and if you created the file ‘text.txt’ in the program’s directory. If everything went right, you should get the following output:
SecurityManager: null
File successfully opened
UTF-8
First note that the instance of SecurityManager we got from System.getSecurityManager() is null. There is no SecurityManager so everything is allowed and we were able to successfully open a file and read the system property.
Now let’s put security to play! We will need a file defining current security policy. It is a file that tells the SecurityManager what it should allow and what it should deny. Below is an example of such a file:
grant {
};
As you see, there is nothing written inside the ‘grant’ block. It means that there are no permissions specified and (almost) all system functions will be denied. Put that in a file called ‘test.policy’ and place it in the application’s directory (along with file ‘text.txt’). You can read much more about structure of .policy files here.
With the policy file in place, we should tell the JVM to create a SecurityManager and use file ‘test.policy’ for the security policy. We do it by specifying two system properties while running the SecurityTest program: -Djava.security.manager and -Djava.security.policy=test.policy. You can specify them for example in Eclipse in ‘Run Configurations…->Arguments->VM arguments:’ dialog. Alternatively you can specify them straight from the command line (supposing you exported your code to SecurityTest.jar and put it in the same directory where ‘test.policy’ is:
java -Djava.security.manager -Djava.security.policy=test.policy
-jar SecurityTest.jar
Using these parameters run the program! If everything goes well, this time SecurityManager activates and you should see something like this:
SecurityManager: java.lang.SecurityManager@1a46e30
Exception in thread "main"
java.security.AccessControlException: access denied
(java.io.FilePermission test.txt read)
...
First line indicates that SecurityManager is registered. The exception you see on the next line is proper behavior. InputFileReader’s constructor internally checks if there is a SecurityManager installed. If so, it calls it to check if reading the specified file is allowed according to the current security policy. The security policy (which we specified in ‘test.policy’ file) contains no permissions for reading a file, so SecurityManager throws AccessControlException.
What to do to allow reading files? We have to put a specific rule to ‘test.policy’. Rules for accessing files are implemented by FilePermission class. You can specify which file the rule applies to and what kind of access is being granted. Below you see what must be written in ‘test.policy’ file:
grant {
permission java.io.FilePermission "test.txt", "read";
};
This rule grants reading on file ‘text.txt’ (you could also use “<<ALL FILES>>” to grant the reading of all files). With this permission in place, let’s run the program once again:
SecurityManager: java.lang.SecurityManager@1a46e30
File successfully opened
Exception in thread "main"
java.security.AccessControlException:
access denied (java.util.PropertyPermission file.encoding read)
As you see this time file was successfully opened, but next exception appeared while trying to read the property “file.encoding”. Permission allowing programs to access system properties is called PropertyPermission. We define it following way:
grant {
permission java.io.FilePermission "test.txt", "read";
permission java.util.PropertyPermission "file.encoding", "read";
};
It will allow reading of property “file.encoding”. This time when we run the program, everything will be allowed by the SecurityManager and we should get following output:
SecurityManager: java.lang.SecurityManager@1a46e30
File successfully opened
UTF-8
Writing .policy files for a big application can be tedious, especially if you don’t know yet the correct syntax. Fortunately there is help in form of ‘policytool’, which is a small program distributed along with JDK. You can read something about it here.
This short introduction shows just a tiny bit of SecurityManager’s features. You can do a lot more with it, like for example defining your own permissions and using them in your classes. You can also set principals for every permission and specify files containing digital signatures for them, so that a user running your program must be in possession of a key file to access specific functions. You can read about this functionality for example on this Sun’s tutorial. There is also a bunch of useful links concering security on this site.
Using Java SecurityManager to grant/deny access to system functions的更多相关文章
- java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
java.lang.IllegalAccessError: tried to access field org.slf4j.impl.Static.. java.lang.IllegalAccessE ...
- java.lang.IllegalAccessError: tried to access method com.google.common.base.Stopwatch.<init>()V from 解决
在用spark的yarn-cluster模式跑fpgrowth进行频繁项集挖掘的时候,报如下错误: ERROR yarn.ApplicationMaster: User class threw exc ...
- Atitit. 。Jna技术与 解决 java.lang.Error: Invalid memory access
Atitit. .Jna技术与 解决 java.lang.Error: Invalid memory access 1. 原因与解决1 2. jNA (这个ms sun 的)1 3. Code1 4. ...
- cannot access the system temp folder
cannot access the system temp folder. please, make sure your application have full control rights on ...
- ACCESS的System.Data.OleDb.OleDbException: INSERT INTO 语句的语法错误
一直用的是SQL 数据库,突然改用Access了,使用起来就是没有SQL 顺畅,老是出来些意想不到的错误.今天用Access做的网站程序进行添加数据,调试了一下午,总是异常…… 提示ACCESS的Sy ...
- JAVA之旅(二十三)——System,RunTime,Date,Calendar,Math的数学运算
JAVA之旅(二十三)--System,RunTime,Date,Calendar,Math的数学运算 map实在是太难写了,整理得我都晕都转向了,以后看来需要开一个专题来讲这个了,现在我们来时来学习 ...
- java 标准输出与标准错误 out与 err 区别 用法 联系 java中的out与err区别 System.out和System.err的区别 System.out.println和System.err.println的区别 Java重定向System.out和System.err
本文关键词: java 标准输出与标准错误 out与 err 区别 用法 联系 java中的out与err区别 System.out和System.err的区别 System.out.pri ...
- 开源网络准入系统(open source Network Access Control system)
开源网络准入系统(open source Network Access Control system) http://blog.csdn.net/achejq/article/details/5108 ...
- java SecurityManager
---- 众所周知,Java语言具有完善的安全框架,从编程语言,编译器.解释程序到Java虚拟机,都能确保Java系统不被无效的代码或敌对的编译器暗中破坏,基本上,它们保证了Java代码按预定的规则运 ...
随机推荐
- js stringObject的indexOf方法
我所写的这个是基本知识的基本知识,为什么我还是要写呢,所谓说好记性不如烂比头,作为一名前端开发人员,太多相似的代码见的又太多,但是又不常见,所以很容易忘记,那我把indexOf原理讲清楚 indexO ...
- (转载)在Delphi中利用MSDASC来配置数据库链接
在Delphi中利用MSDASC来配置数据库链接 在运行期进行数据库的连接是一个问题,自己写一个窗体配置吧,数据库不一样,所用的参数也不一样,还有那讨厌的连接字符串,有时真不知该写什么好.那天无意中发 ...
- osg(OpenSceneGraph)学习笔记1:智能指针osg::ref_ptr<>
OSG的智能指针,osg::ref_ptr<> osg::Referenced类管理引用计数内存块,osg::ref_ptr需要使用以它为基类的其它类作为模板参数. osg::ref_pt ...
- 在 IIS MIME 类型中添加 md 扩展名
最近在了解 Knowledge Base (知识库)的内容,对两个平台比较感兴趣,一个是 Raneto,一个是 MDwiki,两者都是使用md文件作为内容存储. 需要注意的是,使用IIS部署网站后,需 ...
- ∑–△型模数转换器(ADC)简介
∑–△型模数转换器(ADC) 1.概述 近年来,随着超大规模集成电路制造水平的提高,Σ-Δ型模数转换器正以其分辨率高.线性度好.成本低等特点得到越来越广泛的应用.Σ-Δ型模数转换器方案早在20世纪60 ...
- Codeforces Round #321 div2
好像前几场的题解忘记写了, Orz 状态太差, 平均出两题 都不好意思写了 , 连掉4场, 都要哭晕了. 很水的一场, 写完A B C就去睡了 D题其实不难, E题研究Ing(已用一种奇怪的姿势 ...
- 【C#】动态加载dll程序集
原文:http://www.cnblogs.com/bomo/archive/2013/03/01/2938165.html 很多时候我们需要用到引用其他程序集,有些程序集是.Net生成的,可以支持反 ...
- C语言中的volatile
转自C语言的那些小秘密之volatile volatile的重要性对于搞嵌入式的程序员来说是不言而喻的,对于volatile的了解程度常常被不少公司在招聘嵌入式编程人员面试的时候作为衡量一个应聘者是否 ...
- python邮件收发SAMPLE
#!/usr/bin/env python # -*- encoding: utf-8 -*- import os, socket from time import localtime, strfti ...
- CAS单点登录配置[4]:客户端配置
本节介绍一下客户端如何配置,客户端配置没有服务端那么复杂... 客户端Tomcat配置 1 首先确认证书文件已经拷贝到Tomcat的目录下,我们新建两个客户端的web应用,分别命名为Client1,C ...