Monday 7 November 2011

In ASP.NET, prevent XSS with automatic html encoding

Yesterday when looking for the ASP.NET XSS mappings I found an article that presents a solution that I have been looking for ages: Changing the behaviour of the ASP.NET <%= tag so that it encodes by default.


His technique of hooking the compilation step is absolutely brilliant

If you look at the code:
  • He creates a class (SafeEncodingCSharpCodeProvider)  that implements CSharpCodeProvider
  • in there he overrides GenerateCodeFromStatement(System.CodeDom.CodeStatement statement, TextWriter writer, CodeGeneratorOptions options)
  • then finds a CodeMethodInvokeExpression that is a Write
  • and wraps the parameter in a call to SafeEncodingHelper.SafeEncodingCSharpCodeProvider.EncodeHtmlIfNeeded
This is a massive step on the right direction, but there are a couple things that we should also take into account:
  • encoding is done with the HttpUtility.HtmlAttributeEncode which is not as sounds as the AntiXSSLibrary (note how he added an extra patch to encode ' )
  • we will need to take into account where in the page's HTML is the output going to be used (an HtmlElement, vs an Attribute, vs Javascript, vs CSS), and this can only be done with Static Analysis technology (SAST)
I also like the ability to change the framework the developer is coding on top, and make it secure by-default. This is another example of making security invisible since it allow us to add security in a way that it is invisible/transparent to developers. In that worlds, the devs only need to care about security when they are doing security-sensitive actions (which must still be supported, but should be the exception, not the norm).

One interesting question is where we want to do this change as a hardcoded compiler step (Steve's example), or do it directly on the code before it is compiled (as I show in the  Fixing/Encoding .NET code in real time (in this case Response.Write) example)?