Skip to content
This repository has been archived by the owner on May 5, 2023. It is now read-only.

Commit

Permalink
Use vm2 module to prevent privilege escalation of untrusted code (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Jul 12, 2021
1 parent 7ad1041 commit 852043f
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -27,7 +27,8 @@
"dependencies": {
"ast-types": "^0.13.2",
"escodegen": "^1.8.1",
"esprima": "^4.0.0"
"esprima": "^4.0.0",
"vm2": "^3.9.3"
},
"devDependencies": {
"@types/escodegen": "^0.0.6",
Expand Down
10 changes: 4 additions & 6 deletions src/index.ts
Expand Up @@ -2,7 +2,8 @@ import { isRegExp } from 'util';
import { generate } from 'escodegen';
import { parseScript } from 'esprima';
import { visit, namedTypes as n, builders as b } from 'ast-types';
import { Context, RunningScriptOptions, runInNewContext } from 'vm';
import { Context, RunningScriptOptions } from 'vm';
import { VM } from 'vm2';

/**
* Compiles sync JavaScript code into JavaScript with async Functions.
Expand Down Expand Up @@ -136,11 +137,8 @@ namespace degenerator {
options: CompileOptions = {}
): (...args: A) => Promise<R> {
const compiled = degenerator(code, names);
const fn = runInNewContext(
`${compiled};${returnName}`,
options.sandbox,
options
);
const vm = new VM(options);
const fn = vm.run(`${compiled};${returnName}`);
if (typeof fn !== 'function') {
throw new Error(
`Expected a "function" to be returned for \`${returnName}\`, but got "${typeof fn}"`
Expand Down
14 changes: 14 additions & 0 deletions test/test.ts
Expand Up @@ -159,5 +159,19 @@ describe('degenerator()', () => {
assert.equal(val, 'foo');
});
});
it('should prevent privilege escalation of untrusted code', async() => {
let err;
try {
const fn = compile<typeof process>(
`const f = this.constructor.constructor('return process');`,
'f',
[],
);
await fn();
} catch(_err) {
err = _err;
}
assert.equal(err.message,'process is not defined')
});
});
});

0 comments on commit 852043f

Please sign in to comment.