Last time around we looked at SRE from a conceptual perspective, this time lets look at from a code perspective. Lets trace the program flow and understand in depth what SRE code does.
SRE is a HttpModule, the main class file is AntiXssModule.cs which inherits from IHttpModule. In the Init() event of HttpModule we hook on to HttpApplication.PostMapRequestHandler() event which gets raised when an ASP.NET handler is processing the current user request. In this case we are trying to find out when the ASP.NET Page handler is processing the page. As System.Web.UI.Page is both a HttpHandler and Page class that an ASP.NET page represents, we can use it to hook on to the PreRender event. Additional checks are performed to determine whether the page is excluded or whether the class is marked with SupressAntiXssEncodingAttribute.
LoadConfig uses the Configuration/ModuleConfiguration.cs class to load and parse the XML to create an object of ModuleConfiguration class and stores it in Application state variable for which can be reused through out the lifetime of the application. There is a drawback with using this approach whenever you make a change to antixssmodule.config file, the application needs to be restarted for those changes to be applied.
In the PostMapRequestHandler after the checks we call the XssProtection.Protect method which hooks on to the Page.PreRender event. This way we wait till page gets processed, all properties and controls are built by ASP.NET. During prerender we iterate through the control collection of the page and find controls which need to be encoded. Specified properties in the configuration file are then encoded based on the encoding type using the AntiXss library. As the properties are dynamically defined in the XML configuration file, property values are set using reflection. In essence XssProtection class is the main class responsible for encoding the page controls properties.
For more information and insight into code please check http://www.codeplex.com/antixss.