Ejemplo n.º 1
0
def rule_manager():
    filtable = Table('filter')
    firewalliot.block_rules()
    db.create_all()
    db.session.query(AuthConns).delete()
    db.session.commit()
    open('/var/log/firewall', 'w').close()
    while True:
        for row in db.session.query(AuthConns):
            if int(row.sessiontime) <= int(time.time()):
                try:
                    rule0 = Rule(
                        jump='ACCEPT',
                        protocol='udp',
                        matches=[Match('udp', '--dst ' + str(row.ip_addr))])
                    filtable.delete_rule('FORWARD', rule0)
                except IptablesError as e:
                    pass
                db.session.delete(
                    AuthConns.query.filter(AuthConns.id == row.id).first())
            elif not row.fw_status:
                rule0 = Rule(
                    jump='ACCEPT',
                    protocol='udp',
                    matches=[Match('udp', '--dst ' + str(row.ip_addr))])
                filtable.prepend_rule('FORWARD', rule0)
                cwfwrule = AuthConns.query.filter_by(id=row.id).first()
                cwferule.fw_status = True
            elif not row.ip_port:
                log_lookup()
                manage_logging()
            else:
                pass
        db.session.commit()
        time.sleep(15)
Ejemplo n.º 2
0
def unblock_outgoing_packets(proto,
                             ipsrc=None,
                             portsrc=None,
                             ipdst=None,
                             portdst=None):
    """
    Unblocks outgoing packets coming from the kernel using iptables command.
    """
    matches = []
    if portsrc:
        matches.append(Match('tcp', '--sport ' + str(portsrc)))
    if portdst:
        matches.append(Match('tcp', '--dport ' + str(portdst)))
    rule = Rule(
        #in_interface=interface,
        protocol=proto,
        source=ipsrc,
        destination=ipdst,
        matches=matches,
        jump='DROP')

    table = Table('filter')
    try:
        table.delete_rule('OUTPUT', rule)
    except IptablesError:
        print("Unknown rule !", proto, ipsrc, portsrc, ipdst, portdst)
Ejemplo n.º 3
0
def block_rules():
    nattable = Table('nat')
    filtable = Table('filter')

    filtable.set_policy('INPUT', 'ACCEPT')

    nattable.flush_chain('POSTROUTING')
    filtable.flush_chain('FORWARD')
    filtable.flush_chain('OUTPUT')
    filtable.flush_chain('INPUT')
    #nattable.delete_chain()

    rulessh = Rule(protocol='tcp',
                   matches=[Match('tcp', '--dport 22')],
                   jump='ACCEPT')
    filtable.append_rule('INPUT', rulessh)

    rulecs = Rule(in_interface='wlan0',
                  out_interface='eth0',
                  protocol='udp',
                  matches=[Match('udp', '--dport 32100')],
                  jump='ACCEPT')
    filtable.append_rule('FORWARD', rulecs)

    rulefreturn = Rule(in_interface='eth0',
                       out_interface='wlan0',
                       jump='ACCEPT',
                       matches=[Match('state', '--state RELATED,ESTABLISHED')])
    filtable.append_rule('FORWARD', rulefreturn)

    rule0 = Rule(jump='ACCEPT',
                 matches=[Match('state', '--state RELATED,ESTABLISHED')])
    filtable.append_rule('INPUT', rule0)

    rule1 = Rule(out_interface='eth0', jump='MASQUERADE')
    nattable.append_rule('POSTROUTING', rule1)

    rule2 = Rule(out_interface='wlan0', jump='ACCEPT')
    filtable.append_rule('OUTPUT', rule2)

    rule3 = Rule(out_interface='eth0', jump='ACCEPT')
    filtable.append_rule('OUTPUT', rule3)

    rule4 = Rule(in_interface='wlan0', jump='ACCEPT')
    filtable.append_rule('INPUT', rule4)

    rule5 = Rule(in_interface='lo', jump='ACCEPT')
    filtable.append_rule('INPUT', rule5)

    rule6 = Rule(out_interface='lo', jump='ACCEPT')
    filtable.append_rule('OUTPUT', rule6)

    filtable.set_policy('FORWARD', 'DROP')
    filtable.set_policy('INPUT', 'DROP')
    filtable.set_policy('OUTPUT', 'DROP')
