class VPNClient(): def __init__(self, tkns): self.clients = [] self.iface = TunTapDevice(flags=IFF_TAP | IFF_NO_PI, name=iface) if addr is not None and netmask is not None: self.iface.addr = addr if addr is not None and netmask is not None: self.iface.netmask = netmask self.iface.hwaddr = macaddr self.iface.mtu = mtu self.iface.persist(True) self.iface.up() self.loop = asyncio.get_event_loop() os.system(ifup) self.ifacethread = IFaceThread(self.iface) self.ifacethread.start() if not sys.platform == 'win32': self.loop.add_signal_handler(signal.SIGINT, lambda: self.loop.stop()) self.loop.add_signal_handler(signal.SIGTERM, lambda: self.loop.stop()) i = 0 for tkn in tkns: c = VPNBot(self, self.ifacethread, i) i += 1 future = asyncio.ensure_future(c.start(tkn), loop=self.loop) future.add_done_callback(lambda f: self.loop.stop()) self.clients.append(c) self.loop.call_later(.1, self.poll_thread) print("Tap interface started") print( f"VARS: MTU{mtu}, ADDR{addr}, HWADDR{macaddr}, DSCVPN{TUNVER} - {len(tkns)} clients" ) try: self.loop.run_forever() except KeyboardInterrupt: print('Received signal to terminate bot and event loop.') finally: self.loop = asyncio.get_event_loop() for x in self.clients: asyncio.ensure_future(x.close(), loop=self.loop) self.loop.run_forever() self.ifacethread.stop() def is_mine(self, user): for x in self.clients: if x.user == user: return True return False def poll_thread(self): for c in self.clients: asyncio.ensure_future(c.send_pkts(), loop=self.loop) self.loop.call_later(.1, self.poll_thread)
def create_tun_interface(): from pytun import TunTapDevice tun1 = TunTapDevice(name="gtw") tun1.addr = '192.168.13.10' tun1.persist(True) tun2 = TunTapDevice(name='tun_socket') tun2.addr = '192.168.13.1' tun2.persist(True) server_program(tun2.addr)
class backend: def __init__(self): self.tun = TunTapDevice(name='strangenet', flags=pytun.IFF_TUN | pytun.IFF_NO_PI) logging.debug('Created Linux tun device ' + self.tun.name) self.tun.addr = os.getenv('STRANGENET_IP', '10.0.0.1') logging.info('Assigned Linux tun device IP: ' + self.tun.addr) self.tun.netmask = os.getenv('STRANGENET_NETMASK', '255.255.255.0') logging.info('Configured Linux tun device netmask: ' + self.tun.netmask) self.tun.persist( True) # TODO figure out what this does and if we need it self.tun.mtu = 256 self.tun.up() logging.info('Linux tun device is up!') # setup polling self.poller = select.poll() self.poller.register(self.tun, select.POLLIN) def set_mtu(self, mtu): self.tun.mtu = mtu # called by main code when data is recieved from XBee def tx(self, payload): logging.info('Writing payload') print(payload) self.tun.write(payload) def poll(self, timeout): logging.debug('Checking for packets on TUN...') events = self.poller.poll(timeout) if events: # lists are true iff. they are non-empty # FIXME properly read the (fd, event) tuple, iterate list logging.debug("Select poller reports TUN is readable...") data = self.tun.read(self.tun.mtu) logging.debug("Incoming packets on TUN...") #sys.stdout.buffer.write(data) pack = ip.IP(data) return {"IP": pack.dst, "payload": data} else: logging.debug("No packets from TUN.") return None def phy_noroute(self, invalidip, datastart): pass
def run(self): """ Method called when starting the daemon. """ try: logger.info("TapDaemon has started") tap0 = TunTapDevice(name="tap0", flags=IFF_TAP) tap0.hwaddr = '\x00\x11\x22\x33\x44\x55' tap0.addr = '192.168.0.1' tap0.dstaddr = '192.168.0.2' tap0.netmask = '255.255.255.0' tap0.mtu = 1500 tap0.persist(True) tap0.up() logger.info("tap0 interface created") except: logger.exception("exception: ") try: tap1 = TunTapDevice(name="tap1", flags=IFF_TAP) tap1.hwaddr = '\x00\x11\x22\x33\x44\x66' tap1.addr = '192.168.1.1' tap1.dstaddr = '192.168.1.2' tap1.netmask = '255.255.255.0' tap1.mtu = 1500 tap1.persist(True) tap1.up() logger.info("tap1 interface created") except: logger.exception("exception: ") try: while True: time.sleep(2) frame = Ethernet(dst="\x01\x02\x03\x04\x05\x06", src="\x0A\x0B\x0C\x0D\x0E\x0F", type = 0x9100, data = "\x02\x55\x44\x00\x11\x00\x00\x00\x33\x22\x00\x00" + "\x61"*40) # "\x11\x00\x00\x00\x33\x22\x00\x00" #"\x00\x03\x08\x00" tap0.write("\x11\x22\x33\x44" + str(frame)) logger.info("Frame send to tap0") logger.info("Waiting for frame in tap1...") buf = tap1.read(tap1.mtu) logger.info("Received %s", hexlify(buf)) logger.info("\n\n ---------------------------------------------------") except: logger.exception("exception: ")
class TunTap(object): def __init__(self, name, ip, netmask): self.tun = TunTapDevice(name=name, flags=pytun.IFF_TUN | pytun.IFF_NO_PI) self.tun.addr = ip self.tun.netmask = netmask self.mtu = 1500 self.tun.persist(True) self.tun.up() def getfd(self): return self.tun def recv(self): return self.tun.read(self.mtu) def send(self, buf): print(len(buf), buf) self.tun.write(buf)
import sys import pytun from pytun import TunTapDevice try: import uvloop except ImportError: uvloop = None COUNT = 0 tun = TunTapDevice(name="mytun_serv", flags=pytun.IFF_TUN | pytun.IFF_NO_PI) tun.addr = "10.10.10.2" tun.dstaddr = "10.10.10.1" tun.netmask = "255.255.255.0" tun.mtu = 1048 tun.persist(True) tun.up() STREAM_ID = 100 class VPNServerProtocol(QuicConnectionProtocol): # -00 specifies 'dq', 'doq', and 'doq-h00' (the latter obviously tying to # the version of the draft it matches). This is confusing, so we'll just # support them all, until future drafts define conflicting behaviour. SUPPORTED_ALPNS = ["dq", "doq", "doq-h00"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._vpn = None
class VPN: def run(self, tokens): self.loop = asyncio.get_event_loop() self.tokens = tokens self.clients = [] self.channels = [] self.session = None self.ready = False async def runner(): try: await self.start() except: pass loop = asyncio.get_event_loop() future = asyncio.ensure_future(runner(), loop=loop) try: loop.run_forever() except: return async def receive(self, message): try: if (len(message.attachments) == 1): async with aiohttp.ClientSession() as session: async with session.get( message.attachments[0].url) as response: d = await response.read() self.ifacethread.recv_batch(d) elif len(message.content) > 0: self.ifacethread.recv_batch(b64decode(message.content)) except Exception as e: print(e) traceback.print_exc() def send_pkts(self): asyncio.ensure_future(self._send_pkts(), loop=self.loop) async def _send_pkts(self): while not self.ready: # Wait for initialization to finish await asyncio.sleep(1) continue if len(self.ifacethread.batches) > 0: b = await self.ifacethread.get_batch() pkts, cln = b if debug: print(f" batch {cln} | {len(pkts)} (LB:{time()-self.lastsend}") self.lastsend = time() channel = choice(self.channels) if cln < 1480: pktxt = b64encode(b''.join(pkts)).decode("utf-8") asyncio.ensure_future(channel.send(pktxt), loop=self.loop) else: fd = BytesIO() fc = 0 for q in pkts: if debug: print(f" send {len(q)} | {fc}") fd.write(q) asyncio.ensure_future(channel.send( file=discord.File(BytesIO(fd.getvalue()), "d")), loop=self.loop) self.loop.call_later(1.5, self.send_pkts) else: self.loop.call_later(0.3, self.send_pkts) async def start(self): print('Starting...') print(f'Creating {len(self.tokens)} clients') for client in range(len(self.tokens)): print(f'Creating client #{client}') self.clients.append(VPNBot(self, client)) # Set the first client as the receiver self.clients[0].receiver = True for client, token in enumerate(self.tokens): print(f'Starting client #{client} with token {token}') self.loop.create_task(self.clients[client].start(token)) self.session = aiohttp.ClientSession() self.iface = TunTapDevice(flags=IFF_TAP | IFF_NO_PI, name=iface) if addr is not None and netmask is not None: self.iface.addr = addr if addr is not None and netmask is not None: self.iface.netmask = netmask self.iface.hwaddr = macaddr self.iface.mtu = mtu self.iface.persist(True) self.iface.up() os.system(ifup) self.ifacethread = IFaceThread(self.iface) self.ifacethread.start() self.lastsend = time() print("Tap interface started") print(f"VARS: MTU{mtu}, ADDR{addr}, HWADDR{macaddr}") self.loop.call_later(.1, self.send_pkts) while any(client.ready == False for client in self.clients): # Wait for all clients to come up await asyncio.sleep(1) continue self.channels = [ client.get_channel(ispchan) for client in self.clients ] self.ready = True
def __create_tun(self, ip_sec): tun = TunTapDevice(name='SYNC' + ip_sec) tun.addr = self.__ip_prefix + ip_sec tun.netmask = '255.255.255.0' tun.persist(True) tun.up()
cksum = (cksum >> 16) + (cksum & 0xffff) cksum += (cksum >> 16) return (~cksum) & 0xFFFF def shortToBytes(short): high = (short & 0xff00) >> 8 low = (short & 0x00ff) return chr(high) + chr(low) if __name__ == '__main__': tap = TunTapDevice(name='ipsec-tap', flags=IFF_TAP) tap.up() tap.persist(True) while True: try: buf = tap.read(tap.mtu) print 'old', hexlify(buf) # Valeri @ studentpub new_addr = struct.pack('4B', 192, 168, 10, 174) new_buf = buf[:34] + new_addr + buf[38:] ip_header = new_buf[18:38] checksum = ip_checksum([format(ord(c), "x") for c in ip_header], 20) print hex(checksum) final_buf = new_buf[:28] + shortToBytes(checksum) + new_buf[30:] print 'new', hexlify(final_buf)