Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending/overriding existing ASP.NET controls

Tags:

asp.net

vb.net

I have a project with a whole bunch of labels, text boxes, and other web controls. There are literally hundreds of them.

I want now to be able to override certain properties in order to run content through an anti-XSS library. For example, when I set the text property of a label using data from a database I want to automatically run a function to scrub out any potentially malicious code.

I also tried overriding the text property using a class that implements IExtenderProvider but I could't get it to help.

Had I been building this from scratch I may have opted to create a new label class that inherits the system label class. Due to the size of the project I would rather not do that.

Any thoughts?

like image 434
christok Avatar asked Nov 10 '22 11:11

christok


1 Answers

First, I'll note that the right way to avoid XSS vulnerabilities is to properly encode user input before embedding it in your page. For example, if you're assigning a plain text string to the Text property of a Label, you need to encode the value because the Text property is rendered verbatim as HTML:

label.Text = HttpUtility.HtmlEncode(user.Name)

(Note: By "plain text" I mean text where characters like < and & don't have any special meaning.)

Second, as an additional defense-in-depth measure, you should validate user input when you collect it. But input validation does not negate the need to properly encode user input (because something might slip by). Always encode user input!

Okay, let's assume you're going to do that as time and testing allow, but you need a quick fix right now. You can create control adapters that change how particular types of controls are rendered. Here's an example which adds some asterisks to every single <asp:Label> in your application:

Imports System.Web.UI
Imports System.Web.UI.WebControls.Adapters

Public Class LabelControlAdapter
    Inherits WebControlAdapter

    Protected Overrides Sub RenderContents(writer As HtmlTextWriter)
        Dim label As Label = Me.Control
        label.Text = "***" + label.Text + "***"  ' TODO: Use your anti-XSS library
        MyBase.RenderContents(writer)
    End Sub
End Class

You can create additional control adapters for other types of controls, or modify LabelControlAdapter to sniff the type of Me.Control and do something different.

You also need to add a .browser file to your site's App_Browsers folder that lists each of the control types you're adapting:

<browsers>
    <browser refID="Default">
        <controlAdapters>
            <adapter
                controlType="System.Web.UI.WebControls.Label"
                adapterType="TempVBWebApp.LabelControlAdapter, TempVBWebApp" />
        </controlAdapters>
    </browser>
</browsers>
like image 174
Michael Liu Avatar answered Nov 14 '22 22:11

Michael Liu