I am trying to detect JavaScript in my querystrings value.
I have the following c# code
private bool checkForXSS(string value)
{
Regex regex = new Regex(@"/((\%3C)|<)[^\n]+((\%3E)|>)/I");
if (regex.Match(value).Success) return true;
return false;
}
This works for detecting <script></script>
tags but unfortunately if there were no tags a match is not reached.
Is it possible for a regex to match on JavaScript keywords and semi-colons etc?
This is not meant to cover all XSS attack bases. Just a way to detect simple JS attacks that can be in a string value.
Thanks
I am trying to detect JavaScript in my querystrings value.
I have the following c# code
private bool checkForXSS(string value)
{
Regex regex = new Regex(@"/((\%3C)|<)[^\n]+((\%3E)|>)/I");
if (regex.Match(value).Success) return true;
return false;
}
This works for detecting <script></script>
tags but unfortunately if there were no tags a match is not reached.
Is it possible for a regex to match on JavaScript keywords and semi-colons etc?
This is not meant to cover all XSS attack bases. Just a way to detect simple JS attacks that can be in a string value.
Thanks
Share Improve this question edited Oct 9, 2009 at 9:45 w4ymo asked Oct 5, 2009 at 16:10 w4ymow4ymo 3122 gold badges8 silver badges21 bronze badges 1- 1 Ok, and then you must detect the presence of the substring "onmouseover", etc... Read my post stackoverflow./questions/1520973/… – Rodrigo Commented Oct 5, 2009 at 16:39
4 Answers
Reset to default 9Nº 1 Rule: Use a whitelist, not a blacklist.
You are preventing one way to do a XSS, not any. To achieve this, you must validate the input against what you should accept as a user input, i.e.
- If you expect a number, validate the input against
/^\d{1, n}$/
- If you expect a string, validate it against
/^[\s\w\.\,]+$/
, etc...
For further info, start reading the Wikipedia entry, the entry at OWASP, webappsec articles and some random blog entries written by unknown people
That's a pretty lame way of preventing cross-site scripting attacks. You need to use a pletely different approach: make sure that your user-supplied input is:
Validated such that it matches the semantics of the data being gathered;
Appropriately quoted every time that it is used to construct expressions to be interpreted by some language interpreter (SQL, HTML, Javascript - even when going to a plain-text logfile). Appropriate quoting pletely depends on the output context, and there is no single way to do it.
There are many ways to embed javascript. E.g.
%3Cp+style="expression(alert('hi'))"
will make it through your filter.
You probably can't find a magical regexp that will find all JS and that won't reject a lot of valid query strings.
This kind of checking might be useful, but it should only be one part of a defense-in-depth.
It should be enough for you to check if the tag <script
is present.
private bool checkForXSS(string value)
{
return value.IndexOf("<script") != -1;
}