Ejemplo n.º 4
0
 def setDefaultPolicy(self):
     self.printMessage("set default policy", None)
     self.filter.set_policy('INPUT', 'DROP')
     self.filter.append_rule(
         'INPUT',
         Rule(matches=[Match('state', '--state ESTABLISHED,RELATED')],
              jump='ACCEPT'))
     self.filter.set_policy('OUTPUT', 'ACCEPT')
     self.filter.set_policy('FORWARD', 'DROP')
     self.filter.append_rule(
         'FORWARD',
         Rule(matches=[Match('state', '--state ESTABLISHED,RELATED')],
              jump='ACCEPT'))
Ejemplo n.º 5
0
def force_add(ip_addr):
    filtable = Table('filter')
    rule0 = Rule(jump='ACCEPT',
                 protocol='udp',
                 matches=[Match('udp', '--dst ' + ip_addr)])
    filtable.prepend_rule('FORWARD', rule0)

    rule1 = Rule(jump='LOG',
                 protocol='udp',
                 matches=[
                     Match('udp', '--dst ' + ip_addr),
                     Match('limit', '--limit 1/hour --limit-burst 1')
                 ])
    filtable.prepend_rule('FORWARD', rule1)
Ejemplo n.º 6
0
 def testMatchTcpNotFlags(self):
     rule = Rule(protocol='tcp', jump='ACCEPT')
     rule.matches.append(Match('tcp', '--tcp-flags ! ACK,SYN ACK'))
     self.assertEqual(rule.specbits(), [
         '-p', 'tcp', '-m', 'tcp', '--tcp-flags', '!', 'ACK,SYN', 'ACK',
         '-j', 'ACCEPT'
     ])
Ejemplo n.º 7
0
def block_icmp_port_unreachable():
    """
    Blocks ICMP port unreachable packets sent by the kernel when a UDP port is hit without any service listening.
    """
    match = Match('icmp', '--icmp-type port-unreachable')
    rule = Rule(protocol="icmp", matches=[match], jump='DROP')
    Table('filter').append_rule('OUTPUT', rule)
Ejemplo n.º 8
0
    def addFilter(self, start, end, destination, duration, message):
        if debug_cleanup:
            duration = 10
        with self.lock:
            ip = toips(start)
            l = end - start + 1
            slash = tobits(l)

            for s, e in self.rules:
                if start >= s and start <= e:
                    print 'overlapping rule ignored (start) %s/%d' % (ip,
                                                                      slash)
                    return
                if end >= s and end <= e:
                    print 'overlapping rule ignored (end) %s/%d' % (ip, slash)
                    return

            rule = Rule(protocol='tcp',
                        source='%s/%d' % (ip, slash),
                        matches=[Match('tcp', '--destination-port 587')],
                        jump=Target(option['jump'],
                                    '--to-destination %s' % destination))
            if not self.debug:
                self.table.append_rule(option['chain'], rule)
            self.database.insert(start, end, duration, message)
            self.rules[(start, end)] = rule
            print "added %s/%d" % (ip, slash)
Ejemplo n.º 9
0
 def testMatchMultiportDports(self):
     rule = Rule(jump='ACCEPT')
     rule.matches.append(Match('multiport', '--dports 20,21,22,80,25,1720'))
     self.assertEqual(rule.specbits(), [
         '-m', 'multiport', '--dports', '20,21,22,80,25,1720', '-j',
         'ACCEPT'
     ])
Ejemplo n.º 10
0
 def testMatch(self):
     rule = netfilter.parser.parse_rule(
         '-m state --state ESTABLISHED,RELATED')
     self.assertEqual(
         rule,
         Rule(matches=[Match('state', '--state ESTABLISHED,RELATED')]))
     self.assertEqual(rule.specbits(),
                      ['-m', 'state', '--state', 'ESTABLISHED,RELATED'])
Ejemplo n.º 11
0
 def redirectHttp(self, interface, proxy_port):
     if self.__ipv6: return
     self.printMessage("redirect HTTP to port %s" % proxy_port, interface)
     self.nat.append_rule(
         'PREROUTING',
         Rule(in_interface=interface,
              protocol='tcp',
              matches=[Match('tcp', '--dport 80')],
              jump=Target('REDIRECT', '--to-port %s' % proxy_port)))
