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'
71 # END OF DEFAULT SETTINGS
75 execfile(os.path.expanduser(BASEDIR + "/settings/ip_blocks.conf"))
79 # read the previous blocklist
80 WHITELIST = set(WHITELIST.split()) if WHITELIST else set()
83 BLACKLIST = set(BLACKLIST.split()) if BLACKLIST else set()
88 fd = open(BLOCKEDFILE)
90 ip, typ = line.strip().split(' ')
91 if ip not in BLACKLIST:
98 pass #ignore non-existing file
100 # determine current load
101 fd = open("/proc/loadavg")
102 avgload = int(float(fd.readline().split()[2]))
105 conn = psycopg2.connect('dbname=nominatim')
107 cur.execute("select count(*)/60 from new_query_log where starttime > now() - interval '1min'")
108 dbload = int(cur.fetchone()[0])
110 BLOCK_LIMIT = max(BLOCK_LOWER, BLOCK_UPPER - BLOCK_LOADFAC * (dbload - 75))
111 BULKLONG_LIMIT = max(BULK_LOWER, BULKLONG_LIMIT - BULK_LOADFAC * (avgload - 14))
112 if len(prevbulks) > MAX_BULK_IPS:
113 BLOCK_LIMIT = max(3600, BLOCK_LOWER - (len(prevbulks) - MAX_BULK_IPS)*10)
115 # get the new block candidates
117 SELECT ipaddress, max(count) FROM
119 (SELECT ipaddress, sum(case when endtime is null then 1 else 1+1.5*date_part('epoch',endtime-starttime) end) as count FROM new_query_log
120 WHERE starttime > now() - interval '1 hour' GROUP BY ipaddress) as i
123 (SELECT ipaddress, count * 3 FROM
124 (SELECT ipaddress, sum(case when endtime is null then 1 else 1+1.5*date_part('epoch',endtime-starttime) end) as count FROM new_query_log
125 WHERE starttime > now() - interval '10 min' GROUP BY ipaddress) as i
126 WHERE count > %s)) as o
128 """, (BULKLONG_LIMIT, BULKSHORT_LIMIT))
134 if c[0] not in WHITELIST and c[0] not in BLACKLIST:
135 if c[1] > BLOCK_UPPER and c[0] not in prevbulks:
137 if c[0] not in prevblocks:
138 emergencyblocks.append(c[0])
142 # IPs from the block list that are no longer in the bulk list
143 deblockcandidates = set()
144 # IPs from the bulk list that are no longer in the bulk list
145 debulkcandidates = set()
146 # new IPs to go into the block list
150 for ip in prevblocks:
155 deblockcandidates.add(ip)
159 if bulkips[ip] > BLOCK_LIMIT:
161 newlyblocked.append(ip)
166 debulkcandidates.add(ip)
168 # cross-check deblock candidates
169 if deblockcandidates:
171 SELECT DISTINCT ipaddress FROM new_query_log
172 WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
173 """ % ("','".join(deblockcandidates), BLOCKCOOLOFF_PERIOD))
177 deblockcandidates.remove(c[0])
178 # deblocked IPs go back to the bulk pool to catch the ones that simply
179 # ignored the HTTP error and just continue to hammer the API.
180 # Those that behave and stopped will be debulked a minute later.
181 for ip in deblockcandidates:
184 # cross-check debulk candidates
187 SELECT DISTINCT ipaddress FROM new_query_log
188 WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
189 AND starttime > date_trunc('day', now())
190 """ % ("','".join(debulkcandidates), BULKCOOLOFF_PERIOD))
194 debulkcandidates.remove(c[0])
196 for ip in bulkips.iterkeys():
199 # write out the new list
200 fd = open(BLOCKEDFILE, 'w')
202 fd.write(ip + " block\n")
204 fd.write(ip + " bulk\n")
206 fd.write(ip + " ban\n")
210 logstr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
211 fd = open(LOGFILE, 'a')
212 if deblockcandidates:
213 fd.write(logstr % ('unblocked:', ', '.join(deblockcandidates)))
215 fd.write(logstr % (' debulked:', ', '.join(debulkcandidates)))
217 fd.write(logstr % ('new bulks:', ', '.join(bulkips.keys())))
219 fd.write(logstr % ('dir.block:', ', '.join(emergencyblocks)))
221 fd.write(logstr % ('new block:', ', '.join(newlyblocked)))