Secure Nashorn JS Execution

前端 未结 9 1314
故里飘歌
故里飘歌 2020-12-04 12:07

How can I securely execute some user supplied JS code using Java8 Nashorn?

The script extends some computations for some servlet based reports. The app has many diff

9条回答
  •  忘掉有多难
    2020-12-04 12:43

    I've researched ways of allowing users to write a simple script in a sandbox that is allowed access to some basic objects provided by my application (in the same way Google Apps Script works). My conclusion was that this is easier/better documented with Rhino than with Nashorn. You can:

    1. Define a class-shutter to avoid access to other classes: http://codeutopia.net/blog/2009/01/02/sandboxing-rhino-in-java/

    2. Limit the number of instructions to avoid endess-loops with observeInstructionCount: http://www-archive.mozilla.org/rhino/apidocs/org/mozilla/javascript/ContextFactory.html

    However be warned that with untrusted users this is not enough, because they can still (by accident or on purpose) allocate a hugh amount of memory, causing your JVM to throw an OutOfMemoryError. I have not found a safe solution to this last point yet.

提交回复
热议问题