Ejemplo n.º 12
0
def force_remove(ip_addr):
    filtable = Table('filter')
    try:
        rule0 = Rule(jump='ACCEPT',
                     protocol='udp',
                     matches=[Match('udp', '--dst ' + str(ip_addr))])
        filtable.delete_rule('FORWARD', rule0)
    except IptablesError as e:
        pass

    try:
        rule1 = Rule(jump='LOG',
                     protocol='udp',
                     matches=[
                         Match('udp', '--dst ' + ip_addr),
                         Match('limit', '--limit 1/hour --limit-burst 1')
                     ])
        filtable.delete_rule('FORWARD', rule1)
    except IptablesError as e:
        pass
Ejemplo n.º 13
0
def unblock_icmp_port_unreachable():
    """
    Remove the rule that blocks ICMP port unreachable.
    """

    match = Match('icmp', '--icmp-type port-unreachable')
    rule = Rule(protocol="icmp", matches=[match], jump='DROP')
    try:
        Table('filter').delete_rule('OUTPUT', rule)
    except IptablesError:
        print("Try to remove unexisting icmp port-unreachable")
Ejemplo n.º 14
0
 def set_rule(self, in_int, port, src_ip):
     '''
     Make netfilter rule.
     -I INPUT -i $int_in -p tcp --dport $port -j ACCEPT
     '''
     rule = Rule(in_interface=f"{in_int}",
                 source=f"{src_ip}",
                 protocol="tcp",
                 matches=[Match("tcp", f"--dport {port}")],
                 jump="ACCEPT")
     return rule
Ejemplo n.º 15
0
 def acceptProtocol(self,
                    interface,
                    protocol,
                    ports,
                    destination=None,
                    source=None):
     port_str = ','.join(ports)
     self.printMessage(
         "allow selected %s INPUT (ports: %s)" % (protocol, port_str),
         interface)
     self.filter.append_rule(
         'INPUT',
         Rule(in_interface=interface,
              destination=destination,
              source=source,
              protocol=protocol,
              matches=[
                  Match('state', '--state NEW'),
                  Match('multiport', "--destination-port %s" % port_str)
              ],
              jump='ACCEPT'))
Ejemplo n.º 16
0
def manage_logging():
    filtable = Table('filter')
    for row in db.session.query(AuthConns):
        if row.ip_port and not row.port_status:

            rule0 = Rule(jump='ACCEPT',
                         protocol='udp',
                         matches=[
                             Match(
                                 'udp', '--dst ' + str(row.ip_addr) +
                                 ' --dport ' + str(row.ip_port))
                         ])
            filtable.prepend_rule('FORWARD', rule0)

            try:
                rule1 = Rule(jump='LOG',
                             protocol='udp',
                             matches=[
                                 Match('udp', '--dst ' + str(row.ip_addr)),
                                 Match('limit',
                                       '--limit 1/hour --limit-burst 1')
                             ])
                filtable.delete_rule('FORWARD', rule1)
            except IptablesError as e:
                pass
            try:
                rule2 = Rule(
                    jump='ACCEPT',
                    protocol='udp',
                    matches=[Match('udp', '--dst ' + str(row.ip_addr))])
                filtable.delete_rule('FORWARD', rule2)
            except IptablesError as e:
                pass

            row.port_status = True

        else:
            pass
Ejemplo n.º 17
0
 def add_rule(chain, source, to):
     """Adds a rule to the given table."""
     rule = Rule(protocol='tcp')
     if chain == 'PREROUTING':
         interface = outbound_network_interface()
         rule.in_interface = interface
     else:
         rule.out_interface = 'lo'
         interface = 'lo'
     rule.matches = [Match('tcp', '--dport {0}'.format(source))]
     rule.jump = Target('REDIRECT', '--to-port {0}'.format(to))
     table.prepend_rule(chain, rule)
     log.debug('Added a redirect for %s to %s on %s.', source, to,
               interface)
