Myna. Sandbox

Creates a sandbox for running JavaScript code with restrictions on access to Java and and hosting code.

Summary
Myna. SandboxCreates a sandbox for running JavaScript code with restrictions on access to Java and and hosting code.
Examples
Functions
Myna. SandboxConstructor function for Sandbox class
throwClass function Throws a sandbox exception, also known as a sandbox violation.
Myna. Sandbox. getCurrentClass function returns the currently executing sandbox or null if no sandboxes are currently executing.
Myna. Sandbox. bypassClass function bypasses all sandboxes for the duration of a function.
Myna. Sandbox. bypassFnClass function wraps a function in a sandbox bypass
Myna. Sandbox. isDebugModeClass Function returns true if the current MynThread is in sandbox debug mode.
Properties
whitelistregex[] to whitelist Java classes.
debugboolean, default false indicates whether this sandbox should execute in debug mode.
sandboxRulesArray of sandbox whitelist rules.
scopeObject that represents the global scope within the sandbox.
classPropertyWhitelistObject that contains property whitelists for java classes within the sandbox.
Functions
globalBeforeOverride function to be executed before every function call and property access in a proxied Java object
globalAfterOverride function to be executed after every function call and property access in a proxied object
onSandboxExceptionOverride global violation exception handler for this sandbox;
addScopeObjectsAdd one or more properties to the sandbox scope
addProxyDefAdd an override for specific functions and properties for a Java class.
addWhitelistClassAdds a class regex to the sandbox’s whitelist
addWhitelistPropertyAdds a class property regex to the sandbox’s whitelist
createJavaProxyWraps an object with a proxy object that enforces the sandbox’s property permissions.
executeStringExecutes a JS string in the sandbox
executePathExecutes the code stored in the supplied MynaPath, in the sandbox
importFromFileImports proxy rules from a rules file.
wrapFunctionwraps a function in a sandbox bypass, and proxies any Java objects returned when called.

Examples

var sandbox = new Myna.Sandbox({
whitelist:[
/^java\.net\.URL$/,
/^java\.net\.URLConnection$/,
/^java\.io\.InputStream$/
]

});
// Per-class property whitelists
// see the "options.file" constructor property and "importFromFile"
// function for a more compact way to define class and property
// whitelists

sandbox.addWhitelistProperty(
/^java\.net\.URL$/
/openConnection/
);
sandbox.addWhitelistProperty(
/^java\.net\.URLConnection$/
/getInputStream/
);
sandbox.addWhitelistProperty(
/^java\.io\.InputStream$/
/^.*$/
);

sandbox.addProxyDef(/java.net.Url/,{
properties:{
openConnection:{
beforeFn:function (proxy) {
if (proxy){
//disallow proxies
Myna.Sandbox.throw("URL:openConnection cannot be called with a proxy")
}
}
}
}
});

//This sets what will be visible in the parent scope of the code executed
//in the sandbox
sandbox.addScopeObjects(
{
website:new java.net.URL("http://goodsite.com"),
log:log,
error:error,
savePage:savePage
}
)

// good for code that is non-interactive, or places results in it's
// global scope
sandbox.executePath("/scripts/somescript.sjs")
var result1 = sandbox.scope.someResultValue;

//good for loading a script library, and the executing a function
result2 = sandbox.executePath(
"/scripts/somescript.sjs",
"doStuff",
[arg1,arg2]
);

//can also execute arbitrary strings. Just pass a "path" for error messages
result3 = sandbox.executeString(
mySandboxedCode,
"dynamic_code_{0}.sjs".format(runId),
"doStuff",
[arg1,arg2]
);

Functions

Myna. Sandbox

Myna.Sandbox = function(options)

Constructor function for Sandbox class

Parameters

optionsObject that describes the options for this connection.  See Options below.

Options

whitelistOptional, default [] regex whilelist of classes explicitly allowed in this sandbox.  This can also be set via file option to the constructor, or later via importFromFile This can be a single string (“^java.net.URL$”) a single regex (/^java.net.URL$/) or an array of either type [“^java.net.URL$”, /^java.net.URLConnection$/]
fileOptional MynaPath or Myna.File pointing to a proxy ruleset file.  This will be merged with whitelist, but is really intended as an alternative way of setting the whitelisted classes and properties.  See importFromFile for file format
debugOptional, default false If true, then the server will be placed in a sandbox debug mode while executing code.  This will result in the sandboxRules property being set to an array of rule strings appropriate for adding to a proxy ruleset file that can be included with importFromFile
mynaStandardObjectsOptional, default false Normally, only JavaScript standard objects are included in the sandbox scope.  Setting this property to true allows access to the “web-safe” Myna functions as well (see list below).

