我正在编写一个 Java 服务器,它必须处理用户使用 Jython 提供的 Python 代码。显然,我不能在没有破解者访问他/她不应该访问的文件和系统命令的风险的情况下执行它。几个小时以来,我一直在寻找某种方法来限制特定线程的文件权限,而我得到的最接近的方法是限制整个应用程序的文件权限。是否有一个类实现了类似这样的事情,或者有某种方法可以做到这一点?
最佳答案
您可以尝试使用 java.lang.SecurityManager .另见 this question关于使用安全管理器为每个线程设置不同的安全设置。
您可以像这样设置安全管理器和安全策略:
jython -Djava.security.manager=securitymanager -Djava.security.policy=policyfile
其中 securitymanager 是要使用的安全管理器,policyfile 包含策略规范,例如 here .如果您使用策略文件作为安全策略的来源,下面是一个示例:
grant {
permission java.security.AllPermission;
}
Jython 需要一些权限才能启动,包括:
grant {
permission java.io.FilePermission "${user.home}${/}-", "read, write";
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.RuntimePermission "getProtectionDomain";
};
(假设您的缓存目录位于当前用户的 HOME 目录下)。这将做一些接近您需要的事情,允许对当前用户 HOME 下的文件进行读写访问,并禁止访问文件系统的所有其他部分。这是结果(第一个 open() 指的是当前用户 HOME 目录下的一个文件,因为这是当前工作目录):
>>> f1=open('test.txt', 'r')
>>> f2=open('/tmp/test.txt', 'r')
Traceback (innermost last):
File "<console>", line 1, in ?
java.security.AccessControlException: access denied (java.io.FilePermission /tmp/test.txt read)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:342)
at java.security.AccessController.checkPermission(AccessController.java:553)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.lang.SecurityManager.checkRead(SecurityManager.java:888)
at java.io.File.exists(File.java:748)
at org.python.core.PyFile._setup(Unknown Source)
at org.python.core.PyFile.file_init(Unknown Source)
at org.python.core.PyFile$1.new_impl(Unknown Source)
at org.python.core.PyType.invoke_new_(Unknown Source)
at org.python.core.PyType.type___call__(Unknown Source)
at org.python.core.PyType.__call__(Unknown Source)
at org.python.core.PyObject.__call__(Unknown Source)
at org.python.pycode._pyx2.f$0(<console>:1)
at org.python.pycode._pyx2.call_function(<console>)
at org.python.core.PyTableCode.call(Unknown Source)
at org.python.core.PyCode.call(Unknown Source)
at org.python.core.Py.runCode(Unknown Source)
at org.python.core.Py.exec(Unknown Source)
at org.python.util.PythonInterpreter.exec(Unknown Source)
at org.python.util.InteractiveInterpreter.runcode(Unknown Source)
at org.python.util.InteractiveInterpreter.runsource(Unknown Source)
at org.python.util.InteractiveInterpreter.runsource(Unknown Source)
at org.python.util.InteractiveConsole.push(Unknown Source)
at org.python.util.InteractiveConsole.interact(Unknown Source)
at org.python.util.jython.main(Unknown Source)
java.security.AccessControlException: java.security.AccessControlException: access denied (java.io.FilePermission /tmp/test.txt read)
>>>
关于python - 线程的 Java 文件权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8075014/