Use HttpModule to implement unified Control, intervention, and processing (for example, filter keywords and AntiXSS) based on outputs. The prototype of ASP. Net WebForm Control to display attributes

Source: Internet
Author: User
/* Use HttpModule to uniformly intervene and process (for example, filter keywords) ASP. net WebForm Control output rendering a few days ago, reading Lao Zhao's "a complete keyword filtering solution", wrote HttpModule "output stream" intermediate "string" and then used "replace ", implement the "output-based intervention processing" Filtering Scheme, and implement ASP in HttpModule. net (*. aspx) can be directly deployed without modifying any original code!" Bytes. Recently, I was thinking about a unified and general intervention solution for global solutions to "cross-site scripting attacks" to achieve secure output. The common solution to "XSS attacks" is to "HTML/JavaScript Encode" first when "output" is used, and then output Safe Html/JavaScript. ASP. Net WebControl and its attributes are not automatically output after Encode, that is, they are not naturally immune to XSS Attack's "What's wrong with ASP. NET? HTML encoding http://msmvps.com/blogs/calinoiu/archive/2006/06/13/102957.aspx《Which ASP. NET Controls Automatically Encodes? "Blacklist" for "insecure controls and attributes"> ASP. some of Net WebForm Sever WebControl/HtmlControl's unified processing schemes for "text display or output"-related attributes currently use reflection (performance) when traversing all controls) only System. web. UI. the "Text" attribute of the control in the WebControls namespace is System. web. UI. the "Value" attribute of the control in the HtmlControls namespace can naturally intervene in the dynamic Ad The Control leakage of d processes the display-related attributes of other names, and there are some cases where the Control automatically added by WebForm Page is handled too much, so it is still not perfect. Other forms of Response output (for example: Response. <% = post-code class member variable %> of the Write and pre-code ), custom UserControl and WebCustomControl controls cannot be processed if they are not "Text" or "Value"-named display attributes, of course, the property of "Text" or "Value" that is irrelevant to the display may also be accidentally hurt. After the solution is gradually improved, in theory, we should be able to "Ignore" unnecessary controls and properties, and separately process them according to the situations of "insecure" controls and properties, there is still a certain amount of work. In addition, the performance has not been evaluated, and the traversal control may have some bottlenecks. In fact, I think using HttpModule. dll, HttpHandler. dll, Global. asax also has some performance bottlenecks, because all requests and outputs must flow through here. The following complete code is ControlsPropertyFilterHttpModule. csweb. configtest. aspx (note that the XSS Attack test code is available, so you don't have to worry about alert.) * // ControlsPropertyFilterHttpModule. csnamespace Microshaoft {using System; using System. web; using System. web. UI; using System. reflection; public class ControlsPropertyFilterHttpModule: IHttpModule {private HttpApplication _ contextApplication; public void Init (HttpApplication context) {_ contextApplicat Ion = context; _ contextApplication. postMapRequestHandler + = new EventHandler (_ contextApplication_PostMapRequestHandlerProcess);} public void Dispose () {_ contextApplication = null; _ contextApplication. dispose ();} public void _ contextApplication_PostMapRequestHandlerProcess (object sender, EventArgs e) {IHttpHandler handler = null; if (_ contextApplication = null) {return;} if (_ contextApplicat Ion. Context. Handler is Page) {handler = _ contextApplication. Context. Handler;} if (handler! = Null) {Page page = handler as Page; // page. preRender + = new EventHandler (page_PreRender); page. preRenderComplete + = new EventHandler (page_PreRender) ;}} private void page_PreRender (object sender, EventArgs e) {Page page = sender as Page; ControlCollection cc = page. controls; RecursiveProcessControls (cc);} private static void RecursiveProcessControls (ControlCollection cc) {foreach (Control c In cc) {Type t = c. getType (); // attributes related to various Text display need to be processed according to the control type. // currently, only the PropertyInfo pi of the Text and Value attributes is processed. getProperty ("Text"); // Server WebControls if (pi! = Null) {string s = (string) (pi. getValue (c, null); s = string. format ("Microshaoft processes [{0}]", s); // s = HttpUtility. htmlEncode (s); // AntiXSS pi. setValue (c, s, null);} pi = t. getProperty ("Value"); // Server HtmlControls if (pi! = Null) {string s = (string) (pi. getValue (c, null); s = string. format ("Microshaoft processes [{0}]", s); // s = HttpUtility. htmlEncode (s); // AntiXSS pi. setValue (c, s, null);} if (c. hasControls () {RecursiveProcessControls (c. controls );}}}}}

// Test. aspx <% @ Page language = "c #" AutoEventWireup = "true" %> <% @ Import Namespace = "System. Data" %> <! Doctype html public "-// W3C // dtd html 4.0 Transitional // EN"> <HTML> <HEAD> <title> WebForm1 </title> <meta name = "generator" content = "editplus"/> <meta name = "author" content = ""/> <meta name = "keywords" content = ""/> <meta name = "description" content = ""/> <script language = "C #" runat = "server"> protected void Page_Load (object sender, eventArgs ea) {h1.Text + = "<script> alert ('hl Xss attack')" + "</scr" + "Ept>"; DataTable dt = MakeTable ("F1", "F2"); string expression = "1 = 1 or f1 = '2'"; DataView dv = dt. defaultView; dv. sort = "f1 desc"; dv. rowFilter = expression; maid = dv; maid (); gridview1.DataSource = dv; gridview1.DataBind (); TextBox tb = new TextBox (); tb. text = "dynamic TextBox"; p1.Controls. add (tb);} void datagrid1_ItemDataBound (object sender, DataGridItemEvent Args e) {// foreach (TableCell cell in e. Item. Cells) /// {// if (cell. Text! = String. empty) // {// cell. text = HttpUtility. htmlEncode (cell. text); ///} //} void gridviewrowdatabound (object sender, GridViewRowEventArgs e) {// foreach (TableCell cell in e. row. cells) // {// if (cell. text! = String. empty) // {// cell. text = HttpUtility. htmlEncode (cell. text); //} private static DataTable MakeTable (string c1Name, string c2Name) {DataTable table = new DataTable (); DataColumn column = new DataColumn (c1Name, typeof (int); table. columns. add (column); column = new DataColumn (c2Name, typeof (string); table. columns. add (column); table. rows. add (1, "<script> alert ('datagrid xss attack') </scr" + "ERT>"); table. rows. add (2, "\ u003c" + "scr" + "ept \ u003ealert \ u0028 \ u0022gridview XSS \ u0041ttack \ u0022 \ u0029 \ u003c/script \ u003e "); return table ;} </script> </HEAD> <body MS_POSITIONING = "GridLayout"> <form id = "Form1" method = "post" runat = "server"> <asp: textBox ID = "tb1" Text = "static textBox" runat = "server"/> <asp: label ID = "l1" Text = "static label" runat = "server"/> <asp: Panel id = "p1" runat = "server"/> <asp: hyperlink ID = "h1" NavigateUrl = "http://www.baidu.com" runat = "server"> Baidu Hyperlink <script> alert ('hl Xss attack') </script> </asp: hyperlink> <input ID = "Value2" Type = "Text" Value = "static HtmlControls HtmlInputText" runat = "server"/> <asp: listBox ID = "lb1" Width = "" runat = "server"> <asp: ListItem> <script> alert ('lb Xss attack') </script> </asp: listItem> <asp: ListItem> </asp: ListBox> <ASP: dataGrid ID = "maid" runat = "server" AutoGenerateColumns = "True" OnItemDataBound = "maid"/> <ASP: gridView ID = "gridview1" runat = "server" AutoGenerateColumns = "True" OnRowDataBound = "gridview1_RowDataBound"/> </form> </body> </HTML>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.