Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to remove some post data with an HttpModule?

I'm converting an old classic asp website to asp.net.

The application is basically an extension of a tool set for a given set of users but it is hosted at an external vendor.

To perform a seamless transfer to this application it POSTS some xml data which is firing off the "potentially dangerous Request.Form value". I know I could turn off the validateRequest flag but I would rather not do this.

I have written an httpmodule which takes this data and uses it to authenticate the user, is it possible to use the same module, or a different module for that matter, to remove these "bad" values in the post data before that data is "validated"?

Otherwise if none of these ideas work, I am open to other suggestions.

like image 430
David Avatar asked Jun 24 '09 17:06

David


1 Answers

Yes. The following class implements the IHttpModule Interface and registers and event that will fire before the HttpRequestValidationException check occurs. It checks that the request is a POST and that "testinput" is not null and then HTML Encodes it. The Class needs to be registered in your Web.config as an httpModule.

class...

using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Web;

public class PrevalidationSanitizer : System.Web.IHttpModule
{
    private HttpApplication httpApp;

    public void Init(HttpApplication httpApp)
    {
        this.httpApp = httpApp;
        httpApp.PreRequestHandlerExecute += new System.EventHandler(PreRequestHandlerExecute_Event);
    }

    public void Dispose() { }

    public void PreRequestHandlerExecute_Event(object sender, System.EventArgs args)
    {
        NameValueCollection form = httpApp.Request.Form;

        Type type = form.GetType();

        PropertyInfo prop = type.GetProperty("IsReadOnly", BindingFlags.Instance 
            | BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

        prop.SetValue(form, false, null);

        if (httpApp.Request.RequestType == "POST" != null 
            && httpApp.Request.Form["testinput"])
                httpApp.Request.Form.Set("testinput"
                    , httpApp.Server.HtmlEncode(httpApp.Request.Form["testinput"]));
    }
}

web.config entry...

<system.web>
  <httpModules>
    <add type="PrevalidationSanitizer" name="PrevalidationSanitizer" />
...
like image 108
MyItchyChin Avatar answered Feb 05 '23 17:02

MyItchyChin