简体   繁体   中英

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.

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.

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.

您需要验证每个查询字符串输入以确保您有有效的数据。我不会直接将值写入页面。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM