jsheroes/community-help

Safe regex for email

danielmocan opened this issue · 3 comments

I was trying out Liran`s suggestion to validate regex expressions.

I used safer-regex but I have a problem validating email regex, I even used the regex used by w3c ( /^[a-zA-Z0-9.!#$%&’+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)$/ )
I still receive false ( not safe regex ).

const safe = require("safer-regex");
email = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
// emailowasp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
console.log( safe(`${email}`, false ) ); // raise False

Does anyone have any suggestions?

Hi @danielmocan,

Great to see you are following secure code best practices!

Both email regex that you're using seem suspicious. One of the attributes of bad regexs is repeating capture groups, which you can spot in both of them. In the first one email it shows up near the end with the string ending in [a-zA-Z0-9-]+)*$/; and the second one emailowasp also has a repeating +)* capturing group.
They are indeed both vulnerable.

Proof of Concept

I crafted a malicious email address and used it against one of those email regexes and the result you can see below using regex101:

image

The malicious email input is available here https://pastebin.com/Wwb4n18G
It will not necessarily have the same effect when running it on a live JS regex engine but it should at least alarm you.

Alternative solution

If you're trying to match a common pattern like an e-mail address or an IP address then I suggest always betting on one of the existing libraries for this instead of writing your own. In our case for the JavaScript / Node.js world it would be the validator project.

P.S.
I'm not sure where you got the emailowasp regex one, would be happy to get a reference.

Hi @lirantal,

Thank you for answering my question.
I somehow forgot about validator.js, now that you mentioned it I remembered it.
email owasp regex is from here OWASP
I think you mentioned them a few times.

I will change my problematic regex validations to use validator.js ( and see if I can add validator.js for the safe regex patterns as well ).

Yes OWASP has great resources but validator will be a better choice for this purpose.
Goodluck!