Myna Standard Objects

Returns

a Sandbox instance

throw

Myna.Sandbox.throw = function(msg,
className,
property)

Class function Throws a sandbox exception, also known as a sandbox violation.

Parameters

msgString message regarding this error.
classNameOptional String If this error could have been prevented by whitelisting a class, this should contain the appropriate String class name
propertyOptional String If this error could have been prevented by whitelisting a class and property, this should contain the appropriate String property name

Detail

This will unwind the stack back to the sandbox execution call and cannot be captured from within the sandbox code.  However this can be caught outside the sandbox.  This is useful for proxyDefs with custom function handler, e.g. throwing errors on certain types of input.  These can also be handled globally via onSandboxException

Myna. Sandbox. getCurrent

Myna.Sandbox.getCurrent = function()

Class function returns the currently executing sandbox or null if no sandboxes are currently executing.

Myna. Sandbox. bypass

Myna.Sandbox.bypass = function(fun)

Class function bypasses all sandboxes for the duration of a function.

Parameters

funfunction to execute outside the sandbox

example

sandbox.globalAfter = function () {
Myna.Sandbox.bypass(function () {
new Myna.File("log").appendString(
"accessed property " + chain.array.propertyName
);
})

return arguments.callee.chain.lastReturn;
}

See Also

Myna. Sandbox. bypassFn

Myna.Sandbox.bypassFn = function(fun)

Class function wraps a function in a sandbox bypass

Parameters

funfunction to wrap

example

var newScope={};
newScope.log =Myna.Sandbox.bypassFn(function (text,type) {
new Myna.File("log").appendString(
"[{0}] {1}: {2}".format(
new Date.format("Y-m-d H:i:s"),
type||"debug",
text
)
);
})

sandbox.addScopeObjects(newScope);

See Also

Myna. Sandbox. isDebugMode

Myna.Sandbox.isDebugMode = function ()

Class Function returns true if the current MynThread is in sandbox debug mode.

See debug

Properties

whitelist

regex[] to whitelist Java classes.

This is normally set in the constructor or a rules file

Example

/^java\.net\.\w+$/

debug

boolean, default false indicates whether this sandbox should execute in debug mode.  In debug mode, sandbox violations do not result in errors but rather get logged as type “sandbox” and write the rules necessary to whitelist the access to sandboxRules.  This is helpful for debugging and for gathering baseline rules.

This can be set in the constructor

sandboxRules

Array of sandbox whitelist rules.  These are generated when sandbox exceptions are raised in debug mode.  These are strings that can be appended a proxy rules file, and imported via importFromFile or the file constructor parameter.

scope

Object that represents the global scope within the sandbox.  This can only be modified via addScopeObjects, but can be read to view objects created within the sandbox

classPropertyWhitelist

Object that contains property whitelists for java classes within the sandbox.  This should only be modified via <addWhitelistPropery> or via a rules file

Functions

globalBefore

Override function to be executed before every function call and property access in a proxied Java object

Parameters

variousFor wrapped functions, these will be the parameters to the underlying function.  For property access there are no parameters

Special variables

This will be called in a chain along with any other interceptor functions as per Function.createChainFunction.  The name of the property or function being accessed can be found in

arguments.callee.chain.array.propertyName

Also, like all chain functions, you can find the last returned value in

This is useful for global input filtering for all proxied functions.

Example

sandbox.globalBefore = function () {
var chain = arguments.callee.chain;
//alter arguments to next function in the chain
chain.args = chain.args.map(function (arg) {
if(arg && typeof arg == "string"){
//escape HTML to prevent XSS attacks
return String(arg).escapeHtml();
} else {
return arg;
}
})

}

See

globalAfter

Override function to be executed after every function call and property access in a proxied object

Parameters

variousFor wrapped functions, these will be the parameters to the underlying function.  For property access there are no parameters

