Esempio n. 1
0
def create_device_fixture():
    def db_insert(table):
        try:
            dbc_handler.session.add(table)
            dbc_handler.session.commit()
        except exc.SQLAlchemyError as e:
            print(f"Error: {e}")
            dbc_handler.session.rollback()
        except Exception as e:
            print(f"{e}")

    for i in range(5, 10):
        print(f"ROUTER: {i}")

        keys = genwgkeys.Keys()
        keys.gen_b64_keys()

        router = Router(device_id=f'DEV081{i}',
                        user_pw=f'userpw{i}',
                        device_pw=f'rootpw{i}',
                        wgprvkey=keys.private_wg_key.decode("utf-8"),
                        wgpubkey=keys.public_wg_key.decode("utf-8"),
                        ip=f'10.0.23.1{i}')

        db_insert(router)

    for i in range(1, 2):
        print(f"GATEWAY: {i}")
        gateway = Gateway(name='gateone', os='debian10', ip='172.16.42.50')
        db_insert(gateway)
Esempio n. 2
0
        def got(started, msg, f):
            res = f.result()
            duration = 1000. * (time.process_time() - started)
            print("{}: {} in {}".format(msg, res, duration))
            if msg == "REQUEST GATEWAY":
                # TODO: open interface
                from tunfish.model import Router
                router = Router()
                router.device_id = self.data['device_id']
                print(f"{self.data}")

                router.dev.link('add', ifname=self.data['device_id'], kind='wireguard')
                idx = router.dev.link_lookup(ifname=self.data['device_id'])[0]
                print(f"IDX: {idx}")
                # router.dev.addr('add', index=idx, address=self.data['ip'], mask=24)
                router.dev.addr('add', index=idx, local=self.data['ip'], mask=32, address='192.168.42.50')
                print(f"setup config")
                cfg = {
                    "interface": self.data['device_id'],
                    "listen_port": 42002,
                    "private_key": self.data['wgprvkey'],
                    "peers": [{"public_key": res['wgpubkey'], "endpoint": res['endpoint'] + ":" + str(res['listen_port']), "allowed_ips": ["0.0.0.0/0"]}]
                }
                print(f"res PUBKEY: {res['wgpubkey']}")

                #
                router.wg.set_device(ifname=self.data['device_id'], config=cfg)

                # bring up interface
                router.dev.link('set', index=idx, state='up')

                # set rule
                # router.dev.rule('del', table=10, src='192.168.100.10/24')
                router.dev.rule('add', table=10, src='192.168.100.10/24')
                # set route
                # router.dev.route('del', table=10, src='192.168.100.10/24', oif=idx)
                router.dev.route('add', table=10, src='192.168.42.50/24', gateway='192.168.100.10', oif=idx)

                # iptables
                chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "POSTROUTING")
                rule = iptc.Rule()
                rule.out_interface = "tf0815"
                target = iptc.Target(rule, "MASQUERADE")
                rule.target = target
                chain.insert_rule(rule)
Esempio n. 3
0
 def add_client(self, data):
     print(f"received data from tf-ctl: {data}")
     network = self.dbc_handler.session.query(Network).filter_by(
         name=data['network']).first()
     network.router.append(Router(**data))
     print(f"NETWORK_QUERY:{network.__dict__}")
     try:
         self.dbc_handler.session.add(network)
         self.dbc_handler.session.commit()
     except exc.SQLAlchemyError as e:
         print(f"Error: {e}")
         self.dbc_handler.session.rollback()
     except Exception as e:
         print(f"{e}")
Esempio n. 4
0
        def got(started, msg, ff):
            print(f"result received")
            res = ff.result()
            duration = 1000. * (time.process_time() - started)
            print("{}: {} in {}".format(msg, res, duration))
            if msg == "REQUEST GATEWAY":
                # TODO: open interface
                from tunfish.model import Router
                router = Router()

                # new interface/wg control
                print(f"new control")
                router.interface.create(ifname=self.data['device_id'],
                                        ip=self.data['ip'] + "/" +
                                        self.data['mask'],
                                        privatekey=self.data['wgprvkey'],
                                        listenport=42001)
                router.interface.addpeer(ifname=self.data['device_id'],
                                         publickey=res['wgpubkey'],
                                         endpointaddr=res['endpoint'],
                                         endpointport=res['listen_port'],
                                         keepalive=10,
                                         allowedips={'0.0.0.0/0'})

                # set rule
                # router.dev.rule('del', table=10, src='192.168.100.10/24')
                # router.dev.rule('add', table=10, src='172.16.100.15/16')
                # router.dev.rule('add', table=10, src='10.0.23.15/16')
                router.dev.rule('add',
                                table=10,
                                src=self.data['ip'] + "/" + self.data['mask'])
                # set route
                # router.dev.route('del', table=10, src='192.168.100.10/24', oif=idx)
                idx = router.dev.link_lookup(ifname=self.data['device_id'])[0]
                router.dev.route('add',
                                 table=10,
                                 src='10.0.42.15/16',
                                 gateway='10.0.23.15',
                                 oif=idx)

                # iptables
                chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "POSTROUTING")
                rule = iptc.Rule()
                rule.out_interface = "tf-0815"
                target = iptc.Target(rule, "MASQUERADE")
                rule.target = target
                chain.insert_rule(rule)
