]> git.openstreetmap.org Git - nominatim.git/blob - utils/cron_banip.py
714df2831c5e81e74ac676ccbee0b621daa42ec7
[nominatim.git] / utils / cron_banip.py
1 #!/usr/bin/python
2 #
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.
7 #
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
11 # like this:
12 #
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
18 #    </Directory>
19 #
20 #    <Location /nominatim-www>
21 #        AddHandler fcgi:/var/run/php5-fpm-www.sock .php
22 #    </Location>
23 #    <Location /nominatim-bulk>
24 #        AddHandler fcgi:/var/run/php5-fpm-bulk.sock .php
25 #    </Location>
26 #
27 #    Redirect 509 /nominatim-block/
28 #    ErrorDocument 509 "Bandwidth limit exceeded."
29 #    Redirect 403 /nominatim-ban/
30 #    ErrorDocument 403 "Access blocked."
31 #
32 #    RewriteEngine On
33 #    RewriteMap bulklist txt:/home/wherever/ip-block.map
34 #    RewriteRule ^/(.*) /nominatim-${bulklist:%{REMOTE_ADDR}|www}/$1 [PT]
35 #
36
37 import os
38 import psycopg2
39 import datetime
40
41 BASEDIR = os.path.normpath(os.path.join(os.path.realpath(__file__), '../..'))
42
43 #
44 # DEFAULT SETTINGS
45 #
46 # Copy into settings/ip_blcoks.conf and adapt as required.
47 #
48 BLOCKEDFILE= BASEDIR + '/settings/ip_blocks.map'
49 LOGFILE= BASEDIR + '/log/restricted_ip.log'
50
51 # space-separated list of IPs that are never banned
52 WHITELIST = ''
53 # space-separated list of IPs manually blocked
54 BLACKLIST = ''
55
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'
60
61 BULKLONG_LIMIT=8000
62 BULKSHORT_LIMIT=2000
63 BLOCK_UPPER=19000
64 BLOCK_LOWER=4000
65 BLOCK_LOADFAC=380
66 BULK_LOADFAC=160
67 BULK_LOWER=1500
68 MAX_BULK_IPS=85
69
70 #
71 # END OF DEFAULT SETTINGS
72 #
73
74 try:
75     execfile(os.path.expanduser(BASEDIR + "/settings/ip_blocks.conf"))
76 except IOError:
77     pass
78
79 # read the previous blocklist
80 WHITELIST = set(WHITELIST.split()) if WHITELIST else set()
81 prevblocks = []
82 prevbulks = []
83 BLACKLIST = set(BLACKLIST.split()) if BLACKLIST else set()
84 newblocks = set()
85 newbulks = set()
86
87 try:
88     fd = open(BLOCKEDFILE)
89     for line in fd:
90         ip, typ = line.strip().split(' ')
91         if ip not in BLACKLIST:
92             if typ == 'block':
93                 prevblocks.append(ip)
94             elif typ == 'bulk':
95                 prevbulks.append(ip)
96     fd.close()
97 except IOError:
98     pass #ignore non-existing file
99
100 # determine current load
101 fd = open("/proc/loadavg")
102 avgload = int(float(fd.readline().split()[2]))
103 fd.close()
104 # DB load
105 conn = psycopg2.connect('dbname=nominatim')
106 cur = conn.cursor()
107 cur.execute("select count(*)/60 from new_query_log where starttime > now() - interval '1min'")
108 dbload = int(cur.fetchone()[0])
109
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)
114
115 # get the new block candidates
116 cur.execute("""
117   SELECT ipaddress, max(count), max(ua) FROM
118    ((SELECT * FROM
119      (SELECT ipaddress, sum(case when endtime is null then 1 else 1+1.5*date_part('epoch',endtime-starttime) end) as count, substring(max(useragent) from 1 for 30) as ua FROM new_query_log
120       WHERE starttime > now() - interval '1 hour' GROUP BY ipaddress) as i
121    WHERE count > %s)
122    UNION
123    (SELECT ipaddress, count * 3, ua FROM
124      (SELECT ipaddress, sum(case when endtime is null then 1 else 1+1.5*date_part('epoch',endtime-starttime) end) as count, substring(max(useragent) from 1 for 30) as ua FROM new_query_log 
125       WHERE starttime > now() - interval '10 min' GROUP BY ipaddress) as i
126    WHERE count > %s)) as o
127   GROUP BY ipaddress
128 """, (BULKLONG_LIMIT, BULKSHORT_LIMIT))
129
130 bulkips = {}
131 emergencyblocks = []
132 useragentblocks = []
133
134 for c in cur:
135     if c[0] not in WHITELIST and c[0] not in BLACKLIST:
136         missing_agent = not c[2] or c[2].startswith('Java/1.')
137         if (missing_agent or c[1] > BLOCK_UPPER) and c[0] not in prevblocks:
138             newblocks.add(c[0])
139             if missing_agent:
140                 useragentblocks.append(c[0])
141             else:
142                 emergencyblocks.append(c[0])
143         else:
144             bulkips[c[0]] = c[1]
145
146 # IPs from the block list that are no longer in the bulk list
147 deblockcandidates = set()
148 # IPs from the bulk list that are no longer in the bulk list
149 debulkcandidates = set()
150 # new IPs to go into the block list
151 newlyblocked = []
152
153
154 for ip in prevblocks:
155     if ip in bulkips:
156         newblocks.add(ip)
157         del bulkips[ip]
158     else:
159         deblockcandidates.add(ip)    
160         
161 for ip in prevbulks:
162     if ip in bulkips:
163         if bulkips[ip] > BLOCK_LIMIT:
164             newblocks.add(ip)
165             newlyblocked.append(ip)
166         else:
167             newbulks.add(ip)
168         del bulkips[ip]
169     else:
170         debulkcandidates.add(ip)
171
172 # cross-check deblock candidates
173 if deblockcandidates:
174     cur.execute("""
175         SELECT DISTINCT ipaddress FROM new_query_log
176         WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
177         """ % ("','".join(deblockcandidates), BLOCKCOOLOFF_PERIOD))
178
179     for c in cur:
180         newblocks.add(c[0])
181         deblockcandidates.remove(c[0])
182 # deblocked IPs go back to the bulk pool to catch the ones that simply
183 # ignored the HTTP error and just continue to hammer the API.
184 # Those that behave and stopped will be debulked a minute later.
185 for ip in deblockcandidates:
186     newbulks.add(ip)
187
188 # cross-check debulk candidates
189 if debulkcandidates:
190     cur.execute("""
191         SELECT DISTINCT ipaddress FROM new_query_log
192         WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
193         AND starttime > date_trunc('day', now())
194         """ % ("','".join(debulkcandidates), BULKCOOLOFF_PERIOD))
195
196     for c in cur:
197         newbulks.add(c[0])
198         debulkcandidates.remove(c[0])
199
200 for ip in bulkips.iterkeys():
201     newbulks.add(ip)
202
203 # write out the new list
204 fd = open(BLOCKEDFILE, 'w')
205 for ip in newblocks:
206     fd.write(ip + " block\n")
207 for ip in newbulks:
208     fd.write(ip + " bulk\n")
209 for ip in BLACKLIST:
210     fd.write(ip + " ban\n")
211 fd.close()
212
213 # write out the log
214 logstr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
215 fd = open(LOGFILE, 'a')
216 if deblockcandidates:
217     fd.write(logstr % ('unblocked:', ', '.join(deblockcandidates)))
218 if debulkcandidates:
219     fd.write(logstr % (' debulked:', ', '.join(debulkcandidates)))
220 if bulkips:
221     fd.write(logstr % ('new bulks:', ', '.join(bulkips.keys())))
222 if emergencyblocks:
223     fd.write(logstr % ('dir.block:', ', '.join(emergencyblocks)))
224 if useragentblocks:
225     fd.write(logstr % (' ua block:', ', '.join(useragentblocks)))
226 if newlyblocked:
227     fd.write(logstr % ('new block:', ', '.join(newlyblocked)))
228 fd.close()