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.
13 from datetime import datetime, timedelta
14 from collections import defaultdict
19 # Copy into settings/ip_blcoks.conf and adapt as required.
21 BASEDIR = os.path.normpath(os.path.join(os.path.realpath(__file__), '../..'))
22 BLOCKEDFILE= BASEDIR + '/settings/ip_blocks.map'
23 LOGFILE= BASEDIR + '/log/restricted_ip.log'
25 # space-separated list of IPs that are never banned
27 # space-separated list of IPs manually blocked
29 # user-agents that should be blocked from bulk mode
30 # (matched with startswith)
33 # time before a automatically blocked IP is allowed back
34 BLOCKCOOLOFF_DELTA=timedelta(hours=1)
35 # quiet time before an IP is released from the bulk pool
36 BULKCOOLOFF_DELTA=timedelta(minutes=15)
48 # END OF DEFAULT SETTINGS
52 with open(BASEDIR + "/settings/ip_blocks.conf") as f:
53 code = compile(f.read(), BASEDIR + "/settings/ip_blocks.conf", 'exec')
58 BLOCK_LIMIT = BLOCK_LOWER
60 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'
62 format_pat= re.compile(r'(?P<ip>[a-f\d\.:]+) - - \['+ time_regex + r'] "(?P<query>.*?)" (?P<return>\d+) (?P<bytes>\d+) "(?P<referer>.*?)" "(?P<ua>.*?)"')
63 time_pat= re.compile(r'[a-f\d:\.]+ - - \[' + time_regex + '\] ')
65 logtime_pat = "%d/%b/%Y:%H:%M:%S %z"
67 MONTHS = { 'Jan' : 1, 'Feb' : 2, 'Mar' : 3, 'Apr' : 4, 'May' : 5, 'Jun' : 6,
68 'Jul' : 7, 'Aug' : 8, 'Sep' : 9, 'Oct' : 10, 'Nov' : 11, 'Dec' : 12 }
71 def __init__(self, logline):
72 e = format_pat.match(logline)
74 raise ValueError("Invalid log line:", logline)
77 self.date = datetime(int(e['t_year']), MONTHS[e['t_month']], int(e['t_day']),
78 int(e['t_hour']), int(e['t_min']), int(e['t_sec']))
79 qp = e['query'].split(' ', 2)
85 if qp[0] == 'OPTIONS':
88 if '/search' in qp[1]:
90 elif '/reverse' in qp[1]:
92 elif '/details' in qp[1]:
94 elif '/lookup' in qp[1]:
98 self.query = e['query']
99 self.retcode = int(e['return'])
100 self.referer = e['referer'] if e['referer'] != '-' else None
101 self.ua = e['ua'] if e['ua'] != '-' else None
103 def get_log_time(logline):
104 e = format_pat.match(logline)
108 #return datetime.strptime(e['time'], logtime_pat).replace(tzinfo=None)
109 return datetime(int(e['t_year']), MONTHS[e['t_month']], int(e['t_day']),
110 int(e['t_hour']), int(e['t_min']), int(e['t_sec']))
114 """ An apache log file, unpacked. """
116 def __init__(self, filename):
117 self.fd = open(filename)
118 self.len = os.path.getsize(filename)
123 def seek_next(self, abstime):
124 self.fd.seek(abstime)
126 l = self.fd.readline()
127 return LogEntry.get_log_time(l) if l is not None else None
129 def seek_to_date(self, target):
130 # start position for binary search
132 fromdate = self.seek_next(0)
133 if fromdate > target:
135 # end position for binary search
137 while -toseek < self.len:
138 todate = self.seek_next(self.len + toseek)
139 if todate is not None:
142 if todate is None or todate < target:
144 toseek = self.len + toseek
148 bps = (toseek - fromseek) / (todate - fromdate).total_seconds()
149 newseek = fromseek + int((target - fromdate).total_seconds() * bps)
150 newdate = self.seek_next(newseek)
153 error = abs((target - newdate).total_seconds())
159 oldfromseek = fromseek
160 fromseek = toseek - error * bps
162 if fromseek <= oldfromseek:
163 fromseek = oldfromseek
164 fromdate = self.seek_next(fromseek)
166 fromdate = self.seek_next(fromseek)
167 if fromdate < target:
170 fromseek -= error * bps
175 toseek = fromseek + error * bps
177 if toseek > oldtoseek:
179 todate = self.seek_next(toseek)
181 todate = self.seek_next(toseek)
185 toseek += error * bps
186 if toseek - fromseek < 500:
195 pass # ignore invalid lines
200 self.whitelist = set(WHITELIST.split()) if WHITELIST else set()
201 self.blacklist = set(BLACKLIST.split()) if BLACKLIST else set()
202 self.prevblocks = set()
203 self.prevbulks = set()
206 fd = open(BLOCKEDFILE)
208 ip, typ = line.strip().split(' ')
209 if ip not in self.blacklist:
211 self.prevblocks.add(ip)
213 self.prevbulks.add(ip)
216 pass #ignore non-existing file
228 def add_long(self, logentry):
230 if logentry.request is not None:
233 if logentry.ua is None:
236 def add_short(self, logentry):
237 self.short_total += 1
238 if logentry.request is not None:
240 self.add_long(logentry)
242 def new_state(self, was_blocked, was_bulked):
244 # deblock only if the IP has been really quiet
245 # (properly catches the ones that simply ignore the HTTP error)
246 return None if self.long_total < 20 else 'block'
247 if self.long_api > BLOCK_UPPER or self.short_api > BLOCK_UPPER / 3:
248 # client totally overdoing it
251 if self.short_total < 20:
252 # client has stopped, debulk
254 if self.long_api > BLOCK_LIMIT or self.short_api > BLOCK_LIMIT / 3:
255 # client is still hammering us, block
259 if self.long_api > BULKLONG_LIMIT or self.short_api > BULKSHORT_LIMIT:
261 # return 'uablock' # bad useragent
268 if __name__ == '__main__':
269 if len(sys.argv) < 2:
270 print("Usage: %s logfile startdate" % sys.argv[0])
273 if len(sys.argv) == 2:
274 dt = datetime.now() - BLOCKCOOLOFF_DELTA
276 dt = datetime.strptime(sys.argv[2], "%Y-%m-%d %H:%M:%S")
278 if os.path.getsize(sys.argv[1]) < 2*1030*1024:
279 sys.exit(0) # not enough data
281 lf = LogFile(sys.argv[1])
282 if not lf.seek_to_date(dt):
287 shortstart = dt + BLOCKCOOLOFF_DELTA - BULKCOOLOFF_DELTA
288 notlogged = bl.whitelist | bl.blacklist
290 stats = defaultdict(IPstats)
292 for l in lf.loglines():
293 if l.ip not in notlogged:
294 stats[l.ip].add_long(l)
295 if l.date > shortstart:
299 for l in lf.loglines():
300 if l.ip not in notlogged:
301 stats[l.ip].add_short(l)
302 if l.request is not None and l.retcode == 200:
305 # adapt limits according to CPU and DB load
306 fd = open("/proc/loadavg")
307 cpuload = int(float(fd.readline().split()[2]))
309 # check the number of excess connections to apache
310 dbcons = int(subprocess.check_output("netstat -s | grep 'connections established' | sed 's:^\s*::;s: .*::'", shell=True))
311 fpms = int(subprocess.check_output('ps -Af | grep php-fpm | wc -l', shell=True))
312 dbload = max(0, dbcons - fpms)
314 numbulks = len(bl.prevbulks)
315 BLOCK_LIMIT = max(BLOCK_LIMIT, BLOCK_UPPER - BLOCK_LOADFAC * dbload)
316 BULKLONG_LIMIT = max(BULK_LOWER, BULKLONG_LIMIT - BULK_LOADFAC * cpuload)
317 if numbulks > MAX_BULK_IPS:
318 BLOCK_LIMIT = max(3600, BLOCK_LOWER - (numbulks - MAX_BULK_IPS)*10)
319 # if the bulk pool is still empty, clients will be faster, avoid having
320 # them blocked in this case
323 BLOCK_LIMIT = BLOCK_UPPER
326 # collecting statistics
333 # write out new state file
334 fd = open(BLOCKEDFILE, 'w')
335 for k,v in stats.items():
336 wasblocked = k in bl.prevblocks
337 wasbulked = k in bl.prevbulks
338 state = v.new_state(wasblocked, wasbulked)
339 if state is not None:
340 if state == 'uablock':
343 elif state == 'emblock':
346 elif state == 'block':
349 elif state == 'bulk':
352 fd.write("%s %s\n" % (k, state))
358 for i in bl.blacklist:
359 fd.write("%s ban\n" % i)
362 # TODO write logs (need to collect some statistics)
363 logstr = datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
364 fd = open(LOGFILE, 'a')
366 fd.write(logstr % ('unblocked:', ', '.join(unblocked)))
368 fd.write(logstr % (' debulked:', ', '.join(debulked)))
370 fd.write(logstr % ('new bulks:', ', '.join(bulked)))
372 fd.write(logstr % ('dir.block:', ', '.join(emblocked)))
374 fd.write(logstr % (' ua block:', ', '.join(uablocked)))
376 fd.write(logstr % ('new block:', ', '.join(blocked)))