1

I have a register model with a regular expression, but in C# we have Regex.ValidateMatchTimeout to prevent DDoS attacks. The question is, how implement a regex with timelimit in a model?

A normal regex in my model:

[DataType(DataType.EmailAddress)]
[Required]
[Display(Name = "Email")]
[StringLength(80, ErrorMessage = "Email too large.")]
[RegularExpression(@"^([a-zA-Z0-9_.-]+)@(outlook|hotmail|yahoo)\.\w{2,}$", ErrorMessage = "Invalid email.")]
public string Email { get; set; }
Joe
  • 307
  • 5
  • 14

2 Answers2

1

The RegularExpression attribute does not allow you to specify a timeout in any way. You could, on the other hand, set the global default timeout. If nothing is configured, the timeout would be infinite.

AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", TimeSpan.FromSeconds(1));

More info:

An alternative would be to create your own attribute, based on the reference source.

Community
  • 1
  • 1
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
0

Accepted answer is wrong (or perhaps outdated), because you can use MatchTimeoutInMilliseconds property, present in RegularExpressionAttribute

[RegularExpression(@"^([a-zA-Z0-9_.-]+)@(outlook|hotmail|yahoo)\.\w{2,}$", MatchTimeoutInMilliseconds = 1000, ErrorMessage = "Invalid email.")]

https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.regularexpressionattribute.matchtimeoutinmilliseconds

By the way, even you think your Regex is super-duper smart and awesome and fast, you could still fall pray to a maliciously crafted input that will take your regex for a spin. At scale, that can eventually take your system down.

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123