Saturday, 22 December 2018

How to Preventing JavaScript Injection Attacks in MVC application / Cross-site scripting attack / XSS attack

It is a security vulnerability found in Web applications. XSS allows hackers to inject client-side script into Web pages, and later, if that web page is viewed by others, the stored script gets executed. The consequences of XSS may range from a petty nuisance like displaying an alert() box to a significant security risk, like stealing session cookies. 

In MVC [ValidateInput(true)] by default which restricts  and encodes all HTML. This is a security measure in place, to prevent XSS attack. But if for some reason, you want to disablHTMLml encoding you may decorate the Controller Class or Controler Action method [ValidateInput(false)]. At this moment your application is open for an XSS attack. So you need to carefully avoid this attack by designing your application.

You need to tell your application what and all are allowed to encode coming from the request URL.
Let say I want to accept only <b></b> and <u></u> tags. You can design your application 

[HttpPost]
// Input validation is disabled, so the users can submit HTML
[ValidateInput(false)]
public ActionResult Create(Comment comment)
{
    StringBuilder sbComments = new StringBuilder();
    
    // Encode the text that is coming from comments textbox
    sbComments.Append(HttpUtility.HtmlEncode(comment.Comments));
    
    // Only decode bold and underline tags
    sbComments.Replace("&lt;b&gt;""<b>");
    sbComments.Replace("&lt;/b&gt;""</b>");
    sbComments.Replace("&lt;u&gt;""<u>");
    sbComments.Replace("&lt;/u&gt;""</u>");
    comment.Comments = sbComments.ToString();

    // HTML encode the text that is coming from name textbox
    string strEncodedName = HttpUtility.HtmlEncode(comment.Name);
    comment.Name = strEncodedName;

    if (ModelState.IsValid)
    {
        db.Comments.AddObject(comment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(comment);
}

Note: Read MSDN documentation on XSS and it's countermeasures. 

No comments:

Post a Comment