Richard77
Richard77

Reputation: 21621

How to use AntiXSS library in ASP.NET 4.5

I've upgraded an application from Asp.Net 3.5 to Asp.Net 4.5. I've seen many post about the merit of using AntiXSS library. I didn't see so far any telling how to use it.

It's suggested to enabled it in the web.config like this:

<httpRuntime ... 
      encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, 
      Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

I'd like to know whether enabling the library in the web.config is the only thing I need to do or should also encode input values from TextBoxes?

Thanks for helping

EDIT

Let's say, I have a textbox like this:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

Should I encode the input in the code-behind:

string value = SomeEncodeMethod(TextBox1.Text)

Do I need to do this?

Upvotes: 1

Views: 8634

Answers (2)

Sheo Dayal Singh
Sheo Dayal Singh

Reputation: 1673

How to use AntiXSS library in our projct.

Firstly we need to download AntiXss 4.2.1.msi from this location

https://www.microsoft.com/en-us/download/details.aspx?id=28589

and install it and then copy the AntiXSSLibrary.dll from below loaction(It will be stored after installation) and then we can use it in our project.

C:\Program Files (x86)\Microsoft Information Security\AntiXSS Library v4.2\NET40

Upvotes: 1

Gabor Lengyel
Gabor Lengyel

Reputation: 15570

Razor in .NET MVC (and also the <%: tag in aspx) encodes values automatically to an html context. This means that when you do @myVar in cshtml with Razor, any < will become &lt;, " will become &quote; and so on. But by default it uses a blacklist and only encodes a few characters, leaves everything else alone.

If you switch to AntiXSS as described in your question, this default encoder is changed to AntiXSS. The main benefit is that AntiXSS is a whitelist encoder, it has a list of a few characters that are ok to be left alone (letters and numbers, mainly), and everything else is encoded. This is slightly more secure and might prevent some attacks that would otherwise be possible.

You need to be aware though that this encoding is not always enough. To prevent XSS, you need to choose the right encoding for the right context. For an html context (and also for html attribute values, mostly), the default encoding is ok. However, it is not ok for a Javascript context. For instance this is vulnerable to XSS in a cshtml with either the default or the AntiXss html encoder:

<script>
    var myVar=@myVar;
</script>

To make this secure, you need to encode it to a Javascript context with JavaScriptEncode() in AntiXss and put it between quotes ('). Note that without the quotes, it's still vulnerable to XSS.

Upvotes: 1

Related Questions