Is the below safe regex function a safe alternative for a Node.js server regex compare function? Of course I should be writing safe regex, but as a secondary precaution, does the below work? Is 250 milliseconds okay?
const vm = require('vm');
const safeRegex = (strToCheck, regex, flags = 'gi') => {
if (typeof strToCheck !== 'string') return false;
const ctx = {
strToCheck: null,
regex: null,
result: null
};
ctx.strToCheck = strToCheck;
ctx.regex = new RegExp(regex, flags);
const context = vm.createContext(ctx);
const script = new vm.Script('const result = strToCheck.match(regex);');
try {
script.runInContext(context, { timeout: 250 }); // milliseconds
return context.result === null ? false : true;
} catch(err) {
console.log('timeout exceeded; failing');
return false;
}
}
module.exports = safeRegex;
console.log(safeRegex('test', 'te'));
console.log(safeRegex('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac', '^(a+)*b$'));
The above function was inspired from this article: https://www.josephkirwin.com/2016/03/12/nodejs_redos_mitigation/