Esempio n. 5
0
def create_device_fixture():

    router = Router(device_id='DEV0815',
                    user_pw='userpw',
                    device_pw='rootpw',
                    wgprvkey='wgprivkey',
                    wgpubkey='wgpubkey',
                    ip='192.168.100.10')

    try:
        dbc_handler.session.add(router)
        dbc_handler.session.commit()
    except exc.SQLAlchemyError as e:
        print(f"Error: {e}")
        dbc_handler.session.rollback()
    except Exception as e:
        print(f"{e}")
Esempio n. 6
0
    def open_interface(self, data):
        print(f"data: {data}")

        # create keypair
        import pysodium
        from base64 import b64encode
        keys = pysodium.crypto_box_keypair()

        # TODO: open interface
        router = Router()

        #self.gateway.router.interface.create(ifname=data['device_id'], ip='10.0.42.15/16', privatekey=b64encode(keys[1]),
        #                        listenport=42001)

        # new interface/wg control
        router.interface.create(ifname=data['device_id'],
                                ip='10.0.42.15/16',
                                privatekey=b64encode(keys[1]),
                                listenport=42001)
        # router.interface.addpeer(ifname=data['device_id'], publickey=data['wgpubkey'], endpointaddr=data['ip'], endpointport=42001, keepalive=10)
        router.interface.addpeer(ifname=data['device_id'],
                                 publickey=data['wgpubkey'],
                                 keepalive=10,
                                 allowedips={'0.0.0.0/0'})

        # iptables for wg-interface
        chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "FORWARD")
        rule = iptc.Rule()
        rule.out_interface = "tf-0815"
        target = iptc.Target(rule, "ACCEPT")
        rule.target = target
        chain.insert_rule(rule)

        chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "POSTROUTING")
        rule = iptc.Rule()
        rule.out_interface = "eth0"
        target = iptc.Target(rule, "MASQUERADE")
        rule.target = target
        chain.insert_rule(rule)

        return b64encode(keys[0])
Esempio n. 7
0
 def close_interface(self, data):
     router = Router()
     router.interface.delete(ifname=data['device_id'])
Esempio n. 8
0
        def openInterface(data):
            # POSTFIX = "gw"
            POSTFIX = ""
            print(f"data: {data}")

            # TODO: create wg keys
            # TODO: replace subprocess !!!
            # import subprocess

            # subprocess.call(f"wg genkey | tee privatekey+{data['device_id']} | wg pubkey > publickey+{data['device_id']}", shell=True)
            # with open(f"privatekey+{data['device_id']}", 'r') as f:
            #     priv = f.read()
            #     print(f"PRIV: {priv}")
            #     f.close()
            # with open(f"publickey+{data['device_id']}", 'r') as f:
            #     pub = f.read()
            #     print(f"PUB: {pub}")
            #     f.close()
            # subprocess.call(f"rm privatekey+{data['device_id']} && rm publickey+{data['device_id']}", shell=True)

            import pysodium
            from base64 import b64encode
            keys = pysodium.crypto_box_keypair()
            priv = b64encode(keys[1])
            pub = b64encode(keys[0])

            # TODO: open interface
            router = Router()
            router.device_id = data['device_id'] + POSTFIX
            print(f"{data}")

            router.dev.link('add',
                            ifname=data['device_id'] + POSTFIX,
                            kind='wireguard')
            idx = router.dev.link_lookup(ifname=data['device_id'] + POSTFIX)[0]
            print(f"IDX: {idx}")
            # router.dev.addr('add', index=idx, address='192.168.42.50', mask=24)
            router.dev.addr('add',
                            index=idx,
                            local='192.168.42.50',
                            mask=32,
                            address='192.168.100.10')
            print(f"setup config")
            cfg = {
                "interface":
                data['device_id'] + POSTFIX,
                "listen_port":
                42001,
                "private_key":
                priv,
                "peers": [{
                    "public_key": data["wgpubkey"],
                    "allowed_ips": ["0.0.0.0/0"]
                }]
            }

            router.wg.set_device(ifname=data['device_id'] + POSTFIX,
                                 config=cfg)

            print(f"clientpubkey: {len(data['wgpubkey'])}")
            print(f"clientpubkey: {data['wgpubkey']}")

            router.dev.link('set', index=idx, state='up')

            # iptables for wg-interface
            chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "FORWARD")
            rule = iptc.Rule()
            rule.out_interface = "tf_gateone"
            target = iptc.Target(rule, "ACCEPT")
            rule.target = target
            chain.insert_rule(rule)

            chain = iptc.Chain(iptc.Table(iptc.Table.NAT), "POSTROUTING")
            rule = iptc.Rule()
            rule.out_interface = "eth0"
            target = iptc.Target(rule, "MASQUERADE")
            rule.target = target
            chain.insert_rule(rule)

            return pub