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.
1: public void Init(HttpApplication context)
3: this.LoadConfig(context, AppDomain.CurrentDomain.BaseDirectory +
5: if (objConfig != null)
7: objApp = context;
8: objApp.PostMapRequestHandler += new
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.
1: void objApp_PostMapRequestHandler(object sender, EventArgs e)
3: //...validations & exclusion checks
4: if (objConfig != null)
6: string strVirPath = objApp.Context.Request.FilePath;
7: if (objConfig.IsPageExcluded(strVirPath.ToLower()))
13: //attribute checks
14: object attributes = ((Page)pageHandler).GetType().GetCustomAttributes (typeof(SupressAntiXssEncodingAttribute), true);
15: if (attributes.Length > 0)
17: Page page = (Page)pageHandler;
19: //Calling the static class to do the rest of the job
20: XssProtection.Protect(page, objConfig);
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.
The following is a screenshot of Visio sequence diagram of the above things.
For more information and insight into code please check http://www.codeplex.com/antixss.