views:

108

answers:

2

I'm working on an app that needs to accept a RegEx from the user, to do so I'm using the following code:

Regex user_searchPattern = new Regex(this.userInput_regEx.Text);

Is doing this safe?
Is there a need to sanitize the user input, and if so how?

+7  A: 

You might get an error if the regular expression has an invalid syntax or it might consume a exponential amount of time and space when processed if a so-called pathological regular expression is tested on some particular string.

Gumbo
Yep, agree with the patholigical issue - I would consider this wide open to a denial of service attack for this reason.
Steve Haigh
I'd run the regexp in a thread with a specific timeout to avoid DoS (if relevant, because if the user DoSs his own computer, I don't much care)
Vinko Vrsalovic
This is a client side Forms app so if they want to DoS themselves more power to them...
Unkwntech
OK, so I'd mistakenly assumed it was some sort of public facing API, but even so it's not helpful to your users to let them run a regex that kills their machine, I think you still need to consider how to handle this case for a good user experience.
Steve Haigh
Agreed, I'll find a good way to work around that, but I just wanted to make sure there was nothing major that I was aware of.
Unkwntech
A: 

User input is always evil. What do you mean with "safe". Can it contain errors that will make your code throw an exception or fail in some other way? Yes, it certainly can, so you should be prepared for that of course.

Fredrik Mörk