Skip to content

patriksimek/vm2

Repository files navigation

vm2NPM VersionNPM DownloadsPackage QualityNode.js CIKnown Vulnerabilities

‼️Project Discontinued‼️

TL;DR The library contains critical security issues and should not be used for production! The maintenance of the project has been discontinued. Consider migrating your code toisolated-vm.

Dear community,

It's been a truly remarkable journey for me since the vm2 project started nine years ago. The original intent was to devise a method for running untrusted code in Node, with a keen focus on maintaining in-process performance. Proxies, an emerging feature in JavaScript at that time, became our tool of choice for this task.

From the get-go, we recognized the arduous task that lay ahead, as we tried to safeguard against the myriad of escape scenarios JavaScript presented. However, the thrill of the chase kept us going, hopeful that we could overcome these hurdles.

Through the years, this project has seen numerous contributions from passionate individuals. I wish to extend my deepest gratitude to all of you. Special thanks go to @XmiliaH, whose unwavering dedication in maintaining and improving this library over the last 4 years was instrumental to its sustained relevance.

Unfortunately, the growing complexity of Node has brought us to a crossroads. We now find ourselves facing an escape so complicated that fi xing it seems impossible. And this isn't about one isolated issue. Recent reports have highlighted that sustaining this project in its current form is not viable in the long term.

Therefore, we must announce the discontinuation of this project.

You may wonder, "What now?"

While this may seem like an end, I see it as an opportunity for you to transition your projects and adapt to a new solution. We would recommend migrating your code to theisolated-vm,a library which employs a slightly different, yet equally effective, approach to sandbo xing untrusted code.

Thank you all for your support and understanding during this journey.

Warm Regards, Patrik Simek


The original Readme is available here.

vm2 is a sandbox that can run untrusted code with whitelisted Node's built-in modules.Securely!

Features

  • Runs untrusted code securely in a single process with your code side by side
  • Full control over the sandbox's console output
  • The sandbox has limited access to the process's methods
  • It is possible to require modules (built-in and external) from the sandbox
  • You can limit access to certain (or all) built-in modules
  • You can securely call methods and exchange data and callbacks between sandboxes
  • Is immune to all known methods of attacks
  • Transpiler support

How does it work

  • It uses the internal VM module to create a secure context.
  • It usesProxiesto prevent escaping from the sandbox.
  • It overrides the built-in require to control access to modules.

What is the difference between Node's vm and vm2?

Try it yourself:

constvm=require('vm');
vm.runInNewContext('this.constructor.constructor( "return process" )().exit()');
console.log('Never gets executed.');
const{VM}=require('vm2');
newVM().run('this.constructor.constructor( "return process" )().exit()');
// Throws ReferenceError: process is not defined

Installation

IMPORTANT:VM2 requires Node.js 6 or newer.

npm install vm2

Quick Example

const{VM}=require('vm2');
constvm=newVM();

vm.run(`process.exit()`);// TypeError: process.exit is not a function
const{NodeVM}=require('vm2');
constvm=newNodeVM({
require:{
external:true,
root:'./'
}
});

vm.run(`
var request = require('request');
request('http:// google ', function (error, response, body) {
console.error(error);
if (!error && response.statusCode == 200) {
console.log(body); // Show the HTML for the Google homepage.
}
});
`,'vm.js');

Documentation

VM

VM is a simple sandbox to synchronously run untrusted code without therequirefeature. Only JavaScript built-in objects and Node'sBufferare available. Scheduling functions (setInterval,setTimeoutandsetImmediate) are not available by default.

Options:

  • timeout- Script timeout in milliseconds.WARNING:You might want to use this option together withallowAsync=false.Further, operating on returned objects from the sandbox can run arbitrary code and circumvent the timeout. One should test if the returned object is a primitive withtypeofand fully discard it (doing logging or creating error messages with such an object might also run arbitrary code again) in the other case.
  • sandbox- VM's global object.
  • compiler-javascript(default) orcoffeescriptor custom compiler function. The library expects you to have coffee-script pre-installed if the compiler is set tocoffeescript.
  • eval- If set tofalseany calls toevalor function constructors (Function,GeneratorFunction,etc.) will throw anEvalError(default:true).
  • wasm- If set tofalseany attempt to compile a WebAssembly module will throw aWebAssembly.CompileError(default:true).
  • allowAsync- If set tofalseany attempt to run code usingasyncwill throw aVMError(default:true).

IMPORTANT:Timeout is only effective on synchronous code that you run throughrun.Timeout doesNOTwork on any method returned by VM. There are some situations when timeout doesn't work - see#244.

const{VM}=require('vm2');

constvm=newVM({
timeout:1000,
allowAsync:false,
sandbox:{}
});

vm.run('process.exit()');// throws ReferenceError: process is not defined

You can also retrieve values from VM.

letnumber=vm.run('1337');// returns 1337

TIP:See tests for more usage examples.

NodeVM

UnlikeVM,NodeVMallows you to require modules in the same way that you would in the regular Node's context.

