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]:
96 self.query = e['query']
97 self.retcode = int(e['return'])
98 self.referer = e['referer'] if e['referer'] != '-' else None
99 self.ua = e['ua'] if e['ua'] != '-' else None
101 def get_log_time(logline):
102 e = format_pat.match(logline)
106 #return datetime.strptime(e['time'], logtime_pat).replace(tzinfo=None)
107 return datetime(int(e['t_year']), MONTHS[e['t_month']], int(e['t_day']),
108 int(e['t_hour']), int(e['t_min']), int(e['t_sec']))
112 """ An apache log file, unpacked. """
114 def __init__(self, filename):
115 self.fd = open(filename)
116 self.len = os.path.getsize(filename)
121 def seek_next(self, abstime):
122 self.fd.seek(abstime)
124 l = self.fd.readline()
125 return LogEntry.get_log_time(l) if l is not None else None
127 def seek_to_date(self, target):
128 # start position for binary search
130 fromdate = self.seek_next(0)
131 if fromdate > target:
133 # end position for binary search
135 while -toseek < self.len:
136 todate = self.seek_next(self.len + toseek)
137 if todate is not None:
140 if todate is None or todate < target:
142 toseek = self.len + toseek
146 bps = (toseek - fromseek) / (todate - fromdate).total_seconds()
147 newseek = fromseek + int((target - fromdate).total_seconds() * bps)
148 newdate = self.seek_next(newseek)
151 error = abs((target - newdate).total_seconds())
157 oldfromseek = fromseek
158 fromseek = toseek - error * bps
160 if fromseek <= oldfromseek:
161 fromseek = oldfromseek
162 fromdate = self.seek_next(fromseek)
164 fromdate = self.seek_next(fromseek)
165 if fromdate < target:
168 fromseek -= error * bps
173 toseek = fromseek + error * bps
175 if toseek > oldtoseek:
177 todate = self.seek_next(toseek)
179 todate = self.seek_next(toseek)
183 toseek += error * bps
184 if toseek - fromseek < 500:
193 pass # ignore invalid lines
198 self.whitelist = set(WHITELIST.split()) if WHITELIST else set()
199 self.blacklist = set(BLACKLIST.split()) if BLACKLIST else set()
200 self.prevblocks = set()
201 self.prevbulks = set()
204 fd = open(BLOCKEDFILE)
206 ip, typ = line.strip().split(' ')
207 if ip not in self.blacklist:
209 self.prevblocks.add(ip)
211 self.prevbulks.add(ip)
214 pass #ignore non-existing file
226 def add_long(self, logentry):
228 if logentry.request is not None:
231 if logentry.ua is None:
234 def add_short(self, logentry):
235 self.short_total += 1
236 if logentry.request is not None:
238 self.add_long(logentry)
240 def new_state(self, was_blocked, was_bulked):
242 # deblock only if the IP has been really quiet
243 # (properly catches the ones that simply ignore the HTTP error)
244 return None if self.long_total < 20 else 'block'
245 if self.long_api > BLOCK_UPPER or self.short_api > BLOCK_UPPER / 3:
246 # client totally overdoing it
249 if self.short_total < 20:
250 # client has stopped, debulk
252 if self.long_api > BLOCK_LIMIT or self.short_api > BLOCK_LIMIT / 3:
253 # client is still hammering us, block
257 if self.long_api > BULKLONG_LIMIT or self.short_api > BULKSHORT_LIMIT:
259 # return 'uablock' # bad useragent
266 if __name__ == '__main__':
267 if len(sys.argv) < 2:
268 print("Usage: %s logfile startdate" % sys.argv[0])
271 if len(sys.argv) == 2:
272 dt = datetime.now() - BLOCKCOOLOFF_DELTA
274 dt = datetime.strptime(sys.argv[2], "%Y-%m-%d %H:%M:%S")
276 if os.path.getsize(sys.argv[1]) < 2*1030*1024:
277 sys.exit(0) # not enough data
279 lf = LogFile(sys.argv[1])
280 if not lf.seek_to_date(dt):
285 shortstart = dt + BLOCKCOOLOFF_DELTA - BULKCOOLOFF_DELTA
286 notlogged = bl.whitelist | bl.blacklist
288 stats = defaultdict(IPstats)
290 for l in lf.loglines():
291 if l.ip not in notlogged:
292 stats[l.ip].add_long(l)
293 if l.date > shortstart:
297 for l in lf.loglines():
298 if l.ip not in notlogged:
299 stats[l.ip].add_short(l)
300 if l.request is not None and l.retcode == 200:
303 # adapt limits according to CPU and DB load
304 fd = open("/proc/loadavg")
305 cpuload = int(float(fd.readline().split()[2]))
307 # check the number of excess connections to apache
308 dbcons = int(subprocess.check_output("netstat -s | grep 'connections established' | sed 's:^\s*::;s: .*::'", shell=True))
309 fpms = int(subprocess.check_output('ps -Af | grep php-fpm | wc -l', shell=True))
310 dbload = max(0, dbcons - fpms)
312 numbulks = len(bl.prevbulks)
313 BLOCK_LIMIT = max(BLOCK_LIMIT, BLOCK_UPPER - BLOCK_LOADFAC * dbload)
314 BULKLONG_LIMIT = max(BULK_LOWER, BULKLONG_LIMIT - BULK_LOADFAC * cpuload)
315 if numbulks > MAX_BULK_IPS:
316 BLOCK_LIMIT = max(3600, BLOCK_LOWER - (numbulks - MAX_BULK_IPS)*10)
317 # if the bulk pool is still empty, clients will be faster, avoid having
318 # them blocked in this case
321 BLOCK_LIMIT = BLOCK_UPPER
324 # collecting statistics
331 # write out new state file
332 fd = open(BLOCKEDFILE, 'w')
333 for k,v in stats.items():
334 wasblocked = k in bl.prevblocks
335 wasbulked = k in bl.prevbulks
336 state = v.new_state(wasblocked, wasbulked)
337 if state is not None:
338 if state == 'uablock':
341 elif state == 'emblock':
344 elif state == 'block':
347 elif state == 'bulk':
350 fd.write("%s %s\n" % (k, state))
356 for i in bl.blacklist:
357 fd.write("%s ban\n" % i)
360 # TODO write logs (need to collect some statistics)
361 logstr = datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
362 fd = open(LOGFILE, 'a')
364 fd.write(logstr % ('unblocked:', ', '.join(unblocked)))
366 fd.write(logstr % (' debulked:', ', '.join(debulked)))
368 fd.write(logstr % ('new bulks:', ', '.join(bulked)))
370 fd.write(logstr % ('dir.block:', ', '.join(emblocked)))
372 fd.write(logstr % (' ua block:', ', '.join(uablocked)))
374 fd.write(logstr % ('new block:', ', '.join(blocked)))