]> 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
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_LOADFAC=300
65 BULK_LOADFAC=100
66
67 #
68 # END OF DEFAULT SETTINGS
69 #
70
71 try:
72     execfile(os.path.expanduser(BASEDIR + "/settings/ip_blocks.conf"))
73 except IOError:
74     pass
75
76 # determine current load
77 fd = open("/proc/loadavg")
78 avgload = int(float(fd.readline().split()[1]))
79 fd.close()
80
81 # read the previous blocklist
82 WHITELIST = set(WHITELIST.split()) if WHITELIST else set()
83 prevblocks = []
84 prevbulks = []
85 BLACKLIST = set(BLACKLIST.split()) if BLACKLIST else set()
86 newblocks = set()
87 newbulks = set()
88
89 try:
90     fd = open(BLOCKEDFILE)
91     for line in fd:
92         ip, typ = line.strip().split(' ')
93         if ip not in BLACKLIST:
94             if typ == 'block':
95                 prevblocks.append(ip)
96             elif typ == 'bulk':
97                 prevbulks.append(ip)
98     fd.close()
99 except IOError:
100     pass #ignore non-existing file
101
102 # current number of bulks
103 numbulks = len(prevbulks)
104
105 BLOCK_LIMIT = BLOCK_UPPER - BLOCK_LOADFAC * (numbulks - 30)
106 BULKLONG_LIMIT = BULKLONG_LIMIT - BULK_LOADFAC * (avgload - 16)
107
108 conn = psycopg2.connect('dbname=nominatim')
109 cur = conn.cursor()
110
111 # get the new block candidates
112 cur.execute("""
113   SELECT ipaddress, max(count) FROM
114    ((SELECT * FROM
115      (SELECT ipaddress, sum(CASE WHEN type = 'search' THEN 3 ELSE 1 END) as count FROM new_query_log
116       WHERE starttime > now() - interval '1 hour' GROUP BY ipaddress) as i
117    WHERE count > %s)
118    UNION
119    (SELECT ipaddress, count * 4 FROM
120      (SELECT ipaddress, sum(CASE WHEN type = 'search' THEN 2 ELSE 1 END) as count FROM new_query_log 
121       WHERE starttime > now() - interval '10 min' GROUP BY ipaddress) as i
122    WHERE count > %s)) as o
123   GROUP BY ipaddress
124 """, (BULKLONG_LIMIT, BULKSHORT_LIMIT))
125
126 bulkips = {}
127 emergencyblocks = []
128
129 for c in cur:
130     if c[0] not in WHITELIST and c[0] not in BLACKLIST:
131         if c[1] > BLOCK_UPPER and c[0] not in prevbulks:
132             newblocks.add(c[0])
133             if c[0] not in prevblocks:
134                 emergencyblocks.append(c[0])
135         else:
136             bulkips[c[0]] = c[1]
137
138 # IPs from the block list that are no longer in the bulk list
139 deblockcandidates = set()
140 # IPs from the bulk list that are no longer in the bulk list
141 debulkcandidates = set()
142 # new IPs to go into the block list
143 newlyblocked = []
144
145
146 for ip in prevblocks:
147     if ip in bulkips:
148         newblocks.add(ip)
149         del bulkips[ip]
150     else:
151         deblockcandidates.add(ip)    
152         
153 for ip in prevbulks:
154     if ip in bulkips:
155         if bulkips[ip] > BLOCK_LIMIT:
156             newblocks.add(ip)
157             newlyblocked.append(ip)
158         else:
159             newbulks.add(ip)
160         del bulkips[ip]
161     else:
162         debulkcandidates.add(ip)
163
164 # cross-check deblock candidates
165 if deblockcandidates:
166     cur.execute("""
167         SELECT DISTINCT ipaddress FROM new_query_log
168         WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
169         """ % ("','".join(deblockcandidates), BLOCKCOOLOFF_PERIOD))
170
171     for c in cur:
172         newblocks.add(c[0])
173         deblockcandidates.remove(c[0])
174 # deblocked IPs go back to the bulk pool to catch the ones that simply
175 # ignored the HTTP error and just continue to hammer the API.
176 # Those that behave and stopped will be debulked a minute later.
177 for ip in deblockcandidates:
178     newbulks.add(ip)
179
180 # cross-check debulk candidates
181 if debulkcandidates:
182     cur.execute("""
183         SELECT DISTINCT ipaddress FROM new_query_log
184         WHERE ipaddress IN ('%s') AND starttime > now() - interval '%s'
185         """ % ("','".join(debulkcandidates), BULKCOOLOFF_PERIOD))
186
187     for c in cur:
188         newbulks.add(c[0])
189         debulkcandidates.remove(c[0])
190
191 for ip in bulkips.iterkeys():
192     newbulks.add(ip)
193
194 # write out the new list
195 fd = open(BLOCKEDFILE, 'w')
196 for ip in newblocks:
197     fd.write(ip + " block\n")
198 for ip in newbulks:
199     fd.write(ip + " bulk\n")
200 for ip in BLACKLIST:
201     fd.write(ip + " ban\n")
202 fd.close()
203
204 # write out the log
205 logstr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
206 fd = open(LOGFILE, 'a')
207 if deblockcandidates:
208     fd.write(logstr % ('unblocked:', ', '.join(deblockcandidates)))
209 if debulkcandidates:
210     fd.write(logstr % (' debulked:', ', '.join(debulkcandidates)))
211 if bulkips:
212     fd.write(logstr % ('new bulks:', ', '.join(bulkips.keys())))
213 if emergencyblocks:
214     fd.write(logstr % ('dir.block:', ', '.join(emergencyblocks)))
215 if newlyblocked:
216     fd.write(logstr % ('new block:', ', '.join(newlyblocked)))
217 fd.close()