jahu
jahu

Reputation: 5657

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.

Example:

If I set this in my web.config

<security>
    <requestFiltering>
        <filteringRules>
            <filteringRule name="Stop spam" scanUrl="false" scanQueryString="true">
                <denyStrings>
                    <clear />
                    <add string="spam" />
                </denyStrings>
                <scanHeaders>
                    <clear />
                </scanHeaders>
                <appliesTo>
                    <clear />
                </appliesTo>
            </filteringRule>
        </filteringRules>
    </requestFiltering>
</security>

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?

Upvotes: 3

Views: 1663

Answers (1)

jahu
jahu

Reputation: 5657

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";
    if
    (
        Regex.IsMatch(content, rule, RegexOptions.IgnoreCase) ||
        Regex.IsMatch(Request.Url.Query, rule, RegexOptions.IgnoreCase)
    )
    {
        // TODO: Do some logging here
        throw new Exception("Get off my 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.

Upvotes: 1

Related Questions