Special variables

This will be called in a chain along with any other interceptor functions as per Function.createChainFunction.  The name of property or function being accessed can be found in

arguments.callee.chain.array.propertyName

Also, like all chain functions, you can find the last returned value in

arguments.callee.chain.lastReturn

This value should be returned from any “after” functions unless altering return value is intended.

This is useful for global output filtering for all proxied functions.

Example

sandbox.globalAfter = function () {
Myna.Sandbox.bypass(function () {
new Myna.File("log").appendString(
"accessed property " + chain.array.propertyName
);
})

return arguments.callee.chain.lastReturn;
}

See

onSandboxException

Myna.Sandbox.prototype.onSandboxException=function ()

Override global violation exception handler for this sandbox;

Parameters

exceptionsandbox exception object

This is only called for sandbox violations.  By default it returns false.  This function should be overridden for custom sandbox exception handling.

Override functions can return boolean true to suppress this exception.

addScopeObjects

Myna.Sandbox.prototype.addScopeObjects = function(objectStruct)

Add one or more properties to the sandbox scope

Parameters

objectStructJS object where each property should a be a top-level property or function in the sandbox scope

Detail

each property in objectStruct will be merged into the sandbox’s scope, based on type:

functionsWrapped in a sandbox escape (see <Myna.sandbox.bypassFn>).  This means the sandbox class restrictions will not apply
arraysCopied as new array, and each item passed again to addScopeObjects
plain JS objectsCopied as new object, and each member passed again to addScopeObjects
datesCloned as new Date object
Java objectsPassed to createJavaProxy before assigning

Note

Information from the sandbox’s settings is used by addScopeObjects to construct the sandbox scope.  This means that this function should be called after all other sandbox configuration.

addProxyDef

Myna.Sandbox.prototype.addProxyDef =function(classPattern,
settings)

Add an override for specific functions and properties for a Java class.  This overrides any generic white-listing provided via addWhitelistProperty.  Useful for altering input or output or conditional restrictions

Parameters

classPatternclassName regex to apply these settings to
settingssettings Object definition.  See “Settings” below

Settings

propertyWhitelistOptional, default []:tuple.value, Regex list of properties that are accessible.
beforeFnOptional, default null Function to run before accessing a property, or running a function.  This runs after the globalBefore
afterFnFunction to run after accessing a property, or running a function.  This runs before the globalAfter

addWhitelistClass

Myna.Sandbox.prototype.addWhitelistClass =function(classRegex)

Adds a class regex to the sandbox’s whitelist

Parameters

classRegexRegeExp regex to add

This allows Java classes that match this regex to be created within the sandbox.  This can also be set via a rules file in the constructor.

Note

By default no properties of these classes can be accessed within the sandbox.  See addWhitelistProperty

Example

sandbox.addWhitelistClass(/^java\.net\.URL$/)

addWhitelistProperty

Myna.Sandbox.prototype.addWhitelistProperty =function(classRegex,
propertyRegex)

Adds a class property regex to the sandbox’s whitelist

Parameters

classRegexRegeExp regex of className to apply
propertyRegexRegeExp regex of property name to apply

This can also be set via a rules file in the constructor

Note

This will also call addWhitelistClass using the classRegex

Example

sandbox.addWhitelistProperty(/^java\.net\.URL$/,/^toString$/)

createJavaProxy

Myna.Sandbox.prototype.createJavaProxy = function(obj)

Wraps an object with a proxy object that enforces the sandbox’s property permissions.

Parameters

objobject to wrap.  If this is not a valid Java Object, or if it is already a Java object proxy, it will be returned unaltered

This is called automatically inside addScopeObjects when a Java object is encountered.

See

executeString

Myna.Sandbox.prototype.executeString = function(string,
path,
functionName,
args)

Executes a JS string in the sandbox

Parameters

stringCode to execute
pathpath to .js or .sjs file to execute within the sandbox
functionNameOptional, default undefined String If defined, this is the name of a function to execute after loading the script into the sandbox
argOptional, default undefined Array If defined, and array of arguments to pass to the function

Returns

result of functionName or undefined

executePath

Myna.Sandbox.prototype.executePath = function(path,
functionName,
args)

Executes the code stored in the supplied MynaPath, in the sandbox

