Anicho
Anicho

Reputation: 2667

Protecting my self from cross-site scripting

I have implemented a Request.QueryString["somestr"].ToString();

I suppress cross site scripting by doing HttpUtility.HtmlEncode(Request.QueryString["somestr"].ToString();

I still have an issue where a user can do:

myfriendlydomain.com/?somestr=';alert(WOO XSS SUCCEDED);test='

How can I prevent this from happening?

As requested:

//Code Behind
if(request.querystring["somestr"] != null)
{
  AffiliatesEmail = HttpUtility.HtmlEncode(Request.QueryString["somestr"].ToString();    
}

//Front End
<script type="text/javascript">
  //<![CDATA[
    /*** Do not change ***/
    var SomeVAR = {};
    SomeVAR.Tracking.Sale.orderRef = '<%= AffiliatesEmail %>';
  //]]>
</script>

<script src="https://www.somethirdparty.com/somejscript.js" type="text/javascript" defer="defer"> </script>

This is our implementation. Anything afterwards I do not believe is relevant.

Upvotes: 5

Views: 2478

Answers (3)

Widor
Widor

Reputation: 13275

By knowing the context in which you are using the AffiliatesEmail string, it helps to know how thorough you have to be in validating and sanitising the string.

Let's say for example, that we know AffiliatesEmail was only valid if it were numeric. That way, you'd be protected if you rejected any Request.QueryString["somestr"] which didn't validate as a number.

Now, I suspect that AffiliatesEmail is in fact supposed to be a valid email address.

Using that knowledge, we can now validate it as an email address and reject everything else:

using System.Net.Mail;
try
{       
    MailAddress ma = new MailAddress(AffiliatesEmail);
}
catch (FormatException fe)
{
    //Email isn't valid, so don't output it to the client!!!
}

The code above simply validates whether the string is an email address (as defined by .NET) - if it's not, then we don't need to worry about what it is, because we simply don't trust it.

So don't get too hung up on santising everthing that gets put in the querystring - by simply knowing the bounds of what is acceptable, you can avoid complex regexes and XSS-cleaning routines.

Upvotes: 1

user596075
user596075

Reputation:

You can use the JavaScriptStringEncode() Method to scrub the string and encode it to prevent this from happening.

Another way is to use the AntiXSS library.

Upvotes: 2

Tim
Tim

Reputation: 4099

You need to validate every querystring input to make sure you have valid data coming in. I wouldn't write the value directly out to a page, either.

Upvotes: 0

Related Questions