CodeSOD: Evaluating Regexes

This post was originally published on this site

The Daily WTF

Stack V supports a web application that accepts regexes from users. For legacy reasons, the users must supply the surrounding / characters, as well. There was some validation to ensure that the inputs were correct, but QA discovered that invalid regular expressions were getting through.

They filed a bug, it got triaged, and then shipped off to a contractor to patch. This was the contractor’s solution:

const isRegex = (string) => { try { // eslint-disable-next-line no-new-func return new Function(` “use strict”; try { new RegExp(${string}); return true; } catch (e) { return false; } `)(); } catch(e) { return false; } };

Here, we use string interpolation to generate some JavaScript code. It tries to construct a regex using our input string, and returns false if it doesn’t compile. We then execute that generated code using new Function, which just evals the string. And then, in true

To read the full article click on the 'post' link at the top.