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':
 
  90                 elif '/search' in qp[1]:
 
  92                 elif '/reverse' in qp[1]:
 
  94                 elif '/details' in qp[1]:
 
  96                 elif '/lookup' in qp[1]:
 
 100         self.query = e['query']
 
 101         self.retcode = int(e['return'])
 
 102         self.referer = e['referer'] if e['referer'] != '-' else None
 
 103         self.ua = e['ua'] if e['ua'] != '-' else None
 
 105     def get_log_time(logline):
 
 106         e = format_pat.match(logline)
 
 110         #return datetime.strptime(e['time'], logtime_pat).replace(tzinfo=None)
 
 111         return datetime(int(e['t_year']), MONTHS[e['t_month']], int(e['t_day']),
 
 112                              int(e['t_hour']), int(e['t_min']), int(e['t_sec']))
 
 116     """ An apache log file, unpacked. """
 
 118     def __init__(self, filename):
 
 119         self.fd = open(filename)
 
 120         self.len = os.path.getsize(filename)
 
 125     def seek_next(self, abstime):
 
 126         self.fd.seek(abstime)
 
 128         l = self.fd.readline()
 
 129         return LogEntry.get_log_time(l) if l is not None else None
 
 131     def seek_to_date(self, target):
 
 132         # start position for binary search
 
 134         fromdate = self.seek_next(0)
 
 135         if fromdate > target:
 
 137         # end position for binary search
 
 139         while -toseek < self.len:
 
 140             todate = self.seek_next(self.len + toseek)
 
 141             if todate is not None:
 
 144         if todate is None or todate < target:
 
 146         toseek = self.len + toseek
 
 150             bps = (toseek - fromseek) / (todate - fromdate).total_seconds()
 
 151             newseek = fromseek + int((target - fromdate).total_seconds() * bps)
 
 152             newdate = self.seek_next(newseek)
 
 155             error = abs((target - newdate).total_seconds())
 
 161                 oldfromseek = fromseek
 
 162                 fromseek = toseek - error * bps
 
 164                     if fromseek <= oldfromseek:
 
 165                         fromseek = oldfromseek
 
 166                         fromdate = self.seek_next(fromseek)
 
 168                     fromdate = self.seek_next(fromseek)
 
 169                     if fromdate < target:
 
 172                     fromseek -= error * bps
 
 177                 toseek = fromseek + error * bps
 
 179                     if toseek > oldtoseek:
 
 181                         todate = self.seek_next(toseek)
 
 183                     todate = self.seek_next(toseek)
 
 187                     toseek += error * bps
 
 188             if toseek - fromseek < 500:
 
 197                 pass # ignore invalid lines
 
 202         self.whitelist = set(WHITELIST.split()) if WHITELIST else set()
 
 203         self.blacklist = set(BLACKLIST.split()) if BLACKLIST else set()
 
 204         self.prevblocks = set()
 
 205         self.prevbulks = set()
 
 208             fd = open(BLOCKEDFILE)
 
 210                 ip, typ = line.strip().split(' ')
 
 211                 if ip not in self.blacklist:
 
 213                         self.prevblocks.add(ip)
 
 215                         self.prevbulks.add(ip)
 
 218             pass #ignore non-existing file
 
 230     def add_long(self, logentry):
 
 232         if logentry.request is not None:
 
 235             if logentry.ua is None:
 
 238     def add_short(self, logentry):
 
 239         self.short_total += 1
 
 240         if logentry.request is not None:
 
 242         self.add_long(logentry)
 
 244     def new_state(self, was_blocked, was_bulked):
 
 246             # deblock only if the IP has been really quiet
 
 247             # (properly catches the ones that simply ignore the HTTP error)
 
 248             return None if self.long_total < 20 else 'block'
 
 249         if self.long_api > BLOCK_UPPER or self.short_api > BLOCK_UPPER / 3:
 
 250                 # client totally overdoing it
 
 253             if self.short_total < 20:
 
 254                 # client has stopped, debulk
 
 256             if self.long_api > BLOCK_LIMIT or self.short_api > BLOCK_LIMIT / 3:
 
 257                 # client is still hammering us, block
 
 261         if self.long_api > BULKLONG_LIMIT or self.short_api > BULKSHORT_LIMIT:
 
 263             #    return 'uablock' # bad useragent
 
 270 if __name__ == '__main__':
 
 271     if len(sys.argv) < 2:
 
 272         print("Usage: %s logfile startdate" % sys.argv[0])
 
 275     if len(sys.argv) == 2:
 
 276         dt = datetime.now() - BLOCKCOOLOFF_DELTA
 
 278         dt = datetime.strptime(sys.argv[2], "%Y-%m-%d %H:%M:%S")
 
 280     if os.path.getsize(sys.argv[1]) < 2*1030*1024:
 
 281         sys.exit(0) # not enough data
 
 283     lf = LogFile(sys.argv[1])
 
 284     if not lf.seek_to_date(dt):
 
 289     shortstart = dt + BLOCKCOOLOFF_DELTA - BULKCOOLOFF_DELTA
 
 290     notlogged = bl.whitelist | bl.blacklist
 
 292     stats = defaultdict(IPstats)
 
 294     for l in lf.loglines():
 
 295         if l.ip not in notlogged:
 
 296             stats[l.ip].add_long(l)
 
 297         if l.date > shortstart:
 
 301     for l in lf.loglines():
 
 302         if l.ip not in notlogged:
 
 303             stats[l.ip].add_short(l)
 
 304         if l.request is not None and l.retcode == 200:
 
 307     # adapt limits according to CPU and DB load
 
 308     fd = open("/proc/loadavg")
 
 309     cpuload = int(float(fd.readline().split()[2]))
 
 311     # check the number of excess connections to apache
 
 312     dbcons = int(subprocess.check_output("netstat -s | grep 'connections established' | sed 's:^\s*::;s: .*::'", shell=True))
 
 313     fpms = int(subprocess.check_output('ps -Af | grep php-fpm | wc -l', shell=True))
 
 314     dbload = max(0, dbcons - fpms)
 
 316     numbulks = len(bl.prevbulks)
 
 317     BLOCK_LIMIT = max(BLOCK_LIMIT, BLOCK_UPPER - BLOCK_LOADFAC * dbload)
 
 318     BULKLONG_LIMIT = max(BULK_LOWER, BULKLONG_LIMIT - BULK_LOADFAC * cpuload)
 
 319     if numbulks > MAX_BULK_IPS:
 
 320         BLOCK_LIMIT = max(3600, BLOCK_LOWER - (numbulks - MAX_BULK_IPS)*10)
 
 321     # if the bulk pool is still empty, clients will be faster, avoid having
 
 322     # them blocked in this case
 
 325         BLOCK_LIMIT = BLOCK_UPPER
 
 328     # collecting statistics
 
 335     # write out new state file
 
 336     fd = open(BLOCKEDFILE, 'w')
 
 337     for k,v in stats.items():
 
 338         wasblocked = k in bl.prevblocks
 
 339         wasbulked = k in bl.prevbulks
 
 340         state = v.new_state(wasblocked, wasbulked)
 
 341         if state is not None:
 
 342             if state == 'uablock':
 
 345             elif state == 'emblock':
 
 348             elif state == 'block':
 
 351             elif state == 'bulk':
 
 354             fd.write("%s %s\n" % (k, state))
 
 360     for i in bl.blacklist:
 
 361         fd.write("%s ban\n" % i)
 
 364     # TODO write logs (need to collect some statistics)
 
 365     logstr = datetime.now().strftime('%Y-%m-%d %H:%M') + ' %s %s\n'
 
 366     fd = open(LOGFILE, 'a')
 
 368         fd.write(logstr % ('unblocked:', ', '.join(unblocked)))
 
 370         fd.write(logstr % (' debulked:', ', '.join(debulked)))
 
 372         fd.write(logstr % ('new bulks:', ', '.join(bulked)))
 
 374         fd.write(logstr % ('dir.block:', ', '.join(emblocked)))
 
 376         fd.write(logstr % (' ua block:', ', '.join(uablocked)))
 
 378         fd.write(logstr % ('new block:', ', '.join(blocked)))