Terence Eden. He has a beard and is smiling.
Theme Switcher:

Blunt Banhammer Blocks Basic Bots Ballistically

· 32 comments · 1,350 words · Viewed ~9,082 times

🄯 CC BY-SADigital Object Identifier10.59350/bwbef-dkh55


I cut bot traffic to my site by over 80% with a simple trap.

Last month, my hobby website OpenBenches.org transferred more than 2.5TB of data to visitors. As much as I'd like to think the site is enormously popular, it looks like it is just AI bots endlessly crawling the data and slurping up the images.

So I've built B6 to be an indiscriminate tool to eradicate these unwanted parasites.

It is very loosely inspired by Jeff Starr's Blackhole, but works even on sites with heavy caching.

Here's the high level description of how it works.

  • Create a directory like /honeypot/ on your site
  • Put some code in index.php within the directory
  • Add the honeypot as an explicit "Disallow" in robots.txt
  • Include a hidden link to to the honeypot on every page of your site
  • If something accesses that page, write its IP address to your .htaccess
  • The .htaccess bans the IP address from ever accessing your site again.

This blog post shows you how you can build this yourself and discusses some of the problems it might cause.

Bad Robots!

The file robots.txt lives at the root of your website. It contains a list of instructions to automated web crawlers. Respectful bots will read it and refuse to look at specific parts of your site.

Add these two lines to it:

Copied to 📋
 User-agent: *
Disallow: /honeypot/

That says bots shouldn't visit any page in the honeypot directory.

Bots generally check for updates every 24 hours, so either wait a day or manually submit it to major crawlers.

.htaccess

The .htaccess file contains a list of instructions for how your server should process requests.

Find the bit of your .htaccess file which looks like this:

Copied to 📋
 <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

Edit it to look like this:

Copied to 📋
 <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

### BLOCKED IPs
    #   TEST-NET-1
    RewriteCond %{REMOTE_ADDR} "=192.0.2.1"
    RewriteRule ^ - [R=402,L]
### /BLOCKED IPs

It is important that these rules come before any other rewrite rules.

Change the end of this IfModule to look like:

Copied to 📋
 </IfModule>

ErrorDocument 402 "Payment Required - Access Denied."

If an IP address is in the blocked IP list, the server will send an error code and a readable message. You can add whatever plain text you like here.

Wipe Them All Out

Inside the honeypot directory, create a file called index.php (or whatever you like). When this page is visited, it grabs the visitor's IP address and the name of its User Agent. It then places them in the BLOCKED IPs section.

Copied PHP to 📋
 PHP//  What's their IP?
$IP = get_client_ip();

//  User Agent
$UA = isset( $_SERVER["HTTP_USER_AGENT"] ) ? $_SERVER["HTTP_USER_AGENT"] : "";

//  Get the existing .htaccess file.
$htaccess_file = "../.htaccess";
$htaccess = file_get_contents( $htaccess_file );

//  Split by newline.
$htaccess_lines = explode( separator: "\n", string: $htaccess );

//  Where's our start block?
$start = "###   BLOCKED IPs";
$end   = "###   /BLOCKED IPs";

//  Exit if the .htaccess doesn't have the block.
if ( !in_array( needle: $start, haystack: $htaccess_lines ) ) { die(); }

//  This is where to start from.
$start_block = array_search( needle: $start, haystack: $htaccess_lines );

//  Add the line after the start block.
//  Include a date.
$htaccess_lines[ $start_block ] = $start . "\n" . 
    "\t#\t" . date( "c" ) . "\t{$UA}\n" . 
    "\tRewriteCond %{REMOTE_ADDR} \"={$IP}\" [OR]";

//  Turn the array back to a string.
$newHtaccess = implode( separator: "\n", array: $htaccess_lines );

//  Save the new .htaccess file.
file_put_contents( filename: $htaccess_file, data: $newHtaccess );

function get_client_ip():string
{
    //  Adapted from https://github.com/ibericode/koko-analytics/blob/main/src/Resources/functions/collect.php

    //  X-Forwarded-For sometimes contains a comma-separated list of IP addresses
    //  @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
    $ips = empty( $_SERVER["HTTP_X_FORWARDED_FOR"] ) ?
        [] :
        \array_map( "trim", \explode( ",", $_SERVER["HTTP_X_FORWARDED_FOR"] ) );

    //  Always add REMOTE_ADDR and HTTP_CLIENT_IP to list of ip addresses, if set
    foreach ( ["REMOTE_ADDR", "HTTP_CLIENT_IP"] as $key ) {
        if ( !empty( $_SERVER[$key] ) ) {
            $ips[] = $_SERVER[$key];
        }
    }

    //  Return first valid IP address from list
    foreach ( $ips as $ip ) {
        if ( \filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
            return $ip;
        }
    }

    return "";
}

