KosD
KosD

Reputation: 81

XSS Payload That Can Bypass Special Character Check

I developed the following C# algorithm to prevent XSS attacks:

private bool Is_There_XSS_Payload(string arg)

{
    
   Regex regex = new Regex(@"^[a-zA-Z0-9]+$");
    
   bool result = regex.IsMatch(arg);
    
   return result;
    
 }

If the arg parameter contains any non-alphanumeric character, it returns false and does not make progress with the parameter.

Here the question is, can any XSS payload bypass this algorithm? Do I need a data encoding algorithm, or is only this validation enough to prevent XSS attacks?

Upvotes: 0

Views: 2041

Answers (1)

Gabor Lengyel
Gabor Lengyel

Reputation: 15599

Cross-site scripting is fundamentally an output encoding problem, and it is (almost) impossible to prevent via input filtering in a real application, except some very special cases.

As your filter is very strict (not even allowing whitespace for example), sure, if you can apply this to ALL input, I can't see how any meaningful XSS could be performed. But this filter will not work for any real-world application, you will need at least some other characters in general, and there your problems already start. Even without other characters, this could be used to reference already existing functions in special cases and so on.

Also, what would this be applied to? User input is not just GET parameters and POST body. Would you apply this to cookie values too? That will surely break a lot of existing (framework or 3rd party) code like authentication or CSRF protection. But if not applied to cookies or request headers, how will you ensure that cookie values or request headers are not ever used in output? Like 3 years in the future, when even you, let alone other devs will have forgotten this?

And then what about DOM XSS, where server-side filtering doesn't even join the game, as all of the attack purely exploits Javascript? Any filtering on the server-side is useless for that, only proper encoding in the client-side code helps.

So to sum it up, sure, in theory such a filter would prevent most XSS (though not even that is true in special cases where referencing existing code might lead to vulnerabilities). But the real problem is that this filter is not practical for most applications, and it completely disregards DOM XSS.

Any input filtering solution attempt to XSS will almost certainly be flawed in some way, and a skilled and resourceful attacker will find ways to get around it. XSS can only be securely prevented by context-aware output encoding (ie. applying the right encoding at all the right places).

Upvotes: 1

Related Questions