]> git.openstreetmap.org Git - nominatim.git/blob - utils/cron_banip.py
Merge remote-tracking branch 'upstream/master'
[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 # user-agents that should be blocked from bulk mode
56 # (matched with startswith)
57 UA_BLOCKLIST = ()
58
59 # time before a automatically blocked IP is allowed back
60 BLOCKCOOLOFF_PERIOD='1 hour'
61 # quiet time before an IP is released from the bulk pool
62 BULKCOOLOFF_PERIOD='15 min'
63
64 BULKLONG_LIMIT=8000
65 BULKSHORT_LIMIT=2000
66 BLOCK_UPPER=19000
67 BLOCK_LOWER=4000
68 BLOCK_LOADFAC=380
69 BULK_LOADFAC=160
70 BULK_LOWER=1500
71 MAX_BULK_IPS=85
72
73 #
74 # END OF DEFAULT SETTINGS
75 #
76
77 try:
78     execfile(os.path.expanduser(BASEDIR + "/settings/ip_blocks.conf"))
79 except IOError:
80     pass
81
82 # read the previous blocklist
83 WHITELIST = set(WHITELIST.split()) if WHITELIST else set()
84 prevblocks = []
85 prevbulks = []
86 BLACKLIST = set(BLACKLIST.split()) if BLACKLIST else set()
87 newblocks = set()
88 newbulks = set()
89
90 try:
91     fd = open(BLOCKEDFILE)
92     for line in fd:
93         ip, typ = line.strip().split(' ')
94         if ip not in BLACKLIST:
95             if typ == 'block':
96                 prevblocks.append(ip)
97             elif typ == 'bulk':
98                 prevbulks.append(ip)
99     fd.close()
100 except IOError:
101     pass #ignore non-existing file
102
103 # determine current load
104 fd = open("/proc/loadavg")
105 avgload = int(float(fd.readline().split()[2]))
106 fd.close()
107 # DB load
108 conn = psycopg2.connect('dbname=nominatim')
109 cur = conn.cursor()
110 cur.execute("select count(*)/60 from new_query_log where starttime > now() - interval '1min'")
111 dbload = int(cur.fetchone()[0])
112
113 BLOCK_LIMIT = max(BLOCK_LOWER, BLOCK_UPPER - BLOCK_LOADFAC * (dbload - 75))
114 BULKLONG_LIMIT = max(BULK_LOWER, BULKLONG_LIMIT - BULK_LOADFAC * (avgload - 14))
115 if len(prevbulks) > MAX_BULK_IPS:
116     BLOCK_LIMIT = max(3600, BLOCK_LOWER - (len(prevbulks) - MAX_BULK_IPS)*10)
117 # if the bulk pool is still empty, clients will be faster, avoid having
118 # them blocked in this case
119 if len(prevbulks) < 10:
120     BLOCK_LIMIT = 2*BLOCK_UPPER
121
122
123 # get the new block candidates
124 cur.execute("""
125   SELECT ipaddress, max(count), max(ua) FROM
126    ((SELECT * FROM
127      (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
128       WHERE starttime > now() - interval '1 hour' GROUP BY ipaddress) as i
129    WHERE count > %s)
130    UNION
131    (SELECT ipaddress, count * 3, ua FROM
132      (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 
133       WHERE starttime > now() - interval '10 min' GROUP BY ipaddress) as i
134    WHERE count > %s)) as o
135   GROUP BY ipaddress
136 """, (BULKLONG_LIMIT, BULKSHORT_LIMIT))
137
138 bulkips = {}
139 emergencyblocks = []
140 useragentblocks = []
141
142 for c in cur:
143     if c[0] not in WHITELIST and c[0] not in BLACKLIST:
144         # check for user agents that receive an immediate block
145         missing_agent = not c[2]
146         if not missing_agent:
147             for ua in UA_BLOCKLIST:
148                 if c[2].startswith(ua):
149                     missing_agent = True
150                     break
151         if (missing_agent or c[1] > BLOCK_UPPER) and c[0] not in prevblocks:
152             newblocks.add(c[0])
153             if missing_agent:
154                 useragentblocks.append(c[0])
155             else:
156                 emergencyblocks.append(c[0])
157         else:
158             bulkips[c[0]] = c[1]
159
160 # IPs from the block list that are no longer in the bulk list
161 deblockcandidates = set()
162 # IPs from the bulk list that are no longer in the bulk list
163 debulkcandidates = set()
164 # new IPs to go into the block list
165 newlyblocked = []
166
167
168 for ip in prevblocks:
169     if ip in bulkips:
170         newblocks.add(ip)
171         del bulkips[ip]
172     else:
173         deblockcandidates.add(ip)    
174         
175 for ip in prevbulks:
176     if ip not in newblocks:
177         if ip in bulkips:
178             if bulkips[ip] > BLOCK_LIMIT:
179                 newblocks.add(ip)
180                 newlyblocked.append(ip)
181             else:
182                 newbulks.add(ip)
183             del bulkips[ip]
184         else:
185             debulkcandidates.add(ip)
186
187 # cross-check deblock candidates
188 if deblockcandidates:
189     cur.execute("""
190         SELECT DISTINCT ipaddress FROM new_query_log
191         WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
192         """ % ("','".join(deblockcandidates), BLOCKCOOLOFF_PERIOD))
193
194     for c in cur:
195         newblocks.add(c[0])
196         deblockcandidates.remove(c[0])
197 # deblocked IPs go back to the bulk pool to catch the ones that simply
198 # ignored the HTTP error and just continue to hammer the API.
199 # Those that behave and stopped will be debulked a minute later.
200 for ip in deblockcandidates:
201     newbulks.add(ip)
202
203 # cross-check debulk candidates
204 if debulkcandidates:
205     cur.execute("""
206         SELECT DISTINCT ipaddress FROM new_query_log
207         WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
208         AND starttime > date_trunc('day', now())
209         """ % ("','".join(debulkcandidates), BULKCOOLOFF_PERIOD))
210
211     for c in cur:
212         newbulks.add(c[0])
213         debulkcandidates.remove(c[0])
214
215 for ip in bulkips.iterkeys():
216     newbulks.add(ip)
217
218 # write out the new list
219 fd = open(BLOCKEDFILE, 'w')
220 for ip in newblocks:
221     fd.write(ip + " block\n")
222 for ip in newbulks:
223     fd.write(ip + " bulk\n")
224 for ip in BLACKLIST:
225     fd.write(ip + " ban\n")
226 fd.close()
227
228 # write out the log
229 logstr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
230 fd = open(LOGFILE, 'a')
231 if deblockcandidates:
232     fd.write(logstr % ('unblocked:', ', '.join(deblockcandidates)))
233 if debulkcandidates:
234     fd.write(logstr % (' debulked:', ', '.join(debulkcandidates)))
235 if bulkips:
236     fd.write(logstr % ('new bulks:', ', '.join(bulkips.keys())))
237 if emergencyblocks:
238     fd.write(logstr % ('dir.block:', ', '.join(emergencyblocks)))
239 if useragentblocks:
240     fd.write(logstr % (' ua block:', ', '.join(useragentblocks)))
241 if newlyblocked:
242     fd.write(logstr % ('new block:', ', '.join(newlyblocked)))
243 fd.close()