No one's getting past..

php document icon/logo @ _256 px the 'page' is only a shadow. poetic, huh. Anti-Hammer!

Automatically ban web site hammers! Protect your valuable server resources for genuine clients.

Anti-Hammer is a php script that runs before your pages do, watching. As requests arrive, Anti-Hammer checks how long it's been since that client's last  request. If a reasonable amount of time has passed, the page is served as usual. But if not, their "Hammer Count" is increased. Oh oh!

When the hammer count reaches preset levels, their hammering is suspended, and instead of the page, they get a cute message (read: warning), and must wait X amount of seconds before trying again.

The more they hammer, the longer they have to wait, incrementally. Simple.

You can even set an absolute cut-off point, beyond which they simply get a blank page, nothing, until their ban lifts (hours later).

Everything is configurable.
 

No Way Around Anti-Hammer!

Anti-Hammer uses its own php-session-like-but-better client tracking mechanism..

This works very like php sessions, except it works for ALL clients, regardless of their advertised capabilities, and works regardless of whether or not they have cookies enabled. Yes! You can even Anti-Hammer the GoogleBot! Not that you would want or need to, it's a rather well-behaved bot.

Rather than wait for some session ID to come back (that would be on the second request, you see, and we haven't even sent one yet), Anti-Hammer uses a mix of available client properties to create a unique client ID there-and-then, and from that point, recognizes the client by this ID (which is an MD5 of all that data concatenated together). It's pretty similar to the way a php_session is created, except Anti-Hammer doesn't need the browser to send anything back.

Anti-Hammer's storage mechanism (a serialized array in a flat file) is the same as a php session, too. And like a php session, it is anonymous; aside from the hammer time info, we store no other data server-side.

Unless you want that..

Anti-Hammer also comes with a mechanism to allow  certain bots and other friendly spidering entities (matching specific criteria, including a known IP address/range), usually search engine spiders, to pass clean through Anti-Hammer, if required, or alternatively, allow them a faster hammer rate.

Did I mention everything is configurable?
 

Test it!

If you really must, you can test it here at corz.org (yes, of course it's running here!), preferably some low content page, like the..

Anti-Hammer Test Page

 

Quick-Start Guide:

 

Ensure your server is running at least PHP5.1!

Unzip the Anti-Hammer package..

And drop anti-hammer.php and the anti-hammer directory into your site somewhere together, maybe inside /includes/ or /inc/ or something like that.
 

Make the anti-hammer/ directory writable..

If you run php as a cgi/*suexec, you can probably get off with doing nothing, so long as the directory is owned by your user account. For everyone else, the easiest method is probably via ftp, simply set all its permissions to world-writable (777). Or else in a shell..
chmod -R 777 /path/to/anti-hammer
 
NOTE: There is nothing inherently insecure about having a writeable directory, even a world-writeable directory. And for the paranoid, there are plenty of .htaccess tricks to ease your mind.

Also note: Technically, you only need to make the lists/ and sessions/ directories writeable, but doing the whole lot is just fine, too.
 

Set your Anti-Hammer preferences..

That's inside anti-hammer.php, in a decent text editor, by which I mean with syntax highlighting, like these are.
 

Setup php auto_prepend..

Anti-Hammer needs to run as a php "auto-prepend", so it runs before your pages do. To achieve this magic, add the following command to your site's main (root) .htaccess file..

php_value auto_prepend_file "/full/real/server/path/to/anti-hammer.php"

..replacing the path with the actual path, of course. If php runs as cgi/*suexec on your site, or you have global control, do this in your site's global/local php.ini, instead ..

auto_prepend_file = "/full/real/server/path/to/anti-hammer.php"

NOTE: You need to use the FULL, REAL path on the server. If you site is in /var/www/vhosts/mydomain.com/httpdocs/ then you need to add ALL that. Run a phpinfo(); command on your site to discover the path to your web site (aka. "DOCUMENT_ROOT").

If that sounds too complex, or you just prefer better, more interesting methods, grab (and use) debug-report.zip, from here..

 

You're done!

Once the auto_prepend is in place, before any php file on your site is served to a client (web browser, spider, bot, any client), Anti-Hammer runs, interrogating the client's hammer status, and acting accordingly, either passing control directly back to the requested page, or halting the request in its tracks, with a terse warning.

To test all this, simply install Anti-Hammer and load your front page, refresh it repeatedly, over and over like bots do, quickly. Careful now! You will get banned!

 

exemptions.ini
(allowing certain known clients special privileges)

The big advantage of preventing bots (and people!) from clobbering your website and overloading your server, is that you have more resources freed up for valid clients..

If you want, you can choose to allow certain clients (usually known friendly spiders and bots) to bypass Anti-Hammer altogether, or alternatively, hammer at a faster rate. If you do, you will be utilizing exemptions.ini.

exemptions.ini, which lives in the exemptions/ directory (along with the IP lists), is a standard plain text .ini file containing a list of pairs of known User Agent strings and the text file in which to find their IP/Mask information.

Here's a slightly chopped-down example version..
 
	[exemptions]

	Mozilla/5.0 (compatible; Googlebot=google.txt
	Googlebot=google.txt
	gsa-crawler (Enterprise; S4-E9LJ2B82FJJAA=google.txt

	msnbot=msn.txt
	MSNBOT=msn.txt
	Mozilla/4.0 (compatible; MSIE 6.0; Windows NT; MS Search=msn.txt

	Scooter/3.3Y!CrawlX=altavista.txt

	Scooter=inktomi.txt
	Yahoo=inktomi.txt
	slurp=inktomi.txt

	Excite=excite.txt
	Infoseek=infoseek.txt

	Lycos_Spider=lycos.txt

	NorthernLight=northernlight.txt

	Mozilla/2.0 (compatible; Ask=askjeeves.txt
	teoma_agent1=askjeeves.txt
 

How exemptions.ini works..

On the left  (of the "=" sign), is the expected User Agent string. This can be a partial match, but it must match from the very first character of the client's user agent string. Ideally, you want to roll as many variations as possible into a single line, without being so generic as to pull in every client under the Sun and create needless processing overhead (certain Yahoo! and msn bots post only "Mozilla/4.0", for example. They can meet the Anti-Hammer like everyone else!), but still retain enough information to positively identify a particular client.

For example, the string "Yahoo" will match all  the following bots:
Yahoo! Mindset
Yahoo-Blogs/v3.9 (compatible; Mozilla 4.0; MSIE 5.5; http://help.yahoo.com/help/us/ysearch/crawling/crawling-02.html )
Yahoo-MMAudVid/1.0 (mms dash mmaudvidcrawler dash support at yahoo dash inc dot com)
Yahoo-MMCrawler/3.x (mms dash mmcrawler dash support at yahoo dash inc dot com)
YahooFeedSeeker/1.0 (compatible; Mozilla 4.0; MSIE 5.5; my.yahoo.com/s/publishers.html)
YahooSeeker-Testing/v3.9 (compatible; Mozilla 4.0; MSIE 5.5; http://search.yahoo.com/)
YahooSeeker/1.1 (compatible; Mozilla 4.0; MSIE 5.5; http://help.yahoo.com/help/us/shop/merchant/)
YahooSeeker/1.2 (compatible; Mozilla 4.0; MSIE 5.5; yahooseeker at yahoo-inc dot com ; http://help.yahoo.com/help/us/shop/merchant/)
YahooSeeker/CafeKelsa-dev (compatible; Konqueror/3.2; FreeBSD ;cafekelsa-dev-webmaster@yahoo-inc.com ) (KHTML, like Gecko)
YahooVideoSearch www.yahoo.com/
YahooYSMcm/2.0.0
 
Similarly, many Googlebots are matched against the simple word, "Googlebot". If your user agent string is a tad generic, and matches against a client that isn't  the expected bot, it's not a problem; Anti-Hammer won't find them in the specified IP list and continues as normal. It's designed this way to catch clients pretending to be known bots, of which there are a surprising number.

NOTE: User agent strings are checked in order, and ini file processing halts as soon as a match is found. Note the two "Scooter" entries; if the Yahoo! version was before the AltaVista version, the AltaVista bot would never be allowed an exemption, as Anti-Hammer would always be looking inside inktomi.txt for its IP information.

NOTE: Matches are CaSe SeNsITiVE! If you want to match "msnbot" and "MSNBOT", you need two entries. Why? Because in tests, a case-insensitive match is at least three times slower than a Case Sensitive match. So make a second entry!
 
On the right, is the text file to look at for IP Mask information; where the specified user agent is expected to be making requests FROM. It's the standard Spider IP list format, one IP/Mask per line, as found here..
http://www.iplists.com/
http://www.iplists.com/nw/ <- updated, reorganised, with msnbot & more.

A blog URI is listed on that page, where updates are posted (maybe two or three times a year).
I've included the most recent lists in the Anti-Hammer zip package (and have started to add to and improve them with updated information), in place and ready-to-go, along with an exemptions.ini file already setup to handle the major friendly spiders.

Remember, you don't need to add all the bots, or even any bots; only bots, spiders, and other clients that you wish to give special privileges to. Even they shouldn't be hammering, really!

If you wish to set a special rate for known clients, rather than allow them to simply bypass Anti-Hammer, all you do is switch the "true" in your allow_bots preference (which can be considered "infinite hammer_time"), for a integer (aka. plain number) representing 1/100th Second, just like the regular hammer_time preference, e.g..

$anti_hammer['allow_bots'] = 50;

A value of 50 would enable two-hits-per-second spidering, but nothing faster, which is half the normal hammer_time of one second ($anti_hammer['hammer_time'] = 100;).

Effectively we have two available hammer rates; one for known good clients, and one for everyone else.
 

I, Admin.

While I'm here I should add, there's also the facility to enable one correctly configured browser to bypass Anti-Hammer at all times. This is designed for busy webmasters who sometimes, in the course of their daily activities, will need to hammer their own site. I know I do!

This, setting ("admin_agent_string"), along with many other settings, can be found in the preferences section inside anti-hammer.php. Essentially, you tag a unique string onto the end of your browser's User Agent string (perhaps with user-agent-switcher), so that Anti-Hammer can recognize you as you. It's not high-security, but it is handy. I've used a similar approach to avoid logging my own hits for years.
 

Caveats:

One-Way Sessions..

Not requiring that the client send back the ID, potentially has one undesirable side-effect..

If two clients share the same IP (perhaps a proxy) and are using a perfecty identical browsers (in every way, down to the user's locale), and are browsing your site at the exact same time, and view a page within one second of each other (or whatever you set the hammer_time to), it is possible that they may unwittingly increment each other's hammer count!

Clearly this would be a rare situation, but still, good to know.

 

Source Code & Download..


You can view the php source code here..


image of php document icon, transparent
 

And download a ready-to-go zip package, right here..


image of php zip package (basically a cardboard box with some writing on it, to let you know it;s php in there
 

Thank You!

If you want to show your appreciation, you can do that here..

 

Bye Now!

If you have any problems at all, installing or using Anti-Hammer, PLEASE DO leave a comment below, or contact me some other way, let me know about it, so I can fix it, ta.

Have fun!

;o) Cor

 
 
cbparser powered comments..

cor - 30.10.09 5:29 pm

Hopefully this marks the beginning of a new trend; each of my "wee scripts" deserves a page of its own, with usage instructions, comments and all that. So here we are.

Have fun!

;o) Cor


astro - 05.12.09 12:56 am

I am attempting to install this, but whenI add the php_value line to my htaccess, I get 500 errors on my site
i have set permissions for hte php file, and have verified the path info, does something need to be set in the server PHP.ini file? I would need to contact the host and ask them to set that if so.

It sounds like your server runs some kind of php suexec (where php runs as a cgi). If that's so, you would need to add the directive into a local or global php.ini file, instead of .htaccess.

The format is slightly different, see any php.ini file for specifics. This devblog entry explains the difference between regular and cgi flavours of php, and demonstrates how to add your php_value type statements with full examples. ;o) Cor



Laurent - 14.12.09 5:23 pm

Sorry, I normally speak French,

Thank you for the valuable advice, read over your website: the more I find interesting.
I am still a child before rewriting in PHP.
May I thank you very much all your explanations!

Laurent - Geneva - Switzerland


Don - 22.12.09 5:46 pm

Your website was recommended over on the forums at phpfreaks.com and I've alreayd bookmarked a half dozen pages. Awesome stuff here!!


Miauw - 16.01.10 5:25 pm

Can't get it to work. No error is shown, it just doesn't work; I can hold refresh and nothing happens. Rechecked the paths 100 times and seems to be all correct.

Run the file directly, to check you haven't messed it up editing your prefs. You should see a nice message telling you how to install anti-hammer. ;o) Cor



Katica - 20.01.10 10:10 am

Your site is very interesting. Tried out anti-hammer, but get the same problem as Miauw. Checked the path 100 times. I've created the folder for the log, made it writtable, no log is created. Tried to rewrite anti-hammer.php as it just output a sentence, nothing happenned, seems that auto-pretend is not working at all.
Any idea or advice? Thanks is advance.

auto_prepend_file is perhaps disabled - speak to the server admins. ;o) Cor



Matt Lewandowsky - 30.01.10 12:28 am

This script looks interesting, but before I even think about trying it, I'm curious what its impact may be on a fancy, heavy "Web 2.0" site which can potentially have a few hundred objects on a single page. Normal users in such a case can easily end up requesting a few hundred objects every few seconds, if someone keeps clicking (for example) "Next Page" and their browser's cache is somehow broken, causing every image to be re-requested.

Also, have you tested this method with non-Apache servers, particularly those which use FastCGI PHP? I've got sites running with PHP-FPM, so I'd be curious to know if you've actually tried it with a custom per-instance php.ini.

There hasn't been any testing, akaik, on non-Apache servers; that's why I make stuff all pretty for release; so YOU can test it! I don't foresee any problems.

For pages with lots of "generated objects", so long as you setup your skip preferences correctly anti-hammer will rapidly ignore these, and requests for regular images and such aren't affected by anti-hammer, anyway.

;o) Cor



cor - 15.03.10 3:38 am

If you can't get anti-hammer to work, and want me to help, you will need to provide more information. Lots more. Also, you will need to enable php error reporting of some kind, so you can see the what the error is. Once you know that, you may not need help.

NOTE: You need PHP5 to run anti-hammer. At least, to run it without some hacking, you will.

Matt, one of the reasons I made stuff available is so that YOU can tell ME exactly these sorts of things! I'm rarely on other servers these days.

Why not download it and check out the prefs section. You can specify which kinds of resources are affected by anti-hammer (images and such are not affected), which are ignored, and more; maybe give it a whirl on your test server.

;o) Cor


oussamaDZ - 11.05.10 6:28 am

Thanks smiley for :D


unkown

Tweaked my own prefs in, installed and everything works fine :-)
Lately I've been pinged a BIG time with whatnots and this kills practically all of it.
I'm a VERY happy chap :-D

A question - how big the .ht_hammer can grow? Before there are some effects, that is...

Great "add-on" even to a Joomla site, I suppose it's ok to direct people here with a link (?). I'm sure quite a few people could use this one.

A HUGE thank you, mate.

Inward links from original sites are always welcome. Anti-hammer's log file has no limit, other than the space available; it doesn't mind. My site's logger has a clean-up facility which archives my logs at a particular size. If requested, I could look at putting something similar together an add-on for anti-hammer; automatic clean-up. ;o) Cor



moogy - 16.08.10 7:24 am

If it doesn't work for you...

And your error logs don't show anything (you have enabled error logging, right?), try using php.ini rather than .htaccess and check the logs again. Also make sure the anti-hammer directory is writeable..

Only about one other person in the world visits my site regularly, but this'll keep 'em in line for sure. Thanks cor, this is awesome


proxylist.co - 31.08.10 7:16 pm

This is exactly what I'm looking for the proxylist.co proxy list site.

Many thanks!


hecker - 23.01.11 2:23 pm

I got anti-hammer to work just fine. Thanks for that! But I am uncomfortable setting permissions in the directory it is in to 777, which is the only way the code will run.

I therefore tried to put the directory above the root, but that didn't work.

Having a directory below the root that is set to 777 is risky. I wonder if there is a way to avoid this situation.

My PHP runs as DSO API.


The directory anti-hammer runs from does NOT need to be chmod 777, only the directory where the temporary anonymous sessions are kept.

ps. I'd love you to explain exactly how having a deirectory below the root set to 777 is risky. ;o) Cor



Tim - 14.02.11 4:10 pm

Great script, but I have a slight issue with it. When the site pushes out a temporary redirect header (e.g. to proceed after submitting a form, or for example, to jump out to the admin login form), it appears to trigger immediately.

Any quick way to resolve this?

EDIT : (it just did it when submitting this comment form on your site too)

Highly unlikely! Anti-hammer only triggers at the preset levels. If you are almost at trigger point, then it is an easy thing to trigger the anti-hammer mechanism. Simply adjust the levels to suit your needs. ;o) Cor



KKolya - 16.02.11 12:04 am

Same problem as others have reported above: php_value auto_prepend_file simply doesn't seem to work here, despite htaccess working in general.

auto_prepend_file is sometimes disabled at the server (httpd.conf) level, and there's not a lot you can do about it except ask the admins to enable it. If you explain what it is for; anti-hammer; they will probably agree; it's in their best interests. Also see my earlier posts, above. ;o) Cor



Barry - 10.09.11 6:11 am

I think we all should donate at least $1 (more if you can)


I have been coming to this site for about a year now for the best .htaccess tutorial on the web - period. Tonight I was doing the same when I came across the anti-hammer link. I have just downloaded it, so I can only anticipate the benefits to my Easy Profit Bot Review Website,
but I already owe you a debt of gratitude for the countless hours of frustration that I did NOT have to suffer once I found your .htaccess tutorial.

I am donating $1 right now. I think everyone that sees this comment should also, more if you can spare the change!

We all know that this site is worth much, much more. Collectively, lets show our appreciation thru donation, so this site can continue to provide the priceless value that it has to me, to you and to everyone of our visitors that had an enriched user experience because of the tips and hints we found on corz.org.

I guess, what I mean is, "Thanks! Here's a hundred pennies for your thoughts!"

Thanks for your kind words. I really do wish everyone would follow your advice, for so many reasons! Good luck with your project(s)! ;o) Cor



MadeUpName - 17.10.11 5:01 pm

My host deactivated my website multiple times due to spam bots. This script saved it! Very powerful and efficient. Thanks
Does the script allow Bing bots?

It can allow whatever bots you like, see inside ./anti-hammer/exemptions/ ;o) Cor



CasperX - 01.11.11 5:16 pm

I have an error in my file
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at X:*****\******\anti-hammer\anti-hammer.php:1) in X:*****\******\index.php on line 2
please tell me how to fix this error? smiley for :erm:

These sorts of errors are common for new php coders. You probably have a white space somewhere it shouldn't be (maybe altering anti-hammer's preferences), or somehting like that (Google: php "headers already sent" for lots of information about this error.

You also might want to consider using output buffering (ob_start();) at the beginning of your scripts. ;o) Cor



Mickey - 03.11.11 3:25 pm

I've gotten this to work with WordPress, but I'm having a problem getting it to work with Joomla. Does anyone know of any settings that need to be adjusted for this to work with Joomla? Any settings with the anti-hammer.php file? smiley for :roll:

I have no idea, but if you let us know the kind of error(s) you are getting, someone might.

[edit]I just installed anti-hammer at my son's Joomla site, works great.

As for yours, if something isn't working your php error log should be your fist port of call.[/edit]

;o) Cor



Max - 14.03.12 9:30 pm

If you wanted to block the 777 from others you could just make it so only your servers ip can access the file.

That is what the .htaccess file in that directory is for.


Now as a question I have is do you have an updated ip list the one thing im scared of is this thread is somewhat old and I do not want my search engine ranking to go down because certain bots cannot access it.

Old? Seriously? smiley for :lol: You are a funny one!

At any rate, it is your responsibility to keep your own exemptions up to date. See the links provided (above). They don't change much.

Also note: good spiders will NOT hammer your site in the first place, so your "ranking" cannot be affected. Want proof? Google: Anti-Hammer.

;o) Cor



Leo - 20.04.12 4:44 pm

Hi, Cor.

The content of your site is really amazing. It's a powerful reference.

Yesterday, I was refreshing the Anti-Hammer Test Page (http://corz.org/hammer-test.php) to test it. After some (a lot!) clicks, I received a 503 HTTP error. I thought "Dude! I broke the site! Sh*t!". But then I came back to reality and realized this could be another protection.

Using an online proxy service, I could reach your site again. But without it, I was still seeing the 503 HTTP error.

The question is: this 503 HTTP error page is an Anti-Hammer feature or another security resource you use?

Thanks in advance for the answer and thanks for sharing your rich knowledge.

Best regards,
Leo.

I'm actually working on Anti-Hammer right now, adding many new features. A 503 ("503 Service Temporarily Unavailable") response is the standard response Anti-Hammer sends when you activate its protections. The idea being, if you back off, the service will become available again. After 50 violations (configurable) the ban is permenent (well, 24 hours at corz.org. Again, configurable)

The latest version (currently running at corz.org) will also send 501 and 403 responses, depending on the kind of violation encountered. Anti-Hammer can now protect referer spam (via black & white lists as well as by direct interrogation of referring pages), deny script-kiddie and h4x0r requests, bad IPs, user agents and more.

Download coming soon. More testing and documentation still required!

;o) Cor



 

Leave a comment, become part of this site!


First, confirm that you are human by entering the code you see..

(if you find it difficult to read, refresh the page for a new code)


gd verification image

 
 
 
 
Machine Translations
Simplified Chinese translation of this page Deutsch translation of this page French translation of this page German translation of this page Italian translation of this page Japanese translation of this page Korean translation of this page Portuguese translation of this page Polish translation of this page Spanish translation of this page World translation of this page
 
NOTE: This Will Mangle Technical Output (e.g. scripts).
 
Bitcoin logo 16px  Get FREE Bitcoins, every day!