Feature 3: Regex timeout (TimeOut) “Regex” has been the - TopicsExpress



          

Feature 3: Regex timeout (TimeOut) “Regex” has been the most preferred way of doing validations. In case you are new to Regex, please see the Regex video where I have explained how regex is implemented. But because of the typical parsing logic of regex it is exposed to DOS attacks. Let us try to understand in detail what I mean by that. For instance consider this regular expression - “^(\d+)$”. This regex expression says that it can have only numbers. You can also see the regex symbolic diagram which shows how the regex will be evaluated .Now let’s say if we want to validate “123456X”. It will have six paths as shown in the below figure. But if we add one more number to it, it will take seven paths. In other words as the length increases a regex takes more time to evaluate. In other words the time taken to evaluate is linearly proportional to the length of the characters. Now let’s complicate the previously defined regex from “^(\d+)$” to “^(\d+)+$” . If you see the regex symbolic diagram it’s pretty complex. If we now try to validate “123456X”, it will run through 32 paths. If you add one more character the number pf paths become 64. In other words for the above regex, the time taken to evaluate rises exponentially with the number of characters. Now the question you would ask is, how does it matter? This linear rise of evaluation time can be exploited by hackers to do a DOS (Denial of Service) attack. They can put a long, a really long string and make your application hang forever. The proper solution for this would be to have a timeout on the regex operation. Good news, in .NET 4.5 you can now define a timeout property as shown in the below code. So if you get any kind of malicious string, the application will not go in a loop forever. try { var regEx = new Regex(@”^(\d+)+$”, RegexOptions.Singleline, TimeSpan.FromSeconds(2)); var match = regEx.Match(“123453109839109283090492309480329489812093809x”); } catch (RegexMatchTimeoutException ex) { Console.WriteLine(“Regex Timeout”); }
Posted on: Mon, 03 Feb 2014 18:39:58 +0000

Trending Topics



Recently Viewed Topics




© 2015