Skip to content

Instantly share code, notes, and snippets.

@joekir
Created March 15, 2016 02:18
Show Gist options
  • Save joekir/32790ce60798a2d85ee1 to your computer and use it in GitHub Desktop.
Save joekir/32790ce60798a2d85ee1 to your computer and use it in GitHub Desktop.
Uses the Node.js vm to isolate a RegExp so catastrophic backtracks do not halt the node process.
const util = require('util');
const vm = require('vm');
var sandbox = {
result: null
};
var context = vm.createContext(sandbox);
console.log('Sandbox initialized: ' + vm.isContext(sandbox));
var script = new vm.Script('result = /^(A+)*B/.test(\'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC\');');
try{
// One could argue if a RegExp hasn't processed in a given time.
// then, its likely it will take exponential time.
script.runInContext(context, { timeout: '1000' }); // milliseconds
} catch(e){
console.log('ReDos occurred'); // Take some remedial action here...
}
console.log(util.inspect(sandbox)); // Check the results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment