jahu jahu - 9 months ago 55
ASP.NET (C#) Question

How to block requests based on post data?

In IIS I can set request filtering based on url or query string and this allows me to block some malicious GET requests, however this does not work against post data.


If I set this in my web.config

<filteringRule name="Stop spam" scanUrl="false" scanQueryString="true">
<clear />
<add string="spam" />
<clear />
<clear />

Requests that have word "spam" in the query string will be blocked. However I need to also block POST requests that contain this word (for example from a form). Can I set up a deny rule that will filter and deny requests based on POST data and if so, how do I do that?

Answer Source

It appears that this cannot be done in IIS, however I did manage to come up with a workaround in the site itself. Adding this to Global.asax does seem to do the job:

protected void Application_BeginRequest(object sender, EventArgs e)
    var sr = new System.IO.StreamReader(Request.InputStream);
    string content = sr.ReadToEnd();
    var rule = @"spam";
        Regex.IsMatch(content, rule, RegexOptions.IgnoreCase) ||
        Regex.IsMatch(Request.Url.Query, rule, RegexOptions.IgnoreCase)
        // TODO: Do some logging here
        throw new Exception("Get off me lawn!");

Just a little heads up. Don't use this unless you know what you are doing. This will test all requests (and using regex at that), so it's going to slow the site down. It won't solve all malicious requests either.