示例#1
0
    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.Rule()
        rule.protocol = "tcp"
        rule.src = "127.0.0.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)
示例#2
0
    def test_flush_user_chains(self):

        chain1 = iptc.Chain(iptc.Table(iptc.Table.FILTER),
                            "iptc_test_flush_chain1")
        chain2 = iptc.Chain(iptc.Table(iptc.Table.FILTER),
                            "iptc_test_flush_chain2")
        iptc.Table(iptc.Table.FILTER).create_chain(chain1)
        iptc.Table(iptc.Table.FILTER).create_chain(chain2)

        rule = iptc.Rule()
        rule.target = iptc.Target(rule, chain2.name)
        chain1.append_rule(rule)

        rule = iptc.Rule()
        rule.target = iptc.Target(rule, chain1.name)
        chain2.append_rule(rule)

        self.assertEquals(len(chain1.rules), 1)
        self.assertEquals(len(chain2.rules), 1)

        filter_table = iptc.Table(iptc.Table.FILTER)
        filter_table.flush()

        self.assertTrue(not filter_table.is_chain(chain1.name))
        self.assertTrue(not filter_table.is_chain(chain2.name))
示例#3
0
    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)
示例#4
0
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)
示例#5
0
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)
示例#6
0
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]
示例#7
0
def set_internal_firewall(network,port_list):
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    chain.flush()

    for port in port_list:
        rule = iptc.Rule()
        rule.target = iptc.Target(rule, "ACCEPT")
        rule.protocol = "tcp"
        rule.src = network
        match = iptc.Match(rule, "tcp")
        match.dport = str(port)
        rule.add_match(match)
        chain.insert_rule(rule)

    rule = iptc.Rule()
    rule.target = iptc.Target(rule, "ACCEPT")
    match = iptc.Match(rule, "state")
    match.state = "RELATED,ESTABLISHED"
    rule.add_match(match)
    chain.insert_rule(rule)

    rule = iptc.Rule()
    rule.target = iptc.Target(rule, "ACCEPT")
    rule.in_interface = "lo"
    chain.insert_rule(rule)

    chain.set_policy("DROP")
示例#8
0
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]
示例#9
0
    def initialize(self):
        tb = iptc.Table(iptc.Table.FILTER)
        c = iptc.Chain(tb, 'INPUT')
        c.flush()

        # Accept loopback
        r = iptc.Rule()
        r.in_interface = 'lo'
        t = iptc.Target(r, 'ACCEPT')
        r.target = t
        c.append_rule(r)

        # Accept designated apps
        r = iptc.Rule()
        t = iptc.Target(r, 'genesis-apps')
        r.target = t
        c.append_rule(r)

        # Allow ICMP (ping)
        shell('iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT')

        # Accept established/related connections
        # Unfortunately this has to be done clasically
        shell('iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT')

        # Reject all else by default
        r = iptc.Rule()
        t = iptc.Target(r, 'DROP')
        r.target = t
        c.append_rule(r)

        self.save()
示例#10
0
    def test_rule_insert(self):
        rules = []

        rule = iptc.Rule()
        rule.protocol = "tcp"
        rule.src = "127.0.0.1"
        target = iptc.Target(rule, "ACCEPT")
        rule.target = target
        self.chain.insert_rule(rule)
        rules.append(rule)

        rule = iptc.Rule()
        rule.protocol = "udp"
        rule.src = "127.0.0.1"
        target = iptc.Target(rule, "REJECT")
        target.reject_with = "host-unreach"
        rule.target = target
        self.chain.insert_rule(rule)
        rules.append(rule)

        rule = iptc.Rule()
        rule.protocol = "tcp"
        rule.dst = "10.1.1.0/255.255.255.0"
        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)
示例#11
0
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())))
示例#12
0
    def __init__(self):

        self.backup()

        log.debug("Starting FirewallManager")

        table = iptc.Table(iptc.Table.FILTER)

        # Crear chain
        try:
            table.create_chain("c-lock")
        except Exception as e:
            log.debug("c-lock exists!")

        # TODO ¿Debería venir desde ACCEPT?
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
        # TODO Añadir que mande aquí todos los puertos protegidos, o todas las conexiones si se protege todo
        rule = iptc.Rule()  # *
        rule.protocol = "tcp"
        # Apuntar INPUT a c-lock
        rule.target = iptc.Target(rule, "c-lock")
        chain.insert_rule(rule, position=len(chain.rules))

        # c-lock config
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "c-lock")
        '''
        TODO 1b53c7b5-55d7-4834-9719-1ef86a7bfe12
        if unmanaged_ports:
            OPEN(unmanaged_ports)
            DROP_ALL
        else:
            DROP (PROTECTED_PORTS)
        '''
        # Drop all the rest
        rule = iptc.Rule()
        rule.protocol = "tcp"
        rule.target = iptc.Target(rule, "DROP")
        chain.insert_rule(rule)

        # Accept all established
        rule = iptc.Rule()
        rule.protocol = "tcp"
        rule.target = iptc.Target(rule, "ACCEPT")
        match = iptc.Match(rule, "state")
        match.state = "RELATED,ESTABLISHED"
        rule.add_match(match)
        chain.insert_rule(rule)

        # TODO Accept all OUTPUT

        # Accept all localhost connections
        rule = iptc.Rule()  # *
        rule.protocol = "tcp"
        rule.src = "127.0.0.1"
        rule.target = iptc.Target(rule, "ACCEPT")
        chain.insert_rule(rule)
