我使用 JVM 安全管理器自定义策略发现了某种意外行为。
仓库:https://github.com/pedrorijo91/jvm-sec-manager
在分支主控中,进入 /code
文件夹:
- 自定义策略文件授予文件
../allow/allow.txt
的文件读取权限 - 没有文件权限
../deny/deny.txt
- HelloWorld.java 中的代码尝试读取这两个文件
- 有一个
run.sh
脚本来运行命令
现在一切都按预期工作:允许的文件读取,但另一个抛出安全异常:java.security.AccessControlException:访问被拒绝(“java.io.FilePermission”“../deny/deny.txt” ““读”)
但是如果我将两个文件(../allow/allow.txt
和 ../deny/deny.txt
)移动到 code
文件夹(更改自定义策略和 java 代码以使用这些文件),我也不异常(exception)。 (分支“意外”)
当前目录是特殊情况还是发生了其他情况?
最佳答案
简要说明
此行为在许多地方都有记录:
后两个重申了第一个的结束语,其中指出:
Code can always read a file from the same directory it's in (or a subdirectory of that directory); it does not need explicit permission to do so.
换句话说,如果
(HelloWorld.class.getProtectionDomain().getCodeSource().implies(
new CodeSource(new URL("file:" + codeDir),
(Certificate[]) null)) == true)
然后 HelloWorld
将默认被授予对指定目录及其子目录的读取权限。特别是对于 code
目录本身,这应该具有一定的直观意义,否则该类甚至无法访问其内部的 public
访问类非常封装。
完整的故事
这基本上取决于ClassLoader
:如果是statically mapped 向其所属的 ProtectionDomain
分配任何权限
该类(适用于 java.net.URLClassLoader 和 sun.misc.Launcher$AppClassLoader(特定于 OpenJDK 的默认系统类加载器))这些权限将无论政策
是否有效,始终遵循域。
解决方法
对于与授权相关的任何事情,典型的“快速而肮脏”的解决方法是扩展 SecurityManager
并覆盖令您烦恼的方法;即在本例中为 checkRead
方法组。
另一方面,为了获得一个不降低 AccessController 和 friend 的灵活性的更彻底的解决方案,您必须编写一个至少覆盖 URLClassLoader 的类加载器#getPermissions(CodeSource)
和/或将加载类的域的 CodeSource
限制到文件级别(默认情况下由 URLClassLoader
分配的域的代码源和AppClassLoader
暗示(递归地).class 文件的类路径条目(JAR 或目录)。为了进一步粒度,您的加载程序还可以分配您自己的域子类的实例和/或封装您自己的子类的代码源的域,分别覆盖 ProtectionDomain#implies(Permission)
和/或 CodeSource#implies(CodeSource)
;例如,前者可以支持“否定许可”语义,而后者可以将代码源含义基于任意逻辑,可能与物理代码位置解耦(例如“信任级别”)。
根据评论进行澄清
为了证明在不同的类加载器下这些权限实际上很重要,请考虑以下示例:有两个类,A
和 B
; A
具有 main
方法,该方法仅调用 B
上的方法。此外,应用程序是使用不同的系统类加载器启动的,该加载器 a) 在每个类的基础上(而不是默认情况下在每个类路径条目的基础上)将域分配给它加载的类,而不 b) 分配对这些域的任何权限。
加载器:
package com.example.q45897574;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
public class RestrictiveClassLoader extends URLClassLoader {
private static final Pattern COMMON_SYSTEM_RESOURCE_NAMES = Pattern
.compile("(((net\\.)?java)|(java(x)?)|(sun|oracle))\\.[a-zA-Z0-9\\.\\-_\\$\\.]+");
private static final String OWN_CLASS_NAME = RestrictiveClassLoader.class.getName();
private static final URL[] EMPTY_URL_ARRAY = new URL[0], CLASSPATH_ENTRY_URLS;
private static final PermissionCollection NO_PERMS = new Permissions();
static {
String[] classpathEntries = AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty("java.class.path");
}
}).split(File.pathSeparator);
Set<URL> classpathEntryUrls = new LinkedHashSet<>(classpathEntries.length, 1);
for (String classpathEntry : classpathEntries) {
try {
URL classpathEntryUrl;
if (classpathEntry.endsWith(".jar")) {
classpathEntryUrl = new URL("file:jar:".concat(classpathEntry));
}
else {
if (!classpathEntry.endsWith("/")) {
classpathEntry = classpathEntry.concat("/");
}
classpathEntryUrl = new URL("file:".concat(classpathEntry));
}
classpathEntryUrls.add(classpathEntryUrl);
}
catch (MalformedURLException mue) {
}
}
CLASSPATH_ENTRY_URLS = classpathEntryUrls.toArray(EMPTY_URL_ARRAY);
}
private static byte[] readClassData(URL classResource) throws IOException {
try (InputStream in = new BufferedInputStream(classResource.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
while (in.available() > 0) {
out.write(in.read());
}
return out.toByteArray();
}
}
public RestrictiveClassLoader(ClassLoader parent) {
super(EMPTY_URL_ARRAY, parent);
for (URL classpathEntryUrl : CLASSPATH_ENTRY_URLS) {
addURL(classpathEntryUrl);
}
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name == null) {
throw new ClassNotFoundException("< null >", new NullPointerException("name argument must not be null."));
}
if (OWN_CLASS_NAME.equals(name)) {
return RestrictiveClassLoader.class;
}
if (COMMON_SYSTEM_RESOURCE_NAMES.matcher(name).matches()) {
return getParent().loadClass(name);
}
Class<?> ret = findLoadedClass(name);
if (ret != null) {
return ret;
}
return findClass(name);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String modifiedClassName = name.replace(".", "/").concat(".class");
URL classResource = findResource(modifiedClassName);
if (classResource == null) {
throw new ClassNotFoundException(name);
}
byte[] classData;
try {
classData = readClassData(classResource);
}
catch (IOException ioe) {
throw new ClassNotFoundException(name, ioe);
}
return defineClass(name, classData, 0, classData.length, constructClassDomain(classResource));
}
@Override
protected PermissionCollection getPermissions(CodeSource codesource) {
return NO_PERMS;
}
private ProtectionDomain constructClassDomain(URL codeSourceLocation) {
CodeSource cs = new CodeSource(codeSourceLocation, (Certificate[]) null);
return new ProtectionDomain(cs, getPermissions(cs), this, null);
}
}
A
:
package com.example.q45897574;
public class A {
public static void main(String... args) {
/*
* Note:
* > Can't we set the security manager via launch argument?
* No, it has to be set here, or bootstrapping will fail.
* > Why?
* Because our class loader's domain is unprivileged.
* > Can't it be privileged?
* Yes, but then everything under the same classpath entry becomes
* privileged too, because our loader's domain's code source--which
* _its own_ loader creates, thus escaping our control--implies _the
* entire_ classpath entry. There are various workarounds, which
* however fall outside of this example's scope.
*/
System.setSecurityManager(new SecurityManager());
B.b();
}
}
B
:
package com.example.q45897574;
public class B {
public static void b() {
System.out.println("success!");
}
}
非特权测试:
确保在政策层面没有授予任何内容;然后运行(假设基于 Linux 的操作系统 - 适当修改类路径):
java -cp "/home/your_user/classpath/" \
-Djava.system.class.loader=com.example.q45897574.RestrictiveClassLoader \
-Djava.security.debug=access=failure com.example.q45897574.A
您应该收到 NoClassDefFoundError
以及 com.example.q45897574.A
失败的 FilePermission
。
特权测试:
现在向 A
授予必要的权限(再次确保更正 codeBase(代码源 URL)和权限目标名称):
grant codeBase "file:/home/your_user/classpath/com/example/q45897574/A.class" {
permission java.io.FilePermission "/home/your_user/classpath/com/example/q45897574/B.class", "read";
};
...然后重新运行。这次执行应该成功完成。
关于java - JVM 安全管理器文件权限 - 自定义策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45897574/