简体   繁体   中英

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. 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. (preferably by throwing a compile error for user feedback)

Edit 1: By the way I tried to use Rhino and 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.

What comes to my mind is that an easy implementation of this would be to create wrapper Java classes in some package. Than check if a java object in script does not have that path and throw an error. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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