示例#13
0
    def test_target_compare(self):
        t1 = iptc.Target(iptc.Rule(), "MARK")
        t1.set_mark = "0x123"

        t2 = iptc.Target(iptc.Rule(), "MARK")
        t2.set_mark = "0x123"

        self.failUnless(t1 == t2)

        t2.reset()
        t2.set_mark = "0x124"
        self.failIf(t1 == t2)
示例#14
0
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)
示例#15
0
def init_vnsf_forward_chain():
    # sudo iptables -t nat -A POSTROUTING --out-interface eth2 -j MASQUERADE
    table = iptc.Table(iptc.Table.NAT)
    chain = iptc.Chain(table, "POSTROUTING")
    chain.flush()
    rule = iptc.Rule()
    rule.out_interface = settings.wan_interface
    target = iptc.Target(rule, "MASQUERADE")
    rule.target = target
    chain.insert_rule(rule)

    # iptables -N vnsf-forward
    table = iptc.Table(iptc.Table.FILTER)
    vnsf_forward_chain = table.create_chain(settings.vnsf_forward_chain)

    # iptables -A vnsf-forward -j RETURN
    rule = iptc.Rule()
    target = iptc.Target(rule, "RETURN")
    rule.target = target
    vnsf_forward_chain.append_rule(rule)

    # iptables -A FORWARD --in-interface eth1 -j vnsf-forward
    chain = iptc.Chain(table, "FORWARD")
    chain.flush()
    rule = iptc.Rule()
    rule.in_interface = settings.lan_interface
    target = iptc.Target(rule, settings.vnsf_forward_chain)
    rule.target = target
    chain.insert_rule(rule)

    # iptables -A FORWARD --in-interface eth1 --out-interface eth2 -j ACCEPT
    rule = iptc.Rule()
    rule.in_interface = settings.lan_interface
    rule.out_interface = settings.wan_interface
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.append_rule(rule)

    # iptables -A FORWARD --in-interface eth2 --out-interface eth1 -m state \
    #   --state ESTABLISHED, RELATED -j ACCEPT
    rule = iptc.Rule()
    rule.in_interface = settings.wan_interface
    rule.out_interface = settings.lan_interface
    match = iptc.Match(rule, "state")
    match.state = "RELATED,ESTABLISHED"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    rule.add_match(match)
    chain.append_rule(rule)
示例#16
0
def allowFwd(anIP):
    # allows all forwarding to/by a client on the network
    # iptables -A FORWARD -s $IP_CLIENT -j ACCEPT
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "FORWARD")
    rule = iptc.Rule()
    rule.src = anIP + "/255.255.255.255"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.append_rule(rule)
    # iptables -A FORWARD -d $IP_CLIENT -j ACCEPT
    rule2 = iptc.Rule()
    rule2.dst = anIP + "/255.255.255.255"
    target2 = iptc.Target(rule2, "ACCEPT")
    rule2.target = target
    chain.append_rule(rule2)
示例#17
0
def main():
    #global parse_packet.block
    global chain, set_ips
    print "block packet", parse_packet.set_block
    #tup=()
    print "length of block", len(parse_packet.set_block)

    #for j in range(len(parse_packet.set_block)):
    for tup in parse_packet.set_block:
        #tup=parse_packet.set_block.pop()
        if tup[1] == "tcp":
            print "TUPLE VALUE", tup[0]
            rule = iptc.Rule()
            rule.in_interfaces = "eth0"
            rule.src = tup[0]
            rule.protocol = "tcp"
            match = rule.create_match("tcp")
            #match.dport = str(tup[1])
            rule.target = iptc.Target(rule, "DROP")
            print rule

            chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")

            #iptc.Chain.insert_rule(,rule,position=1)
            chain.insert_rule(rule)
            set_ips.add(("eth0", "tcp", "INPUT chain", "DROP", "%s" % tup[0]))
            print "set_ips", set_ips
        if tup[1] == "icmp":
            print "TUPLE VALUE", tup[0]
            rule = iptc.Rule()
            rule.in_interfaces = "eth0"
            rule.src = tup[0]
            rule.protocol = "icmp"
            match = rule.create_match("icmp")
            #match.dport = str(tup[1])
            rule.target = iptc.Target(rule, "DROP")
            print "rule", rule

            chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")

            print "chain ", chain
            #iptc.Chain.insert_rule(,rule,position=1)
            chain.insert_rule(rule)
            set_ips.add(("eth0", "icmp", "INPUT chain", "DROP", "%s" % tup[0]))
            print "set_ips", set_ips
            print "chain rule", chain.rules
            print "deleting ", len(chain.rules)
            print "chain name", chain.name
示例#18
0
    def create_rule(self, ip, port):
        """Create a new firewall rule

        Args: 
            ip: IP address
            port: port number

        Returns:
            The firewall rule to white list

        Raises:
            Hyp3rArmorFirewallError: if something is wrong with the IP or port
        """

        if not (ip and valid_ip(ip)):
            raise Hyp3rArmorFirewallError(
                "Not valid IP address: {}".format(ip))

        if not (port and valid_port(port)):
            raise Hyp3rArmorFirewallError("Not valid port: {}".format(port))

        rule = iptc.Rule()
        rule.src = str(ip) + "/32"
        rule.protocol = "tcp"
        rule.target = iptc.Target(rule, "ACCEPT")

        m_dport = iptc.Match(rule, "tcp")
        #iptc wants this as a string
        m_dport.dport = str(port)
        rule.add_match(m_dport)

        m_state = iptc.Match(rule, "state")
        m_state.state = "NEW"
        return rule
示例#19
0
def allow_loopback(chain: iptc.Chain) -> None:
    """Allow local loopback services"""
    logger.debug('Allowing loopback packages...')
    rule = iptc.Rule()
    rule.target = iptc.Target(rule, 'ACCEPT')
    rule.in_interface = 'lo'
    ensure_rule(chain, rule)
def allowEstablished():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'INPUT')
    rule = iptc.Rule()
    match = rule.create_match('state')
    match.state = "RELATED,ESTABLISHED"
    rule.target = iptc.Target(rule, 'ACCEPT')
    chain.insert_rule(rule)
def allowLoopback():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.in_interface = "lo"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.insert_rule(rule)
def drop():
    # chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), Chain)
    # rule = iptc.Rule()
    # rule.protocol = protocol
    # rule.in_interface = interface
    # rule.add_match(match)
    # match = iptc.Match(rule, "iprange")
    # match.src_range = "192.168.1.100-192.168.1.200"
    # match.dst_range = "172.22.33.106"
    # rule.add_match(match)
    # target = iptc.Target(rule, targets)
    # rule.target = target
    # chain.insert_rule(rule)
    rule = iptc.Rule()
    rule.protocol = protocol
    match = iptc.Match(rule, protocol)
    match.sport = source_port
    match.dport = destination_port
    rule.add_match(match)
    match = iptc.Match(rule, "iprange")
    match.src_range = source_Range
    match.dst_range = destination_Range
    rule.src = source
    rule.dst = destination
    rule.add_match(match)
    rule.target = iptc.Target(rule, targets)
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), Chain)
    chain.insert_rule(rule)
示例#23
0
    def test_rule_replace(self):
        rule = iptc.Rule()
        rule.protocol = "tcp"
        rule.src = "127.0.0.1"
        target = iptc.Target(rule, "ACCEPT")
        rule.target = target
        self.chain.insert_rule(rule, 0)

        rule = iptc.Rule()
        rule.protocol = "udp"
        rule.src = "127.0.0.1"
        target = iptc.Target(rule, "ACCEPT")
        rule.target = target

        self.chain.replace_rule(rule, 0)
        self.failUnless(self.chain.rules[0] == rule)
示例#24
0
def addToBlacklist(ip, port):
    user = Blacklist(ip=ip, port=port)
    try:
        db.session.add(user)
        db.session.commit()
        if port != '*':
            command = ("iptables -A INPUT -p tcp --sport {} -s {} -j DROP").format(str(port), str(ip))
            if os.name == 'nt':
                command = "netsh advfirewall firewall add rule name=IPblock dir=in protocol=tcp remoteip={} localport={} action=block".format(ip, port)
                print(command)
            os.system(command)
            return "blocked"
        else:
            if os.name == 'nt':
                command = "netsh advfirewall firewall add rule name=IPblock dir=in protocol=tcp remoteip={} action=block".format(ip)
                print(command)
                os.system(command)
                return "blocked"
            rule = iptc.Rule()
            rule.protocol = 0
            rule.src = str(ip)
            target = iptc.Target(rule, "DROP")
            rule.target = target
            chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
            chain.insert_rule(rule)
        return "blocked"
    except sqlalchemy.exc.IntegrityError:
        return "ip {} is already blocked on {} port".format(ip, port if port != '*' else "all")
