I created a simple .NET web form application which runs on .NET 4.7.2.
This application has a text box, a submit button and a label. When you click on the submit button the application displays the text box content.
To make this application vulnerable to Cross site scripting, I disable the request validation (validateRequest=false) in its web.config. This allows me to type in the text field the value: XSS<img src=x onerror=confirm("HACKED")> and submit.
Upon clicking Submit I see the pop up
In order to prevent XSS attack, I went and got the NUGet package for AntiXss library and reference it in my web.config as per the instruction from Microsoft AntiXss document.
However, nothing encoded and my web app still vulnerable to XSS attack until I explicitly encode the value in my code.
protected void Button1_Click(object sender, EventArgs e)
{
//Label1.Text = TextBox1.Text;
Label1.Text = AntiXssEncoder.HtmlEncode(TextBox1.Text,true);
}
With the value encoded using AntiXss library, the application now displays the value instead of executing that script and creates the pop up.
So I have three questions:
- What does the web.config encoderType="System.Web.Security.AntiXss.AntiXssEncoder" really do because it does not change my test result wether I put it in or remove it out of my web.config. According to Micrsoft document, this sets the default handler for HTML and URL encoding tasks.
- If I have to encode each and every text fields to prevent XSS attack, is there a site wide approach to encode all of its fields? it does not seem like a practical solution for a site (not MVC) that has hundred of pages with numerous input field spread out all over the place and having to HTMLEncode one by one.
- How does validateRequest work with XSS prevention other than display that standard .NET detect dangerous request page? Can I catch it as exception and display an error message on my page instead of display the default error page like the one below.