Setting The Trap

Web crawlers look at a page, find every link on it, then visit those links. So we need to put a link to the honeypot on every page - but in such a way that normal users will not find it or click it.

This adds a link, removes it from the accessibility tree, and gives it impossible to click text (a zero width joiner).

Copied HTML to 📋
 HTML<a id="honey" aria-hidden="true" href="/honeypot/index.php">‍</a>

This CSS hides it from normal viewers and removes the mouse cursor from view.

Copied CSS to 📋
 CSS#honey {
    display: none !important;
    cursor:  none !important;
}

Problems This Might Cause

It's unlikely that a human will find the link, click on it, and be banned. But if they do, consider put a message in the blocking text telling them how they can get unblocked.

Some useful bots ignore robots.txt. If they identify themselves via a User-Agent string (and they should) you can manually remove them from .htaccess. You could also code in an allow list exemption for them. But, of course, many bad bots lie about who they really are.

Conversely, not all bots crawl every link. This won't catch bots which respect robots.txt but are nevertheless problematic.

If you have thousands of different bots blocked, the performance of your server might slow down while .htaccess is parsed. There's weak anecdotal evidence that it adds a slight overhead. But, personally, I don't think that's worth worrying about.

Bots often use hijacked IP addresses. After the bot has moved, an innocent party might be blocked from your site. Each block has a timestamp associated with it. You could periodically unblock older entries.

Bots rotate through hundreds of different IP addresses. So the same bot might get blocked multiple times.

Bots might see the CSS marks the link as hidden and refuse to follow it. Instead of CSS, you could use invisible spaces or other characters which would be hard for a human to see but appear visible to a bot.

Similarly, a smart bot might refuse to visit a path called /honeypot/ so choose a better name for it. A smarter bot would see that touching the honeypot leads to a ban - so perhaps a selection of traps are needed?

As is implied in the name, this is a blunt banhammer. It doesn't give a warning, nor does it look at User-Agent, Country, or any other signal. You touch the honeypot and you receive an instaban. No warning and no automated way to appeal.

Alternatives

There are alternative ways to do this. Some bots don't send language headers, some use older versions of HTTP, they often have severely outdated User Agent strings. Those are all reasonable ways to block something which is probably a bot. There are likely to be a few false positives though.

But B6 has no false positives. A normal user can't follow the link to the trap and a well-behaved bot won't follow the link.

Things like Anubis require a lot of work to set up and annoy normal users. B6 doesn't require a specific hosting environment and is never shown to normal users.

It Works!

Since running B6 a week ago, I've blocked over 400 IP addresses and seen a significant fall in traffic. I've not had any complaints yet. Sadly, none of the bots have paid to remove the paywall!

Drop from 216GB to 26GB per day.

At peak, my site was seeing 216GB of data transfer per day. That's now dropped to around 25GB.

I don't claim this is the most sophisticated bot blocker in existence - but I enjoyed building it myself. I'll probably add something to records the geolocation of the IP and maybe remove any block older than a certain age.

If you'd like to use it or improve this code, I'd be grateful if you treated it as AGPL v3 licensed.


Share this post on…