示例#25
0
    def setUpCommon(self):
        EnableObjStats()
        SetTraceLevel(7)
        self._ip = '127.0.0.1'
        self._port = 8282
        self._serverAddr = self._ip + ':' + str(self._port)
        self._idle = 2
        self._interval = 2
        self._probe = 2
        timeMargin = 1  # for the margin of error
        self._timeout = self._idle + (self._interval *
                                      self._probe) + timeMargin

        # iptables -[A|D] OUTPUT -p tcp --sport $port -j DROP
        self._chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), 'OUTPUT')
        self._rule = iptc.Rule()
        self._rule.protocol = 'tcp'
        match = self._rule.create_match('tcp')
        match.sport = str(self._port)
        self._rule.target = iptc.Target(self._rule, 'DROP')

        self._ioSvc = BasicIoService()
        self._os = ObexServer(self.__class__.__name__, '', self._port,
                              self._ioSvc)
        self._oc = ObexClient(self.__class__.__name__, self._ioSvc)
示例#26
0
def createRule(cmdDic):
    rule = iptc.Rule()
    if cmdDic['-s'] != '':
        rule.src = cmdDic['-s']
    if cmdDic['-d'] != '':
        rule.dst = cmdDic['-p']
    if cmdDic['-p'] != '':
        rule.protocol = cmdDic['-p']
        match = iptc.Match(rule, cmdDic['-p'])
        if cmdDic['-dport'] != '':
            match.dport = cmdDic['-dport']
        if cmdDic['-sport'] != '':
            match.sport = cmdDic['-sport']
        rule.add_match(match)
    if cmdDic['-m'] != '':
        match = iptc.Match(rule, cmdDic['-m'])
        if cmdDic['-src-range'] != '':
            match.src_range = cmdDic['-src-range']
        if cmdDic['-dst-range'] != '':
            match.dst_range = cmdDic['-dst-range']
        rule.add_match(match)
    if cmdDic['-j'] != '':
        rule.target = iptc.Target(rule, cmdDic['-j'])

    return rule
示例#27
0
    def rule_builder6(self):
        self._rule6.target = iptc.Target(self._rule6, self._target)
        log.debug('Set rule6 target: %s', self._rule6.target)

        if self._proto:
            self._rule6.protocol = self._proto
            log.debug('Set rule6 proto: %s', self._rule6.protocol)

        if self._ports:
            self._rule6.create_match(self._rule6.protocol).dport = self._ports
            log.debug('Set rule6 dport: %s', self._ports)

        if self._sources:
            self._rule6.src = ','.join([
                ip.compressed for ip in self._sources
                if isinstance(ip, IPv6Network)
            ])
            log.debug('Set rule6 src: %s', self._rule6.src)

        if self._dests:
            self._rule6.dst = ','.join([
                ip.compressed for ip in self._dests
                if isinstance(ip, IPv6Network)
            ])
            log.debug('Set rule6 src: %s', self._rule6.dst)

        uid = str(uuid.uuid4())
        m = self._rule6.create_match("comment")
        m.comment = f"{Configuration.get('self-uuid')}-{uid}"

        self._uuids.append(uid)

        log.info('Built IPTables rule: %s', self._rule6)
示例#28
0
 def drop_udp_rule(self):
     rule = iptc.Rule()
     rule.in_interface = "eth0"
     rule.src = self.ip
     rule.protocol = "udp"
     rule.target = iptc.Target(rule, "DROP")
     return rule
示例#29
0
    def setMarking(self,
                   flowId,
                   table="mangle",
                   chain="POSTROUTING",
                   markId=None):
        if not markId:
            tcMgr = TrafficControl()
            markId = tcMgr.generateMark()

        rule = iptc.Rule()

        if flowId.srcAddress:
            rule.src = flowId.srcAddress

        if flowId.dstAddress:
            rule.dst = flowId.dstAddress

        if flowId.prot:
            rule.protocol = flowId.prot
            match = iptc.Match(rule, flowId.prot)

            if flowId.srcPort:
                match.sport = flowId.srcPort

            if flowId.dstPort:
                match.dport = flowId.dstPort

            rule.add_match(match)

        target = iptc.Target(rule, "MARK")
        target.set_mark = str(markId)
        rule.target = target
        chain = iptc.Chain(iptc.Table(table), chain)
        chain.insert_rule(rule)
示例#30
0
def allowEthernet():
    chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
    rule = iptc.Rule()
    rule.in_interface = "eth0"
    target = iptc.Target(rule, "ACCEPT")
    rule.target = target
    chain.insert_rule(rule)