简体   繁体   English

在java中安全地运行javascript代码

[英]Safely running javascript code in java

I am sorry if this is an unclear title because I do not know all the terminology, so please bear with me. 如果这个标题不清楚,我很抱歉,因为我不知道所有的术语,所以请耐心等待。

So I am trying to create a controlled environment to run any JavaScript code in a Java application. 所以我试图创建一个受控环境来运行Java应用程序中的任何JavaScript代码。 Note: code is created by a user so I have to block/prevent code that is specifically trying to access/modify java variables that are not supposed to be at reach. 注意:代码是由用户创建的,因此我必须阻止/阻止专门尝试访问/修改不应该触及的java变量的代码。 (preferably by throwing a compile error for user feedback) (最好通过抛出编译错误以便用户反馈)

Edit 1: By the way I tried to use Rhino and Nashorn. 编辑1:顺便说一句,我尝试使用Rhino和Nashorn。

Here is a simple example. 这是一个简单的例子。

public class ScriptRunner{
    public Foo foo=new Foo();
    //this is not supposed to be accessed by the script
    public int money=0;

    public Object run(){
        return compiler.compile(STRING START (obtained from a file)

        function main(someObject){
            //this is not allowed
            someObject.money=10000000000000000000000;
            //or this
            var someBlacklistedJavaObject=.....
            someBlacklistedJavaObject.someFuncton();

            //but this is allowed
            someObject.foo.name="Bob";
            return someObject.foo.someFunction();
        }

        STRING END).run("main",this);
    }

}

Also I am not sure if this would be one of the possible solution but I can't use the built in java security class due to some unreachable code implementing it and not allowing to set the security object to anything else. 此外,我不确定这是否是可能的解决方案之一,但我不能使用内置的java安全类,因为实现它的一些无法访问的代码,并且不允许将安全对象设置为其他任何东西。

What comes to my mind is that an easy implementation of this would be to create wrapper Java classes in some package. 我想到的是,一个简单的实现方法是在某个包中创建包装Java类。 Than check if a java object in script does not have that path and throw an error. 然后检查脚本中的java对象是否没有该路径并抛出错误。 But the problem is that I have no idea how to do that. 但问题是我不知道该怎么做。

Here is a simple visualization of what I am trying to do. 这是我想要做的简单可视化。

Edit 2: It is desirable to maintain a low Java compatibility profile, but it's not 100% necessary. 编辑2:希望保持低Java兼容性配置文件,但这不是100%必要的。

在Nashorn中使用ClassFilter (注意:要求Java> = 1.8.0_40)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM