#!/usr/local/bin/python
'''\
Author: Greg Hewgill'''

import os, re, select, sys, time

SCAN_TIME = 60
SCAN_COUNT = 3
RELEASE_TIME = 900

def ipfw(cmd):
    #print time.ctime(), "ipfw", cmd
    r = os.system("ipfw %s | logger -p auth.info" % cmd)
    if r != 0:
        print "  error %d" % r

addrs = {}
while True:
    ready = select.select([sys.stdin], [], [], 60)
    now = time.time()
    if len(ready[0]) > 0:
        s = sys.stdin.readline()
        m = re.search("(Invalid user|authentication error) .* from ([0-9.]+)", s)
        if m:
            addr = m.group(2)
            if addr not in addrs:
                addrs[addr] = {'times': [], 'rule': 0}
            addrs[addr]['times'] += [now]
            if addrs[addr]['rule'] == 0 and len(addrs[addr]['times']) >= SCAN_COUNT:
                rule = 29000
                while rule in [x['rule'] for x in addrs.values()]:
                    rule += 1
                addrs[addr]['time'] = now
                addrs[addr]['rule'] = rule
                ipfw("add %d deny ip from %s to any" % (rule, addr))
    else:
        for a in addrs.values():
            while len(a['times']) > 0 and a['times'][0] < now-SCAN_TIME:
                a['times'].pop()
            if a['rule'] != 0 and now >= a['time'] + RELEASE_TIME:
                ipfw("show %d" % a['rule'])
                ipfw("delete %d" % a['rule'])
                a['rule'] = 0

