Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate HTML input to prevent XSS?

For example, StackExchange whitelists a subset of HTML: https://meta.stackexchange.com/questions/1777/what-html-tags-are-allowed-on-stack-exchange-sites

How could you do that in your controller to make sure user input is safe?

like image 621
Jason Beck Avatar asked Nov 04 '22 21:11

Jason Beck


1 Answers

This approach is not identical to StackExchange, but I found the AntiXSS 4.x library to a simple way to sanitize the input to allow "safe" HTML.

http://www.microsoft.com/en-us/download/details.aspx?id=28589 You can download a version here, but I linked it for the useful DOCX file. My preferred method is to use the NuGet package manager to get the latest AntiXSS package.

You can use the HtmlSanitizationLibrary assembly found in the 4.x AntiXss library. Note that GetSafeHtml() is in the HtmlSanitizationLibrary, under Microsoft.Security.Application.Sanitizer.

content = Sanitizer.GetSafeHtml(userInput);

This can be done before saving to the database. The advantage is removing malicious content immediately, and not having to worry about it when you output it. The disadvantage is that it won't handle any existing database content, and you do have to apply this any time you're making database updates.

The alternate approach is to use this method every time you output content.

I'd love to hear what the preferred approach is.

like image 101
Jason Beck Avatar answered Nov 15 '22 11:11

Jason Beck