Ejemplo n.º 18
0
    def acceptIcmp(self, interface=None):
        self.printMessage("allow selected icmp INPUT", interface)
        if self.__ipv6:
            self.filter.append_rule(
                'INPUT',
                Rule(in_interface=interface, protocol='icmpv6', jump='ACCEPT'))
        else:
            types = [
                'echo-request', 'network-unreachable', 'host-unreachable',
                'port-unreachable', 'fragmentation-needed', 'time-exceeded'
            ]

            for type in types:
                self.filter.append_rule(
                    'INPUT',
                    Rule(in_interface=interface,
                         protocol='icmp',
                         matches=[Match('icmp', "--icmp-type %s" % (type))],
                         jump='ACCEPT'))
Ejemplo n.º 19
0
 def testRewriteDestPorts(self):
     print('Runnning Test Rewrite Dest Ports...')
     match = Match('multiport', '--destination-ports 1,2,3')
     print('\tMatch: ' + str(match))
     self.assertEqual(match.options(), {'dports': ['1,2,3']})
     print('...Done')
Ejemplo n.º 20
0
 def testRewriteDestPort(self):
     print('Running Test Rewrite Dest Port...')
     match = Match('tcp', '--destination-port 1234')
     print('\tMatch: ' + str(match))
     self.assertEqual(match.options(), {'dport': ['1234']})
     print('...Done')
Ejemplo n.º 21
0
 def testRewriteSourcePort(self):
     print('Match Test Case Set:\nRunning Test Rewrite Source Port...')
     match = Match('tcp', '--source-port 1234')
     print('\tMatch: ' + str(match))
     self.assertEqual(match.options(), {'sport': ['1234']})
     print('...Done')
Ejemplo n.º 22
0
 def testRewriteDestPorts(self):
     match = Match("multiport", "--destination-ports 1,2,3")
     self.assertEqual(match.options(), {"dports": ["1,2,3"]})
Ejemplo n.º 23
0
 def testRewriteDestPorts(self):
     match = Match("tcp", "--destination-port 1234")
     self.assertEqual(match.options(), {"dport": ["1234"]})
Ejemplo n.º 24
0
 def testRewriteDestPorts(self):
     match = Match('multiport', '--destination-ports 1,2,3')
     self.assertEqual(match.options(), {'dports': ['1,2,3']})
Ejemplo n.º 25
0
    def createRules(s, clients):

        # Create firewall rules for all connections
        for key in clients:

            # Get robot by anchor
            r = s.db.query(Robot)\
                            .join('container')\
                            .filter(Robot.anchor==key)\
                            .first()

            if not r:
                # robot doesn't exist - skip
                s.log.critical('Robot {0} does NOT exist'.format(key))
                continue

            # Get virtual address of client from dict
            vaddress = clients[key]['Virtual Address']

            # Gen WebSocket port
            r.wsport = s.ws_port.gen()
            s.log.debug('Gen WebSocket port {0} for robot {1}'.format(
                r.wsport, key))

            # Save container external WebSocket port in database
            s.db.add(r)
            s.db.commit()

            # Make client firewall rules
            s.log.info('Create firewall rule for: {0} -> {1}'.format(
                vaddress, r.container.address))
            client_rule = Rule(protocol='tcp',
                               destination=r.container.address,
                               source=vaddress,
                               in_interface='tun0',
                               jump=Target(
                                   'DNAT', '--to-destination {0}'.format(
                                       r.container.address)))

            # Make container firewall rules
            s.log.info('Create firewall rule for: {0} <- {1}'.format(
                vaddress, r.container.address))
            container_rule = Rule(protocol='tcp',
                                  source=r.container.address,
                                  destination=vaddress,
                                  in_interface='veth.{0}'.format(r.anchor),
                                  jump=Target(
                                      'DNAT',
                                      '--to-destination {0}'.format(vaddress)))
            master_rule = Rule(
                protocol='tcp',
                source=r.container.address,
                destination=GATEWAY_ADDRESS,
                in_interface='veth.{0}'.format(r.anchor),
                matches=[Match('tcp', '--dport 11311')],
                jump=Target('DNAT',
                            '--to-destination {0}:11311'.format(vaddress)))

            s.log.info('Create firewall rule for: WebSocket -> {0}'.format(
                r.container.address))
            websock_rule = Rule(
                protocol='tcp',
                matches=[Match('tcp', '--dport {0}'.format(r.wsport))],
                jump=Target(
                    'DNAT',
                    '--to-destination {0}:9090'.format(r.container.address)))

            # Append rules to table
            s.table.append_rule('PREROUTING', client_rule)
            s.table.append_rule('PREROUTING', container_rule)
            s.table.append_rule('PREROUTING', master_rule)
            s.table.append_rule('PREROUTING', websock_rule)

            # Append rules to internal list
            s.rules[r.anchor] = {
                'client': client_rule,
                'container': container_rule,
                'master': master_rule,
                'websock': websock_rule
            }
Ejemplo n.º 26
0
 def testMatchMark(self):
     rule = Rule(jump='ACCEPT')
     rule.matches.append(Match('mark', '--mark 0x64'))
     self.assertEqual(rule.specbits(),
                      ['-m', 'mark', '--mark', '0x64', '-j', 'ACCEPT'])
Ejemplo n.º 27
0
 def testRewriteSourcePort(self):
     match = Match('tcp', '--source-port 1234')
     self.assertEqual(match.options(), {'sport': ['1234']})
Ejemplo n.º 28
0
 def testRewriteSourcePort(self):
     match = Match('tcp', '--source-port 1234')
     self.assertEqual(match.options(), {'sport': ['1234']})
Ejemplo n.º 29
0
 def testRewriteDestPorts(self):
     match = Match('tcp', '--destination-port 1234')
     self.assertEqual(match.options(), {'dport': ['1234']})
Ejemplo n.º 30
0
 def testMatchState(self):
     rule = Rule(jump='ACCEPT')
     rule.matches.append(Match('state', '--state ESTABLISHED,RELATED'))
     self.assertEqual(
         rule.specbits(),
         ['-m', 'state', '--state', 'ESTABLISHED,RELATED', '-j', 'ACCEPT'])
Ejemplo n.º 31
0
 def testRewriteSourcePorts(self):
     match = Match('multiport', '--source-ports 1,2,3')
     self.assertEqual(match.options(), {'sports': ['1,2,3']})
Ejemplo n.º 32
0
 def testRewriteSourcePort(self):
     match = Match("tcp", "--source-port 1234")
     self.assertEqual(match.options(), {"sport": ["1234"]})
Ejemplo n.º 33
0
 def testRewriteSourcePorts(self):
     match = Match("multiport", "--source-ports 1,2,3")
     self.assertEqual(match.options(), {"sports": ["1,2,3"]})
Ejemplo n.º 34
0
 def testMatchTos(self):
     rule = Rule(jump='ACCEPT')
     rule.matches.append(Match('tos', '--tos 0x10'))
     self.assertEqual(rule.specbits(),
                      ['-m', 'tos', '--tos', '0x10', '-j', 'ACCEPT'])
Ejemplo n.º 35
0
 def testRewriteDestPorts(self):
     match = Match('tcp', '--destination-port 1234')
     self.assertEqual(match.options(), {'dport': ['1234']})
Ejemplo n.º 36
0
 def testRewriteSourcePorts(self):
     match = Match('multiport', '--source-ports 1,2,3')
     self.assertEqual(match.options(), {'sports': ['1,2,3']})
Ejemplo n.º 37
0
from netfilter.rule import Rule, Match

from netfilter.table import Table

x = 0
while x == 0:
    table_name = input('table_name : ')
    chain_name = input('chain_name : ')

    rule = Rule(
        in_interface=input('in_interface : '),
        protocol=input('protocol : '),
        matches=[Match(input('name : '), '--dport ' + input('dport : '))],
        jump=input('jump : '))

    table = Table(table_name)

    table.append_rule(chain_name, rule)
    y = input('Do you want Exit ?')
    if y == 'yes':
        x = 1
Ejemplo n.º 38
0
 def testRewriteDestPorts(self):
     match = Match('multiport', '--destination-ports 1,2,3')
     self.assertEqual(match.options(), {'dports': ['1,2,3']})
Ejemplo n.º 39
0
 def testMatchTcpSport(self):
     rule = Rule(protocol='tcp', jump='ACCEPT')
     rule.matches.append(Match('tcp', '--sport 1234'))
     self.assertEqual(
         rule.specbits(),
         ['-p', 'tcp', '-m', 'tcp', '--sport', '1234', '-j', 'ACCEPT'])