Thursday, November 5, 2015

Regex Timeout

Timeout is used to prevent DOS attack.
If some hacker puts long string as input on form that is validated with regular expression then application would be hanged. Preventing from this situation need to set timeout.
Timeout feature is provided in .net framework 4.5

Without below given timeout parameter, this IsMatch statement will get hanged.
TimeSpan.FromSeconds(2)

Example

class Program
{
static void Main(string[] args)
{
   if Validate("815640753863946969814609141061480419060941869400616086849408614610189x"))
   Console.WriteLine("Validated");           
}

 static bool Validate(string input)
 {
    try
    {
return Regex.IsMatch(input, @"^(\d+)+$", RegexOptions.Singleline,       TimeSpan.FromSeconds(2));
    }
    catch (RegexMatchTimeoutException ex)
    {
        Console.WriteLine("Big or bad data: " + ex.Message);
    }
    return false;
 }

}

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...