Parameters

pathpath to .js or .sjs file to execute within the sandbox
functionNameOptional, default undefined String If defined, this is the name of a function to execute after loading the script into the sandbox
argOptional, default undefined Array If defined, and array of arguments to pass to the function

Returns

result of functionName or undefined.

See: executeString

importFromFile

Myna.Sandbox.prototype.importFromFile =function(file)

Imports proxy rules from a rules file.

Parameters

fileMynaPath or Myna.File instance

Proxy rules files are text files with entries whitelisting classes and class properties.  Each rule is terminated by a line break

Class rules consist of the text “class:” followed by a regular expression describing the classname.

class:java.util.Collections\$UnmodifiableRandomAccessList
class:java\.util\.ArrayList

Property rules consist of the text “property:” followed by a regular expression describing the classname, followd by “:” and then a regular expression describing the property name

property:java\.util\.ArrayList:toArray
property:java\.util\.ArrayList:toString
property:java\.util\.Collections\$UnmodifiableRandomAccessList:get
property:java\.util\.Collections\$UnmodifiableRandomAccessList:size

This can be used from the constructor by passing the file option

wrapFunction

Myna.Sandbox.prototype.wrapFunction = function(f)

wraps a function in a sandbox bypass, and proxies any Java objects returned when called.

This is normally called from within addScopeObjects

Parameters

ffunction reference to wrap
Myna.Sandbox = function(options)
Constructor function for Sandbox class
Myna.Sandbox.throw = function(msg,
className,
property)
Class function Throws a sandbox exception, also known as a sandbox violation.
Myna.Sandbox.getCurrent = function()
Class function returns the currently executing sandbox or null if no sandboxes are currently executing.
Myna.Sandbox.bypass = function(fun)
Class function bypasses all sandboxes for the duration of a function.
Myna.Sandbox.bypassFn = function(fun)
Class function wraps a function in a sandbox bypass
Myna.Sandbox.isDebugMode = function ()
Class Function returns true if the current MynThread is in sandbox debug mode.
Myna.Sandbox.prototype.onSandboxException=function ()
Override global violation exception handler for this sandbox;
Myna.Sandbox.prototype.addScopeObjects = function(objectStruct)
Add one or more properties to the sandbox scope
Myna.Sandbox.prototype.addProxyDef =function(classPattern,
settings)
Add an override for specific functions and properties for a Java class.
Myna.Sandbox.prototype.addWhitelistClass =function(classRegex)
Adds a class regex to the sandbox’s whitelist
Myna.Sandbox.prototype.addWhitelistProperty =function(classRegex,
propertyRegex)
Adds a class property regex to the sandbox’s whitelist
Myna.Sandbox.prototype.createJavaProxy = function(obj)
Wraps an object with a proxy object that enforces the sandbox’s property permissions.
Myna.Sandbox.prototype.executeString = function(string,
path,
functionName,
args)
Executes a JS string in the sandbox
Myna.Sandbox.prototype.executePath = function(path,
functionName,
args)
Executes the code stored in the supplied MynaPath, in the sandbox
Myna.Sandbox.prototype.importFromFile =function(file)
Imports proxy rules from a rules file.
Myna.Sandbox.prototype.wrapFunction = function(f)
wraps a function in a sandbox bypass, and proxies any Java objects returned when called.
A MynaPath is a file URI String with certain automatic translations.
A Javascript friendly proxy for java.io.File
Array of sandbox whitelist rules.
Myna extensions to the JavaScript Number object
Additional functions on the JS Array object
Additional object related functions
Additional functions on the JS Object object
Additional functions on the JS String object
Additional functions on the JS Function object
This date class adapted from http://code.google.com/p/flexible-js-formatting/.
Stores the results of one or more validation operations
A store for validation functions that can be used to validate objects
Stores execution times between begin() and end() functions
A specialized array for working with tabular data
Static class for converting English words to plural and singular forms
Global instance of Myna.Profiler.
boolean, default false indicates whether this sandbox should execute in debug mode.
Function.createChainFunction=function(initialChain)
returns a function that will execute a chain of functions when called.
Object that represents the global scope within the sandbox.
Override function to be executed before every function call and property access in a proxied Java object
Override function to be executed after every function call and property access in a proxied object