DownloadRawTest

contents

  1. <?php /* --- ۞---> text { encoding:utf-8;bom:no;linebreaks:unix;tabs:4sp; } */
  2. /* direct access -> \/ */ $anti_hammer_version = '0.9.9.1';
  3. if (realpath($_SERVER['SCRIPT_FILENAME']) == realpath(__FILE__)) { die(direct()); }
  4. // find: (.*)//distro(\t)?(.*)\n //distro
  5. // replace: \3\n //distro
  6. /*
  7. Anti-Hammer Pro
  8. Automatically set temporary bans for web site hammering.
  9. Interrogate Referers and protect your site against Referer Spam.
  10. Deny h4x0r requests to sensitive resources.
  11. Protect your valuable server resources for genuine clients.
  12. Full details here..
  13. https://corz.org/server/tools/anti-hammer/
  14. Have fun!
  15. ;o)
  16. (c) 2007->tomorrow! corz.org
  17. NOTE: This needs php >= v5.1 to work.
  18. */
  19. //*> prefs..
  20. /*
  21. File Types
  22. [default: $anti_hammer['types'] = 'php,html';]
  23. Which file types (extensions) to protect with the anti-hammer?
  24. We only want to count hits on the main pages, not associated files, css,
  25. Javascript includes, and such (if they are generated by php), as many of
  26. these will normally be requested within milliseconds of the initial page hit.
  27. If we run the anti-hammer indiscriminately, such files, would automatically
  28. count towards hammering, and folk would probably be penalized on their first
  29. visit. If you don't use php to generate other (non - .php) files, the
  30. anti-hammer won't be running anyway - it only runs before php scripts, as
  31. it's designed to protect server resources, not bandwidth; basic requests get
  32. spat out without any real processing power or memory usage.
  33. These list items matches the extension of the *actual* physical script file,
  34. regardless of the requested URI, so for example, these..
  35. http://mysite.com/ (assuming something.php is your default index)
  36. http://mysite.com/index.php
  37. http://mysite.com/foo.php?page=bar.htm
  38. http://mysite.com/genny.php?image=img1.jpg
  39. .. would *all* match 'php'. Other extensions are fine, so long as they are
  40. parsed by php on your setup. Separate entries with commas, and put the whole
  41. thing in quotes..
  42. Extensionless files are not supported.
  43. */
  44. $anti_hammer['types'] = 'php,html';
  45. /*
  46. Generated Extensions
  47. [default: $anti_hammer['gen_types'] = 'jpg,png';]
  48. This is an list of (usually) image extensions which you serve via php. As
  49. there may be many of these on a single page, we want to skip these, too.
  50. These list items match the extension of the *request*, regardless of the
  51. physical script file generating the output. Links such as..
  52. http://mysite.com/gen.php?image=foo.jpg
  53. http://mysite.com/png-pusher.html/foo.jpg
  54. .. would match "jpg".
  55. Separate entries with commas and put the whole thing in quotes..
  56. */
  57. $anti_hammer['gen_types'] = 'jpg,png';
  58. /*
  59. NOTES:
  60. The file type *generating* these url's MUST be included in your
  61. $anti_hammer['types'] (above), presumably. 'php'.
  62. You could also use the above preference to skip other (non-image)
  63. generated types, if you have such things onsite.
  64. */
  65. /*
  66. Skip certain files and folders..
  67. aka, basic "Ignore"..
  68. [default: $anti_hammer['skip'] = '/chat/,/foobar/members,rdf.php,/blog/rss.php';]
  69. A list of areas/folders and specific files you DON'T want the
  70. anti-hammer to cover. Enter the full path (from site root) to each
  71. file/folder.
  72. You can also skip ALL the instances of "rss.php", etc. on your entire
  73. site by using only the file name, e.g..
  74. $anti_hammer['skip'] = 'rdf.php,rss.php';
  75. This also works for folder. Using the full path enables you to target
  76. specific files and folders, using only the name gives you blanket
  77. coverage. Your call.
  78. Basically, if your string is contained anywhere within the requested
  79. URI (including the query string), the script returns control to your
  80. page immediately, bypassing Anti-Hammer.
  81. Do put commas *between* entries.
  82. */
  83. $anti_hammer['skip'] = 'css-init.php,?ajax=true&,/chat/,/corz/ampsig/amp.php,/foobar/members,/blog/rdf.php,/blog/rss.php,/devblog/rss.php,/devblog/rdf.php,hotlink.php';//distro $anti_hammer['skip'] = '/chat/,/foobar/members,rdf.php,/blog/rss.php';
  84. // similarly, you can set some POST variables that, when encountered, will cause
  85. // Anti-Hammer to skip processing.
  86. //
  87. $anti_hammer['skip_post'] = 'ajax';//distro $anti_hammer['skip_post'] = 'ajax-post';
  88. /*
  89. RSS feeds are a good example of a file to skip (assuming they are
  90. php-generated). Firefox, for example, will often grab all the feeds on a
  91. page at-once, quickly notching up a user's hammer count.
  92. */
  93. /*
  94. Hammer Time!
  95. [default: $anti_hammer['hammer_time'] = 99;] (just under one second)
  96. If they make two requests within this time, the counter increases by one.
  97. The faster and more capable your server, the lower this setting can be.
  98. The higher you set this, the more likely they are to get a warning.
  99. 100 is a reasonable setting for a fast server, enabling one-hit-per-second
  100. spidering, but penalizing anything faster. If your site has a lot of "power
  101. users", perhaps 75, even 50.
  102. Enter an integer, representing 100th/s..
  103. */
  104. $anti_hammer['hammer_time'] = 25;
  105. /*
  106. Trigger levels.
  107. [default: $anti_hammer['trigger_levels'] = '5,10,20,30';]
  108. Enter the number of violations that will trigger each of the four levels..
  109. i.e. At the default settings, they get their first warning after five
  110. violations (with a ban time of three seconds, set below). The time penalty
  111. increases after ten and twenty violations, up to the maximum level of 30
  112. violations (which imposes the maximum ban time of 20 seconds). You can set
  113. the actual times in the next preference, "waiting_times".
  114. Specify four integer values for the four triggers, separated by commas, put
  115. the whole thing in quotes.
  116. */
  117. $anti_hammer['trigger_levels'] = '10,15,25,50';//distro $anti_hammer['trigger_levels'] = '5,10,20,30';
  118. /*
  119. Ban Times.
  120. [default: $anti_hammer['waiting_times'] = '3,5,10,20';]
  121. This list sets the individual times that offenders will be 'banned' for.
  122. They will have to wait *this* long before they can try again.
  123. Each of the four setting corresponds to one of the above trigger_levels.
  124. Specify four integer values, separated by commas, whole thing in quotes.
  125. */
  126. $anti_hammer['waiting_times'] = '3,5,10,15';//distro $anti_hammer['waiting_times'] = '3,5,10,20';
  127. /*
  128. Rolling Trigger Times
  129. [default: $anti_hammer['rolling_trigger'] = false;]
  130. This increases the ban time automatically with EACH hammer.
  131. <hit>
  132. You must wait three seconds..
  133. <hit>
  134. You must wait four seconds..
  135. <hit>
  136. You must wait five seconds..
  137. And so on.
  138. */
  139. $anti_hammer['rolling_trigger'] = false;
  140. /*
  141. Cut-Off
  142. [default: $anti_hammer['cut_off'] = '']
  143. You can also set an absolute cut-off point.
  144. Anyone receiving this many hammer violations is simply dropped, and from
  145. that point onward, their pages die before it even begins - blank - and
  146. the client is sent a "503 Service Temporarily Unavailable" response.
  147. This works with both preset and rolling triggers.
  148. Leave blank to disable the cut-off.
  149. */
  150. $anti_hammer['cut_off'] = '100';//distro $anti_hammer['cut_off'] = '';
  151. /*
  152. Bye Bye! Message.
  153. [default: $anti_hammer['cut_off_msg'] = '<h1>Bye Now!</h1>';]
  154. A final word from our sponsor?
  155. This is the final message they see before it all goes blank.
  156. It should be HTML. No other text is presented.
  157. */
  158. $anti_hammer['cut_off_msg'] = '<h1>Bye Now!</h1>';
  159. /*
  160. Ban Time
  161. [default: $anti_hammer['ban_time'] = '12';]
  162. And for how many hours will the above cut-off (ban) last?
  163. */
  164. $anti_hammer['ban_time'] = '6';
  165. // NOTE: If you set your Garbage Collection age to any less than this, you
  166. // effectively reset all bans older than THAT figure.
  167. //
  168. // In other words, ensure your garbage collection age ('GC_age', below)
  169. // is larger than your 'ban_time' setting here, probably x2.
  170. // Think: if GC happened one minute after someone was banned, and their
  171. // session ID file was >= GC_age, it would be cleaned up! Then no ban!
  172. //
  173. // Also Note: Humans are daily creatures; a 12h ban is effectively 24h!
  174. /*
  175. SEO-aware indexes
  176. When a user asks for /index.php, they get redirected to /
  177. immediately, bypassing anti-hammer for the initial request.
  178. If you prefer to perform this sort of magic elsewhere (in your header, perhaps)
  179. remember to add a sleep for anti-hammer, at least as long as your hammer time.
  180. NOTE: this redirection only occurs when no data is POST-ed, so as not to mess
  181. with any forms you might have running. Obviously search engine spiders would
  182. not be making these sorts of requests (POSTing forms), anyway.
  183. */
  184. $anti_hammer['seo_indexes'] = true;
  185. /*
  186. Log File Location
  187. [default: $anti_hammer['log'] = '.ht_hammers';]
  188. We will log each banned hit, for reference.
  189. EITHER:
  190. enter a simple file name, e.g..
  191. $anti_hammer['log'] = '.ht_hammers';
  192. in which case Anti-Hammer will log hammers to your "lists" folder
  193. OR..
  194. enter FULL path to the log location, e.g..
  195. $anti_hammer['log'] = $_SERVER['DOCUMENT_ROOT'].'/logs/.ht_hammers'
  196. NOTE: If you enter a custom full path location and the parent directory does
  197. not exist, Anti-Hammer will not attempt to create it, and you will get no
  198. logging.
  199. */
  200. $anti_hammer['log'] = $_SERVER['DOCUMENT_ROOT'].'/inc/log/.ht_hammers';//distro $anti_hammer['log'] = '.ht_hammers';
  201. //
  202. // It is recommend you watch this log very carefully for the first
  203. // NOTE: few minutes/days after installation, in case of unexpected side-
  204. // effects. And in that case, please do mail me about it!
  205. /*
  206. Kill Message.
  207. [default: $anti_hammer['kill_msg'] = 'Please do not hammer this site.<br />';]
  208. When a request is killed - send this message (before the other text).
  209. You can use any valid HTML in here, header tags, or whatever you like..
  210. */
  211. $anti_hammer['kill_msg'] = '<h1>Please do not hammer '.$_SERVER['HTTP_HOST'].'!</h1>';
  212. /* NOTE: No <br /> is placed after this text.
  213. If you aren't using <h> tags, and want a break, add it yourself. */
  214. /*
  215. Page Title.
  216. [default: $anti_hammer['page_title'] = 'Please do not hammer this site!';]
  217. This is what is displayed in the title bar of their browser.
  218. Keep this one plain text.
  219. */
  220. $anti_hammer['page_title'] = 'Please do not hammer corz.org!';//distro $anti_hammer['page_title'] = 'Please do not hammer this site!';
  221. /*
  222. WebMaster's Name
  223. [default: $anti_hammer['webmaster'] = 'the webmaster';]
  224. Name of the webmaster, will be included in the kill page.
  225. e.g. "If you believe this is in error, please mail <Insert Name> about it!"
  226. */
  227. $anti_hammer['webmaster'] = 'cor';//distro $anti_hammer['webmaster'] = 'the webmaster';
  228. /*
  229. Admin Bypass
  230. [default: $anti_hammer['admin_agent_string'] = 'MyCrazyUserAgentString';]
  231. If you insert this exact string into your web browser's user-agent string
  232. (just tag it onto the end), you can bypass the hammer altogether.
  233. Very handy for busy webmasters.
  234. */
  235. $anti_hammer['admin_agent_string'] = 'The Halle Berry Cosmological Society';//distro $anti_hammer['admin_agent_string'] = 'MyCrazyUniqueUserAgentString';
  236. // It's not advisable to go messing with the main body of your
  237. // NOTE: browser's user agent string. Lots of web designers rely on this
  238. // information to serve you beautiful, functional web pages.
  239. /*
  240. WebMaster email address (string).
  241. [default: $anti_hammer['error_mail'] = 'bugs at mydomain dot com';]
  242. The usual text format of so-and-so at such-and-such dot com works well.
  243. This is tagged on to the end of the massage inside <> angle brackets,
  244. to look like an address.
  245. */
  246. $anti_hammer['error_mail'] = 'bugs at corz dot org';//distro $anti_hammer['error_mail'] = 'bugs at mydomain dot com';
  247. /*
  248. Client Data Set
  249. [default: $anti_hammer['client_data'] = 'user_agent,accepts,language,encoding,charset,remote_ip';]
  250. You can specify which parts of the client's data set will be used to create
  251. the client's unique ID. The more elements you use, the less chance you have
  252. of colliding two client ID's. By default, Anti-Hammer uses them all.
  253. But your server might be under stress or attack, or some other scenario,
  254. and you would prefer to identify clients by, for example, only their IP
  255. Address. That way, *any* request from that IP would be assigned the same
  256. Client ID, regardless of what other information they may or may not
  257. present.
  258. This is simply a list of client properties. Choose from; 'user_agent', 'accepts',
  259. 'language', 'encoding', 'charset', and 'remote_ip', and create a simple list,
  260. separated by commas.
  261. */
  262. $anti_hammer['client_data'] = 'user_agent,accepts,language,encoding,charset,remote_ip';
  263. /*
  264. Lookup Failures.
  265. When an event worth logging occurs, we can lookup the host name of the
  266. client to add to our logs. This takes a moment, but only occurs while
  267. logging bad clients, and can be useful in quickly identifying abusers
  268. (or good bots using bad user agent string - to come)
  269. */
  270. $anti_hammer['lookup_failures'] = true;
  271. /*
  272. Allow known bots?
  273. [default: $anti_hammer['allow_bots'] = false;]
  274. We can allow certain bots to bypass the Anti-Hammer.
  275. Do do this, specify the expected user agent strings in..
  276. path-to/anti-hammer/exemptions/exemptions.ini
  277. and then supply an IP-mask file where said user agent is expected to be
  278. making requests FROM, one ip per line, in the standard Spider IP list format
  279. as found here..
  280. http://www.iplists.com/
  281. http://www.iplists.com/nw/ <- updated, reorganised, with msnbot+more
  282. A blog URI is listed there, where list updates are posted.
  283. (this doesn't happen a lot, maybe 2-3 times a year)
  284. NOTE: User agent string matches are CaSe SenSiTivE! If you want to match
  285. "msnbot" and "MSNBOT", you need two entries. (a case-insensitive
  286. test is roughly five times slower than case-sensitive; so testing
  287. two separate entries is much faster)
  288. NOTE: If cooking up your own anti-hammer.ini, you probably do not want to
  289. include the generic user agent strings (e.g. Yahoo's "Mozilla/4.0"),
  290. which would create a lot of processing overhead, as ALL browsers
  291. send that. Doh! (More notes within that file.)
  292. You can set this to "true" (no quotes), in which case, all specified bots
  293. are simply allowd to bypass anti-hammer. You can also set it to an integer,
  294. e.g..
  295. $anti_hammer['allow_bots'] = 50;
  296. ..that integer representing the hammer_time that will apply to the specified
  297. clients. "50" would enable 2 hits-per-second spidering, but nothing faster,
  298. which is half the normal hammer_time of One Second (hammer_time=100).
  299. */
  300. $anti_hammer['allow_bots'] = true;//distro $anti_hammer['allow_bots'] = false;
  301. /*
  302. The following two preferences control Anti-Hammer's built-in Client session
  303. Garbage collection routines..
  304. */
  305. /*
  306. Garbage Collection Limit
  307. [default: $anti_hammer['GC_limit'] = 1000;]
  308. To prevent your server's hard drive filling up with stale client sessions,
  309. we run a periodic garbage collection routine to sweep up the old files.
  310. How periodically, is up to you. By default, Anti-Hammer will check for
  311. garbage every 1,000 hits.
  312. Obviously, you can chage this number to anything you like, depending on how
  313. busy your site is, and how much space you have on the disks.
  314. If you don't want Anti-Hammer to clean up its garbage, set this to 0. And
  315. ensure you have some other mechanism to handle it.
  316. Remember to ensure that this limit falls well outside your longest ban time,
  317. probably at least 2x that.
  318. */
  319. $anti_hammer['GC_limit'] = 1000;
  320. /*
  321. GarbAge!
  322. [default: $anti_hammer['GC_age'] = 24;]
  323. How old, in hours, is considered "stale"?
  324. Any ID files older than this will be swept away (deleted).
  325. */
  326. $anti_hammer['GC_age'] = 24;
  327. /*
  328. NOTE: The previous two preferences have no effect if you set the following
  329. preference ('use_php_sessions') to true. They are only for Anti-Hammer's
  330. built-in client session files.
  331. */
  332. /*
  333. Use php sessions..
  334. [default: $anti_hammer['use_php_sessions'] = false;]
  335. You would think it might be a nice idea to detect if the client has cookies
  336. enabled, and if so, use php sessions, only falling-back to some other method
  337. when they have not. However, it is not possible to detect whether or not a
  338. client has cookies enabled, with a single request. You need Two. Clearly,
  339. that isn't a lot of use for a protection mechanism designed to be able to
  340. operate before they have even had one. So you need to choose now..
  341. By default, Anti-Hammer will use its own session mechanism, writing client-
  342. unique data to files in a directory of your choosing, irrespective of their
  343. ability to accept cookies. As it is an independent system, it in no way
  344. interferes with any session magic you may have running on your site, and in
  345. most scenarios is just as fast as php's own session handling.
  346. However, you may wish to use that, instead; particularly if you have
  347. millions of hits a day, and your web server stores the php sessions in a
  348. some uberfast /tmp space you can't otherwise get to, where the difference
  349. might be worth it. Or if in-website space is extremely limited. At any rate,
  350. you have a choice.
  351. NOTE: if you enable this, you will ALWAYS start a php session with each
  352. request. This usually presents no problems, but you and your server may know
  353. better. Testing is always advised! I tested it this way for many months on
  354. corz.org, with no issues whatsoever, and I use php sessions all over the
  355. site. If you use proper names in your session, everything should work fine.
  356. ALSO NOTE: With this enabled, if the client/spider/script kiddie/etc. has
  357. cookies disabled in their web browser, they bypass Anti-Hammer protection!
  358. ** This is why, by default, Anti-Hammer uses its *own* session mechanism. **
  359. There should be no performance concerns; Anti-Hammer writes the data in the
  360. same way as a php session; a simple serialized array in a flat file.
  361. */
  362. $anti_hammer['use_php_sessions'] = false;
  363. /*
  364. Referer Spam protection
  365. You can ask Anti-Hammer to consult black and white lists (available online)
  366. of known bad and (optionally) good referers.
  367. Additionally, you can have Anti-Hammer /create/ these lists dynamically,
  368. by direct interrogation of the referring URL, black-listing referers that
  369. have no actual link back to your site.
  370. Welcome to..
  371. Responsive Adaptive Dynamic Anti-Referer (RADAR) Spam Protection! (TM) heh
  372. */
  373. /*
  374. Validate Referers? (yes, there's one 'r'!)
  375. This is the master switch for Referer Protection.
  376. */
  377. $anti_hammer['validate_referers'] = false; // true/false
  378. /* location of white and black lists..
  379. These are inside the "lists" directory (set below).
  380. */
  381. $anti_hammer['white_list'] = 'white-list.txt';
  382. $anti_hammer['black_list'] = 'black-list.txt';
  383. /*
  384. "Auxiallary" black-list. [aka, "The BANNED Referers List"]
  385. An extra black-list. This list is read-only (it will not be updated by
  386. Anti-Hammer) most useful if you wish to add a second bad referers list which
  387. you have compiled by hand, or downloaded.
  388. It would also be a handy place to store your "Permanently Banned" referers.
  389. Essesntially, this is a list of KNOWN bad referers, certified, if you like.
  390. It should be noted that the longer your list, the longer it will take to
  391. check. To give you an idea, a list 432KB in length, containing 25,635 items
  392. takes approx 0.05 seconds to check, compared to less than 0.001 seconds for
  393. a short list with under 1000 items. I'll allow it!
  394. */
  395. $anti_hammer['banned_referers_list'] = 'banned_referers.txt';
  396. /*
  397. If you ONLY want to use a black-list..
  398. You don't have to use a white-list. Instead you can simply allow /all/
  399. referers that are NOT listed in your black-list. In other words, any referer
  400. found in your black-list gets the 'bad_referer_msg', everyone else can pass
  401. straight through. To achieve this, comment out the white_list location preference,
  402. like so..
  403. //$anti_hammer['white_list'] = 'white-list.txt';
  404. From then on, Anti-Hammer will consult only your black-list for bad
  405. referers, allowing all others to pass.
  406. If you don't want Anti-Hammer to interrogate and add new bad referers to the
  407. black-list, set:
  408. $anti_hammer['interrogate_referers']= false;
  409. Remember to set the location of your black-list!
  410. Obviously, using ONLY a white-list is pointless, without a black-list for
  411. bad referers, all requests pass straight through (or must be re-fetched, if
  412. interrogate_referers=true).
  413. */
  414. /*
  415. List (and check) ONLY domain names?
  416. Rather than record the entire URL in the black and white lists, we can list
  417. only the domain name. This saves time checking the lists in future, and
  418. makes for smaller lists.
  419. Set to true or false, you can still have partial matches in your lists, so
  420. "www.google" matches "www.google.com", "www.google.co.uk", and so on.
  421. The difference is, when set to true, Anti-Hammer would expect the match to
  422. happen right from the start of the entry, e.g. "google.com" would NOT match
  423. against a referring hit from..
  424. http://www.google.com/search?q=foo+bar.
  425. Of course, "www.google.com" would match the hit.
  426. When this is set to false (use *full* URL's), matches can be anywhere in the
  427. string, e.g. "google.com" WOULD match against a referring hit from..
  428. http://www.google.com/search?q=foo+bar
  429. You can have a mixed black-list, with domains-only (perhaps from an online
  430. source) and append full URL's to it - Anti-Hammer will work with both.
  431. However..
  432. If you have a list of full URL's, and use Anti-Hammer in domains_only mode
  433. (true), it's unlikely Anti-Hammer will find any matches in the full URL
  434. entries of your list.
  435. If you want to move from full URL's to a domain-only list, it's best to
  436. either start with a new list, or else do some fairly simple regexp search &
  437. replace on the full URL list to create a domain-only list. HOWEVER..
  438. See the next preference.
  439. */
  440. $anti_hammer['domains_only'] = true;
  441. /*
  442. The scheme is the "http" part of the referring URL. When working with full
  443. URL's ('domains_only' = false) we normally record this, e.g.
  444. http://www.badspammer.com/buymyshit.html
  445. But you can disable recording the scheme, so instead we record..
  446. www.badspammer.com/buymyshit.html
  447. ..which will probably also disable your text editor's fancy text-to-URL
  448. magic, but does have one important advantage..
  449. With this set to false, you can use mixed lists with both domain-only and
  450. full-URL entries and Anti-Hammer will be able to match entries either way
  451. around. This could be handy if you like to record full URL's for your own
  452. generated bad-referer list but add other (domain-only) sources to your list
  453. from time to time, perhaps from a web site that distributes such things.
  454. If this is something that you intend to do, see the 'banned_list' preference
  455. (above), which provides a convenient way to use an auxiallary black-list.
  456. */
  457. $anti_hammer['record_scheme'] = false;
  458. /*
  459. You can insert your (universal) analytics code here to have anti-hammer
  460. spit out your Google Analytics JavaScript on "bad JuJu" pages..
  461. Set to empty ('') to disable this.
  462. */
  463. $anti_hammer['analytics_code'] = 'UA-31003967-1';
  464. /*
  465. What message to send to these clients?
  466. You can use HTML in this message.
  467. If you wish to insert more into your feck-off page, maybe ads and stuff,
  468. search this document for "die_spammer"
  469. */
  470. $anti_hammer['bad_referer_msg'] = '<h1>Bad vibes from referring page!</h1>
  471. <h2><a href="https://corz.org/server/tools/anti-hammer/" title="Get Anti-Hammer Protection for your own site"
  472. target="_blank" rel="noopener noreferrer">Anti-Hammer</a> couldn\'t access a referring link on the calling page. So it looks fake.<br />
  473. If this is a members-only page or admin area with a real link to corz.org, you can request to be white-listed.</h2>
  474. <h3>If you believe this is an error, please <a href="https://corz.org/corz/contact.php" title="My contact page">email the webmaster</a>.</h3>';
  475. // And a title for the page..
  476. $anti_hammer['title'] = 'Bad JuJu from Referring Page';
  477. // If the page dies from bad ju-ju (Referer Spam Protection), you can include a file on that page.
  478. // It's a fine place to stick an advert!
  479. // basically, this enables you to include a larger chunk of HTML than would
  480. // be comfortable to insert into the 'bad_referer_msg' (above)
  481. //
  482. $anti_hammer['die_insert'] = 'bad-ju-ju.htm';//distro $anti_hammer['die_insert']= 'bad-ju-ju.htm';
  483. //
  484. // NOTE: if the path does not begin with a slash "/", it is assumed to be in the "lists" directory
  485. // some string you want to remove from inward links, if necessary..
  486. // a pagination link is a good example..
  487. $anti_hammer['chop'] = '?page=all';
  488. /*
  489. WARNING!!!!!!
  490. You may want to keep your eye on the black and white lists for a few
  491. days to ensure that there are no false-positives or false-negatives,
  492. as well as pare down links to well-known sites, to prevent bloating your
  493. lists, as well as speeding up the process (it's pretty fast, but still,
  494. no point in grabbing the same site over and over). A good example would
  495. be search engines. A single entry in your white-list, like so..
  496. www.google.
  497. ..will prevent Anti-Hammer from having to fetch each and every hit from
  498. /any/ of google's many international search results pages.
  499. ALSO NOTE: "empty" referers always pass through this validation (typed
  500. links and bots), as do internally referred pages (links from your own
  501. pages).
  502. */
  503. /*
  504. Log Bad Referers?
  505. The whole point of this (well, the main point) is to prevent bad referers
  506. showing up in your referer logs, cut the noise (as well as save on server
  507. resources, of course). However, you may still wish to manually check out
  508. some URL's, especially if you are generating a black-list via interrogation,
  509. to check for false-negatives.
  510. Comment out this preference to NOT log all new bad referers.
  511. */
  512. $anti_hammer['black_log'] = 'black-log.txt';
  513. /*
  514. One would hope you are logging your /real/ traffic sources elsewhere
  515. */
  516. /*
  517. NOTE: you can also disable the lists and simply log the bad referers, if you
  518. wish. However, this would force checking of each and every referer, which
  519. would be wasteful of server resources & bandwidth. It would also mean
  520. multiple entries for each bad referer, as this list is not /checked/
  521. /against/, it is merely a log.
  522. */
  523. /*
  524. Interrogate Referers?
  525. [default: $anti_hammer['interrogate_referers'] = true;]
  526. To prevent referer spam, we can instruct Anti-Hammer to validate unknown
  527. referers by direct interrogation. This involves actually loading the HTML of
  528. the referring page and looking for links back to our page.
  529. If a link is found, the site is added to the white-list and from then on,
  530. allowed to access our resources directly. If a link back to our site is NOT
  531. found, Anti-Hammer adds the page to the black-list and denies referred
  532. access to our resources, permanently.
  533. Of course, external pages are only checked ONE time, thereafter they are in
  534. either the black or white list.
  535. All this can make a HUGE difference to the noise in your logs! At one point
  536. I was getting 1000+ visits/day from referer spammers. *ouch*
  537. NOTE: You will need to enable url fopen wrappers for this to work. e.g..
  538. (in .htaccess):
  539. php_flag allow_url_fopen on
  540. php_flag allow_url_include on
  541. Also note, if a user trips this protection, they get a page telling them
  542. what has happened, with a link to the requested page is also inserted, just
  543. in case anti- hammer has flagged "inaccessible" resources, such as
  544. member-only sites, so valid web users can still get to your page.
  545. If you don't want anti-hammer to do any fetching and interrogating of
  546. referring pages, but DO want it to check some pre-populated black (or white)
  547. list, set this parameter to false. Only do this if you already have your own
  548. pre-populated black (and white) list.
  549. NOTE: If interrogate_referers is set to true, and no list file(s) exist(s),
  550. Anti-Hammer will attempt to create them.
  551. */
  552. $anti_hammer['interrogate_referers'] = true;
  553. /*
  554. Link-Checking Accuracy
  555. Anti-Hammer can have a quick scan through the referring page for our page's
  556. URL (level 1), or it can explode all the <a href= tags on a page and check
  557. our page is in there somewhere (level 2) or else it can scan the document
  558. thoroughly using complex Regular Expressions to ensure a valid link exists
  559. on the referring page (level 3).
  560. Level one is the quickest and least accurate method, level three the slowest
  561. and most accurate. The following min/max times were performed on an old
  562. (slow) laptop Apache server. The test file is a 1MB HTML page with just over
  563. 9000 links on the page, iterated Ten times, for more accurate times; the
  564. final times listed here being 1/10th of that. Expect at least x10 speeds on
  565. a /real/ server.
  566. Level 1 [0.017 - 0.032s]
  567. Level 2 [0.056 - 0.069s]
  568. Level 3 [0.108 - 0.114s]
  569. Unless referer spammers get *very* clever on us, level 1 will probably be
  570. fine.
  571. */
  572. $anti_hammer['link_check_accuracy'] = 2;
  573. /*
  574. Interrogation GET Time-Out
  575. By default, php will time-out a request after 60 seconds.
  576. You may not want Anti-Hammer to wait that long.
  577. Think about it; they came FROM that page, so we would expect that page to be
  578. available right now.
  579. */
  580. $anti_hammer['time_out'] = 10;
  581. /*
  582. Referer GET Limit.
  583. We set the maximum amount of web page data fetched, mainly this is to avoid
  584. a potential server DOS Exploit.
  585. That exploit would be..
  586. A script that loads your web pages from a sequence of randomly generated
  587. referer URI's of pages of HUGE size, potentially Terrabytes. One every
  588. second or less until your server falls over, grabbing each page in its
  589. entirety, checking for back-links.
  590. <deep voice> ... And so the Server Wars began...
  591. Mind you, one would hope that your server would have other security features
  592. to deal with this sort of onslaught, doesn't php itself? And of course,
  593. /they/ would need to have a superior server at their end, perhaps a
  594. distributed model of some kind.. Rally-cry on a forum, the code of a fairly
  595. simple exploit page, but a download away.. if some were so inclined.
  596. But security isn't the only deciding factor here. Anti-Hammer isn't pulling
  597. in all the page resources, images, video and such, just the raw HTML. I
  598. don't have a page onsite generating over 100KB of raw source (Ctrl+U in
  599. Firefox, et-al), though loading ALL the comments on a few of my pages does
  600. get you a Multi-Megabyte document. How much of that is a human be willing to
  601. read, anyway? Should *your* site be so far down a page? It's probably an
  602. auto-scraping-mass-marketing page of some sort. That alone deserves "bad
  603. vibes".
  604. A quick search of my personal collection of saved web pages from the last
  605. couple of decades reveals nothing valuable over 1MB.
  606. Enter the maximum number of BYTES of data you are prepared to accept.
  607. 1024 = 1KB. It's okay to use multipliers here, e.g. 1024*1024 which equals
  608. 1MB, 1024*100 is 100KB, etc., to set max_referer_get to 10MB you could use:
  609. $anti_hammer['max_referer_get'] = 1024*1024*10; // 10MB max
  610. */
  611. $anti_hammer['max_referer_get'] = 1024*1024; // 1MB max
  612. //
  613. // URL Protection
  614. //
  615. // Anti-Hammer can deny resources to clients making h4x0r-type requests to
  616. // known exploit pages. It's also a handy place to put URLs of restricted or
  617. // publicly unavailable features and such-like, e.g..
  618. //
  619. // $1
  620. // %00
  621. // ....//
  622. // ../../
  623. // .aspx
  624. // /RPC2
  625. // /groups
  626. // /url?q=
  627. // script>alert
  628. // =profile;u
  629. // =viewprofile;u
  630. // =|w|
  631. // DSAdClient31.dll
  632. // MSOffice/cltreq.asp
  633. // Netsparker-
  634. // _vti_bin
  635. // addlink.php
  636. // administrator/
  637. // bad-test
  638. // bangsat.php
  639. // cart.php
  640. // clientaccesspolicy.xml
  641. // crossdomain.xml
  642. // customers.php
  643. // etc/group
  644. // etc/passwd
  645. // form.php
  646. // imagens_popup.php
  647. // javascript:alert
  648. // labels.rdf
  649. // owssvr.dll
  650. // password_forgotten.php
  651. // proc/self
  652. // product_category.php
  653. // product_category.php
  654. // profile.php
  655. // r57.php
  656. // register/
  657. // select *
  658. // select+
  659. // signup.php
  660. // union+select
  661. // using+SOCKS
  662. // viewtopic.php
  663. // wp-content/
  664. // xmlrpc
  665. // zboard.php
  666. // zp-core
  667. //
  668. // etc.
  669. //
  670. // These requests will be killed immediately with a "501 Not Implemented"
  671. // response.
  672. //
  673. // This is especially useful if you have an intelligent 404 page, to prevent
  674. // wasting processor power on obviously bad requests.
  675. //
  676. // If you are using the admin bypass capability, you can also put restricted
  677. // URL's in here, meaning only YOU will be able to access them. Neat.
  678. //
  679. // It's not a security measure - such resources need their own authorisation
  680. // mechanisms - this simply prevents casual access by script-kiddies and such.
  681. //
  682. // To enable this functionality, simply uncomment the following preference..
  683. $anti_hammer['banned_urls_list'] = 'banned_urls.txt';//distro //$anti_hammer['banned_urls_list'] = 'banned_urls.txt';
  684. // some message to send in this case..
  685. $anti_hammer['bad_url_message'] = 'The requested URL is not implemented.';
  686. /*
  687. USER AGENT Protection (Bad Bots, spiders, suckers, etc.)
  688. Anti-Hammer can deny resources to clients with known "User Agents". This can
  689. be used to protect your site against web downloaders, bad bots, spiders,
  690. scripts and more.
  691. Note:
  692. You can use Regular Expression in the list entries, so .htaccess ban
  693. lists should port straight across to Anti-Hammer (after removing the
  694. RewriteCond %{HTTP_USER_AGENT} part, of course - a simple block delete).
  695. This eables you to have matches that ONLY match at the start of a User
  696. Agent string and much more, e.g..
  697. ^BadBot
  698. ("^" meaning, "start anchor", in other words, "must match at the start
  699. of the string") would match against "BadBot web sucker", but would NOT
  700. match against "Web Sucker BadBot"
  701. ^BadBot$
  702. ("$" meaning "must match the END of the string") would only match
  703. against "BadBot", but NOT against "BadBot web sucker" (both start and
  704. end anchors are specified)
  705. BadBot$
  706. Would match against "Web Sucker BadBot", but NOT against "BadBot Web
  707. Sucker" (only the end anchor is specified), and so on.
  708. If you want to include any funky characters, actual dots, slashes and
  709. such, precede those with a backslash ("\"), so that the regexp engine
  710. treats them as literal characters, e.g..
  711. BadBot\/1\.
  712. Which would match against "BadBot/1.3", "BadBot/1.0", etc..
  713. If you are not familiar with Regular Expression, I definitely recommend
  714. you GET familiar with it, it is hugely powerful and a massive
  715. time-saver, even for "average" computer users..
  716. These requests will be killed immediately with a "403 Forbidden" response.
  717. To enable this functionality, simply uncomment the following preference..
  718. */
  719. $anti_hammer['banned_agents_list'] = 'banned_agents.txt';//distro //$anti_hammer['banned_agents_list'] = 'banned_agents.txt';
  720. // a message to send to clients with a bad user agent strings..
  721. // Leave as-is to use the default message.
  722. // or uncomment and enter your own message, e.g. "This request has been denied."
  723. //$anti_hammer['bad_agent_message'] = '';
  724. /*
  725. Allow Empty User Agent Strings?
  726. If you wish to deny access to clients NOT sending a User Agent String, set
  727. this to false..
  728. */
  729. $anti_hammer['allow_empty_UA'] = true;
  730. // if set to false, we will send them a message instead of the page..
  731. $anti_hammer['empty_UA_message'] = 'Please configure your web client to send a valid "User Agent" string.';
  732. //2do.. humans could enter a code - then be treated as normal.
  733. /*
  734. Banned IP Addresses
  735. By request, this simple feature enables you to ban individual IP addresses.
  736. You can also ban entire IP blocks, by omitting tha relevant octets, for
  737. example, and entry like this..
  738. 192.168.0.
  739. .. would ban all IP Addresses from 192.168.0.0 - 192.168.0.255
  740. These requests get a 403 response + terse message.
  741. In the future, we may add IP addresses to this list dynamically, for serial
  742. offenders.
  743. To enable this functionality, simply uncomment the following preference..
  744. */
  745. $anti_hammer['banned_ip_list'] = 'banned_ips.txt';//distro //$anti_hammer['banned_ip_list'] = 'banned_ips.txt';
  746. // Some message to send for clients with a banned IP Address..
  747. // You can customize the message that is sent. Leave as-is to use the default.
  748. //$anti_hammer['bad_ip_message'] = '';
  749. //
  750. // :end regular prefs
  751. /*
  752. Advanced overrides..
  753. */
  754. /*
  755. Client ID File Prefix
  756. [default: $anti_hammer['ID_prefix'] = 'HammerID_';]
  757. This text is placed before the client ID in the ID filename. e.g..
  758. "HammerID_06fa71c938a108f4a2b1f1ef091653ef"
  759. You may wish to use a different name..
  760. */
  761. $anti_hammer['ID_prefix'] = 'HammerID_';
  762. /*
  763. Directory Locations..
  764. These are usually best left as-is (in which case they will be inside your
  765. main anti-hammr directory), but you can change them if you need to.
  766. */
  767. $anti_hammer['lists_folder'] = 'lists';
  768. $anti_hammer['sessions_folder'] = 'sessions';
  769. $anti_hammer['exemptions_folder'] = 'exemptions';
  770. // :advanced prefs:
  771. //
  772. // Transform user preferences into real locations..
  773. // Main location of script and data directories..
  774. $anti_hammer['data_path'] = str_replace("\\", '/', dirname(__FILE__));
  775. // if the above line isn't working out your anti-hammer location automatically, you can set it here manually, like so..
  776. //$anti_hammer['data_path'] = realpath($_SERVER['DOCUMENT_ROOT']).'/inc/anti-hammer';
  777. // :end advanced prefs:
  778. //*> end prefs
  779. // testing //debug
  780. if (!isset($_SERVER['HTTP_HOST'])) {
  781. add_log_data( $_SERVER['DOCUMENT_ROOT'].'/inc/log/.ht_hammers', 'NO HOST SENT!!!!!!!!!!!!!!!!!!!!'.create_log_data(true, true));
  782. }
  783. // Firstly.. SEO indexes..
  784. //
  785. // Redirect initial requests for folder/index.php to folder/ (neater, and better for SEO, too)
  786. // better than using .htaccess (if you have $_POST forms, for example). And better than doing
  787. // it later, /after/ you tripped Anti-Hammer with your double request!
  788. if ($anti_hammer['seo_indexes']) {
  789. if (substr($_SERVER['REQUEST_URI'], -9) == 'index.php' and empty($_POST)) {
  790. header('Location: http://'.$_SERVER['HTTP_HOST'].str_replace('index.php', '', $_SERVER['REQUEST_URI']));
  791. die;
  792. }
  793. }
  794. //*> Setup Lists.
  795. // Set the location of the lists folder..
  796. $anti_hammer['lists_folder'] = $anti_hammer['data_path'].'/'.$anti_hammer['lists_folder'];
  797. // Referer lists..
  798. $anti_hammer['white_list'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['white_list'];
  799. $anti_hammer['black_list'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['black_list'];
  800. $anti_hammer['banned_referers_list'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['banned_referers_list'];
  801. $anti_hammer['black_log'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['black_log'];
  802. // Banned URLs..
  803. if (isset($anti_hammer['banned_urls_list'])) { $anti_hammer['banned_urls_list'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['banned_urls_list']; }
  804. // Banned USER AGENTS..
  805. if (isset($anti_hammer['banned_agents_list'])) { $anti_hammer['banned_agents_list'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['banned_agents_list']; }
  806. // Banned IP Addresses
  807. if (isset($anti_hammer['banned_ip_list'])) { $anti_hammer['banned_ip_list'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['banned_ip_list']; }
  808. // a message to send to those who are banned (keep it short!)
  809. $anti_hammer['ip_ban_message'] = '!';//distro $anti_hammer['ip_ban_message'] = 'Your IP Address has been banned.';
  810. // set path of bad ju-ju file..
  811. if (substr($anti_hammer['die_insert'], 0, 1) !== '/') {
  812. $anti_hammer['die_insert'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['die_insert'];
  813. }
  814. // Set log location..
  815. if (substr($anti_hammer['log'], 0, 1) != '/') {
  816. $anti_hammer['log'] = $anti_hammer['lists_folder'].'/'.$anti_hammer['log'];
  817. }
  818. //*> Collect all usable, available client data..
  819. $anti_hammer['user_agent'] = @$_SERVER['HTTP_USER_AGENT'];
  820. $anti_hammer['accepts'] = @$_SERVER['HTTP_ACCEPT'];
  821. $anti_hammer['language'] = @$_SERVER['HTTP_ACCEPT_LANGUAGE'];
  822. $anti_hammer['encoding'] = @$_SERVER['HTTP_ACCEPT_ENCODING'];
  823. $anti_hammer['charset'] = @$_SERVER['HTTP_ACCEPT_CHARSET'];
  824. $anti_hammer['remote_ip'] = $_SERVER['REMOTE_ADDR'];
  825. $anti_hammer['request'] = $_SERVER['REQUEST_URI'];
  826. $anti_hammer['referer'] = @$_SERVER['HTTP_REFERER'];
  827. $anti_hammer['host'] = $_SERVER['HTTP_HOST'];
  828. $anti_hammer['uri'] = 'http://'.$anti_hammer['host'].$anti_hammer['request'];
  829. //*> begin..
  830. $gentime = explode(' ', microtime());
  831. $anti_hammer['now_time'] = $gentime[1].substr($gentime[0], 6, -2); // 1/100th of a second accuracy!
  832. settype($anti_hammer['now_time'], "double"); // scientifically tested!
  833. $anti_hammer['final_time'] = 0; // will be used to set the retry header on killed page (503)
  834. // local server access (for readfile() requests..
  835. // (and as a potential catch-all for user pref errors!))
  836. if ($anti_hammer['remote_ip'] == $_SERVER['SERVER_ADDR']) {
  837. return; // there could be a potential weakness on an easy-access shared web host.
  838. }/*
  839. A note about readfile()..
  840. If you use readfile() to include resources on your pages, remember,
  841. those requests will come in right after the first, and as they are
  842. technically brand new hits, they count towards the hammer.
  843. Use of include is prefered.
  844. However, the code right above this notice should prevent any issues. If
  845. it does /not/, and include isn't working, you might want to hack in
  846. the actual IP Address of the local server. See my debug-report.zip for
  847. a way to easily get this sort of information in your browser.
  848. NOTE: If you are having difficulty include-ing URI resource in your
  849. pages, remember you need to enable BOTH php allow_url_* flags. Here is
  850. the .htaccess version of those two switches..
  851. php_flag allow_url_fopen on
  852. php_flag allow_url_include on
  853. */
  854. //*> Skip Known Clients..
  855. /*
  856. skip protection for known bots and spiders.
  857. okay, this is some cute code! simple, but effective..
  858. we load an ini file of user-agent=ip-mask-file pairs, and check our client's
  859. user agent string for a match (at must match the beginning of the string
  860. exactly). If there is a match, we load the associated IP Mask file, and
  861. run through the IP/masks, again looking for a perfect match at the start of
  862. the two strings. Commented lines are no problem. We use strpos() for both
  863. tests, so it's nice and fast, and the IP test covers our comments, too.
  864. having said (coded) all this, you gotta ask yourself, why are they hammering?
  865. Surely it would be better get them to slow down, instead! (i.e. in robots.txt)
  866. */
  867. $IP_file = '';
  868. $anti_hammer['ini_file'] = $anti_hammer['data_path'].'/'.$anti_hammer['exemptions_folder'].'/exemptions.ini';
  869. if ($anti_hammer['allow_bots']) {
  870. $bot_agent_array = read_bots_ini($anti_hammer['ini_file']);
  871. if (is_array($bot_agent_array)) {
  872. foreach ($bot_agent_array as $bot_agent_string => $IP_file) {
  873. if ($bot_agent_string and strpos($anti_hammer['user_agent'], $bot_agent_string) === 0) {
  874. break;
  875. }
  876. }
  877. if ($IP_file) {
  878. $ip_array = file($anti_hammer['data_path'].'/'.$anti_hammer['exemptions_folder'].'/'.$IP_file);
  879. }
  880. if (is_array($ip_array)) {
  881. foreach($ip_array as $bot_ip) {
  882. if (@strpos($anti_hammer['remote_ip'], trim($bot_ip)) === 0) {
  883. if ($anti_hammer['allow_bots'] > 1) {
  884. $anti_hammer['hammer_time'] = $anti_hammer['allow_bots'];
  885. } else {
  886. return;
  887. }
  888. }
  889. }
  890. }
  891. }
  892. }
  893. // Get user values into usable arrays and do some error-checking.
  894. // trigger thresholds..
  895. if (!stristr($anti_hammer['trigger_levels'], ',') or (str_word_count($anti_hammer['trigger_levels'], 0, "0123456789") != 4)) {
  896. $anti_hammer['trigger_levels'] = '5,10,20,30';
  897. }
  898. // A neat way to create an array from numeric prefs..
  899. $anti_hammer['trigger_levels'] = str_word_count($anti_hammer['trigger_levels'], 1, "0123456789");
  900. // Get user penalty times into correct values..
  901. if (!stristr($anti_hammer['waiting_times'], ',') or (str_word_count($anti_hammer['waiting_times'], 0, "0123456789") != 4)) {
  902. $anti_hammer['waiting_times'] = '3,5,10,20';
  903. }
  904. $anti_hammer['waiting_times'] = str_word_count($anti_hammer['waiting_times'], 1, "0123456789");
  905. // file types to protect..
  906. if (!$anti_hammer['types']) { return; } // no types specified, forget it!
  907. $anti_hammer['types'] = explode(',', $anti_hammer['types']);
  908. // generated types to skip..
  909. $anti_hammer['gen_types'] = explode(',', $anti_hammer['gen_types']);
  910. // ignored locations..
  911. if ($anti_hammer['skip']) {
  912. // ignored locations..
  913. $anti_hammer['skip'] = explode(',', $anti_hammer['skip']);
  914. // run through ignored locations and if matched, return immediately..
  915. foreach($anti_hammer['skip'] as $nogo) {
  916. if (stristr($anti_hammer['request'], trim($nogo))) { return; }
  917. }
  918. }
  919. // Skip requests with certain POSTed variables..
  920. if ($anti_hammer['skip_post']) {
  921. $anti_hammer['skip'] = explode(',', $anti_hammer['skip_post']);
  922. // run through ignored locations and if matched, return immediately..
  923. foreach($anti_hammer['skip'] as $nogo) {
  924. if (is_array($_POST)) {
  925. foreach ($_POST as $pk=>$pv) {
  926. if ($nogo == $pk) {
  927. return;
  928. }
  929. }
  930. }
  931. }
  932. }
  933. // Anti-Hammer only for php files, not generated css, etc..
  934. $ah_type_ok = false;
  935. foreach($anti_hammer['types'] as $ah_type) {
  936. if (!$ah_type) { continue; } // @ to avoid strict php5 errors
  937. if (@end(explode('.', $_SERVER['SCRIPT_FILENAME'])) == trim($ah_type)) {
  938. $ah_type_ok = true;
  939. }
  940. //2do.. could make this code more efficient, for those using MANY types.
  941. }
  942. if ($ah_type_ok /* still! */ == false) { return; }
  943. //*> Admin Bypass..
  944. // (I put this down here so I can gather and test variables)
  945. //
  946. if (stristr($anti_hammer['user_agent'], $anti_hammer['admin_agent_string'])) {
  947. return;
  948. }
  949. //*> skip generated types..
  950. //
  951. if (in_array(@end(explode('.', $_SERVER['REQUEST_URI'])), $anti_hammer['gen_types'])) { return; }
  952. /*
  953. okay, let's do it..
  954. */
  955. //*> read session data..
  956. $anti_hammer['session'] = array();
  957. if ($anti_hammer['use_php_sessions']) {
  958. // Regular php session..
  959. session_start();
  960. $anti_hammer['session'] = $_SESSION['anti_hammer'];
  961. } else { // Anti-Hammer's built-in session mechanism..
  962. // Create a unique ID for this client..
  963. $id_str = '';
  964. $anti_hammer['client_data'] = explode(',', $anti_hammer['client_data']);
  965. foreach ($anti_hammer['client_data'] as $element) {
  966. $id_str .= $anti_hammer[trim($element)];
  967. }
  968. $anti_hammer['client_id'] = md5($id_str);
  969. $fake_sess_file = $anti_hammer['data_path'].'/'.$anti_hammer['sessions_folder'].'/'.$anti_hammer['ID_prefix'].$anti_hammer['client_id'];
  970. if (file_exists($fake_sess_file)) {
  971. $anti_hammer['session'] = read_fake_session($fake_sess_file);
  972. }
  973. }
  974. /*
  975. Useful use of a "cat"..
  976. It seems to me that I unwittingly created a system whereby the less
  977. information a client is wiling to give, the more likely they are to be
  978. banned. I say "seems", because we create an md5 of this information, so the
  979. actual likelyhood of colliding session ID's is astronomically low. However,
  980. I like the *principle* of the thing.
  981. */
  982. //*> Calculate Hammer Rate..
  983. //> How much time since their last request (in 100/th Second)
  984. if (isset($anti_hammer['session']['last_request'])) {
  985. $hammer_rate = $anti_hammer['now_time'] - $anti_hammer['session']['last_request'] + 1; // always +1!
  986. } else {
  987. // new visitor (no session, yet)
  988. $hammer_rate = $anti_hammer['hammer_time'] + 1; // so long as it's greater than hammer_time
  989. }
  990. //*> BANS!
  991. /*
  992. Check for BANS..
  993. Their ban has elapsed..
  994. */
  995. if ($hammer_rate > ($anti_hammer['ban_time']*60*60*100)) { // {@24} = 8640000 = 24 hours (in 100th/second)
  996. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'] - 1;
  997. $hammer_rate = $anti_hammer['hammer_time'] + 1;
  998. $anti_hammer['session']['hammer'] = $anti_hammer['trigger_levels'][0]-3; // Repeat-offenders do not start from Zero!
  999. unset($anti_hammer['session']['cut_off']);
  1000. // do not return yet - we still need to write the updated session data.
  1001. }
  1002. /*
  1003. BANNED!
  1004. CUT_OFF has already been set -- BYE NOW!
  1005. */
  1006. if ($anti_hammer['cut_off'] and isset($anti_hammer['session']['cut_off'])) {
  1007. send_503_kill('', 60 * 60 * $anti_hammer['ban_time']);
  1008. }
  1009. /*
  1010. OKAY, still here..
  1011. */
  1012. //*> GC
  1013. /*
  1014. Start with Garbage Collection..
  1015. */
  1016. if (!$anti_hammer['use_php_sessions']) {
  1017. CollectGarbage($anti_hammer['data_path'].'/'.$anti_hammer['sessions_folder'].'/Counter',
  1018. $anti_hammer['GC_limit'],$anti_hammer['ID_prefix'], $anti_hammer['GC_age']);
  1019. }
  1020. /*
  1021. Miscelleneous Protections..
  1022. */
  1023. if (isset($anti_hammer['banned_ip_list'])) { validate_ip(); } // on fail, send 403 (Forbidden) error
  1024. if (isset($anti_hammer['banned_urls_list'])) { validate_url(); } // on fail, send 501 (Service Not Implemented) error
  1025. if (isset($anti_hammer['banned_agents_list'])) { validate_agent(); } // on fail, send 403 error
  1026. if (!$anti_hammer['allow_empty_UA'] and !$anti_hammer['user_agent']) {
  1027. $msg = '';
  1028. if (isset($anti_hammer['empty_UA_message'])) {
  1029. $msg = $anti_hammer['empty_UA_message'];
  1030. }
  1031. send_503_kill($msg);
  1032. }
  1033. //*> It's Hammer-Time!
  1034. $killpage = false;
  1035. if ($hammer_rate < $anti_hammer['hammer_time']) {
  1036. $retry_str = 'a few ';
  1037. @$anti_hammer['session']['hammer'] += 1;
  1038. if ($anti_hammer['session']['hammer'] > ($anti_hammer['trigger_levels'][0]-1)) {
  1039. // cut-off..
  1040. if ($anti_hammer['cut_off'] and $anti_hammer['session']['hammer'] > $anti_hammer['cut_off']) {
  1041. $anti_hammer['kill_msg'] = $anti_hammer['cut_off_msg'];
  1042. $anti_hammer['session']['cut_off'] = true;
  1043. }
  1044. if ($anti_hammer['cut_off'] and $anti_hammer['session']['hammer'] == $anti_hammer['cut_off']) {
  1045. $anti_hammer['kill_msg'] = '<h1>THIS IS YOUR LAST WARNING!</h1>'.$anti_hammer['kill_msg'];
  1046. }
  1047. // rolling ban time, increments with each hammer..
  1048. if ($anti_hammer['rolling_trigger']) {
  1049. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'] + (($anti_hammer['session']['hammer']*100)-1);
  1050. $retry_str = ah_int2eng($anti_hammer['session']['hammer']);
  1051. } else {
  1052. // predefined ban levels.. these are more effective, as they shock the user with increasing jumps!
  1053. if (($anti_hammer['session']['hammer'] > $anti_hammer['trigger_levels'][0]) and ($anti_hammer['session']['hammer'] <= $anti_hammer['trigger_levels'][1])) {
  1054. // we simply nudge their start time forward by *this* many seconds (into the future!)..
  1055. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'] + (($anti_hammer['waiting_times'][0]*100)-1); // 299 = Three second penalty.
  1056. $retry_str = ah_int2eng($anti_hammer['waiting_times'][0]);
  1057. } elseif (($anti_hammer['session']['hammer'] > $anti_hammer['trigger_levels'][1]) and ($anti_hammer['session']['hammer'] <= $anti_hammer['trigger_levels'][2])) {
  1058. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'] + (($anti_hammer['waiting_times'][1]*100)-1); // Five second penalty! (by default)
  1059. $retry_str = ah_int2eng($anti_hammer['waiting_times'][1]);
  1060. } elseif (($anti_hammer['session']['hammer'] >= $anti_hammer['trigger_levels'][2]) and ($anti_hammer['session']['hammer'] <= $anti_hammer['trigger_levels'][3])) {
  1061. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'] + (($anti_hammer['waiting_times'][2]*100)-1); // Ten second penalty! (etc.)
  1062. $retry_str = ah_int2eng($anti_hammer['waiting_times'][2]);
  1063. } elseif ($anti_hammer['session']['hammer'] >= $anti_hammer['trigger_levels'][3]) {
  1064. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'] + (($anti_hammer['waiting_times'][3]*100)-1); // Twenty second penalty!
  1065. $retry_str = ah_int2eng($anti_hammer['waiting_times'][3]);
  1066. }
  1067. }
  1068. $killpage = true;
  1069. }
  1070. } else {
  1071. $anti_hammer['session']['last_request'] = $anti_hammer['now_time'];
  1072. }
  1073. //*> write client session data..
  1074. WriteHammerData();
  1075. //*> Kill Page
  1076. if ($killpage) {
  1077. //echo '<pre>anti_hammer:',htmlentities(print_r($anti_hammer,true)),'</pre>';//:debug
  1078. //echo '<pre>_SERVER:',htmlentities(print_r($_SERVER,true)),'</pre>';//:debug
  1079. $km = '<!DOCTYPE HTML SYSTEM><html><head><title>'.$anti_hammer['page_title'].'</title></head><body>'.$anti_hammer['kill_msg'];
  1080. $anti_hammer['session']['last_request_url'] = $_SERVER['REQUEST_URI'];
  1081. $anti_hammer['session']['last_post'] = $_POST;
  1082. if (!isset($anti_hammer['session']['cut_off'])) {
  1083. $km .= '
  1084. You must wait '.$retry_str.'seconds before trying again.<br /><br />
  1085. If you believe this is in error, please mail '.$anti_hammer['webmaster'].' about it!<br />
  1086. &lt;'.$anti_hammer['error_mail'].'&gt;<br />
  1087. <div style="font-size:small;position:fixed;bottom:10px;right:10px;">
  1088. <a title="Automatically Ban Web Site Hammers!
  1089. Protect your valuable server resources for *genuine* clients" target="_blank" rel="noopener noreferrer"
  1090. id="link-Get-Anti-Hammer" href="https://corz.org/server/tools/anti-hammer/">Get Anti-Hammer protection for your own site!</a>
  1091. </div></body></html>';
  1092. // You gotta leave the link in people, that's the deal!
  1093. // corz.org is my livelihood, and this link is the best promotion I have!
  1094. // It's fixed away in the bottom corner, and should not interfere with your page.
  1095. // But if it does, please just move it somewhere else!
  1096. }
  1097. if (file_exists(dirname($anti_hammer['log']))) {
  1098. add_log_data($anti_hammer['log'], create_log_data());
  1099. }
  1100. send_503_kill($km, $anti_hammer['final_time']+1);
  1101. }
  1102. //*> Referer spam!
  1103. if ($anti_hammer['validate_referers']) {
  1104. $validated = validate_referer();
  1105. if (!$validated) {
  1106. die_spammer();
  1107. }
  1108. }
  1109. /*
  1110. fin
  1111. */
  1112. function get_rhost() {
  1113. global $anti_hammer;
  1114. $anti_hammer['remote_host'] = '';
  1115. if ($anti_hammer['lookup_failures']) {
  1116. $anti_hammer['remote_host'] = gethostbyaddr($anti_hammer['remote_ip']).' ';
  1117. }
  1118. }
  1119. // write the updated hammer info to the fake/session file..
  1120. function WriteHammerData() {
  1121. global $anti_hammer;
  1122. if ($anti_hammer['use_php_sessions']) {
  1123. $_SESSION['anti_hammer']['last_request'] = $anti_hammer['session']['last_request'];
  1124. $_SESSION['anti_hammer']['hammer'] = $anti_hammer['session']['hammer'];
  1125. $_SESSION['anti_hammer']['cut_off'] = $anti_hammer['session']['cut_off'];
  1126. } else {
  1127. write_fake_session($GLOBALS['fake_sess_file'], $anti_hammer['session']);
  1128. }
  1129. }
  1130. /*
  1131. Append data to a file.
  1132. To wipe the file, pass true as the 3rd paramater.
  1133. */
  1134. function add_log_data($file, $data, $wipe=false) {
  1135. // if it's not there, try to create it..
  1136. if (!file_exists($file)) $fp = fopen($file, 'wb');
  1137. if (!file_exists($file)) {
  1138. $GLOBALS['errors']['add_log_data'] = "can't create $file";
  1139. return $GLOBALS['errors']['add_log_data'];
  1140. }
  1141. if (strlen($data) < 4) {
  1142. $GLOBALS['errors']['add_log_data'] = "string '$data' too short! (need 4 or more characters)";
  1143. return $GLOBALS['errors']['add_log_data'];
  1144. }
  1145. $flag = 'ab';
  1146. if ($wipe) { $flag = 'wb'; }
  1147. if (is_writable($file)) {
  1148. $fp = fopen($file, $flag);
  1149. $lock = flock($fp, LOCK_EX);
  1150. if ($lock) {
  1151. fwrite($fp, $data);
  1152. flock ($fp, LOCK_UN);
  1153. } else {
  1154. $GLOBALS['errors']['add_log_data'] = "couldn't lock $file";
  1155. return $GLOBALS['errors']['add_log_data'];
  1156. }
  1157. fclose($fp);
  1158. } else {
  1159. $GLOBALS['errors']['add_log_data'] = "can't write to $file";
  1160. return $GLOBALS['errors']['add_log_data'];
  1161. }
  1162. }
  1163. // read serialized array data from a file, and return as an array..
  1164. function read_fake_session($no_cookie_file) {
  1165. if (file_exists($no_cookie_file)) {
  1166. $file_handle = fopen($no_cookie_file, 'rb');
  1167. if ($file_handle) {
  1168. $lock = flock($file_handle, LOCK_EX);
  1169. if ($lock) {
  1170. $file_contents = @fread($file_handle, filesize($no_cookie_file));
  1171. flock ($file_handle, LOCK_UN);
  1172. }
  1173. }
  1174. fclose($file_handle);
  1175. } else { return false; }
  1176. $file_contents = unserialize($file_contents);
  1177. if (is_array($file_contents)) {
  1178. return $file_contents;
  1179. }
  1180. }
  1181. // serialize an array and write the string data to a file..
  1182. function write_fake_session($no_cookie_file, $array) {
  1183. $data = serialize($array);
  1184. if (empty($data)) { return; }
  1185. $fp = @fopen($no_cookie_file, 'wb');
  1186. if ($fp) {
  1187. $lock = flock($fp, LOCK_EX);
  1188. if ($lock) {
  1189. fwrite($fp, $data);
  1190. flock ($fp, LOCK_UN);
  1191. }
  1192. fclose($fp);
  1193. clearstatcache();
  1194. return (1);
  1195. }
  1196. }
  1197. /*
  1198. CollectGarbage
  1199. You could transplant this into another web app fairly easily.
  1200. Useful stuf..
  1201. */
  1202. function CollectGarbage($count_file, $limit, $prefix='HammerID_', $GC_age=12) {
  1203. if ($limit === 0) { return; }
  1204. if (ah_increment_hit_counter($count_file) > $limit) {
  1205. $file_list = array();
  1206. if ($the_dir = @opendir(dirname($count_file))) {
  1207. while (false != ($file = readdir($the_dir))) {
  1208. if ((ord($file) != 46) and strpos($file, $prefix) === 0) {
  1209. $file_path = dirname($count_file).'/'.$file;
  1210. if (file_exists($file_path)) {
  1211. if (@filemtime($file_path) < (time() - $GC_age*60*60)) {
  1212. @unlink($file_path);
  1213. }
  1214. }
  1215. }
  1216. }
  1217. }
  1218. ah_increment_hit_counter($count_file, 0, 1); // reset the counter
  1219. }
  1220. }
  1221. //
  1222. // 2do..
  1223. // Run this in another thread? Or maybe a simple http request, perhaps
  1224. // with $_GET, to flip Ant-Hammer to GC mode in the Background - this task
  1225. // could be done after the request is already sent, even simultaneously;
  1226. // there may be a *lot* of files in this directory.
  1227. //
  1228. // Having said that, it's *very* fast, and only runs once per 10,000 or so
  1229. // ($limit) hits.
  1230. //
  1231. /*
  1232. increment a counter()
  1233. from my "file-tools.php", available elsewhere.
  1234. */
  1235. function ah_increment_hit_counter($count_file, $report_only=false, $reset=false) {
  1236. $count = false;
  1237. if (!file_exists($count_file) or $reset) {
  1238. $file_pointer = fopen($count_file, 'wb');
  1239. fwrite ($file_pointer, '0');
  1240. fclose ($file_pointer);
  1241. return 0;
  1242. }
  1243. // now the counter..
  1244. if (file_exists($count_file)) {
  1245. // read in the old score..
  1246. $count = trim(file_get_contents($count_file));
  1247. if ($report_only) { return $count; }
  1248. if (!$count) { $count = 0; }
  1249. $count++;
  1250. // write out new score..
  1251. if (is_writable($count_file)) {
  1252. $file_pointer = fopen($count_file, 'wb+');
  1253. $lock = flock($file_pointer, LOCK_EX);
  1254. if ($lock) {
  1255. fwrite($file_pointer, $count);
  1256. flock ($file_pointer, LOCK_UN);
  1257. }
  1258. fclose($file_pointer);
  1259. clearstatcache();
  1260. }
  1261. return $count;
  1262. }
  1263. }
  1264. /*
  1265. Integers To English Words.
  1266. Converts 1145432 into..
  1267. "one million, one hundred and forty five thousand, four hundred and thirty two"
  1268. Fairly groovy. ;o)
  1269. The regular version is in my "text-func.php", with some other stuff.
  1270. */
  1271. function ah_int2eng($number) {
  1272. $output = '';
  1273. if ($number < 1) $number = 1;
  1274. $GLOBALS['anti_hammer']['final_time'] = $number;
  1275. $units = array(' ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ');
  1276. $teens = array('ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen ');
  1277. $tenners = array('', '', 'twenty ', 'thirty ', 'fourty ', 'fifty ', 'sixty ', 'seventy ', 'eighty ', 'ninety ');
  1278. $lint = strlen($number);
  1279. if ($lint > 2) $bigger = true;
  1280. for ($x = $lint ; $x >= 1 ; $x--) {
  1281. $last = substr($output, -5, 4);
  1282. $digit = substr($number, 0, 1);
  1283. $number = substr($number, 1);
  1284. if ($x % 3 == 2) {
  1285. if ($digit == 1) { // 10-19..
  1286. $digit = substr($number, 0, 1);
  1287. $number = substr($number, 1);
  1288. $x--;
  1289. if ($last == 'sand') { $output .= 'and '; }
  1290. $output .= $teens[$digit];
  1291. } else { // 20-99..
  1292. if (($last == 'sand') ) { $output .= 'and '; }
  1293. $output .= $tenners[$digit];
  1294. }
  1295. } else {
  1296. if (($x % 3 != 1) and ($digit > 0) and (!empty($output))) { $output .= ', '; }
  1297. $output .= $units[$digit];
  1298. }
  1299. if ((strlen($number) % 3) == 0) {
  1300. $bignum = ah_bignumbers(strlen($number) / 3);
  1301. if (($last == 'dred') and ($bignum != 'thousand')) { $output .= 'and ';}
  1302. $output .= $bignum;
  1303. }
  1304. if ((strlen($number) % 3) == 2 and $digit > 0) {
  1305. $output .= 'hundred and ';
  1306. }
  1307. }
  1308. // clean up the output..
  1309. $output = str_replace(' ', ' ', $output);
  1310. $output = str_replace('red and thou', 'red thou', $output);
  1311. $output = str_replace('red and mill', 'red mill', $output);
  1312. $output = str_replace('lion thousand', 'lion ', $output);
  1313. if (substr($output, -5) == ' and ') { $output = substr($output, 0, -5).' '; }
  1314. return $output;
  1315. }
  1316. /*
  1317. it just looks better, okay! */
  1318. function ah_bignumbers($test) {
  1319. switch ($test) {
  1320. case 0:
  1321. $test = "";
  1322. break;
  1323. case 1:
  1324. $test = "thousand";
  1325. break;
  1326. case 2:
  1327. $test = "million";
  1328. break;
  1329. case 3:
  1330. $test = "trillion"; // <- that's a lot of comments!
  1331. break;
  1332. }
  1333. return $test;
  1334. }
  1335. /*
  1336. function read_ini() [from my 'ini-tools.php']
  1337. pull the data from the ini file and return as an array
  1338. Usage: array (string {path to file})
  1339. returns false on failure.
  1340. */
  1341. function read_bots_ini($data_file) {
  1342. $ini_array = array();
  1343. if (is_readable($data_file)) {
  1344. $file = file($data_file);
  1345. foreach($file as $conf) {
  1346. // if first real character isn't '#' or ';' and there is a '=' in the line..
  1347. if ( (substr(trim($conf),0,1) != '#')
  1348. and (substr(trim($conf),0,1) != ';')
  1349. and (substr_count($conf,'=') >= 1) ) {
  1350. $eq = strpos($conf, '=');
  1351. $ini_array[trim(substr($conf,0,$eq))] = trim(substr($conf, $eq + 1));
  1352. }
  1353. }
  1354. unset($file);
  1355. return $ini_array;
  1356. } else {
  1357. $GLOBALS['errors']['read_bots_ini'] = "ini file: $file does not exist.";
  1358. return false;
  1359. }
  1360. }
  1361. // Validate Referer against Referer lists..
  1362. // returns true for good referers, false for bad referers..
  1363. //
  1364. function validate_referer(){
  1365. global $anti_hammer;
  1366. // if referer is empty, move on..
  1367. if ($anti_hammer['referer'] == '') { return true; }
  1368. // or some token string (not URL - "none" is common), move on..
  1369. if (!$anti_hammer['domains_only'] and strlen($anti_hammer['referer']) < 11) { return true; } // "http://t.co" is the shortest domain (twits!)
  1370. if ($anti_hammer['domains_only'] and strlen($anti_hammer['referer']) < 4) { return true; } // "t.co" is the shortest domain (twits!)
  1371. // "foobar: http://foobar.com" >> "http://foobar.com"
  1372. if (substr($anti_hammer['referer'], 0, 4) != 'http') {
  1373. $arr = explode('http', $anti_hammer['referer']);
  1374. unset($arr[0]);
  1375. $anti_hammer['referer'] = 'http'.trim(implode($arr));
  1376. }
  1377. // OK, we got a real(ish) URL..
  1378. // Parse the URL into "parts"..
  1379. $this_URLArray = parse_url($anti_hammer['referer']);
  1380. // check & SET ['host']
  1381. if (!isset($this_URLArray['host'])) { // something like "baddomain.com" or "baddomain/foobar"
  1382. $this_URLArray = parse_url('http://'.$this_URLArray['path']);
  1383. }
  1384. // An internal referer..
  1385. if ($this_URLArray['host'] == $anti_hammer['host']) { return true; }
  1386. // Validate the lists..
  1387. $black_is_go = false;
  1388. $white_is_go = false;
  1389. $banned_is_go = false;
  1390. if (isset($anti_hammer['black_list']) and !file_exists($anti_hammer['black_list']) and $anti_hammer['interrogate_referers']) {
  1391. add_log_data($anti_hammer['black_list'], ''); // create the file only
  1392. }
  1393. if (isset($anti_hammer['black_list']) and file_exists($anti_hammer['black_list'])) { $black_is_go = true; }
  1394. if (isset($anti_hammer['white_list']) and !file_exists($anti_hammer['white_list']) and $anti_hammer['interrogate_referers']) {
  1395. add_log_data($anti_hammer['white_list'], '');
  1396. }
  1397. if (isset($anti_hammer['white_list']) and file_exists($anti_hammer['white_list'])) { $white_is_go = true; }
  1398. if (isset($anti_hammer['banned_referers_list']) and file_exists($anti_hammer['banned_referers_list'])) { $banned_is_go = true; }
  1399. // Test domain name or entire URL?..
  1400. $test_referer = $anti_hammer['referer'];
  1401. if ($anti_hammer['domains_only']) { $test_referer = $this_URLArray['host']; }
  1402. // There's no white list, check black-list(s) right now..
  1403. if ($black_is_go and !$white_is_go) {
  1404. if (is_listed($anti_hammer['black_list'], $test_referer, $anti_hammer['domains_only'])) { return false; }
  1405. if ($banned_is_go) { if (is_listed($anti_hammer['banned_referers_list'], $test_referer, $anti_hammer['domains_only'])) { return false; } }
  1406. }
  1407. // Using two or three dynamic lists, check white-list first (slightly quicker for friendly referers)..
  1408. if ($white_is_go) {
  1409. if (is_listed($anti_hammer['white_list'], $test_referer, $anti_hammer['domains_only'])) { return true; }
  1410. if ($black_is_go) { if (is_listed($anti_hammer['black_list'], $test_referer, $anti_hammer['domains_only'])) { return false; } }
  1411. if ($banned_is_go) { if (is_listed($anti_hammer['banned_referers_list'], $test_referer, $anti_hammer['domains_only'])) { return false; } }
  1412. }
  1413. // Still here, must be a NEW REFERER..
  1414. // Shall we Interrogate them???
  1415. if ($anti_hammer['interrogate_referers']) {
  1416. $list_pre = '';
  1417. $list_add = @$this_URLArray['path'];
  1418. // (re)set wonky prefs..
  1419. if ($anti_hammer['time_out'] < 1 or $anti_hammer['time_out'] > 120) { $anti_hammer['time_out'] = 10; }
  1420. ini_set('default_socket_timeout', $anti_hammer['time_out']);
  1421. // fetch contents of referring page..
  1422. ini_set('track_errors', 1);
  1423. if ($anti_hammer['max_referer_get'] < 32) { $anti_hammer['max_referer_get'] = 32; }
  1424. $ref_contents = @file_get_contents($anti_hammer['referer'], FALSE, NULL, 32, $anti_hammer['max_referer_get']);
  1425. if (isset($php_errormsg) and $php_errormsg) {
  1426. add_log_data($anti_hammer['black_log'], "GET ERROR:\t".$anti_hammer['referer'].' => '.$php_errormsg."\n");
  1427. $php_errormsg = '';
  1428. }
  1429. // checking domain or full URL?..
  1430. if ($anti_hammer['domains_only']) {
  1431. $list_pre = '';
  1432. $list_add = '';
  1433. } else { // I don't like elseif!
  1434. if ($anti_hammer['record_scheme']) {
  1435. if (isset($this_URLArray['scheme'])) {
  1436. $list_pre = $this_URLArray['scheme'].'://';
  1437. } else {
  1438. $list_pre = 'http://';
  1439. }
  1440. }
  1441. }
  1442. // check page data for back-links..
  1443. // a link to our page exists on their page, add this referer to the white-list and continue..
  1444. if (link_in_page($ref_contents, $anti_hammer['uri'], $anti_hammer['link_check_accuracy'])) {
  1445. if ($white_is_go and !is_listed($anti_hammer['white_list'], $list_pre.$this_URLArray['host'].$list_add, $anti_hammer['domains_only'])) {
  1446. add_log_data($anti_hammer['white_list'], $list_pre.$this_URLArray['host'].$list_add."\n");
  1447. }
  1448. return true;
  1449. } else {
  1450. // no link back to our site, add this referer to the black-list and end page here.
  1451. if ($black_is_go and !is_listed($anti_hammer['black_list'], $list_pre.$this_URLArray['host'].$list_add, $anti_hammer['domains_only'])) {
  1452. // if ($black_is_go) {
  1453. add_log_data($anti_hammer['black_list'], $list_pre.$this_URLArray['host'].$list_add."\n");
  1454. }
  1455. if ($anti_hammer['black_log']) {
  1456. add_log_data($anti_hammer['black_log'], create_log_data(true, true));
  1457. }
  1458. return false;
  1459. }
  1460. }
  1461. }
  1462. function link_in_page($page_string, $link_test, $accuracy=1) {
  1463. switch ($accuracy) {
  1464. case 2: // Method 2.. (more accurate than Method 1, twice as fast as method 3)
  1465. $page_links = explode('href', $page_string); //, $link_limit) // limit set by GET
  1466. $plc = count($page_links);
  1467. for ($i=1; $i < $plc; $i++) { // omit first and last elements
  1468. if (strpos(substr($page_links[$i], 1, stripos($page_links[$i], '>') - 1), $link_test)
  1469. or strpos(substr($page_links[$i], 1, stripos($page_links[$i], '>') - 1), urlencode($link_test))) { return true; }
  1470. }
  1471. break;
  1472. case 3: // Method 3.. (most accurate, slowest method)
  1473. preg_match_all("/a[\s]+[^>]*?href[\s]?=[\s\"\']+(.*?)[\"\']+.*?>([^<]+|.*?)?<\/a>/", $page_string, $matches);
  1474. $matches = $matches[1];
  1475. foreach($matches as $var) {
  1476. if ($var == $link_test or $var == urlencode($link_test)) { return true; }
  1477. }
  1478. break;
  1479. default: // Default Method.. (fastest, least accurate method)
  1480. if (stripos($page_string, $link_test) or stripos($page_string, urlencode($link_test))) { return true; }
  1481. }
  1482. return false;
  1483. }
  1484. // Validate URL against Banned URLs list..
  1485. //
  1486. function validate_url(){
  1487. global $anti_hammer;
  1488. if (file_exists($anti_hammer['banned_urls_list'])) {
  1489. if (is_listed($anti_hammer['banned_urls_list'], urldecode($anti_hammer['request']))) {
  1490. $msg = '';
  1491. if (isset($anti_hammer['bad_url_message'])) {
  1492. $msg = $anti_hammer['bad_url_message'];
  1493. }
  1494. send_501_kill($msg);
  1495. }
  1496. }
  1497. }
  1498. // Validate User Agent against Banned User Agents list..
  1499. //
  1500. function validate_agent(){
  1501. global $anti_hammer;
  1502. if (file_exists($anti_hammer['banned_agents_list'])) {
  1503. if (is_listed_regex($anti_hammer['banned_agents_list'], $anti_hammer['user_agent'])) {
  1504. $msg = '';
  1505. if (isset($anti_hammer['bad_agent_message'])) {
  1506. $msg = $anti_hammer['bad_agent_message'];
  1507. }
  1508. send_403_kill($msg);
  1509. }
  1510. }
  1511. }
  1512. // Validate IP Address against Banned IP Addresses list..
  1513. //
  1514. function validate_ip(){
  1515. global $anti_hammer;
  1516. $ip_array = AH_GrabListFileIntoArray($anti_hammer['banned_ip_list']);
  1517. if (!is_array($ip_array)) { return false; }
  1518. foreach($ip_array as $banned_ip) {
  1519. if (@strpos($anti_hammer['remote_ip'], trim($banned_ip)) === 0) {
  1520. // if (ipCheck($anti_hammer['remote_ip'], trim($banned_ip))) {
  1521. $msg = '';
  1522. if (isset($anti_hammer['bad_ip_message'])) {
  1523. $msg = $anti_hammer['bad_ip_message'];
  1524. } else {
  1525. $msg = $anti_hammer['ip_ban_message'];
  1526. }
  1527. send_403_kill($msg);
  1528. }
  1529. }
  1530. return;
  1531. }
  1532. //// with thanks to claudiu at cnixs dot com
  1533. //function ipCheck ($IP, $CIDR) {
  1534. // list ($net, $mask) = split ("/", $CIDR);
  1535. // $ip_net = ip2long ($net);
  1536. // $ip_mask = ~((1 << (32 - $mask)) - 1);
  1537. // $ip_ip = ip2long ($IP);
  1538. // $ip_ip_net = $ip_ip & $ip_mask;
  1539. // return ($ip_ip_net == $ip_net);
  1540. //}
  1541. // returns true if there is a matching entry in a given list, otherwise false.
  1542. //
  1543. function is_listed($list_array_file, $test_ref, $only_domains=false) {
  1544. $list_array = AH_GrabListFileIntoArray($list_array_file);
  1545. if (!is_array($list_array)) { return false; }
  1546. $pos = false; // only need to set once, for new files.
  1547. foreach ($list_array as $list_ref) {
  1548. $list_ref = trim($list_ref);
  1549. if ($list_ref) {
  1550. $pos = stripos($test_ref, $list_ref); // not FALSE if the list string is IN the test referer string
  1551. if ($only_domains) {
  1552. // should match right at the start === 0
  1553. if ($pos === 0) {
  1554. return true;
  1555. }
  1556. } else {
  1557. // matching anywhere is fine.. (no match equals EXACTLY false)
  1558. if ($pos !== false) {
  1559. return true;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. return false;
  1565. }
  1566. // Used to validate User Agent Strings.
  1567. //
  1568. // Returns true if there is a matching entry in a given list, otherwise false.
  1569. // NOTE: You can use regular expression in the entries.
  1570. //
  1571. function is_listed_regex($list_array_file, $test_ref) {
  1572. $list_array = AH_GrabListFileIntoArray($list_array_file);
  1573. if (!is_array($list_array)) { return false; }
  1574. foreach ($list_array as $list_ref) {
  1575. $list_ref = trim($list_ref);
  1576. if ($list_ref) {
  1577. if (@preg_match("/$list_ref/i", $test_ref)) {
  1578. return true;
  1579. }
  1580. }
  1581. }
  1582. return false;
  1583. }
  1584. // file() has improved!
  1585. function AH_GrabListFileIntoArray($list_file) {
  1586. if (!file_exists($list_file)) { return ''; }
  1587. return file($list_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  1588. }
  1589. function die_spammer() {
  1590. global $anti_hammer;
  1591. $anti_hammer['uri'] = str_replace($anti_hammer['chop'], '', $anti_hammer['uri']);
  1592. $die_msg = '<!DOCTYPE html>
  1593. <html lang="en">
  1594. <head>
  1595. <meta charset="utf-8">
  1596. <meta name="viewport" content="initial-scale=1.0, width=device-width" />
  1597. <title>'.$anti_hammer['title'].'</title>
  1598. <style type="text/css" media="screen">
  1599. body {
  1600. margin: 3rem 4rem;
  1601. background: #FF9100;
  1602. color: #330000;
  1603. font-family:Tahoma, sans-serif;
  1604. }
  1605. a:link, a:visited, a:hover, a:active {
  1606. color: #330000;
  1607. text-decoration: none;
  1608. }
  1609. a:hover { text-decoration: underline; }
  1610. pre { font-size: small; }
  1611. </style>
  1612. </head>
  1613. <body>';
  1614. if ($anti_hammer['analytics_code']) {
  1615. $die_msg .= '
  1616. <script nonce="'.$_SERVER['CSP_NONCE'].'">
  1617. (function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){
  1618. (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  1619. m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  1620. })(window,document,\'script\',\'//www.google-analytics.com/analytics.js\',\'ga\');
  1621. ga(\'create\', \''.$anti_hammer['analytics_code'].'\', \'auto\');
  1622. ga(\'send\', \'pageview\');
  1623. </script>';
  1624. }
  1625. $die_msg .= '
  1626. '.$anti_hammer['bad_referer_msg'].'<br />
  1627. <pre><a href="https://corz.org/server/tools/anti-hammer/" title="Ban Web Site Hammers, protect your valuable resources for /real/ clients.">'.
  1628. 'Anti-Hammer</a>\'s Referer Spam Protection prevented access to: <a href="'.$anti_hammer['uri'].'">'.$anti_hammer['uri'].'</a></pre><br />
  1629. <br />';
  1630. // you may want to insert some google ads or something here..
  1631. if (file_exists($anti_hammer['die_insert'])) {
  1632. ob_start();
  1633. include $anti_hammer['die_insert'];
  1634. $die_msg .= ob_get_clean();
  1635. }
  1636. $die_msg .= '
  1637. </body>
  1638. </html>';
  1639. send_503_kill($die_msg, 1);
  1640. }
  1641. function create_log_data($log_hammer=true, $ref_first=false) {
  1642. global $anti_hammer;
  1643. $log_data = '';
  1644. if ($ref_first) {
  1645. $log_data .= "referer:\t".$anti_hammer['referer']."\n";
  1646. }
  1647. $log_data .= "page: \t".$anti_hammer['request']."\n";
  1648. if ($log_hammer) {
  1649. $log_data .= "time: \t".date('Y.m.d h:i:s A')."\t".'ID: '.$anti_hammer['client_id']."\t"."x ".@$anti_hammer['session']['hammer']."\n";
  1650. }
  1651. get_rhost();
  1652. $log_data .=
  1653. "visitor:\t".$anti_hammer['remote_host'].'['.$anti_hammer['remote_ip'].']'."\t"."(".$anti_hammer['user_agent'].")"."\n"
  1654. ."accepts:\t".$anti_hammer['accepts']."\n";
  1655. if (!$ref_first) {
  1656. $log_data .= "referer:\t".$anti_hammer['referer']."\n";
  1657. }
  1658. return $log_data."\n";
  1659. }
  1660. // send a Service Temporary Unavailable header..
  1661. // $ra_time (Retry-After) time in seconds.
  1662. function send_503_kill($msg='', $ra_time=1) {
  1663. global $anti_hammer;
  1664. header($_SERVER['SERVER_PROTOCOL'].' 503 Service Temporarily Unavailable');
  1665. header('Status: 503 Service Temporarily Unavailable');
  1666. if ($ra_time > 0) header('Retry-After: '.$ra_time);
  1667. header('Connection: Close');
  1668. die($msg);
  1669. }
  1670. function send_501_kill($msg='') {
  1671. header($_SERVER['SERVER_PROTOCOL'].' 501 Not Implemented');
  1672. header('Status: 501 Not Implemented');
  1673. header('Content-Type: text/plain');
  1674. header('Connection: Close');
  1675. if (!$msg) { $msg = "The requested URL is not implemented on this server."; }
  1676. die($msg);
  1677. }
  1678. function send_403_kill($msg='') {
  1679. header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
  1680. header('Status: 403 Forbidden');
  1681. header('Content-Type: text/plain');
  1682. header('Connection: Close');
  1683. if (!$msg) { $msg = "Due to abuse, possibly by a web 'sucker', \nthis request has been denied.\n\nIn other words, go away quickly!"; }
  1684. die($msg);
  1685. }
  1686. function AH_stop_watch() {
  1687. if (func_num_args() > 0) { $press = func_get_arg(0); }
  1688. else { $press = false; }
  1689. static $start_time;
  1690. $time = array_sum(explode(' ', microtime(true)));
  1691. if (!empty($press)) {
  1692. $start_time = $time;
  1693. return ($start_time);
  1694. } else {
  1695. return ($time - $start_time);
  1696. }
  1697. }
  1698. // direct access....
  1699. function direct() {
  1700. return 'This script is designed to run as a php auto-prepend, like so (in .htaccess)..<br /><br />
  1701. <code>php_value auto_prepend_file "/real/full/server/path/to/anti-hammer.php"</code><br /><br />
  1702. If you are running PHP as a CGI, put a line in your local php.ini/.user.ini file, instead:<br /><br />
  1703. <code>auto_prepend_file = "/real/full/server/path/to/anti-hammer.php"</code>';
  1704. }
  1705. /*
  1706. Latest changes:
  1707. 0.9.9.1:
  1708. Improved garbage collection (stale sessions).
  1709. 0.9.9.0:
  1710. Rather than supress any errors in the referrer validation GET completely, we now capture and
  1711. log them to the black log.
  1712. Anti-Hammer no checks that a domain/URL does not already exist in the black/white list before
  1713. adding it, to prevent duplicate entries (which can happen when there are lots of near-
  1714. simultaneous requests)
  1715. */
  1716. ?>

Welcome to corz.org!

I'm always messing around with the back-end.. See a bug? Wait a minute and try again. Still see a bug? Mail Me!