What is vm2?
The vm2 npm package is a sandbox that can run untrusted code with whitelisted built-in modules securely. It provides a secure alternative to the default 'vm' module that comes with Node.js and offers more fine-grained control over what the executed code can do.
What are vm2's main functionalities?
Running Untrusted Code Securely
This feature allows you to execute untrusted JavaScript code in a secure sandbox environment, preventing it from accessing the local system or the host process.
const { NodeVM } = require('vm2');
const vm = new NodeVM();
let result = vm.run('return process.platform;');
Isolation of Modules
With vm2, you can control which modules the sandboxed code can require, either by whitelisting specific modules or by allowing/disallowing external modules.
const { NodeVM } = require('vm2');
const vm = new NodeVM({
require: {
external: true
}
});
vm.run('const fs = require("fs");');
Customizable Sandbox
This feature allows you to create a customizable sandbox with specific global properties that the executed code can interact with.
const { VM } = require('vm2');
const sandbox = { x: 20 };
const vm = new VM({ sandbox });
vm.run('x += 3;');
console.log(sandbox.x); // 23
Hooking Console Methods
vm2 allows you to redirect console methods from the sandboxed code to the host environment, enabling you to hook and handle logs, errors, and other console outputs.
const { NodeVM } = require('vm2');
const vm = new NodeVM({
console: 'redirect'
});
vm.on('console.log', (data) => {
console.log('Sandboxed log:', data);
});
vm.run('console.log("Hello from the sandbox!");');
Other packages similar to vm2
sandboxed-module
The 'sandboxed-module' package is similar to vm2 in that it allows for the execution of code in a sandboxed environment. However, it focuses more on requiring modules in a sandbox rather than executing arbitrary code. It does not provide as strong isolation as vm2.
secure-vm
The 'secure-vm' package is another alternative that provides a sandbox for executing code. It is similar to vm2 but has a different API and may not offer the same level of customization and security features as vm2.
vm2
vm2 is a sandbox that can run untrusted code with whitelisted built-in node objects. Securely!
Features
- Runs untrusted code securely in a single process with your code side by side
- Full control over sandbox's console output
- Sandbox has limited access to process's methods
- Sandbox can require modules (native and external)
- You can limit access to certain (or all) native modules
- You can securely call methods inside sandbox with callbacks
- Is immune to
while (true) {}
(VM only, see docs) - Is immune to all known methods of attacks
- Coffee-Script support
How does it work
- It uses internal VM module to create secure context
- It compiles native modules inside a new context
- It overrides native require to control access to modules
- It forces modules (even native ones) to use
use strict
Installation
npm install vm2
Quick Examples
var VM = require('vm2').VM;
var vm = new VM();
vm.run("process.exit()");
Documentation
1.x to 2.x changes
Buffer
class is no longer globally available by default in NodeVM. To make Buffer
accessible globaly, enable require
option and make sure buffer
module is whitelisted. More info in Known Issues.
VM
VM is a simple sandbox, without require
feature, to synchronously run an untrusted code. Only JavaScript built-in objects are available.
Options:
timeout
- Script timeout in milliseconds.sandbox
- VM's global object.language
- javascript
(default) or coffeescript
var VM = require('vm2').VM;
var options = {
timeout: 1000,
sandbox: {}
};
var vm = new VM(options);
vm.run("process.exit()");
You can also retrieve values from VM.
var number = vm.run("1337");
IMPORTANT: Timeout is only effective on code you run trough run
. Timeout is NOT effective on any method returned by VM.
NodeVM
Unlike VM
, NodeVM
lets you require modules same way like in 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 objectlanguage
- javascript
(default) or coffeescript
require
- true
to enable require
method (default: false
)requireExternal
- true
to enable require
of external modules (default: false
)requireNative
- Array of allowed native modules. (default: all available)requireRoot
- Restricted path where local modules can be required (default: every path)useStrict
- Whether to add use strict
directive to required modules (default: true
)
Available modules: assert
, buffer
, child_process
, constants
, crypto
, tls
, dgram
, dns
, http
, https
, net
, punycode
, querystring
, url
, domain
, events
, fs
, path
, os
, stream
, string_decoder
, timers
, tty
, util
, sys
, vm
, zlib
REMEMBER: The more modules you allow, the more fragile your sandbox becomes.
IMPORTANT: Timeout is not effective for NodeVM so it is not immune to while (true) {}
or similar evil.
var NodeVM = require('vm2').NodeVM;
var options = {
console: 'inherit',
sandbox: {},
require: true,
requireExternal: true,
requireNative: ['fs', 'path'],
requireRoot : "./"
};
var vm = new NodeVM(options);
var functionInSandbox = vm.run("module.exports = function(who) { console.log('hello '+ who); }");
Calling VM's methods
Securely call method in sandbox. All arguments except functions are cloned during the process to prevent context leak. Functions are wrapped to secure closures. Buffers are copied.
IMPORTANT: Method doesn't check for circular objects! If you send circular structure as an argument, your process will stuck in infinite loop.
IMPORTANT: Always use vm.call
method to call methods or callbacks in sandbox. If you call it directly, you are exposing yourself a risk of main global context leakage!
vm.call(functionInSandbox, 'world');
Loading modules by relative path
To load modules by relative path, you must pass full path of the script you're running as a second argument of vm's run
method. Filename then also shows up in any stack traces produced from the script.
vm.run("require('foobar')", "/data/myvmscript.js");
CLI
Before you can use vm2 in command line, install it globally with npm install vm2 -g
.
$ vm2 ./script.js
Known Issues
Allowing buffer
to be required inside NodeVM may crash your app with TypeError: Invalid non-string/buffer chunk
errors (reported here and here). To prevent buffer
from loading, disable require
option or remove buffer
from list of whitelisted native modules. Keep in mind that modules like fs
or stream
do require buffer
internally.
## License
Copyright (c) 2014-2015 Patrik Simek
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.