Class NashornSandboxImpl
- java.lang.Object
-
- delight.nashornsandbox.internal.NashornSandboxImpl
-
- All Implemented Interfaces:
NashornSandbox
public class NashornSandboxImpl extends java.lang.Object implements NashornSandbox
Nashorn sandbox implementation.Created on 2015-08-07
- Version:
- $Id$
-
-
Field Summary
Fields Modifier and Type Field Description protected booleanallowExitFunctionsprotected booleanallowGlobalsObjectsprotected booleanallowLoadFunctionsprotected booleanallowNoBracesprotected booleanallowPrintFunctionsprotected booleanallowReadFunctionsprotected javax.script.Bindingscachedprotected java.util.concurrent.atomic.AtomicBooleanengineAssertedprotected JsEvaluatorevaluatorprotected java.util.concurrent.ExecutorServiceexecutorprotected javax.script.InvocablelazyInvocable(package private) static org.slf4j.LoggerLOGprotected longmaxCPUTimeMaximum CPU time in milliseconds.protected longmaxMemoryMaximum memory of executor thread used.protected intmaxPreparedStatementsThe size of the LRU cache of prepared statements.protected SandboxClassFiltersandboxClassFilterprotected JsSanitizersanitizerprotected javax.script.ScriptEnginescriptEngineprotected SecuredJsCachesuppliedCache
-
Constructor Summary
Constructors Constructor Description NashornSandboxImpl()NashornSandboxImpl(java.lang.String... params)NashornSandboxImpl(javax.script.ScriptEngine engine, java.lang.String... params)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voidallow(java.lang.Class<?> clazz)Add a new class to the list of allowed classes.voidallowExitFunctions(boolean v)Allow Nashorn quit and exit functions.voidallowGlobalsObjects(boolean v)Allow Nashorn globals object $ARG, $ENV, $EXEC, $OPTIONS, $OUT, $ERR and $EXIT.voidallowLoadFunctions(boolean v)Allow Nashorn load and loadWithNewGlobal functions.voidallowNoBraces(boolean v)Force, to check if all blocks are enclosed with curly braces "{}".voidallowPrintFunctions(boolean v)Allow Nashorn print and echo functions.voidallowReadFunctions(boolean v)Allow Nashorn readLine and readFully functions.private voidassertScriptEngine()private voidcheckExecutorPresence()javax.script.CompiledScriptcompile(java.lang.String js)Compile the JavaScript stringjavax.script.BindingscreateBindings()Create new bindings used to replace the state of the current script enginejavax.script.ScriptEnginecreateNashornScriptEngineFactory(java.lang.String... params)private SandboxClassFiltercreateSandboxClassFilter()voiddisallow(java.lang.Class<?> clazz)Remove a class from the list of allowed classes.voiddisallowAllClasses()Remove all classes from the list of allowed classes.private booleanengineBindingUnchanged()java.lang.Objecteval(java.lang.String js)Evaluates the JavaScript string.java.lang.Objecteval(java.lang.String js, javax.script.Bindings bindings)Evaluates the JavaScript string.java.lang.Objecteval(java.lang.String js, javax.script.ScriptContext scriptContext)Evaluates the JavaScript string for a given script contextjava.lang.Objecteval(java.lang.String js, javax.script.ScriptContext scriptContext, javax.script.Bindings bindings)Evaluates the JavaScript string for a given script contextjava.lang.Objecteval(javax.script.CompiledScript compiledScript)Run a pre-compiled JavaScriptjava.lang.Objecteval(javax.script.CompiledScript compiledScript, javax.script.Bindings bindings)java.lang.Objecteval(javax.script.CompiledScript compiledScript, javax.script.ScriptContext scriptContext)java.lang.Objecteval(javax.script.CompiledScript compiledScript, javax.script.ScriptContext scriptContext, javax.script.Bindings bindings)protected java.lang.ObjectexecuteSandboxedOperation(ScriptEngineOperation op)java.lang.Objectget(java.lang.String variableName)Obtains the value of the specified JavaScript variable.private JsEvaluatorgetEvaluator(ScriptEngineOperation op)java.util.concurrent.ExecutorServicegetExecutor()Gets the current executor service.private javax.script.InvocablegetLazySandboxedInvocable()javax.script.InvocablegetSandboxedInvocable()Returns anInvocableinstance, so that method invocations are also sandboxed.protected JsSanitizergetSanitizer()voidinject(java.lang.String variableName, java.lang.Object object)Will add a global variable available to all scripts executed with this sandbox.booleanisAllowed(java.lang.Class<?> clazz)Check if a class is in the list of allowed classes.private voidproduceSecureBindings()protected voidresetEngineBindings()protected voidsanitizeBindings(javax.script.Bindings bindings)protected javax.script.BindingssecureBindings(javax.script.Bindings bindings)voidsetExecutor(java.util.concurrent.ExecutorService executor)Specifies the executor service which is used to run scripts when a CPU time limit is specified.voidsetMaxCPUTime(long limit)Sets the maximum CPU time in milliseconds allowed for script execution.voidsetMaxMemory(long limit)Sets the maximum memory in Bytes which JS executor thread can allocate.voidsetMaxPreparedStatements(int max)The size of prepared statements LRU cache.voidsetScriptCache(SecuredJsCache cache)Overwrites the cache for pre-processed javascript.voidsetWriter(java.io.Writer writer)Sets the writer, when want to have output from writer function called in JS script
-
-
-
Field Detail
-
LOG
static final org.slf4j.Logger LOG
-
sandboxClassFilter
protected final SandboxClassFilter sandboxClassFilter
-
scriptEngine
protected final javax.script.ScriptEngine scriptEngine
-
maxCPUTime
protected long maxCPUTime
Maximum CPU time in milliseconds.
-
maxMemory
protected long maxMemory
Maximum memory of executor thread used.
-
executor
protected java.util.concurrent.ExecutorService executor
-
allowPrintFunctions
protected boolean allowPrintFunctions
-
allowReadFunctions
protected boolean allowReadFunctions
-
allowLoadFunctions
protected boolean allowLoadFunctions
-
allowExitFunctions
protected boolean allowExitFunctions
-
allowGlobalsObjects
protected boolean allowGlobalsObjects
-
allowNoBraces
protected boolean allowNoBraces
-
evaluator
protected JsEvaluator evaluator
-
sanitizer
protected JsSanitizer sanitizer
-
engineAsserted
protected java.util.concurrent.atomic.AtomicBoolean engineAsserted
-
lazyInvocable
protected javax.script.Invocable lazyInvocable
-
maxPreparedStatements
protected int maxPreparedStatements
The size of the LRU cache of prepared statements.
-
suppliedCache
protected SecuredJsCache suppliedCache
-
cached
protected javax.script.Bindings cached
-
-
Method Detail
-
createSandboxClassFilter
private SandboxClassFilter createSandboxClassFilter()
-
createNashornScriptEngineFactory
public javax.script.ScriptEngine createNashornScriptEngineFactory(java.lang.String... params)
-
assertScriptEngine
private void assertScriptEngine()
-
engineBindingUnchanged
private boolean engineBindingUnchanged()
-
produceSecureBindings
private void produceSecureBindings()
-
resetEngineBindings
protected void resetEngineBindings()
-
sanitizeBindings
protected void sanitizeBindings(javax.script.Bindings bindings)
-
eval
public java.lang.Object eval(java.lang.String js) throws ScriptCPUAbuseException, javax.script.ScriptExceptionDescription copied from interface:NashornSandboxEvaluates the JavaScript string.- Specified by:
evalin interfaceNashornSandbox- Parameters:
js- the JavaScript script to be evaluated- Throws:
ScriptCPUAbuseException- when execution time exceeded (when greater than 0 is setjavax.script.ScriptException- when script syntax error occurs- See Also:
NashornSandbox.setMaxCPUTime(long)
-
eval
public java.lang.Object eval(java.lang.String js, javax.script.Bindings bindings) throws ScriptCPUAbuseException, javax.script.ScriptExceptionDescription copied from interface:NashornSandboxEvaluates the JavaScript string.- Specified by:
evalin interfaceNashornSandbox- Parameters:
js- the JavaScript script to be evaluatedbindings- the Bindings to use for evaluation- Throws:
ScriptCPUAbuseException- when execution time exceeded (when greater than 0 is setjavax.script.ScriptException- when script syntax error occurs- See Also:
NashornSandbox.setMaxCPUTime(long)
-
eval
public java.lang.Object eval(java.lang.String js, javax.script.ScriptContext scriptContext) throws ScriptCPUAbuseException, javax.script.ScriptExceptionDescription copied from interface:NashornSandboxEvaluates the JavaScript string for a given script context- Specified by:
evalin interfaceNashornSandbox- Parameters:
js- the JavaScript script to be evaluatedscriptContext- the ScriptContext exposing sets of attributes in different scopes.- Throws:
ScriptCPUAbuseException- when execution time exceeded (when greater than 0 is setjavax.script.ScriptException- when script syntax error occurs- See Also:
NashornSandbox.setMaxCPUTime(long)
-
eval
public java.lang.Object eval(java.lang.String js, javax.script.ScriptContext scriptContext, javax.script.Bindings bindings) throws ScriptCPUAbuseException, javax.script.ScriptExceptionDescription copied from interface:NashornSandboxEvaluates the JavaScript string for a given script context- Specified by:
evalin interfaceNashornSandbox- Parameters:
js- the JavaScript script to be evaluatedscriptContext- the ScriptContext exposing sets of attributes in different scopes.bindings- the Bindings to use for evaluation- Throws:
ScriptCPUAbuseException- when execution time exceeded (when greater than 0 is setjavax.script.ScriptException- when script syntax error occurs- See Also:
NashornSandbox.setMaxCPUTime(long)
-
secureBindings
protected javax.script.Bindings secureBindings(javax.script.Bindings bindings)
-
executeSandboxedOperation
protected java.lang.Object executeSandboxedOperation(ScriptEngineOperation op) throws ScriptCPUAbuseException, javax.script.ScriptException
- Throws:
ScriptCPUAbuseExceptionjavax.script.ScriptException
-
getEvaluator
private JsEvaluator getEvaluator(ScriptEngineOperation op)
-
checkExecutorPresence
private void checkExecutorPresence()
-
setMaxCPUTime
public void setMaxCPUTime(long limit)
Description copied from interface:NashornSandboxSets the maximum CPU time in milliseconds allowed for script execution.Note,
ExecutorServiceshould be also set when time is set greater than 0.- Specified by:
setMaxCPUTimein interfaceNashornSandbox- Parameters:
limit- time limit in milliseconds- See Also:
NashornSandbox.setExecutor(ExecutorService)
-
setMaxMemory
public void setMaxMemory(long limit)
Description copied from interface:NashornSandboxSets the maximum memory in Bytes which JS executor thread can allocate.
Note, thread memory usage is only approximation.
Note,
ExecutorServiceshould be also set when memory limit is set greater than 0. Nashorn takes some memory at start, be generous and give at least 1MB. If bindings are used, Nashorn allocates additional memory for the bindings which might be a multiple of the memory theoretically required by the data types used. For details, see issue 86.Current implementation of this limit works only on Sun/Oracle JVM.
- Specified by:
setMaxMemoryin interfaceNashornSandbox- Parameters:
limit- limit in bytes- See Also:
ThreadMXBean.getThreadAllocatedBytes(long)
-
getSanitizer
protected JsSanitizer getSanitizer()
-
allow
public void allow(java.lang.Class<?> clazz)
Description copied from interface:NashornSandboxAdd a new class to the list of allowed classes.- Specified by:
allowin interfaceNashornSandbox
-
disallow
public void disallow(java.lang.Class<?> clazz)
Description copied from interface:NashornSandboxRemove a class from the list of allowed classes.- Specified by:
disallowin interfaceNashornSandbox
-
isAllowed
public boolean isAllowed(java.lang.Class<?> clazz)
Description copied from interface:NashornSandboxCheck if a class is in the list of allowed classes.- Specified by:
isAllowedin interfaceNashornSandbox
-
disallowAllClasses
public void disallowAllClasses()
Description copied from interface:NashornSandboxRemove all classes from the list of allowed classes.- Specified by:
disallowAllClassesin interfaceNashornSandbox
-
inject
public void inject(java.lang.String variableName, java.lang.Object object)Description copied from interface:NashornSandboxWill add a global variable available to all scripts executed with this sandbox.- Specified by:
injectin interfaceNashornSandbox- Parameters:
variableName- the name of the variableobject- the value, can benull
-
setExecutor
public void setExecutor(java.util.concurrent.ExecutorService executor)
Description copied from interface:NashornSandboxSpecifies the executor service which is used to run scripts when a CPU time limit is specified.- Specified by:
setExecutorin interfaceNashornSandbox- Parameters:
executor- the executor service- See Also:
NashornSandbox.setMaxCPUTime(long)
-
getExecutor
public java.util.concurrent.ExecutorService getExecutor()
Description copied from interface:NashornSandboxGets the current executor service.- Specified by:
getExecutorin interfaceNashornSandbox- Returns:
- current executor service
-
get
public java.lang.Object get(java.lang.String variableName)
Description copied from interface:NashornSandboxObtains the value of the specified JavaScript variable.- Specified by:
getin interfaceNashornSandbox
-
allowPrintFunctions
public void allowPrintFunctions(boolean v)
Description copied from interface:NashornSandboxAllow Nashorn print and echo functions.Only before first
NashornSandbox.eval(String)call cause effect.- Specified by:
allowPrintFunctionsin interfaceNashornSandbox
-
allowReadFunctions
public void allowReadFunctions(boolean v)
Description copied from interface:NashornSandboxAllow Nashorn readLine and readFully functions.Only before first
NashornSandbox.eval(String)call cause effect.- Specified by:
allowReadFunctionsin interfaceNashornSandbox
-
allowLoadFunctions
public void allowLoadFunctions(boolean v)
Description copied from interface:NashornSandboxAllow Nashorn load and loadWithNewGlobal functions.Only before first
NashornSandbox.eval(String)call cause effect.- Specified by:
allowLoadFunctionsin interfaceNashornSandbox
-
allowExitFunctions
public void allowExitFunctions(boolean v)
Description copied from interface:NashornSandboxAllow Nashorn quit and exit functions.Only before first
NashornSandbox.eval(String)call cause effect.- Specified by:
allowExitFunctionsin interfaceNashornSandbox
-
allowGlobalsObjects
public void allowGlobalsObjects(boolean v)
Description copied from interface:NashornSandboxAllow Nashorn globals object $ARG, $ENV, $EXEC, $OPTIONS, $OUT, $ERR and $EXIT.Only before first
NashornSandbox.eval(String)call cause effect.- Specified by:
allowGlobalsObjectsin interfaceNashornSandbox
-
allowNoBraces
public void allowNoBraces(boolean v)
Description copied from interface:NashornSandboxForce, to check if all blocks are enclosed with curly braces "{}".Warning This option is useful to identify potential abuse but is also prone to identify false positives. Please use with caution. Alternatively you can use
setMaxCPUTimeto prevent abusive script execution.Explanation: all loops (for, do-while, while, and if-else, and functions should use braces, because poison_pill() function will be inserted after each open brace "{", to ensure interruption checking. Otherwise simple code like:
while(true) while(true) { // do nothing }or even:while(true)cause unbreakable loop, which force this sandbox to useThread.stop()which make JVM unstable.Properly written code (even in bad intention) like:
while(true) { while(true) { // do nothing }}will be changed into:while(true) {poison_pill(); while(true) {poison_pill(); // do nothing } }which finish nicely when interrupted.For legacy code, this check can be turned off, but with no guarantee, the JS thread will gracefully finish when interrupted.
- Specified by:
allowNoBracesin interfaceNashornSandbox- Parameters:
v-truewhen sandbox should check if all required braces are placed into JS code,falsewhen no check should be performed
-
setWriter
public void setWriter(java.io.Writer writer)
Description copied from interface:NashornSandboxSets the writer, when want to have output from writer function called in JS script- Specified by:
setWriterin interfaceNashornSandbox- Parameters:
writer- the writer, eg.StringWriter
-
setMaxPreparedStatements
public void setMaxPreparedStatements(int max)
Description copied from interface:NashornSandboxThe size of prepared statements LRU cache. Default 0 (disabled).Each statements when
NashornSandbox.setMaxCPUTime(long)is set is prepared to quit itself when time exceeded. To execute only once this procedure per statement set this value.When
NashornSandbox.setMaxCPUTime(long)is set 0, this value is ignored.- Specified by:
setMaxPreparedStatementsin interfaceNashornSandbox- Parameters:
max- the maximum number of statements in the LRU cache
-
createBindings
public javax.script.Bindings createBindings()
Description copied from interface:NashornSandboxCreate new bindings used to replace the state of the current script engineThis can be typically used to override ECMAScript "global" properties
- Specified by:
createBindingsin interfaceNashornSandbox- Returns:
-
getSandboxedInvocable
public javax.script.Invocable getSandboxedInvocable()
Description copied from interface:NashornSandboxReturns anInvocableinstance, so that method invocations are also sandboxed.- Specified by:
getSandboxedInvocablein interfaceNashornSandbox- Returns:
-
getLazySandboxedInvocable
private javax.script.Invocable getLazySandboxedInvocable()
-
setScriptCache
public void setScriptCache(SecuredJsCache cache)
Description copied from interface:NashornSandboxOverwrites the cache for pre-processed javascript. Must be called before the first invocation ofNashornSandbox.eval(String)and its overloads.- Specified by:
setScriptCachein interfaceNashornSandbox- Parameters:
cache- the new cache to use
-
compile
public javax.script.CompiledScript compile(java.lang.String js) throws javax.script.ScriptExceptionDescription copied from interface:NashornSandboxCompile the JavaScript string- Specified by:
compilein interfaceNashornSandbox- Parameters:
js- the JavaScript script to be compiled- Returns:
- a CompiledScript object
- Throws:
javax.script.ScriptException
-
eval
public java.lang.Object eval(javax.script.CompiledScript compiledScript) throws ScriptCPUAbuseException, javax.script.ScriptExceptionDescription copied from interface:NashornSandboxRun a pre-compiled JavaScript- Specified by:
evalin interfaceNashornSandbox- Throws:
ScriptCPUAbuseExceptionjavax.script.ScriptException
-
eval
public java.lang.Object eval(javax.script.CompiledScript compiledScript, javax.script.Bindings bindings) throws ScriptCPUAbuseException, javax.script.ScriptException- Specified by:
evalin interfaceNashornSandbox- Throws:
ScriptCPUAbuseExceptionjavax.script.ScriptException
-
eval
public java.lang.Object eval(javax.script.CompiledScript compiledScript, javax.script.ScriptContext scriptContext) throws ScriptCPUAbuseException, javax.script.ScriptException- Specified by:
evalin interfaceNashornSandbox- Throws:
ScriptCPUAbuseExceptionjavax.script.ScriptException
-
eval
public java.lang.Object eval(javax.script.CompiledScript compiledScript, javax.script.ScriptContext scriptContext, javax.script.Bindings bindings) throws ScriptCPUAbuseException, javax.script.ScriptException- Specified by:
evalin interfaceNashornSandbox- Throws:
ScriptCPUAbuseExceptionjavax.script.ScriptException
-
-