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: [email protected]
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: [email protected]
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: [email protected]
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.

时间: 2024-10-13 00:02:04

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.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory 使用hbm2java时,使用hibernate-distribution- 3.3.1

java.lang.IllegalAccessError: tried to access method org.apache.commons.codec.digest.DigestUtils.getDigest(Ljava/lang/String;)Ljava/security/MessageDigest; from class com.xyb.mis.pay.jingdong.util.Sig

严重: Servlet.service() for servlet [springmvc] in context with path [/xyb-mis-web] threw exception [Handler processing failed; nested exception is java.lang.IllegalAccessError: tried to access method org.apache.commons.codec.digest.DigestUtils.getDige

JAVA之旅(二十三)——System,RunTime,Date,Calendar,Math的数学运算

JAVA之旅(二十三)--System,RunTime,Date,Calendar,Math的数学运算 map实在是太难写了,整理得我都晕都转向了,以后看来需要开一个专题来讲这个了,现在我们来时来学习一些新的小东西吧 一.System 翻译过来系统的意思,系统类,里面的方法都是静态的,可以直接调用 我们来演示一下吧,先从获取系统信息开始: package com.lgl.hellojava; import java.util.Properties; public class HelloJJAVA

java中的new BufferedReader(new InputStreamReader(System.in))

流 JAVA /IO 基本小结 通过一行常见的代码讨论:new BufferedReader(new InputStreamReader(System.in)) java的IO是基于流(stream)概念的,什么是流呢,作为初学者, 我是这样理解的,在各个应用之间传送的是BITS,这些BIT可已被认为是流体,可以就认为是水流,那么用来在各个水源之间转移水的工具应该选择什么呢?一般情况下,水管是可以的,所以数据我将数据源比作水源,将流对象比作水管 这样就有了对流的第一步认识,它再也不神秘了. 对于

ACCESS的System.Data.OleDb.OleDbException: INSERT INTO 语句的语法错误

一直用的是SQL 数据库,突然改用Access了,使用起来就是没有SQL 顺畅,老是出来些意想不到的错误.今天用Access做的网站程序进行添加数据,调试了一下午,总是异常…… 提示ACCESS的System.Data.OleDb.OleDbException: INSERT INTO 语句的语法错误,刚才才在网络上找到了解决的方法,觉得有点不可思议~~在网络上看了看,也是学习ADO.net的人常犯的错误.所以写此日志,以提醒自己 /// <summary> /// 增加一条数据 /// &l

java SecurityManager

---- 众所周知,Java语言具有完善的安全框架,从编程语言,编译器.解释程序到Java虚拟机,都能确保Java系统不被无效的代码或敌对的编译器暗中破坏,基本上,它们保证了Java代码按预定的规则运作.但是,当我们需要逾越这些限制时,例如,读写文件,监听和读写Socket,退出Java系统等,就必须使用数字签名或安全策略文件(*.Policy). ---- 在企业内部网中,本文提出了使用安全策略文件来设置java程序权限的一种简单的方法.由于企业内部网中各台计算机的位置.用途和安全性明确,更适

Java Web项目中连接Access数据库的配置方法

本文是对前几天的"JDBC连接Access数据库的几种方式"这篇的升级.因为在做一些小项目的时候遇到的问题,因此才决定写这篇博客的.昨天已经将博客公布了.可是后来经过一些验证有点问题,所以今天改了一下又一次的公布了 老师决定期末考试採用access数据库实现增删改查.我觉得如今的我已经没有问题了.可是曾经都是在JSP页面中连接access数据库,不管是下面的那种方式都进行了连接的练习,可是如今我想让我的项目中的訪问access数据库的java代码,封装到DAO中,在DAO中连接数据库,

java 标准输出与标准错误 out与 err 区别 用法 联系 java中的out与err区别 System.out和System.err的区别 System.out.println和System.err.println的区别 Java重定向System.out和System.err

操作系统一般都有三个标准文件描述符:标准输入,标准输出,标准出错 这是操作系统的一种抽象表达 不同的语言需要有不同的具体表达方式,当然也不过是另一种包装抽象 比如c++的  cin cout cerr Java中则是的System.in,System.out,System.err 示例 输出结果: ---------------- ---------------- 可以看得出来: 运行多次  err的打印信息位置是不固定的 看下JDK文档:   /** * The "standard"

关于System.getProperty(&quot;java.io.tmpdir&quot;);的输出,及System.getProperty();参数(转自扑球小猫)

1,首先来介绍下System.getProperty("java.io.tmpdir")输出因为这个输出有点特殊. 理论介绍:他是获取系统临时目录.可以是window的temp,linux的临时目录等. 实际:实际上他获取的有时候并不是我们想要获取的.比如一个web程序:如果你不用tomcat,直接一个java类main方法,然后直接输出System.getProperty("java.io.tmpdir")那么结果是你当前系统下的临时文件目录如