3 # Search logs for high-bandwith users and create a list of suspicious IPs.
4 # There are three states: bulk, block, ban. The first are bulk requesters
5 # that need throtteling, the second bulk requesters that have overdone it
6 # and the last manually banned IPs.
8 # The list can then be used in apache using rewrite rules to
9 # direct bulk users to smaller thread pools or block them. A
10 # typical apache config that uses php-fpm pools would look
13 # Alias /nominatim-www/ "/var/www/nominatim/"
14 # Alias /nominatim-bulk/ "/var/www/nominatim/"
15 # <Directory "/var/www/nominatim/">
16 # Options MultiViews FollowSymLinks
17 # AddType text/html .php
20 # <Location /nominatim-www>
21 # AddHandler fcgi:/var/run/php5-fpm-www.sock .php
23 # <Location /nominatim-bulk>
24 # AddHandler fcgi:/var/run/php5-fpm-bulk.sock .php
27 # Redirect 509 /nominatim-block/
28 # ErrorDocument 509 "Bandwidth limit exceeded."
29 # Redirect 403 /nominatim-ban/
30 # ErrorDocument 403 "Access blocked."
33 # RewriteMap bulklist txt:/home/wherever/ip-block.map
34 # RewriteRule ^/(.*) /nominatim-${bulklist:%{REMOTE_ADDR}|www}/$1 [PT]
41 BASEDIR = os.path.normpath(os.path.join(os.path.realpath(__file__), '../..'))
46 # Copy into settings/ip_blcoks.conf and adapt as required.
48 BLOCKEDFILE= BASEDIR + '/settings/ip_blocks.map'
49 LOGFILE= BASEDIR + '/log/restricted_ip.log'
51 # space-separated list of IPs that are never banned
53 # space-separated list of IPs manually blocked
56 # time before a automatically blocked IP is allowed back
57 BLOCKCOOLOFF_PERIOD='1 hour'
58 # quiet time before an IP is released from the bulk pool
59 BULKCOOLOFF_PERIOD='15 min'
67 # END OF DEFAULT SETTINGS
71 execfile(os.path.expanduser(BASEDIR + "/settings/ip_blocks.conf"))
75 # determine current load
76 fd = open("/proc/loadavg")
77 avgload = int(float(fd.readline().split()[1]))
80 BLOCK_LIMIT = BLOCK_UPPER - BLOCK_LOADFAC * avgload
82 # read the previous blocklist
83 WHITELIST = set(WHITELIST.split()) if WHITELIST else set()
86 BLACKLIST = set(BLACKLIST.split()) if BLACKLIST else set()
91 fd = open(BLOCKEDFILE)
93 ip, typ = line.strip().split(' ')
94 if ip not in BLACKLIST:
101 pass #ignore non-existing file
103 conn = psycopg2.connect('dbname=nominatim')
106 # get the new block candidates
108 SELECT ipaddress, max(count) FROM
110 (SELECT ipaddress, sum(CASE WHEN type = 'search' THEN 3 ELSE 1 END) as count FROM new_query_log
111 WHERE starttime > now() - interval '1 hour' GROUP BY ipaddress) as i
114 (SELECT ipaddress, count * 4 FROM
115 (SELECT ipaddress, sum(CASE WHEN type = 'search' THEN 2 ELSE 1 END) as count FROM new_query_log
116 WHERE starttime > now() - interval '10 min' GROUP BY ipaddress) as i
117 WHERE count > %s)) as o
119 """, (BULKLONG_LIMIT, BULKSHORT_LIMIT))
125 if c[0] not in WHITELIST and c[0] not in BLACKLIST:
126 if c[1] > BLOCK_UPPER and c[0] not in prevbulks:
128 if c[0] not in prevblocks:
129 emergencyblocks.append(c[0])
133 # IPs from the block list that are no longer in the bulk list
134 deblockcandidates = set()
135 # IPs from the bulk list that are no longer in the bulk list
136 debulkcandidates = set()
137 # new IPs to go into the block list
141 for ip in prevblocks:
146 deblockcandidates.add(ip)
150 if bulkips[ip] > BLOCK_LIMIT:
152 newlyblocked.append(ip)
157 debulkcandidates.add(ip)
159 # cross-check deblock candidates
160 if deblockcandidates:
162 SELECT DISTINCT ipaddress FROM new_query_log
163 WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
164 """ % ("','".join(deblockcandidates), BLOCKCOOLOFF_PERIOD))
168 deblockcandidates.remove(c[0])
169 # deblocked IPs go back to the bulk pool to catch the ones that simply
170 # ignored the HTTP error and just continue to hammer the API.
171 # Those that behave and stopped will be debulked a minute later.
172 for ip in deblockcandidates:
175 # cross-check debulk candidates
178 SELECT DISTINCT ipaddress FROM new_query_log
179 WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
180 """ % ("','".join(debulkcandidates), BULKCOOLOFF_PERIOD))
184 debulkcandidates.remove(c[0])
186 for ip in bulkips.iterkeys():
189 # write out the new list
190 fd = open(BLOCKEDFILE, 'w')
192 fd.write(ip + " block\n")
194 fd.write(ip + " bulk\n")
196 fd.write(ip + " ban\n")
200 logstr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
201 fd = open(LOGFILE, 'a')
202 if deblockcandidates:
203 fd.write(logstr % ('unblocked:', ', '.join(deblockcandidates)))
205 fd.write(logstr % (' debulked:', ', '.join(debulkcandidates)))
207 fd.write(logstr % ('new bulks:', ', '.join(bulkips.keys())))
209 fd.write(logstr % ('dir.block:', ', '.join(emergencyblocks)))
211 fd.write(logstr % ('new block:', ', '.join(newlyblocked)))