cjs-module-lexer icon indicating copy to clipboard operation
cjs-module-lexer copied to clipboard

Out of bounds memory access

Open devongovett opened this issue 2 years ago • 1 comments

cjs-module-lexer has a stack depth of 2048:

https://github.com/nodejs/cjs-module-lexer/blob/dd9d9f9d9546e2b000d02f1aa038900f170cd438/src/lexer.c#L8

this creates two stacks:

https://github.com/nodejs/cjs-module-lexer/blob/dd9d9f9d9546e2b000d02f1aa038900f170cd438/src/lexer.c#L36-L37

However, when pushing to these stacks, there is no bounds check performed. For example:

https://github.com/nodejs/cjs-module-lexer/blob/dd9d9f9d9546e2b000d02f1aa038900f170cd438/src/lexer.c#L164

If you run with a maliciously crafted input, you can overflow the stack and cause memory corruption.

import { parse, init } from 'cjs-module-lexer';

await init();
console.log(parse('exports.foo = 2;\n' + '{'.repeat(3069) + '}'.repeat(3069)));

Running this causes a Bus error: 10 crash.

This can also cause a crash of node itself by writing the above contents to a file and importing it via ESM.

devongovett avatar Feb 18 '23 20:02 devongovett

Thanks for digging into this. The expectation for protection during development was always that it would only crash the Wasm process and therefore we'd wrap that in a JS error and simply catch it. Wasm errors causing process errors is not something I expected though, in which case we need to introduce these protections carefully.

We can PR the stack checks in the right places and backport across all active release lines as it's a patch. Would be nice to ensure we catch everything at once if possible, but we can also do it gradually. I'll try and put a Sunday afternoon into this soon when I can. PRs very welcome too.

guybedford avatar Feb 19 '23 18:02 guybedford