如何在 Java 中为用户代码创建类白名单?
我正在创建一个运行下载的 Java 代码的应用程序,并且我希望能够准确指定代码可以访问哪些内置 Java 类。我想这涉及使用 ClassLoader 和 SecurityManager,但我在谷歌上找到的内容并没有帮助。
I am creating an application that runs downloaded Java code, and I would like to be able to specify exactly which built-in Java classes the code can access. I imagine this involves using a ClassLoader and SecurityManager, but what I've found on google has not been helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为在您的情况下,您应该创建自定义类加载器或使用配置为从指定 URL 加载类的 UrlClassLoader。请注意,文件系统中的文件可以被解释为 URL,所以不用担心。
例如,如果您有 2 个 jar 文件 foo.jar 和 bar.jar。 foo.jar 是允许的,bar.jar 在您的应用程序部分受到限制。只需将第一个 jar 添加到类加载器的路径中即可。第二个将是不可见的。
如果您希望在访问禁止的类时抛出 SecurityException,则必须实现自己的类加载器。它可能是 2 个 URL 类加载器的组合:一个带有 foo.jar,另一个带有类路径中的 bar.jar。第二个类加载器应该重写方法 loadClass 并在每次成功加载类时抛出安全异常。尽管我没有看到这个解决方案的严重好处。
I think that in your case you should create your custom class loader or use UrlClassLoader configured to load classes from specified URLs. Note that file in file system can be interpreted as URL to, so do not worry.
If for example you have 2 jar files foo.jar and bar.jar. foo.jar is permitted, bar.jar is restricted for the part of your application. Just add to the class loader's path the first jar only. The second will be invisible.
If you wish to throw SecurityException when forbidden classes are accessed yo have to implement your own class loader. It could be a composite of 2 URL class loaders: one with foo.jar, other with bar.jar in a classpath. The second class loader should override method loadClass and throw security exception every time the class is successfully loaded. Although I do not see serious benefits of this solution.