A crafty, nommy, occassionally geeky blog-thing.

Apache Mod_rewrite Blocking Based on HTTP Request

We’ve a client with an ecommerce site that’s being hammered with SQL-Injection attempts. The code itself is sanitizing user input, but its still making database queries for each of those hits. At 10-20 mysql queries/second, sustained for over an hour, this begins to feel more like a DOS attack on the server.1

Since SQL injection involves sending the actual SQL query in the GET request, Apache can parse that string before responding to the request. Enter rewrite rules.

In our case, all of the request began with


followed by requests for various user-related columns.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{THE_REQUEST} ^.*(union).* [NC]
    RewriteRule ^(.*)$ - [F,L]

This condition looks for the string “union” anywhere in HTTP request. Upon a match, the server returns a 403 Forbidden status code.

Multiple strings can be included in that condition. Frex,

RewriteCond %{THE_REQUEST} ^.*(union|information_schema|%2C0x).* [NC]

Perishable Press has an excellent article on blacklisting visitors, based on various parts of the HTTP request.

  1. If I were trying to crack into somebody’s database, I’d pace my queries out to at least once a second. Invariably, its the hammering which brings it to our notice.