3 # Search apache 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.
12 from datetime import datetime, timedelta
13 from collections import defaultdict
18 # Copy into settings/ip_blcoks.conf and adapt as required.
20 BASEDIR = os.path.normpath(os.path.join(os.path.realpath(__file__), '../..'))
21 BLOCKEDFILE= BASEDIR + '/settings/ip_blocks.map'
22 LOGFILE= BASEDIR + '/log/restricted_ip.log'
24 # space-separated list of IPs that are never banned
26 # space-separated list of IPs manually blocked
28 # user-agents that should be blocked from bulk mode
29 # (matched with startswith)
32 # time before a automatically blocked IP is allowed back
33 BLOCKCOOLOFF_DELTA=timedelta(hours=1)
34 # quiet time before an IP is released from the bulk pool
35 BULKCOOLOFF_DELTA=timedelta(minutes=15)
47 # END OF DEFAULT SETTINGS
51 with open(BASEDIR + "/settings/ip_blocks.conf") as f:
52 code = compile(f.read(), BASEDIR + "/settings/ip_blocks.conf", 'exec')
57 BLOCK_LIMIT = BLOCK_LOWER
59 time_regex = r'(?P<t_day>\d\d)/(?P<t_month>[A-Za-z]+)/(?P<t_year>\d\d\d\d):(?P<t_hour>\d\d):(?P<t_min>\d\d):(?P<t_sec>\d\d) [+-]\d\d\d\d'
61 format_pat= re.compile(r'(?P<ip>[(\d\.)]+) - - \['+ time_regex + r'] "(?P<query>.*?)" (?P<return>\d+) (?P<bytes>\d+) "(?P<referer>.*?)" "(?P<ua>.*?)"')
62 time_pat= re.compile(r'[(\d\.)]+ - - \[' + time_regex + '\] ')
64 logtime_pat = "%d/%b/%Y:%H:%M:%S %z"
66 MONTHS = { 'Jan' : 1, 'Feb' : 2, 'Mar' : 3, 'Apr' : 4, 'May' : 5, 'Jun' : 6,
67 'Jul' : 7, 'Aug' : 8, 'Sep' : 9, 'Oct' : 10, 'Nov' : 11, 'Dec' : 12 }
70 def __init__(self, logline):
71 e = format_pat.match(logline)
73 raise ValueError("Invalid log line:", logline)
76 self.date = datetime(int(e['t_year']), MONTHS[e['t_month']], int(e['t_day']),
77 int(e['t_hour']), int(e['t_min']), int(e['t_sec']))
78 qp = e['query'].split(' ', 2)
84 if qp[0] == 'OPTIONS':
87 if qp[1].startswith('/search'):
89 elif qp[1].startswith('/reverse'):
91 elif qp[1].startswith('/details'):
95 self.query = e['query']
96 self.retcode = int(e['return'])
97 self.referer = e['referer'] if e['referer'] != '-' else None
98 self.ua = e['ua'] if e['ua'] != '-' else None
100 def get_log_time(logline):
101 e = format_pat.match(logline)
105 #return datetime.strptime(e['time'], logtime_pat).replace(tzinfo=None)
106 return datetime(int(e['t_year']), MONTHS[e['t_month']], int(e['t_day']),
107 int(e['t_hour']), int(e['t_min']), int(e['t_sec']))
111 """ An apache log file, unpacked. """
113 def __init__(self, filename):
114 self.fd = open(filename)
115 self.len = os.path.getsize(filename)
120 def seek_next(self, abstime):
121 self.fd.seek(abstime)
123 l = self.fd.readline()
124 return LogEntry.get_log_time(l) if l is not None else None
126 def seek_to_date(self, target):
127 # start position for binary search
129 fromdate = self.seek_next(0)
130 if fromdate > target:
132 # end position for binary search
134 while -toseek < self.len:
135 todate = self.seek_next(self.len + toseek)
136 if todate is not None:
139 if todate is None or todate < target:
141 toseek = self.len + toseek
145 bps = (toseek - fromseek) / (todate - fromdate).total_seconds()
146 newseek = fromseek + int((target - fromdate).total_seconds() * bps)
147 newdate = self.seek_next(newseek)
150 error = abs((target - newdate).total_seconds())
156 oldfromseek = fromseek
157 fromseek = toseek - error * bps
159 if fromseek <= oldfromseek:
160 fromseek = oldfromseek
161 fromdate = self.seek_next(fromseek)
163 fromdate = self.seek_next(fromseek)
164 if fromdate < target:
167 fromseek -= error * bps
172 toseek = fromseek + error * bps
174 if toseek > oldtoseek:
176 todate = self.seek_next(toseek)
178 todate = self.seek_next(toseek)
182 toseek += error * bps
183 if toseek - fromseek < 500:
192 pass # ignore invalid lines
197 self.whitelist = set(WHITELIST.split()) if WHITELIST else set()
198 self.blacklist = set(BLACKLIST.split()) if BLACKLIST else set()
199 self.prevblocks = set()
200 self.prevbulks = set()
203 fd = open(BLOCKEDFILE)
205 ip, typ = line.strip().split(' ')
206 if ip not in self.blacklist:
208 self.prevblocks.add(ip)
210 self.prevbulks.add(ip)
213 pass #ignore non-existing file
225 def add_long(self, logentry):
227 if logentry.request is not None:
230 if logentry.ua is None:
233 def add_short(self, logentry):
234 self.short_total += 1
235 if logentry.request is not None:
237 self.add_long(logentry)
239 def new_state(self, was_blocked, was_bulked):
241 # deblock only if the IP has been really quiet
242 # (properly catches the ones that simply ignore the HTTP error)
243 return None if self.long_total < 5 else 'block'
244 if self.long_api > BLOCK_UPPER or self.short_api > BLOCK_UPPER / 3:
245 # client totally overdoing it
248 if self.short_total < 5:
249 # client has stopped, debulk
251 if self.long_api > BLOCK_LIMIT or self.short_api > BLOCK_LIMIT / 3:
252 # client is still hammering us, block
256 if self.long_api > BULKLONG_LIMIT or self.short_api > BULKSHORT_LIMIT:
258 return 'uablock' # bad useragent
265 if __name__ == '__main__':
266 if len(sys.argv) < 2:
267 print("Usage: %s logfile startdate" % sys.argv[0])
270 if len(sys.argv) == 2:
271 dt = datetime.now() - BLOCKCOOLOFF_DELTA
273 dt = datetime.strptime(sys.argv[2], "%Y-%m-%d %H:%M:%S")
275 if os.path.getsize(sys.argv[1]) < 2*1030*1024:
276 sys.exit(0) # not enough data
278 lf = LogFile(sys.argv[1])
279 if not lf.seek_to_date(dt):
284 shortstart = dt + BLOCKCOOLOFF_DELTA - BULKCOOLOFF_DELTA
285 notlogged = bl.whitelist | bl.blacklist
287 stats = defaultdict(IPstats)
289 for l in lf.loglines():
290 if l.ip not in notlogged:
291 stats[l.ip].add_long(l)
292 if l.date > shortstart:
296 for l in lf.loglines():
297 if l.ip not in notlogged:
298 stats[l.ip].add_short(l)
299 if l.request is not None and l.retcode == 200:
302 # adapt limits according to CPU and DB load
303 fd = open("/proc/loadavg")
304 cpuload = int(float(fd.readline().split()[2]))
306 dbload = total200 / BULKCOOLOFF_DELTA.total_seconds()
308 numbulks = len(bl.prevbulks)
309 BLOCK_LIMIT = max(BLOCK_LIMIT, BLOCK_UPPER - BLOCK_LOADFAC * (dbload - 75))
310 BULKLONG_LIMIT = max(BULK_LOWER, BULKLONG_LIMIT - BULK_LOADFAC * (cpuload - 14))
311 if numbulks > MAX_BULK_IPS:
312 BLOCK_LIMIT = max(3600, BLOCK_LOWER - (numbulks - MAX_BULK_IPS)*10)
313 # if the bulk pool is still empty, clients will be faster, avoid having
314 # them blocked in this case
316 BLOCK_LIMIT = 2*BLOCK_UPPER
319 # collecting statistics
326 # write out new state file
327 fd = open(BLOCKEDFILE, 'w')
328 for k,v in stats.items():
329 wasblocked = k in bl.prevblocks
330 wasbulked = k in bl.prevbulks
331 state = v.new_state(wasblocked, wasbulked)
332 if state is not None:
333 if state == 'uablock':
336 elif state == 'emblock':
339 elif state == 'block':
342 elif state == 'bulk':
345 fd.write("%s %s\n" % (k, state))
351 for i in bl.blacklist:
352 fd.write("%s ban\n" % k)
355 # TODO write logs (need to collect some statistics)
356 logstr = datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
357 fd = open(LOGFILE, 'a')
359 fd.write(logstr % ('unblocked:', ', '.join(unblocked)))
361 fd.write(logstr % (' debulked:', ', '.join(debulked)))
363 fd.write(logstr % ('new bulks:', ', '.join(bulked)))
365 fd.write(logstr % ('dir.block:', ', '.join(emblocked)))
367 fd.write(logstr % (' ua block:', ', '.join(uablocked)))
369 fd.write(logstr % ('new block:', ', '.join(blocked)))