32 thoughts on “Blunt Banhammer Blocks Basic Bots Ballistically”

  1. IIS / C# version. Here I'm just dumping the bad IP addresses in a txt file. The IIS process doesn't have write access to the config that actually blocks them, so there's a separate process that runs a powershell script every 5 minutes and checks the blockfile.

    using System;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Web;
    
    namespace Root
    {
        /// Summary description for badbot
    
    public class badbot : IHttpHandler
    {
    
        public void ProcessRequest(HttpContext context)
        {
            string ipAddress = GetClientIpAddress(context.Request);
    
            if (!String.IsNullOrEmpty(ipAddress))
            {
                string path = context.Server.MapPath("~/App_Data");
    
                Directory.CreateDirectory(path);
    
                string filename = Path.Combine(path, "badbots.txt");
    
                lock (typeof(badbot))
                {
                    File.AppendAllText(filename, $"{ipAddress}{Environment.NewLine}");
                }
    
                context.Response.ContentType = "text/plain";
                context.Response.Write("This page is mentioned only from robots.txt telling you not to be here. The only way you could get here is if you read robots.txt telling robots not to go here, and deliberately ignored it. So now your IP address is going to be blocked. If you are a human, that was silly of you.");
            }
        }
    
        public static string GetClientIpAddress(HttpRequest request)
        {
            // AWS ALB, nginx, ARR, etc.
            string xForwardedFor = request.Headers["X-Forwarded-For"];
    
            if (!string.IsNullOrWhiteSpace(xForwardedFor))
            {
                string firstIp = xForwardedFor
                    .Split(',')
                    .Select(ip =&gt; ip.Trim())
                    .FirstOrDefault();
    
                if (IPAddress.TryParse(firstIp, out _))
                {
                    return firstIp;
                }
            }
    
            // Cloudflare (if you ever adopt it)
            string cloudflareIp = request.Headers["CF-Connecting-IP"];
    
            if (!string.IsNullOrWhiteSpace(cloudflareIp) &amp;&amp;
                IPAddress.TryParse(cloudflareIp, out _))
            {
                return cloudflareIp;
            }
    
            // Direct IIS connection
            string userHostAddress = request.UserHostAddress;
    
            if (!string.IsNullOrWhiteSpace(userHostAddress) &amp;&amp;
                IPAddress.TryParse(userHostAddress, out _))
            {
                return userHostAddress;
            }
    
            return null;
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    }
    

    powershell:

    function ban-badbots
    {
        $existingIps = [System.Collections.Generic.HashSet[string]]::new(
            [System.StringComparer]::OrdinalIgnoreCase
        )
    
    Get-WebConfiguration -Filter "/system.webServer/security/ipSecurity/add" |
    ForEach-Object {
        if ($_.ipAddress)
        {
            [void]$existingIps.Add($_.ipAddress)
        }
    }
    
    foreach ($customerFolder in (Get-ChildItem -Path $installPath -Directory))
    {
        $file = Join-Path $customerFolder.FullName "Root\App_Data\badbots.txt"
    
        if (-not (Test-Path $file))
        {
            continue
        }
    
        Write-Host "Processing $file"
    
        $success = $true
        $added = 0
    
        try
        {
            foreach ($ip in (Get-Content $file))
            {
                $ip = $ip.Trim()
    
                if ([string]::IsNullOrWhiteSpace($ip))
                {
                    continue
                }
    
                $parsedIp = $null
    
                if (-not [System.Net.IPAddress]::TryParse($ip, [ref]$parsedIp))
                {
                    Write-Warning "Invalid IP '$ip'"
                    continue
                }
    
                if (-not $existingIps.Contains($ip))
                {
                    Add-WebConfiguration `
                        -Filter "/system.webServer/security/ipSecurity" `
                        -Value @{
                            ipAddress = $ip
                            allowed   = $false
                        }
    
                    [void]$existingIps.Add($ip)
    
                    $added++
    
                    Write-Host "Blocked $ip"
                }
            }
        }
        catch
        {
            $success = $false
            Write-Error $_
        }
    
        if ($success)
        {
            Remove-Item $file -Force
            Write-Host "Added $added IP addresses, deleted $file"
        }
    }
    
    Write-Host "Done."
    }
    

    Reply

  2. @Edent Nice idea, but I've got unsolicited suggestions (sorry) about your implementation.

    If I'm reading it correctly, the PHP script reads, parses and writes the whole htaccess file for every request.

    When a crawler botnet really goes to work on you, you'll be looking at hundreds of thousands of IP addresses - so a large htaccess file - with requests many times per second. That's a heck of a lot of CPU and I/O load which I'm sure you'd rather avoid. Also, if you've not done anything in your server config to prevent concurrent runs of index.php, you're quite likely to shred your htaccess file, with multiple copies of the script writing to the file at the same time.

    Before I severely reduced the scope of spigot, it was seeing upwards of 8 million hits per day - 90 hits per second - and was regularly seeing upwards of 150,000 different IP addresses in any given hour.

    You could, I think, do this out-of-band. Have a static, empty index.html and use something separate that tails your access log, maintaining the htaccess on the fly.

    An infinite maze of twisty little pages

    Reply | Reply to original comment on social.ty-penguin.org.uk

  3. My favourite thing about this implementation is that the only way for bots to not get hit by your B6 is to follow the rules you wrote elsewhere.

    The workaround is compliance. I adore this.

    Reply

  4. Nice idea. I think it could be simplified (and made faster?) by using Apache's RewriteMap feature:

    1. Have the PHP file simply append to a file with a line of the format:
    192.0.2.1 1

    (Note the 1 at the end.)

  5. In your Apache config, definite RewriteMap of type txt on that file:
  6. RewriteMap honeypot_ip_address "txt:/srv/blog/etc/honeypot_ip_address.txt"

  7. Then use that mapping in a condition — something like:
  8. RewriteCond ${honeypot_ip_address:%{REMOTE_ADDR}|0} ="1"
    RewriteRule ^ - [R=402,L]

    That way PHP isn't rewriting your main .htaccess file (and doesn't even need to have privileges to write to it, which is probably safer in case there's ever a PHP exploit, something which I hear does happen from time to time).

    Indeed, because the Apache config isn't changing, you can put this in the virtual host's config file (or one Include-ed from there) and turn off .htaccess use (with AllowOverride None). This is documented as being more efficient, because Apache has loaded all its config at start-up; it doesn't need to check the file-system for a .htaccess file on every request. Though I haven't measured how much difference it makes in practice.

    Reply

    1. One thing to add here as I am trying this out, is that the RewriteMap needs to be in the apache config, not the .htaccess file. I do note that you didn't say you could put it in the .htaccess file, but that is where I tried to put it. So just to save someone else the embarrassment 😀

      Reply

    2. You don't even need PHP to do it. In your virtual host config use

      LogFormat "%h %{honeypot}e" honeypot_logformat CustomLog "/var/www/honeypot.txt" honeypot_logformat env=honeypot SetEnvIf Request_URI "/honeypot/" honeypot=1

      to make Apache write every IP accessing /honeypot/ to an additional logfile you can use as a RewriteMap. And add E=!honeypot to your last RewriteRule so it gets only added once, e.g.

      RewriteEngine on RewriteMap honeypot "txt:/var/www/honeypot.txt" RewriteCond ${honeypot:%{REMOTE_ADDR}|0} =1 RewriteRule ^ - [F,E=!honeypot]

      Reply

      1. Hopefully better formatting:

        LogFormat "%h %{honeypot}e" honeypot_logformat
        CustomLog "/var/www/honeypot.txt" honeypot_logformat env=honeypot
        SetEnvIf Request_URI "/honeypot/" honeypot=1
        

        and

        RewriteEngine on
        RewriteMap honeypot "txt:/var/www/honeypot.txt"
        RewriteCond ${honeypot:%{REMOTE_ADDR}|0} =1
        RewriteRule ^ - [F,E=!honeypot]
        

        Reply

  9. Terence Eden's shared the honeypot he came up with to make a powerful honeypot-powered block against badly-behaved bots. I'm concerned, though: I've seen this pattern before and know that it can be used as a denial-of-service attack. Here's how I'd do it differently...

    Reply | Reply to original comment

  10. That's a pretty neat idea and implementation. What I did is I use lists from Spamhaus, etc. and update them daily and load them into the Firewall. These include AI crawler and currently that are a whooping 611M IPs Maybe I should add that too and see, if other/new IPs pop-up 😉

    Reply

  11. Off the back of yesterday's conversations about PHP-powered honeypots to IP-ban badly-behaved bots, I'd like to share the configuration I've been using to effectively protect Geohashing.site this year.

    Reply | Reply to original comment

  12. Thank you for this! Implemented on a site yesterday as despite running it through Cloudflare i was still getting a huge amount of bandwidth usage from scraper bots. Then I realised I had three additional domains parked on the origin that I had not proxied through Cloudflare and the bots were also getting direct to the IP address through them, and some MX records I was not using. All tight as a ducks behind now!

    Reply

  13. B6는 robots.txt에서 접근을 금지한 숨은 허니팟에 방문하면 해당 IP를 .htaccess에 등록해 사이트 전체 접근을 차단하는 도구임 OpenBenches.org 적용 사례에서 봇 트래픽이 80% 넘게 줄었으며, 하루 데이터 전송량은 최고 216GB에서 약 25GB로 감소함…

    Reply | Reply to original comment on news.hada.io

  14. @Edent One interesting pattern I've noticed, a lot of things try non-SSL before SSL. Here's a filter.d/ to trap them on the port 80 redirect action:

    # Excessive http -> https 301 redirects which bypass the 404 check
    # ignore: "GET / HTTP/1.1" 301
    # ignore: "GET /favicon.ico HTTP/1.1" 301
    # trap: "GET /.env HTTP/1.1" 301
    # trap: "GET /wp-admin/admin.php HTTP/1.1" 301
    [Definition]
    failregex = ^<HOST>.*"(GET|POST) /S.+" 301 .*$
    ignoreregex = (/favicon.ico|/robots.txt|security.txt)

    Reply | Reply to original comment on mstdn.social

  15. Very nice! I do recommend throwing the block data into an sqlite DB instead of writing directly to .htaccess. The DB lets you record whatever metadata you want in a way that's easy to query later, and it avoids race conditions in writing out a new .htaccess. (You can have a cron job that rewrites .htaccess every minute if the DB has been updated, or fire off an update script (with locking) on-demand by shelling out to at now ....)

    Reply

Trackbacks, Pingbacks, and Boosts

What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.

See allowed HTML elements: <a href="" title="">
<abbr title="">
<acronym title="">
<b>
<blockquote cite="">
<br>
<cite>
<code>
<del datetime="">
<em>
<i>
<img src="" alt="" title="" srcset="" width="" height="">
<p>
<pre>
<q cite="">
<s>
<strike>
<strong>

Your post must include a link to this post.

How does this work?
To respond on your own website, write a post which contains a link to this post - then enter the URl of your page here. Learn more about WebMentions.