def test_rule_insert(self): rules = [] rule = iptc.Rule6() rule.protocol = "tcp" rule.src = "::1" target = iptc.Target(rule, "ACCEPT") rule.target = target self.chain.insert_rule(rule) rules.append(rule) rule = iptc.Rule6() rule.protocol = "udp" rule.src = "::1" target = iptc.Target(rule, "REJECT") target.reject_with = "addr-unreach" rule.target = target self.chain.insert_rule(rule) rules.append(rule) rule = iptc.Rule6() rule.protocol = "tcp" rule.dst = "2001::/16" target = iptc.Target(rule, "RETURN") rule.target = target self.chain.insert_rule(rule) rules.append(rule) crules = self.chain.rules self.failUnless(len(rules) == len(crules)) for rule in rules: self.failUnless(rule in crules) crules.remove(rule)
def initChain(): # Is called before threads start, no locking print "Initializing mailcow netfilter chain" # IPv4 if not iptc.Chain(iptc.Table(iptc.Table.FILTER), "MAILCOW") in iptc.Table(iptc.Table.FILTER).chains: iptc.Table(iptc.Table.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), c) rule = iptc.Rule() rule.src = '0.0.0.0/0' rule.dst = '0.0.0.0/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # IPv6 if not iptc.Chain(iptc.Table6(iptc.Table6.FILTER), "MAILCOW") in iptc.Table6(iptc.Table6.FILTER).chains: iptc.Table6(iptc.Table6.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), c) rule = iptc.Rule6() rule.src = '::/0' rule.dst = '::/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # Apply blacklist BLACKLIST = r.hgetall('F2B_BLACKLIST') if BLACKLIST: for bl_key in BLACKLIST: if type(ipaddress.ip_network(bl_key.decode('ascii'), strict=False)) is ipaddress.IPv4Network: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = bl_key target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: log['time'] = int(round(time.time())) log['priority'] = 'crit' log['message'] = 'Blacklisting host/network %s' % bl_key r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print log['message'] chain.insert_rule(rule) r.hset('F2B_PERM_BANS', '%s' % bl_key, int(round(time.time()))) else: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = bl_key target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: log['time'] = int(round(time.time())) log['priority'] = 'crit' log['message'] = 'Blacklisting host/network %s' % bl_key r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print log['message'] chain.insert_rule(rule) r.hset('F2B_PERM_BANS', '%s' % bl_key, int(round(time.time())))
def initChain(): print "Initializing mailcow netfilter chain" # IPv4 if not iptc.Chain(iptc.Table(iptc.Table.FILTER), "MAILCOW") in iptc.Table( iptc.Table.FILTER).chains: iptc.Table(iptc.Table.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), c) rule = iptc.Rule() rule.src = '0.0.0.0/0' rule.dst = '0.0.0.0/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # IPv6 if not iptc.Chain(iptc.Table6(iptc.Table6.FILTER), "MAILCOW") in iptc.Table6(iptc.Table6.FILTER).chains: iptc.Table6(iptc.Table6.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), c) rule = iptc.Rule6() rule.src = '::/0' rule.dst = '::/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # Apply blacklist BLACKLIST = r.hgetall('F2B_BLACKLIST') if BLACKLIST: for bl_key in BLACKLIST: if type(ipaddress.ip_network( bl_key.decode('ascii'), strict=False)) is ipaddress.IPv4Network: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = bl_key target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) else: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = bl_key target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule)
def update_iptables(policy): policies = [p.split() for p in policy] for chain in ['INPUT', 'OUTPUT', 'FORWARD']: rules = [ accept_localhost(iptc.Rule6()), accept_related_established(iptc.Rule6()) ] rules += [ create_rule(iptc.Rule(), p[1], p[2], p[3], p[4]) if len(p) > 2 else create_rule(iptc.Rule(), p[1], None, None, None) for p in policies if p[0] == chain ] write_chain(iptc.Table(iptc.Table.FILTER), chain, rules) write_chain(iptc.Table6(iptc.Table6.FILTER), chain, [create_rule(iptc.Rule6(), 'DROP', None, None, None)])
def unban(net): global lock if not net in bans: logInfo('%s is not banned, skipping unban and deleting from queue (if any)' % net) r.hdel('F2B_QUEUE_UNBAN', '%s' % net) return logInfo('Unbanning %s' % net) if type(ipaddress.ip_network(net)) is ipaddress.IPv4Network: with lock: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule in chain.rules: chain.delete_rule(rule) else: with lock: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule in chain.rules: chain.delete_rule(rule) r.hdel('F2B_ACTIVE_BANS', '%s' % net) r.hdel('F2B_QUEUE_UNBAN', '%s' % net) if net in bans: del bans[net]
def permBan(net, unban=False): global lock if type(ipaddress.ip_network(net, strict=False)) is ipaddress.IPv4Network: with lock: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules and not unban: logCrit('Add host/network %s to blacklist' % net) chain.insert_rule(rule) r.hset('F2B_PERM_BANS', '%s' % net, int(round(time.time()))) elif rule in chain.rules and unban: logCrit('Remove host/network %s from blacklist' % net) chain.delete_rule(rule) r.hdel('F2B_PERM_BANS', '%s' % net) else: with lock: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules and not unban: logCrit('Add host/network %s to blacklist' % net) chain.insert_rule(rule) r.hset('F2B_PERM_BANS', '%s' % net, int(round(time.time()))) elif rule in chain.rules and unban: logCrit('Remove host/network %s from blacklist' % net) chain.delete_rule(rule) r.hdel('F2B_PERM_BANS', '%s' % net)
def initChain(): # Is called before threads start, no locking print("Initializing mailcow netfilter chain") # IPv4 if not iptc.Chain(iptc.Table(iptc.Table.FILTER), "MAILCOW") in iptc.Table(iptc.Table.FILTER).chains: iptc.Table(iptc.Table.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), c) rule = iptc.Rule() rule.src = '0.0.0.0/0' rule.dst = '0.0.0.0/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) # IPv6 if not iptc.Chain(iptc.Table6(iptc.Table6.FILTER), "MAILCOW") in iptc.Table6(iptc.Table6.FILTER).chains: iptc.Table6(iptc.Table6.FILTER).create_chain("MAILCOW") for c in ['FORWARD', 'INPUT']: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), c) rule = iptc.Rule6() rule.src = '::/0' rule.dst = '::/0' target = iptc.Target(rule, "MAILCOW") rule.target = target if rule not in chain.rules: chain.insert_rule(rule)
def test_rule_address(self): # valid addresses rule = iptc.Rule6() for addr in ["::/128", "!2000::1/16", "2001::/64", "!2001::1/48"]: rule.src = addr self.assertEquals(rule.src, addr) rule.dst = addr self.assertEquals(rule.dst, addr) addr = "::1" rule.src = addr self.assertEquals("::1/128", rule.src) rule.dst = addr self.assertEquals("::1/128", rule.dst) # invalid addresses for addr in [ "2001:fg::/::", "2001/ffff::", "2001::/-1", "2001::/129", "::1/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "::1/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:" ]: try: rule.src = addr except ValueError: pass else: self.fail("rule accepted invalid address %s" % (addr)) try: rule.dst = addr except ValueError: pass else: self.fail("rule accepted invalid address %s" % (addr))
def test_rule_standard_target(self): try: target = iptc.Target(iptc.Rule(), "jump_to_chain") except: pass else: self.fail("target accepted invalid name jump_to_chain") rule = iptc.Rule6() rule.protocol = "tcp" rule.src = "::1" target = iptc.Target(rule, "RETURN") self.assertEquals(target.name, "RETURN") target = iptc.Target(rule, "ACCEPT") self.assertEquals(target.name, "ACCEPT") target = iptc.Target(rule, "") self.assertEquals(target.name, "") target.standard_target = "ACCEPT" self.assertEquals(target.name, "ACCEPT") self.assertEquals(target.standard_target, "ACCEPT") target = iptc.Target(rule, self.chain.name) rule.target = target self.chain.insert_rule(rule) self.chain.delete_rule(rule)
def unban(net): log['time'] = int(round(time.time())) log['priority'] = 'info' r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) if not net in bans: log['message'] = '%s is not banned, skipping unban and deleting from queue (if any)' % net r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print '%s is not banned, skipping unban and deleting from queue (if any)' % net r.hdel('F2B_QUEUE_UNBAN', '%s' % net) return log['message'] = 'Unbanning %s' % net r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print 'Unbanning %s' % net if type(ipaddress.ip_network( net.decode('ascii'))) is ipaddress.IPv4Network: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule in chain.rules: chain.delete_rule(rule) else: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule in chain.rules: chain.delete_rule(rule) r.hdel('F2B_ACTIVE_BANS', '%s' % net) r.hdel('F2B_QUEUE_UNBAN', '%s' % net) if net in bans: del bans[net]
def getIPTablesRuleForClient(port, ipVersion, protocol, addr): if ipVersion == IP_VERSION.V4 and iptc.is_table_available( iptc.Table.FILTER): rule = iptc.Rule() rule.create_target('ACCEPT') rule.src = addr rule.protocol = protocol rule.create_match(protocol).dport = str(port) LOG.debug( "Created Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s", ipVersion, port, addr, protocol) elif ipVersion == IP_VERSION.V6 and iptc.is_table_available( iptc.Table6.FILTER): rule = iptc.Rule6() rule.create_target('ACCEPT') rule.src = addr rule.protocol = protocol rule.create_match(protocol).dport = str(port) LOG.debug( "Created Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s", ipVersion, port, addr, protocol) else: rule = None LOG.error( "Could not construct Rule For IPv%s Request: PORT=%s, HOST=%s PROTOCOL=%s", ipVersion, port, addr, protocol) return rule
def __init__(self, conf: dict) -> None: log.debug('IPTables plugin initialising with config: %s', conf) self._table4 = iptc.Table( self._tables[conf['table'] if 'table' in conf else 'filter']) self._table6 = iptc.Table6( self._tables[conf['table'] if 'table' in conf else 'filter']) log.debug('iptables._table4 == %s', self._table4) log.debug('iptables._table6 == %s', self._table6) chain = conf['chain'] if 'chain' in conf else 'INPUT' self._chain4 = iptc.Chain(self._table4, chain) self._chain6 = iptc.Chain(self._table6, chain) log.debug('iptables._chain4 == %s', chain) log.debug('iptables._chain6 == %s', chain) if 'target' in conf: self._target = self._targets[conf['target']] else: self._target = None log.debug('iptables._target == %s', self._target) if 'ports' in conf['match']: self._ports = conf['match']['ports'] else: self._ports = None log.debug('iptables._ports == %s', self._ports) if 'protocol' in conf['match']: self._proto = conf['match']['protocol'] else: self._proto = None log.debug('iptables._proto == %s', self._proto) if 'sources' in conf['match']: self._sources = [ip_network(ip) for ip in conf['match']['sources']] else: self._sources = None log.debug('iptables._sources == %s', self._sources) if 'destinations' in conf['match']: self._dests = [ip_network(ip) for ip in conf['match']['sources']] else: self._dests = None log.debug('iptables._dests == %s', self._dests) self._rule4 = iptc.Rule() self._rule6 = iptc.Rule6() self._uuids: List[str] = [] try: self.rule_builder() except ValueError as e: log.error( 'An error was encountered while initialising the IPTables plugin' ) log.debug(e) raise e
def get_snat6_rule(): rule = iptc.Rule6() rule.src = os.getenv('IPV6_NETWORK', 'fd4d:6169:6c63:6f77::/64') rule.dst = '!' + rule.src target = rule.create_target("SNAT") target.to_source = snat_target return rule
def test_target(name, value, ipv6=False): """ Return True if the target is valid, False otherwise """ try: iptc_rule = iptc.Rule6() if ipv6 else iptc.Rule() _iptc_settarget(iptc_rule, {name: value}) return True except: return False
def test_match(name, value, ipv6=False): """ Return True if the match is valid, False otherwise """ try: iptc_rule = iptc.Rule6() if ipv6 else iptc.Rule() _iptc_setmatch(iptc_rule, name, value) return True except: return False
def test_rule_from_dict(self): rule = iptc.Rule6() rule.protocol = "tcp" rule.src = "::1" target = iptc.Target(rule, "ACCEPT") rule.target = target rule2 = iptc.Rule6.from_dict({"protocol": "tcp", "src": "::1/128", "target": "ACCEPT"}) self.assertEqual(rule, rule2)
def test_rule_compare(self): r1 = iptc.Rule6() r1.src = "::1/128" r1.dst = "2001::/8" r1.protocol = "tcp" r1.in_interface = "wlan+" r1.out_interface = "eth1" r2 = iptc.Rule6() r2.src = "::1/128" r2.dst = "2001::/8" r2.protocol = "tcp" r2.in_interface = "wlan+" r2.out_interface = "eth1" self.failUnless(r1 == r2) r1.src = "::1/ffff::" self.failIf(r1 == r2)
def __init__(self, type, target_name=None): self.type = type if type == IPV4: self._rule = iptc.Rule() else: assert (type == IPV6) self._rule = iptc.Rule6() if target_name is not None: self._rule.create_target(target_name)
def test_rule_to_dict(self): rule = iptc.Rule6() rule.protocol = "tcp" rule.src = "::1/128" target = iptc.Target(rule, "ACCEPT") rule.target = target rule_d = iptc.easy.decode_iptc_rule(rule, ipv6=True) self.assertEqual(rule_d, { "protocol": "tcp", "src": "::1/128", "target": "ACCEPT" })
def test_rule_to_dict(self): rule = iptc.Rule6() rule.protocol = "tcp" rule.src = "::1/128" target = iptc.Target(rule, "ACCEPT") rule.target = target rule_d = iptc.easy.decode_iptc_rule(rule, ipv6=True) # Remove counters when comparing rules rule_d.pop('counters', None) self.assertEqual(rule_d, { "protocol": "tcp", "src": "::1/128", "target": "ACCEPT" })
def test_create_mask(self): rule = iptc.Rule6() # Mask /10 should return \xff\xc0\x00... mask = rule._create_mask(10) self.assertEquals(mask[0], 0xff) self.assertEquals(mask[1], 0xc0) self.assertEquals(mask[2:], [0x00] * 14) # Mask /27 should return \xff\xff\xff\xe0... mask = rule._create_mask(27) self.assertEquals(mask[:3], [0xff, 0xff, 0xff]) self.assertEquals(mask[3], 0xe0) self.assertEquals(mask[4:], [0x00] * 12)
def test_rule_protocol(self): rule = iptc.Rule6() for proto in ["tcp", "udp", "icmp", "AH", "ESP", "!TCP", "!UDP", "!ICMP", "!ah", "!esp"]: rule.protocol = proto self.assertEquals(proto.lower(), rule.protocol) for proto in ["", "asdf", "!"]: try: rule.protocol = proto except ValueError: pass except IndexError: pass else: self.fail("rule accepted invalid protocol %s" % (proto))
def dropIPv6(ip6): try: v = IP(ip6).version() except: return if ip6 not in v6iplist and v == 6: try: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), "INPUT") rule = iptc.Rule6() rule.in_interface = "eth+" rule.src = ip6 rule.target = iptc.Target(rule, "DROP") chain.insert_rule(rule) v6iplist.append(ip6) except Exception as e: print("OpenDXL.dropIPv6.Exception(%s): %s" % (ip6, str(e)))
def create_rule(self, rule_state, ip): """ create rule """ rule = None if self.ip_type(ip) == 'v6': rule = iptc.Rule6() else: rule = iptc.Rule() if rule_state.lower() == JSON_RULE_NETWORK_ACCEPT \ or rule_state.lower() == JSON_RULE_ALLOW: rule.create_target('ACCEPT') else: rule.create_target('DROP') return rule
def setUp(self): self.rule = iptc.Rule6() self.rule.protocol = "icmpv6" self.rule.in_interface = "eth0" self.target = self.rule.create_target("ACCEPT") self.match = self.rule.create_match("icmp6") self.match.icmpv6_type = "echo-request" self.table = iptc.Table6(iptc.Table6.FILTER) self.chain = iptc.Chain(self.table, "ip6tc_test_icmpv6") try: self.table.delete_chain(self.chain) except: pass self.table.create_chain(self.chain)
def block(ip, protocol=None): try: src = ipaddress.ip_address(ip) if src.version == IPv4: table = iptc.Table(iptc.Table.FILTER) newRule = iptc.Rule() elif src.version == IPv6: table = iptc.Table6(iptc.Table6.FILTER) newRule = iptc.Rule6() except ValueError: __logger.error('Invalid source ip address to block') raise Exception("Error") blocked = False for chain in table.chains: for rule in chain.rules: if ipaddress.ip_address(rule.src.split('/')[0]) == src.explode: __logger.debug("IP address is already blocked %s", rule.src) blocked = True if blocked is False: newRule.src = src.exploded if protocol != None: if protocol in __protocols: newRule.protocol = protocol else: __logger.error("Protocol %s not supported", protocol) newRule.Target = newRule.create_target(DROP) iptc.Chain(table, INPUT).insert_rule(newRule) iptc.Chain(table, OUTPUT).insert_rule(newRule) iptc.Chain(table, FORWARD).insert_rule(newRule) # chain = iptc.Chain(table, INPUT) # # chain.insert_rule(newRule) # # chain = iptc.Chain(table, OUTPUT) # # chain.insert_rule(newRule) # # chain = iptc.Chain(table, FORWARD) # # chain.insert_rule(newRule) __logger.warning("Block IP %s", newRule.src)
def test_rule_interface(self): # valid interfaces rule = iptc.Rule6() for intf in ["eth0", "eth+", "ip6tnl1", "ip6tnl+", "!ppp0", "!ppp+"]: rule.in_interface = intf self.assertEquals(intf, rule.in_interface) rule.out_interface = intf self.assertEquals(intf, rule.out_interface) # invalid interfaces for intf in ["itsaverylonginterfacename"]: try: rule.out_interface = intf except ValueError: pass else: self.fail("rule accepted invalid interface name %s" % (intf)) try: rule.in_interface = intf except ValueError: pass else: self.fail("rule accepted invalid interface name %s" % (intf))
def insertEmergencySSHAccessRule(): if iptc.is_table_available(iptc.Table.FILTER): ruleV4 = iptc.Rule() ruleV4.create_target('ACCEPT') ruleV4.protocol = 'tcp' ruleV4.create_match('tcp').dport = '22' chainV4 = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT') deleteIPTablesRuleIgnoringError(ruleV4, chainV4) chainV4.insert_rule(ruleV4) LOG.debug("Inserted Emergency SSH Access Rule for IPv4") if iptc.is_table_available(iptc.Table6.FILTER): ruleV6 = iptc.Rule6() ruleV6.create_target('ACCEPT') ruleV6.protocol = 'tcp' ruleV6.create_match('tcp').dport = '22' chainV6 = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'INPUT') deleteIPTablesRuleIgnoringError(ruleV6, chainV6) chainV6.insert_rule(ruleV6) LOG.debug("Inserted Emergency SSH Access Rule for IPv6")
def _encode_iptc_rule(rule_d, ipv6=False): # Sanity check assert (isinstance(rule_d, dict)) # Basic rule attributes rule_attr = ('src', 'dst', 'protocol', 'in-interface', 'out-interface', 'fragment') iptc_rule = iptc.Rule6() if ipv6 else iptc.Rule() # Avoid issues with matches that require basic parameters to be configured first for name in rule_attr: if name in rule_d: _iptc_setrule(iptc_rule, name, rule_d[name]) for name, value in rule_d.items(): try: if name in rule_attr: #_iptc_setrule(iptc_rule, name, value) continue elif name == 'target': _iptc_settarget(iptc_rule, value) else: _iptc_setmatch(iptc_rule, name, value) except Exception as e: #print('Ignoring unsupported field <{}:{}>'.format(name, value)) continue return iptc_rule
def ban(address): global lock refreshF2boptions() BAN_TIME = int(f2boptions['ban_time']) MAX_ATTEMPTS = int(f2boptions['max_attempts']) RETRY_WINDOW = int(f2boptions['retry_window']) NETBAN_IPV4 = '/' + str(f2boptions['netban_ipv4']) NETBAN_IPV6 = '/' + str(f2boptions['netban_ipv6']) WHITELIST = r.hgetall('F2B_WHITELIST') ip = ipaddress.ip_address(address.decode('ascii')) if type(ip) is ipaddress.IPv6Address and ip.ipv4_mapped: ip = ip.ipv4_mapped address = str(ip) if ip.is_private or ip.is_loopback: return self_network = ipaddress.ip_network(address.decode('ascii')) if WHITELIST: for wl_key in WHITELIST: wl_net = ipaddress.ip_network(wl_key.decode('ascii'), False) if wl_net.overlaps(self_network): log['time'] = int(round(time.time())) log['priority'] = 'info' log['message'] = 'Address %s is whitelisted by rule %s' % ( self_network, wl_net) r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print 'Address %s is whitelisted by rule %s' % (self_network, wl_net) return net = ipaddress.ip_network( (address + (NETBAN_IPV4 if type(ip) is ipaddress.IPv4Address else NETBAN_IPV6) ).decode('ascii'), strict=False) net = str(net) if not net in bans or time.time( ) - bans[net]['last_attempt'] > RETRY_WINDOW: bans[net] = {'attempts': 0} active_window = RETRY_WINDOW else: active_window = time.time() - bans[net]['last_attempt'] bans[net]['attempts'] += 1 bans[net]['last_attempt'] = time.time() active_window = time.time() - bans[net]['last_attempt'] if bans[net]['attempts'] >= MAX_ATTEMPTS: log['time'] = int(round(time.time())) log['priority'] = 'crit' log['message'] = 'Banning %s' % net r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print 'Banning %s for %d minutes' % (net, BAN_TIME / 60) if type(ip) is ipaddress.IPv4Address: with lock: chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'MAILCOW') rule = iptc.Rule() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) else: with lock: chain = iptc.Chain(iptc.Table6(iptc.Table6.FILTER), 'MAILCOW') rule = iptc.Rule6() rule.src = net target = iptc.Target(rule, "REJECT") rule.target = target if rule not in chain.rules: chain.insert_rule(rule) r.hset('F2B_ACTIVE_BANS', '%s' % net, log['time'] + BAN_TIME) else: log['time'] = int(round(time.time())) log['priority'] = 'warn' log['message'] = '%d more attempts in the next %d seconds until %s is banned' % ( MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net) r.lpush('NETFILTER_LOG', json.dumps(log, ensure_ascii=False)) print '%d more attempts in the next %d seconds until %s is banned' % ( MAX_ATTEMPTS - bans[net]['attempts'], RETRY_WINDOW, net)