🌜
🌞
vm2

vm2

v3.9.10

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

npm install vm2

README

vm2 NPM Version NPM Downloads Package Quality Node.js CI Known Vulnerabilities

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 uses Proxies to 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:

const vm = require('vm');
vm.runInNewContext('this.constructor.constructor("return process")().exit()');
console.log('Never gets executed.');
const {VM} = require('vm2');
new VM().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');
const vm = new VM();

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

vm.run(`
    var request = require('request');
    request('http://www.google.com', 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 the require feature. Only JavaScript built-in objects and Node's Buffer are available. Scheduling functions (setInterval, setTimeout and setImmediate) are not available by default.

Options:

  • timeout - Script timeout in milliseconds. WARNING: You might want to use this option together with allowAsync=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 with typeof and 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) or coffeescript or custom compiler function. The library expects you to have coffee-script pre-installed if the compiler is set to coffeescript.
  • eval - If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc.) will throw an EvalError (default: true).
  • wasm - If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError (default: true).
  • allowAsync - If set to false any attempt to run code using async will throw a VMError (default: true).

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

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

const vm = new VM({
    timeout: 1000,
    allowAsync: false,
    sandbox: {}
});

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

You can also retrieve values from VM.

let number = vm.run('1337'); // returns 1337

TIP: See tests for more usage examples.

NodeVM

Unlike VM, NodeVM allows you to require modules in the same way that you would in the regular Node's context.

Options:

  • console - inherit to enable console, redirect to redirect to events, off to disable console (default: inherit).
  • sandbox - VM's global object.
  • compiler - javascript (default) or coffeescript or 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 to coffeescript.
  • eval - If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc.) will throw an EvalError (default: true).
  • wasm - If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError (default: true).
  • sourceExtensions - Array of file extensions to treat as source code (default: ['js']).
  • require - true or object to enable require method (default: false).
  • require.external - Values can be true, 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. sandbox to load, compile, and require modules in the sandbox. Except for events, 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.
  • nesting - WARNING: Allowing this is a security risk as scripts can create a NodeVM which can require any host module. true to enable VMs nesting (default: false).
  • wrapper - commonjs (default) to wrap script into CommonJS wrapper, none to retrieve value returned by the script.
  • argv - Array to be passed to process.argv.
  • env - Object to be passed to process.env.
  • strict - true to loaded modules in strict mode (default: false).

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

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

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

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

// Sync

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

// Async

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

When wrapper is set to none, NodeVM behaves more like VM for 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's run method 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.

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

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');

const vm = new VM();
const script = new VMScript('Math.random()');
console.log(vm.run(script));
console.log(vm.run(script));

It works for both VM and NodeVM.

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

const vm = new NodeVM();
const script = new VMScript('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 with script.compile(). Once the code is compiled, the method has no effect.

Error handling

Errors in code compilation and synchronous code execution can be handled by try-catch. Errors in asynchronous code execution can be handled by attaching uncaughtException event handler to Node's process.

try {
    var script = new VMScript('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 use debugger keyword.
  • You can use step-in to step inside the code running in the sandbox.

Example

/tmp/main.js:

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

// By providing a file name as second argument you enable breakpoints
const script = new VMScript(fs.readFileSync(file), file);

new VM().run(script);

/tmp/sandbox.js

const foo = '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 use freeze methods to make the object read-only. This is only effective inside VM. Frozen objects are affected deeply. Primitive types cannot be frozen.

Example without using freeze:

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

const vm = new VM({
    sandbox: {util}
});

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

Example with using freeze:

const vm = new VM(); // 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)

Unlike freeze, 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 like toJSON, toString or inspect.

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

Cross-sandbox relationships

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

const sandbox = {
    object: new Object(),
    func: new Function(),
    buffer: new Buffer([0x01, 0x05])
}

const vm = new VM({sandbox});

assert.ok(vm.run(`object`) === sandbox.object);
assert.ok(vm.run(`object instanceof Object`));
assert.ok(vm.run(`object`) instanceof Object);
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`) instanceof Function);
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()`) instanceof sandbox.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`) instanceof Buffer);
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)`) instanceof Buffer);

CLI

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

vm2 ./script.js

Known Issues

  • It is not possible to define a class that extends a proxied class.
  • 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.

Deployment

  1. Update the CHANGELOG.md
  2. Update the package.json version number
  3. Commit the changes
  4. Run npm publish

Sponsors

Integromat

Release Notes

3.9.10
Published on July 5, 2022

New Features

61d240f69cc02974be27c7582fee2defd0e6c7a8: Add uptime to process.

Fixes

e3e573fdc99a98a9c7db026e4c40474eb78cab4a: Security fix. 245da82dcdfa67031e065fd7c7a7348b5e21f2b8: Fix inspect showProxy.

3.9.9
Published on February 24, 2022

Fixes

5c2e13bbf0c0518e1958a4307982a999aa181049: Bump ECMA version to 2022.

3.9.8
Published on February 16, 2022

Fixes

777ffb0e021ef89444f215a69365a689d7051896: Fix access to some restricted function properties on non functions and fix findBestExtensionHandler not finding the best handler. 925e3e665acfa37dd3db0ea8e7f02b57277677e8: Try to return nicer parser errors.

3.9.7
Published on February 10, 2022

Fixes

b7f794dfb3034d2173b9da957f48425adc4081c3: Custom Resolver is allowed to return undefined 568934f58cf72339a3dd2a2c578cc28550c19d27: Fixed some bugs introduced in v3.9.6 b6581b4a9cf9a4706b2967fceb5930a3de4d2ac7: Fixed root path checking

3.9.6
Published on February 8, 2022

Fixes

532120d5cdec7da8225fc6242e154ebabc63fe4d: Internal restructuring and security improvements

3.9.5
Published on October 17, 2021

New Features

d9af94ca3a701b9ba6283264fafeef4827786702: Added editor config

Fixes

4f0db94bfa250089d903083fcd6c6cf6cd11b8a9: Fix Promise.then not working 419806086ccbef7b9f11abbd8420d01d9fe6d18c: Fix for missing CallSite properties

3.9.4
Published on October 12, 2021

New Features

4ead241540bb3d6ffcca64ce98d3b263c8f15cb4: Added strict option

Fixes

b4f6e2bd2c4a1ef52fc4483d8e35f28bc4481886: Fix breakouts in VM. e95165b36fd07d20febd00a7b08fc8292ccc703e: Fix for bound function causes TypeError 42c7b83ce8dded5e3ae03142736dcf8306a2c2a8: Allow extending of frozen objects

3.9.3
By Patrik Simek • Published on April 5, 2021

Fixes

  • ff894fcbd43298614bd28bc173d3446961a86913: Fix breakouts in VM.
  • d12bdbdb647ba14d7b788ea6b2089df9c09028df: Fix problems when Promise object is deleted.
  • 77a7681d29ca826400e9bb25b653e4112b270639: Fix oversight that write ability can change on non configurable properties.
  • 8a76a08e22a76a2e5becf53f5df1306327658721: Support shebang as node does.
  • 3f05f9807e0c022df75597e31f191fc5facf8a3c: Fix property typos.
3.9.2
Published on April 29, 2020

New Features

  • 1330a7e151140f34118eced9930cd0e9473cfac3: Added NodeVM options to pass argv and env to the process object.

Fixes

  • 6f1e2c1f19f2a9c582650ebf70fe448029e46845: Fix breakouts in NodeVM.
  • 58b248223e845a56f92cbd6f4fc26c735e17e4be: Made async check more robust.
3.9.1
Published on March 29, 2020

Fixes

  • 2049e4d34d35ff4fc9cf83390571c7b06eeb2e77: Require helpers statically in main.
  • d267a32a127b1b9e7ae8b9f1cde25f0b7705403b: Fix for non-configurable property access.

General

License
MIT
Typescript Types
Built-in
Tree-shakeable
No

Popularity

GitHub Stargazers
3,200
Community Interest
2,930
Number of Forks
227

Maintenance

Commits
10/219/22020
Last Commit
Open Issues
21
Closed Issues
334
Open Pull Requests
2
Closed Pull Requests
29

Versions

Versions Released
10/219/2204
Latest Version Released
Jul 5, 2022
Current Tags
latest3.9.10

Dependencies

Dependencies (0)
Dev Dependencies (3)

Contributors

patriksimek
patriksimek
Commits: 170
XmiliaH
XmiliaH
Commits: 73
orta
orta
Commits: 7
idan-at
idan-at
Commits: 6
alizain
alizain
Commits: 4
harelmo
harelmo
Commits: 2
Shigma
Shigma
Commits: 2
y21
y21
Commits: 2
randalpinto
randalpinto
Commits: 2
Vunovati
Vunovati
Commits: 2
h0ru5
h0ru5
Commits: 1
wojpawlik
wojpawlik
Commits: 1
azu
azu
Commits: 1
tabone
tabone
Commits: 1
undeflife
undeflife
Commits: 1