Options:

  • console-inheritto enable console,redirectto redirect to events,offto disable console (default:inherit).
  • sandbox- VM's global object.
  • compiler-javascript(default) orcoffeescriptor custom compiler function (which receives the code, and it's file path). The library expects you to have coffee-script pre-installed if the compiler is set tocoffeescript.
  • eval- If set tofalseany calls toevalor function constructors (Function,GeneratorFunction,etc.) will throw anEvalError(default:true).
  • wasm- If set tofalseany attempt to compile a WebAssembly module will throw aWebAssembly.CompileError(default:true).
  • sourceExtensions- Array of file extensions to treat as source code (default:['js']).
  • require-true,an object or a Resolver to enablerequiremethod (default:false).
  • require.external- Values can betrue,an array of allowed external modules, or an object (default:false). All paths matching/node_modules/${any_allowed_external_module}/(?!/node_modules/)are allowed to be required.
  • require.external.modules- Array of allowed external modules. Also supports wildcards, so specifying['@scope/*-ver-??],for instance, will allow using all modules having a name of the form@scope/something-ver-aa,@scope/other-ver-11,etc. The*wildcard does not match path separators.
  • require.external.transitive- Boolean which indicates if transitive dependencies of external modules are allowed (default:false).WARNING:When a module is required transitively, any module is then able to require it normally, even if this was not possible before it was loaded.
  • require.builtin- Array of allowed built-in modules, accepts [ "*" ] for all (default: none).WARNING:"*" can be dangerous as new built-ins can be added.
  • require.root- Restricted path(s) where local modules can be required (default: every path).
  • require.mock- Collection of mock modules (both external or built-in).
  • require.context-host(default) to require modules in the host and proxy them into the sandbox.sandboxto load, compile, and require modules in the sandbox.callback(moduleFilename, ext)to dynamically choose a context per module. The default will be sandbox is nothing is specified. Except forevents,built-in modules are always required in the host and proxied into the sandbox.
  • require.import- An array of modules to be loaded into NodeVM on start.
  • require.resolve- An additional lookup function in case a module wasn't found in one of the traditional node lookup paths.
  • require.customRequire- Use instead of therequirefunction to load modules from the host.
  • require.strict-falseto not force strict mode on modules loaded by require (default:true).
  • require.fs- Custom file system implementation.
  • nesting-WARNING:Allowing this is a security risk as scripts can create a NodeVM which can require any host module.trueto enable VMs nesting (default:false).
  • wrapper-commonjs(default) to wrap script into CommonJS wrapper,noneto retrieve value returned by the script.
  • argv- Array to be passed toprocess.argv.
  • env- Object to be passed toprocess.env.
  • strict-trueto loaded modules in strict mode (default:false).

IMPORTANT:Timeout is not effective for NodeVM so it is not immune towhile (true) {}or similar evil.

REMEMBER:The more modules you allow, the more fragile your sandbox becomes.

const{NodeVM}=require('vm2');

constvm=newNodeVM({
console:'inherit',
sandbox:{},
require:{
external:true,
builtin:['fs','path'],
root:'./',
mock:{
fs:{
readFileSync:()=>'Nice try!'
}
}
}
});

// Sync

letfunctionInSandbox=vm.run('module.exports = function(who) { console.log( "hello" + who); }');
functionInSandbox('world');

// Async

letfunctionWithCallbackInSandbox=vm.run('module.exports = function(who, callback) { callback( "hello" + who); }');
functionWithCallbackInSandbox('world',(greeting)=>{
console.log(greeting);
});

Whenwrapperis set tonone,NodeVMbehaves more likeVMfor synchronous code.

assert.ok(vm.run('return true')===true);

TIP:See tests for more usage examples.

Loading modules by relative path

To load modules by relative path, you must pass the full path of the script you're running as a second argument to vm'srunmethod if the script is a string. The filename is then displayed in any stack traces generated by the script.

vm.run('require( "foobar" )','/data/myvmscript.js');

If the script you are running is a VMScript, the path is given in the VMScript constructor.

constscript=newVMScript('require( "foobar" )',{filename:'/data/myvmscript.js'});
vm.run(script);

Resolver

A resolver can be created viamakeResolverFromLegacyOptionsand be used for multipleNodeVMinstances allowing to share compiled module code potentially speeding up load times. The first example ofNodeVMcan be rewritten usingmakeResolverFromLegacyOptionsas follows.

constresolver=makeResolverFromLegacyOptions({
external:true,
builtin:['fs','path'],
root:'./',
mock:{
fs:{
readFileSync:()=>'Nice try!'
}
}
});
constvm=newNodeVM({
console:'inherit',
sandbox:{},
require:resolver
});

VMScript

You can increase performance by using precompiled scripts. The precompiled VMScript can be run multiple times. It is important to note that the code is not bound to any VM (context); rather, it is bound before each run, just for that run.

const{VM,VMScript}=require('vm2');

constvm=newVM();
constscript=newVMScript('Math.random()');
console.log(vm.run(script));
console.log(vm.run(script));

It works for bothVMandNodeVM.

const{NodeVM,VMScript}=require('vm2');

constvm=newNodeVM();
constscript=newVMScript('module.exports = Math.random()');
console.log(vm.run(script));
console.log(vm.run(script));

Code is compiled automatically the first time it runs. One can compile the code anytime withscript pile().Once the code is compiled, the method has no effect.

Error handling

Errors in code compilation and synchronous code execution can be handled bytry-catch.Errors in asynchronous code execution can be handled by attachinguncaughtExceptionevent handler to Node'sprocess.

try{
varscript=newVMScript('Math.random()').compile();
}catch(err){
console.error('Failed to compile script.',err);
}

try{
vm.run(script);
}catch(err){
console.error('Failed to execute script.',err);
}

process.on('uncaughtException',(err)=>{
console.error('Asynchronous error caught.',err);
});

Debugging a sandboxed code

You can debug or inspect code running in the sandbox as if it was running in a normal process.

  • You can use breakpoints (which requires you to specify a script file name)
  • You can usedebuggerkeyword.
  • You can use step-in to step inside the code running in the sandbox.

Example

/tmp/main.js:

const{VM,VMScript}=require('.');
constfs=require('fs');
constfile=`${__dirname}/sandbox.js`;

// By providing a file name as second argument you enable breakpoints
constscript=newVMScript(fs.readFileSync(file),file);

newVM().run(script);

/tmp/sandbox.js

constfoo='ahoj';

// The debugger keyword works just fine everywhere.
// Even without specifying a file name to the VMScript object.
debugger;

Read-only objects (experimental)

To prevent sandboxed scripts from adding, changing, or deleting properties from the proxied objects, you can usefreezemethods to make the object read-only. This is only effective inside VM. Frozen objects are affected deeply. Primitive types cannot be frozen.

Example without usingfreeze:

constutil={
add:(a,b)=>a+b
}

constvm=newVM({
sandbox:{util}
});

vm.run('util.add = (a, b) => a - b');
console.log(util.add(1,1));// returns 0

Example with usingfreeze:

constvm=newVM();// Objects specified in the sandbox cannot be frozen.
vm.freeze(util,'util');// Second argument adds object to global.

vm.run('util.add = (a, b) => a - b');// Fails silently when not in strict mode.
console.log(util.add(1,1));// returns 2

IMPORTANT:It is not possible to freeze objects that have already been proxied to the VM.

Protected objects (experimental)

Unlikefreeze,this method allows sandboxed scripts to add, change, or delete properties on objects, with one exception - it is not possible to attach functions. Sandboxed scripts are therefore not able to modify methods liketoJSON,toStringorinspect.

IMPORTANT:It is not possible to protect objects that have already been proxied to the VM.

Cross-sandbox relationships

constassert=require('assert');
const{VM}=require('vm2');

constsandbox={
object:newObject(),
func:newFunction(),
buffer:newBuffer([0x01,0x05])
}

constvm=newVM({sandbox});

assert.ok(vm.run(`object`)===sandbox.object);
assert.ok(vm.run(`object instanceof Object`));
assert.ok(vm.run(`object`)instanceofObject);
assert.ok(vm.run(`object.__proto__ === Object.prototype`));
assert.ok(vm.run(`object`).__proto__===Object.prototype);

assert.ok(vm.run(`func`)===sandbox.func);
assert.ok(vm.run(`func instanceof Function`));
assert.ok(vm.run(`func`)instanceofFunction);
assert.ok(vm.run(`func.__proto__ === Function.prototype`));
assert.ok(vm.run(`func`).__proto__===Function.prototype);

assert.ok(vm.run(`new func() instanceof func`));
assert.ok(vm.run(`new func()`)instanceofsandbox.func);
assert.ok(vm.run(`new func().__proto__ === func.prototype`));
assert.ok(vm.run(`new func()`).__proto__===sandbox.func.prototype);

assert.ok(vm.run(`buffer`)===sandbox.buffer);
assert.ok(vm.run(`buffer instanceof Buffer`));
assert.ok(vm.run(`buffer`)instanceofBuffer);
assert.ok(vm.run(`buffer.__proto__ === Buffer.prototype`));
assert.ok(vm.run(`buffer`).__proto__===Buffer.prototype);
assert.ok(vm.run(`buffer.slice(0, 1) instanceof Buffer`));
assert.ok(vm.run(`buffer.slice(0, 1)`)instanceofBuffer);

CLI

Before you can use vm2 in the command line, install it globally withnpm install vm2 -g.

vm2./script.js

Known Issues

  • There are known security issues to circumvent the sandbox.
  • It is not possible to define a class that extends a proxied class. This includes using a proxied class inObject.create.
  • Direct eval does not work.
  • Logging sandbox arrays will repeat the array part in the properties.
  • Source code transformations can result a different source string for a function.
  • There are ways to crash the node process from inside the sandbox.

Deployment

  1. Update theCHANGELOG.md
  2. Update thepackage.jsonversion number
  3. Commit the changes
  4. Runnpm publish

Sponsors

Integromat