Search code examples
phpipblocking

How to detect and block an ip If url contains invalid characters


I have a page which has id= in the url. Problem is this is attracting a LOT of unwanted attention from hackers trying to manipulate the url e.g. id=133+order by 1-- (sadly changing the id isn't an option)

I have the following code to get the id and strip any 'badness' out.

$ia = intval($_GET['id']);
$ib = mysql_real_escape_string($ia);
$ic = strip_tags($ib);

but what I would really like to do is ban the ip address of the user for an x amount of time. This way if their ever is a security weakness it would buy me time to detect it and fix it before the hacker (better to be safe than sorry!)

Also its unnecessary CPU usage which id like to rule out.

Does anyone know a php script which can detect and block an ip based on url manipulation for an x amount of time? Or even better anyone fancy showing a basic example of one they have already made?


Solution

  • You have a couple of choices:

    1. Implement the IP-blocking yourself in PHP by simply failing the request if the source IP is contained in some blacklist which you manage.
    2. Somehow tell your server program (Apache, IIS, ...) to block the requests before even accepting the incoming connection.
    3. Write yourself a very simple proxy that accepts your HTTP request if it doesn't originate from a black-listed IP, checks the ID for semantic validity, manages the blacklist, and forwards acceptable requests to your actual webserver.

    Option 1 is fairly straight forward: Maintain a blacklist, check incoming requests against it, and fail them as needed. You can find more info, including a simple code example here: http://perishablepress.com/how-to-block-ip-addresses-with-php/

    The problem with option 1 is that it doesn't really save you any CPU load and is probably even more involved computationally than DaveRandom's suggestion of simply parsing the ID and validating it instead of the source IP.

    Option 2, unfortunately, will depend heavily on the server infrastructure that you are using and in most cases, won't be easily implemented. For this to work, you might have to find a way to modify the server's config files in PHP and then somehow get the server to reread these files. I haven't looked into how to implement this with Apache or IIS, but for Google AppEngine, I know that this is not possible with the current API.

    Option 3 will involve quite a bit of coding (unless you can find a prefab solution somewhere) but should probably be the most flexible solution.

    I am not sure, but, depending on the server you use, it might even be possible to implement a hybrid between option 2 and 3, if your server provides a hook that you can use to check incoming requests before processing them further.