开发者

Regex to detect Javascript In a string

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 Ja开发者_Python百科vaScript 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


Nº 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 completely different approach: make sure that your user-supplied input is:

  1. Validated such that it matches the semantics of the data being gathered;

  2. 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 completely 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