def initialize_vic(): # Read config file and get parameters. log.info ("Reading vic config from "+ DEFAULT_CONFIG_FILE) f = open(DEFAULT_CONFIG_FILE, "r") vic_config = yaml.load(f) f.close() # Configure each vic vic_id = 0 taps = {} for vic in vic_config: log.info ("Configuring vic id: "+ str(vic_id)) ip = vic['ip'] log.info("vic_ip: "+ ip) mac = vic['mac'] log.info("vic_mac: "+ mac) # Create virtual interface tap = TunTapDevice(name="vic-"+str(vic_id), flags=IFF_TAP) tap.hwaddr = '\x00\x11\x22\x33\x44\x55' tap.addr = ip tap.mtu = 1500 tap.up() log.info("Tap device {0} is up with mac: {1}".format("vic-"+str(vic_id), binascii.hexlify(tap.hwaddr))) taps[ip] = tap tap_list = [] for ip in taps.keys(): tap_list.append(taps[ip]) log.info("Waiting for packets on vics...") while True: handle_packets(tap_list)
def __init__(self, side): self.side = int(side) if self.side not in [1, 2]: print("Side must be 1 or 2") raise Exception("Invalid Side") self.tun = TunTapDevice(flags=IFF_TUN | IFF_NO_PI, name='qrtun%d' % self.side) self.tun.addr = '10.0.8.%d' % (self.side) if self.side == 1: self.other_side = 2 else: self.other_side = 1 self.tun.netmask = '255.255.255.0' #MTU must be set low enough to fit in a single qrcode self.tun.mtu = 500 self.epoll = select.epoll() self.epoll.register(self.tun.fileno(), select.EPOLLIN) self.tun.up() self.seq = 0 self.ack = 0 self.outfile = 'resources/toscreen%d.png' % (self.side) self.infile = 'resources/toscreen%d.png' % (self.other_side) self.indata = None self.olddata = "" self.outdata = "" self.msg_read = True self.sent_time = None self.running = False self.qr = qrtools.QR() self.vc = cv2.VideoCapture(0) self.vc.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 720) self.vc.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1280)
def __init__(self, name, address, netmask, mtu): self.name = name self.tun = TunTapDevice(self.name) self.tun.addr = address self.tun.netmask = netmask self.tun.mtu = mtu self.tun.up()
def __init__(self, side): self.side = int(side) if self.side not in [1, 2]: print("Side must be 1 or 2") raise Exception("Invalid Side") self.tun = TunTapDevice(flags=IFF_TUN | IFF_NO_PI, name='qrtun%d' % self.side) self.tun.addr = '10.0.8.%d' % (self.side) if self.side == 1: self.other_side = 2 else: self.other_side = 1 self.tun.netmask = '255.255.255.0' #MTU must be set low enough to fit in a single qrcode self.tun.mtu = 500 self.epoll = select.epoll() self.epoll.register(self.tun.fileno(), select.EPOLLIN) self.tun.up() #self.outfile = 'resources/toscreen%d.png'%(self.side) self.outfile = None self.infile = 'resources/toscreen%d.png' % (self.other_side) self.indata = None self.olddata = "" self.outdata = "" self.running = False self.qr = qrtools.QR() self.vc = cv2.VideoCapture(0) self.vc.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 720) self.vc.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1280) pygame.init() pygame.event.set_allowed(None) pygame.event.set_allowed([pygame.KEYDOWN, pygame.QUIT]) self.screen = pygame.display.set_mode((SIZE, SIZE)) self.scale = 12 pygame.display.set_caption("qrtun - QR Code scale %d" % (self.scale))
class TUNReader(object): """TUN device""" def __init__(self, tun_dev, tun_addr, tun_remote_addr, tun_nm, tun_mtu, wsfactory): self.wsfactory = wsfactory self.tun = TunTapDevice(name=tun_dev, flags=(IFF_TUN|IFF_NO_PI)) self.tun.addr = tun_addr self.tun.dstaddr = tun_remote_addr self.tun.netmask = tun_nm self.tun.mtu = int(tun_mtu) self.tun.up() reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun.name) log.msg(logstr, logLevel=logging.INFO) def fileno(self): return self.tun.fileno() def connectionLost(self, reason): log.msg("Connection lost", logLevel=logging.WARN) def doRead(self): data = self.tun.read(self.tun.mtu) self.wsfactory.tunnel_write(data) def logPrefix(self): return "TUNReader"
class Tun(): """ Initializes the tun device """ def __init__(self, name, address, netmask, mtu): self.name = name self.tun = TunTapDevice(self.name) self.tun.addr = address self.tun.netmask = netmask self.tun.mtu = mtu self.tun.up() """ Reads data from device """ def read(self, nbytes): return self.tun.read(nbytes + PSEUDO_HEADER_SIZE) """ Writes buffer to device """ def write(self, buf): return self.tun.write(buf)
def __init__(self, ip='192.168.1.0', netmask='255.255.255.0'): tap = TunTapDevice(flags=IFF_TAP|IFF_NO_PI, name="tap0") tap.mtu = 1500 tap.addr = ip tap.netmask = netmask self.tap = tap self.tap.up()
class Client: def __init__(self): self.selectors = selectors.DefaultSelector() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.tun = TunTapDevice(name='mytun', flags=IFF_TUN) self.selectors.register(self.tun, selectors.EVENT_READ, self.packetSender) self.selectors.register(self.sock, selectors.EVENT_READ) def packetSender(self, tun, mask): data = tun.read(100) data = self.dnsAssemble(data) self.sock.sendto(data, ('120.78.166.34', 53)) def dnsAssemble(self, data): packet = dnslib.DNSRecord.question("{}group-17.cs305.fun".format(data), "TXT") return packet.pack() def packetReader(self, conn, mask): data = conn.read(1024).decode() packet = dnslib.DNSRecord.parse(data) msg = packet.questions self.tun.write(msg) def run(self): while True: events = self.selectors.select() for key, mask in events: callback = key.data callback(key.fileobj, mask)
def __init__(self, ip='192.168.1.0', netmask='255.255.255.0'): tap = TunTapDevice(flags=IFF_TAP | IFF_NO_PI, name="tap0") tap.mtu = 1500 tap.addr = ip tap.netmask = netmask self.tap = tap self.tap.up()
def __init__(self, *args, **kwargs): super(TunThread, self).__init__(*args, **kwargs) self.running = True self.tun = TunTapDevice(flags=(IFF_TAP | IFF_NO_PI)) self.tun.addr = '10.5.0.1' self.tun.netmask = '255.255.0.0' self.tun.mtu = 1500 self.tun.up()
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 setup_devs(name, if_idx): tap = TunTapDevice(name="{}-tap{}".format(name, if_idx), flags=IFF_TAP | IFF_NO_PI) tap.up() sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 33554432) sock.bind(("{}-eth{}".format(name, if_idx), socket.SOCK_RAW)) return tap, sock
def open(self): self.set_nodelay(True) self.tun = TunTapDevice(flags= (IFF_TAP | IFF_NO_PI)) self.tun.addr = '192.168.1.1' self.tun.dstaddr = '192.168.1.2' self.tun.netmask = '255.255.255.0' self.tun.mtu = 1500 self.tun.up() self.thread = TunThread(tun=self.tun, socket = self) self.thread.start()
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)
def create_tap(self): # identify interface for bridging, will may take some time to be created def get_interface_for_ip(addr): mon_if_name = '' addrs = psutil.net_if_addrs() for netif in addrs: for iface in addrs[netif]: #print (str(iface.family)) if str(iface.family) == 'AddressFamily.AF_INET': ip_addr = ipaddress.IPv4Network((addrs[netif][0].address, addrs[netif][0].netmask), strict=False) print(ip_addr.network_address) if self.args.priv_net_addr.split('/')[0] == str(addrs[netif][0].address): mon_if_name = netif break return mon_if_name mon_if_name = get_interface_for_ip (self.args.priv_net_addr) while mon_if_name == '' or mon_if_name is None: print("waiting for interface to be active " + self.args.priv_net_addr) r("/bin/sleep 2s") mon_if_name = get_interface_for_ip (self.args.priv_net_addr) # create tap self.tap_interface = 'tap0' addrs = psutil.net_if_addrs() if mon_if_name == '': print ('No interface specified') elif self.tap_interface not in addrs: print('Creating tap ' + self.tap_interface + ' for ' + mon_if_name) #os.system("/root/environments/tls/start-tap.sh " + mon_if_name + " 10.0.2.2/24") r("mkdir /dev/net") r("mknod /dev/net/tun c 10 200") r("ip tuntap add tap0 mode tap") r("brctl addbr br0") r("ip link set tap0 up") r("ip link set br0 up") r("brctl addif br0 tap0") r("brctl addif br0 " + mon_if_name) r("ip addr del " + self.args.priv_net_addr + " dev " + mon_if_name) r("ip addr add " + self.args.priv_net_addr + " dev br0") else: print('Tap already created') # Initialize a TAP interface and make it non-blocking self.tap = TunTapDevice(flags = IFF_TAP|IFF_NO_PI, name=self.tap_interface); self.tap.up() fcntl.fcntl(self.tap.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) self.tap.mtu = self.tap_mtu
class TapNode(object): def __init__(self): os.system('sudo ip tuntap add dev esp32 mode tap user ds') time.sleep(1) self.tap = TunTapDevice(name='esp32', flags=IFF_TAP) def write(self, pkt): self.tap.write('\x00\x00\x00\x00' + pkt) print 'Wrote %d WIFI bytes to host' % len(pkt) #hexdump.hexdump(pkt) def read(self): data = self.tap.read(2000)[4:] print 'Read %d bytes from TAP interface' % len(data) return (PktType.WIFI, data)
def main(): global tap, my_mac, my_ip, server if len(sys.argv) != 3: print("Usage: %s url password" % sys.argv[0]) sys.exit(1) server = sys.argv[1] password = sys.argv[2] while server.endswith('/'): server = server[:-1] session = requests.Session() if os.path.exists("/tmp/tap0cache"): with open("/tmp/tap0cache", "rb") as f: data = f.read(10) my_mac = data[:6] my_ip = data[6:10] else: ans = session.post(server + '/connect', password) res = ans.content if ans.status_code != 200: raise ValueError("Failed to connect: " + str(res)) my_mac = res[:6] my_ip = res[6:10] with open("/tmp/tap0cache", "wb") as f: f.write(res) tap = TunTapDevice(flags=IFF_TAP) tap.addr = ".".join(map(str, my_ip)) print("My ip is:", tap.addr) tap.netmask = '255.255.0.0' tap.mtu = 1300 tap.hwaddr = my_mac tap.up() tap_reader = threading.Thread(target=read_data, daemon=True) tap_reader.start() sender = threading.Thread(target=send_data, daemon=True) sender.start() while True: ans = session.post(server + '/recv', my_mac) if ans.status_code == 204: continue if ans.status_code == 403: os.remove("/tmp/tap0cache") if ans.status_code != 200: print("recv: received status code " + str(ans.status_code) + ": " + ans.text) sys.exit(1) def process_packet(data): packet_mac = get_mac(data) if packet_mac == my_mac or packet_mac == BROADCAST: tap.write(data) parse_packets(BytesIO(ans.content), process_packet)
def __init__(self, *args, **kwargs): super(TunThread, self).__init__(*args, **kwargs) self.running = True self.tun = TunTapDevice(flags= (IFF_TAP | IFF_NO_PI)) self.tun.addr = '10.5.0.1' self.tun.netmask = '255.255.0.0' self.tun.mtu = 1500 self.tun.up()
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): self.tun.write(buf)
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)
class TunThread(threading.Thread): def __init__(self, *args, **kwargs): super(TunThread, self).__init__(*args, **kwargs) self.running = True self.tun = TunTapDevice(flags=(IFF_TAP | IFF_NO_PI)) self.tun.addr = '10.5.0.1' self.tun.netmask = '255.255.0.0' self.tun.mtu = 1500 self.tun.up() def write(self, message): self.tun.write(message) def run(self): p = poll() p.register(self.tun, POLLIN) try: while (self.running): #TODO: log IP headers in the future pollret = p.poll(1000) for (f, e) in pollret: if f == self.tun.fileno() and (e & POLLIN): buf = self.tun.read( self.tun.mtu + 18) #MTU doesn't include header or CRC32 if len(buf): mac = buf[0:6] if mac == BROADCAST or (ord(mac[0]) & 0x1) == 1: for socket in macmap.values(): def send_message(): try: socket.rate_limited_downstream( str(buf)) except: pass loop.add_callback(send_message) elif macmap.get(mac, False): def send_message(): try: macmap[mac].rate_limited_downstream( str(buf)) except: pass loop.add_callback(send_message) except: logger.error('closing due to tun error') finally: self.tun.close()
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
class TUNReader(object): """TUN device""" def __init__(self, tun_dev, tun_addr, tun_remote_addr, tun_nm, tun_mtu, wsfactory): self.wsfactory = wsfactory try: self.tun = TunTapDevice(name=tun_dev, flags=(IFF_TUN|IFF_NO_PI)) except: log.msg("Couldn't open the TUN device. Are you root? Is the interface already in use?", logLevel=logging.WARN) sys.exit(ERR) self.tun.addr = tun_addr self.tun.dstaddr = tun_remote_addr self.tun.netmask = tun_nm self.tun.mtu = int(tun_mtu) self.tun.up() reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun.name) log.msg(logstr, logLevel=logging.INFO) def fileno(self): return self.tun.fileno() def connectionLost(self, reason): log.msg("Connection lost", logLevel=logging.INFO) def doRead(self): """Read from host, send to WS to be sent to distant end""" data = self.tun.read(self.tun.mtu) self.wsfactory.tunnel_write(data) def logPrefix(self): return "TUNReader"
class MainHandler(websocket.WebSocketHandler): def __init__(self, *args, **kwargs): super(MainHandler, self).__init__(*args,**kwargs) self.thread = None def open(self): self.set_nodelay(True) self.tun = TunTapDevice(flags= (IFF_TAP | IFF_NO_PI)) self.tun.addr = '192.168.1.1' self.tun.dstaddr = '192.168.1.2' self.tun.netmask = '255.255.255.0' self.tun.mtu = 1500 self.tun.up() self.thread = TunThread(tun=self.tun, socket = self) self.thread.start() def on_message(self, message): print('wrote %s byte message to %s' % (len(message), self.tun.name)) print(':'.join('{0:x}'.format(ord(c)) for c in message)) self.tun.write(message) def on_close(self): print('Closing %s' % self.tun.name) self.tun.close() if self.thread is not None: self.thread.running = False
class TunThread(threading.Thread): def __init__(self, *args, **kwargs): super(TunThread, self).__init__(*args, **kwargs) self.running = True self.tun = TunTapDevice(flags=(IFF_TAP | IFF_NO_PI)) self.tun.addr = '10.5.0.1' self.tun.netmask = '255.255.0.0' self.tun.mtu = 1500 self.tun.up() def run(self): p = poll() p.register(self.tun, POLLIN) try: while (self.running): #TODO: log IP headers in the future pollret = p.poll(1000) for (f, e) in pollret: if f == self.tun.fileno() and (e & POLLIN): buf = self.tun.read( self.tun.mtu + 18) #MTU doesn't include header or CRC32 if len(buf): mac = buf[0:6] if mac == BROADCAST or (ord(mac[0]) & 0x1) == 1: #print 'sending broadcast frame:' #print ':'.join('{0:02x}'.format(ord(c)) for c in buf) for socket in macmap.values(): def send_message(): try: socket.write_message(str(buf), binary=True) except: pass loop.add_callback(send_message) elif macmap.get(mac, False): def send_message(): try: macmap[mac].write_message(str(buf), binary=True) except: pass loop.add_callback(send_message) else: print( "couldn't find recipient for mac %s from %s " % (':'.join('{0:02x}'.format(ord(c)) for c in mac), ':'.join( '{0:02x}'.format(ord(c)) for c in buf[6:12]))) except: print 'closing due to tun error' finally: self.tun.close()
def setup_tap(addr,netmask): tap = TunTapDevice(flags=IFF_TAP) #tap = TapTunnel() print tap.name tap.addr = addr #tun.dstaddr = '10.8.0.2' tap.netmask = netmask tap.mtu = 1500 print tap #tap.persist(True) tap.up() return tap
def main(): global tap, password if len(sys.argv) != 2: print("Usage: %s password" % sys.argv[0]) sys.exit(1) password = sys.argv[1] tap = TunTapDevice(flags=IFF_TAP) tap.addr = ".".join(map(str, IP_PREFIX + (0, 1))) tap.netmask = '255.255.0.0' tap.mtu = 1300 tap.hwaddr = MYMAC tap.up() tap_reader = threading.Thread(target=read_data, daemon=True) tap_reader.start() print('Serving on 8088...') WSGIServer(application, port=8088, numthreads=1000).start()
def __init__(self, tun_dev, tun_addr, tun_remote_addr, tun_nm, tun_mtu, wsfactory): self.wsfactory = wsfactory self.tun = TunTapDevice(name=tun_dev, flags=(IFF_TUN|IFF_NO_PI)) self.tun.addr = tun_addr self.tun.dstaddr = tun_remote_addr self.tun.netmask = tun_nm self.tun.mtu = int(tun_mtu) self.tun.up() reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun.name) log.msg(logstr, logLevel=logging.INFO)
class TunThread(threading.Thread): def __init__(self, *args, **kwargs): super(TunThread, self).__init__(*args, **kwargs) self.running = True self.tun = TunTapDevice(flags= (IFF_TAP | IFF_NO_PI)) self.tun.addr = '10.5.0.1' self.tun.netmask = '255.255.0.0' self.tun.mtu = 1500 self.tun.up() def write(self, message): self.tun.write(message) def run(self): p = poll() p.register(self.tun, POLLIN) try: while(self.running): #TODO: log IP headers in the future pollret = p.poll(1000) for (f,e) in pollret: if f == self.tun.fileno() and (e & POLLIN): buf = self.tun.read(self.tun.mtu+18) #MTU doesn't include header or CRC32 if len(buf): mac = buf[0:6] if mac == BROADCAST or (ord(mac[0]) & 0x1) == 1: for socket in macmap.values(): def send_message(): try: socket.rate_limited_downstream(str(buf)) except: pass loop.add_callback(send_message) elif macmap.get(mac, False): def send_message(): try: macmap[mac].rate_limited_downstream(str(buf)) except: pass loop.add_callback(send_message) except: logger.error('closing due to tun error') finally: self.tun.close()
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 __init__(self, tun_dev, tun_addr, tun_remote_addr, tun_nm, tun_mtu, wsfactory): self.wsfactory = wsfactory try: self.tun = TunTapDevice(name=tun_dev, flags=(IFF_TUN|IFF_NO_PI)) except: log.msg("Couldn't open the TUN device. Are you root? Is the interface already in use?", logLevel=logging.WARN) sys.exit(ERR) self.tun.addr = tun_addr self.tun.dstaddr = tun_remote_addr self.tun.netmask = tun_nm self.tun.mtu = int(tun_mtu) self.tun.up() reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun.name) log.msg(logstr, logLevel=logging.INFO)
def create_tun(tun_name): tun = TunTapDevice(name=tun_name, flags=(IFF_TUN | IFF_NO_PI)) tun.addr = '10.6.0.1' tun.dstaddr = '0.0.0.0' tun.netmask = '0.0.0.0' tun.mtu = 1500 ''' res = os.system('route add default gw' + ' 10.6.0.1 ' + tun_name) if res == 0: return tun else: return None''' return tun
class TunThread(threading.Thread): def __init__(self, *args, **kwargs): super(TunThread, self).__init__(*args, **kwargs) self.running = True self.tun = TunTapDevice(flags= (IFF_TAP | IFF_NO_PI)) self.tun.addr = '10.5.0.1' self.tun.netmask = '255.255.0.0' self.tun.mtu = 1500 self.tun.up() def run(self): p = poll() p.register(self.tun, POLLIN) try: while(self.running): #TODO: log IP headers in the future pollret = p.poll(1000) for (f,e) in pollret: if f == self.tun.fileno() and (e & POLLIN): buf = self.tun.read(self.tun.mtu+18) #MTU doesn't include header or CRC32 if len(buf): mac = buf[0:6] if mac == BROADCAST or (ord(mac[0]) & 0x1) == 1: #print 'sending broadcast frame:' #print ':'.join('{0:02x}'.format(ord(c)) for c in buf) for socket in macmap.values(): def send_message(): try: socket.write_message(str(buf),binary=True) except: pass loop.add_callback(send_message) elif macmap.get(mac, False): def send_message(): try: macmap[mac].write_message(str(buf),binary=True) except: pass loop.add_callback(send_message) else: print("couldn't find recipient for mac %s from %s " % (':'.join('{0:02x}'.format(ord(c)) for c in mac), ':'.join('{0:02x}'.format(ord(c)) for c in buf[6:12]))) except: print 'closing due to tun error' finally: self.tun.close()
class TunTap(object): def __init__(self): self.tun = TunTapDevice(name="fhdi") self.cs = Lock() def open(self): self.tun.addr = '172.16.0.1' self.tun.netmask = '255.255.255.0' self.tun.mtu = 1500 self.tun.up() def close(self): self.tun.close() def write(self, buf): self.cs.acquire() self.tun.write(buf) self.cs.release()
def opened(self): cherrypy.log("YMK in TunWebSocketHandler opened") if TunWebSocketHandler.tun is None: cherrypy.log("YMK in TunWebSocketHandler new tun") tun = TunTapDevice(flags=IFF_TUN | IFF_NO_PI) tun.addr = g.config.get('server', 'ip') # tun.dstaddr = '10.10.0.2' tun.netmask = g.config.get('server', 'netmask') tun.mtu = int(g.config.get('server', 'mtu')) tun.up() TunWebSocketHandler.tun = tun if TunWebSocketHandler.thread is None: cherrypy.log("YMK in TunWebSocketHandler new thread") TunWebSocketHandler.thread = Thread(target=self.background_send) TunWebSocketHandler.thread.daemon = True TunWebSocketHandler.thread.start() TunWebSocketHandler.thread_counter += 1
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: ")
def setUp(self): tap = TunTapDevice(name=TAP_NAME, flags=IFF_TAP) tap.up() self.tap = tap
def __init__(self, tun_dev, tun_addr, tun_remote_addr, tun_nm, tun_mtu, wsfactory): self.tun_dev = tun_dev self.tun_addr = tun_addr self.addr = tun_addr # used by mtcrypt self.tun_nm = tun_nm self.tun_mtu = int(tun_mtu) self.wsfactory = wsfactory if BSD == True: try: self.tunfd = os.open("/dev/"+tun_dev, os.O_RDWR) call(["/sbin/ifconfig", tun_dev, tun_addr, tun_remote_addr, "up"]) except: log.msg("Error opening TUN device. In use? Permissions?", logLevel=logging.WARN) sys.exit(ERR) reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun_dev) log.msg(logstr, logLevel=logging.INFO) elif LINUX == True: try: self.tun = TunTapDevice(name=tun_dev, flags=(IFF_TUN|IFF_NO_PI)) except: log.msg("Error opening TUN device. In use? Permissions?", logLevel=logging.WARN) sys.exit(ERR) self.tun.addr = tun_addr self.tun.dstaddr = tun_remote_addr self.tun.netmask = tun_nm self.tun.mtu = int(tun_mtu) self.tun.up() reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun.name) log.msg(logstr, logLevel=logging.INFO) elif WINDOWS == True: self.overlappedTx = pywintypes.OVERLAPPED() self.overlappedTx.hEvent = win32event.CreateEvent(None, 0, 0, None) addr_tmp = self.tun_addr.split('.') self.tun_ipv4_address = list() for i in range(0, 4): self.tun_ipv4_address.append(int(addr_tmp[i])) nm_tmp = self.tun_nm.split('.') self.tun_ipv4_netmask = list() self.tun_ipv4_network = list() for i in range(0, 4): self.tun_ipv4_netmask.append(int(nm_tmp[i])) self.tun_ipv4_network.append(int(addr_tmp[i]) & int(nm_tmp[i])) self.TAP_IOCTL_CONFIG_POINT_TO_POINT = self.TAP_CONTROL_CODE(5, 0) self.TAP_IOCTL_SET_MEDIA_STATUS = self.TAP_CONTROL_CODE(6, 0) self.TAP_IOCTL_CONFIG_TUN = self.TAP_CONTROL_CODE(10, 0) try: self.tun_handle = self.openTunTap() except: log.msg("Could not open TUN device. Permissions?", logLevel=logging.WARN) sys.exit(ERR) log.msg("Opened TUN device", logLevel=logging.INFO) self.tunRead = TunRead(self.tun_handle, self.wsfactory) self.tunRead.start()
from pytun import TunTapDevice tun = TunTapDevice(name='mytun') print(tun.name) tun.addr = '192.168.137.1' tun.dstaddr = '192.168.137.10' tun.netmask = '255.255.255.255' tun.mtu = 1500 tap.hwaddr = '\x00\x11\x22\x33\x44\x55' print(tap.hwaddr) tun.persists(True) tun.up() buf = tun.read(tun.mtu) tun.write(buf) tun.close()
import fcntl import struct import os import socket import threading 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"]
from tornado import ioloop from ws4py.client.tornadoclient import TornadoWebSocketClient from pytun import TunTapDevice, IFF_TAP, IFF_NO_PI import sys io_loop = ioloop.IOLoop.instance() tap = TunTapDevice(flags=IFF_TAP|IFF_NO_PI, name='vpn-ws%d') class VpnWSClient(TornadoWebSocketClient): def received_message(self, m): tap.write(str(m)) def closed(self, code, reason=None): print "ooops" ws = VpnWSClient(sys.argv[1]) ws.connect() def tap_callback(fd, event): ws.send(tap.read(tap.mtu), binary=True) io_loop.add_handler(tap.fileno(), tap_callback, io_loop.READ) io_loop.start()
if size: # This accounts for a situation where the header is odd cksum += ip_header[pointer] 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)
class TUN(object): """TUN device""" def __init__(self, tun_dev, tun_addr, tun_remote_addr, tun_nm, tun_mtu, wsfactory): self.tun_dev = tun_dev self.tun_addr = tun_addr self.addr = tun_addr # used by mtcrypt self.tun_nm = tun_nm self.tun_mtu = int(tun_mtu) self.wsfactory = wsfactory if BSD == True: try: self.tunfd = os.open("/dev/"+tun_dev, os.O_RDWR) call(["/sbin/ifconfig", tun_dev, tun_addr, tun_remote_addr, "up"]) except: log.msg("Error opening TUN device. In use? Permissions?", logLevel=logging.WARN) sys.exit(ERR) reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun_dev) log.msg(logstr, logLevel=logging.INFO) elif LINUX == True: try: self.tun = TunTapDevice(name=tun_dev, flags=(IFF_TUN|IFF_NO_PI)) except: log.msg("Error opening TUN device. In use? Permissions?", logLevel=logging.WARN) sys.exit(ERR) self.tun.addr = tun_addr self.tun.dstaddr = tun_remote_addr self.tun.netmask = tun_nm self.tun.mtu = int(tun_mtu) self.tun.up() reactor.addReader(self) logstr = ("Opened TUN device on %s") % (self.tun.name) log.msg(logstr, logLevel=logging.INFO) elif WINDOWS == True: self.overlappedTx = pywintypes.OVERLAPPED() self.overlappedTx.hEvent = win32event.CreateEvent(None, 0, 0, None) addr_tmp = self.tun_addr.split('.') self.tun_ipv4_address = list() for i in range(0, 4): self.tun_ipv4_address.append(int(addr_tmp[i])) nm_tmp = self.tun_nm.split('.') self.tun_ipv4_netmask = list() self.tun_ipv4_network = list() for i in range(0, 4): self.tun_ipv4_netmask.append(int(nm_tmp[i])) self.tun_ipv4_network.append(int(addr_tmp[i]) & int(nm_tmp[i])) self.TAP_IOCTL_CONFIG_POINT_TO_POINT = self.TAP_CONTROL_CODE(5, 0) self.TAP_IOCTL_SET_MEDIA_STATUS = self.TAP_CONTROL_CODE(6, 0) self.TAP_IOCTL_CONFIG_TUN = self.TAP_CONTROL_CODE(10, 0) try: self.tun_handle = self.openTunTap() except: log.msg("Could not open TUN device. Permissions?", logLevel=logging.WARN) sys.exit(ERR) log.msg("Opened TUN device", logLevel=logging.INFO) self.tunRead = TunRead(self.tun_handle, self.wsfactory) self.tunRead.start() if WINDOWS == True: def doWrite(self, data): win32file.WriteFile(self.tun_handle, data, self.overlappedTx) win32event.WaitForSingleObject(self.overlappedTx.hEvent, win32event.INFINITE) self.overlappedTx.Offset = self.overlappedTx.Offset + len(data) def openTunTap(self): guid = self.get_device_guid() tun_handle = win32file.CreateFile( r'\\.\Global\%s.tap' % guid, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_SYSTEM|win32file.FILE_FLAG_OVERLAPPED, None) win32file.DeviceIoControl(tun_handle, self.TAP_IOCTL_SET_MEDIA_STATUS, '\x01\x00\x00\x00', None) configTunParam = [] configTunParam += self.tun_ipv4_address configTunParam += self.tun_ipv4_network configTunParam += self.tun_ipv4_netmask configTunParam = ''.join([chr(b) for b in configTunParam]) win32file.DeviceIoControl( tun_handle, self.TAP_IOCTL_CONFIG_TUN, configTunParam, None) return tun_handle def get_device_guid(self): ADAPTER_KEY = r'SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}' TUNTAP_COMPONENT_ID = 'tap0901' with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, ADAPTER_KEY) as adapters: try: for i in range(10000): key_name = reg.EnumKey(adapters, i) with reg.OpenKey(adapters, key_name) as adapter: try: component_id = reg.QueryValueEx(adapter, 'ComponentId')[0] if component_id == TUNTAP_COMPONENT_ID: return reg.QueryValueEx(adapter, 'NetCfgInstanceId')[0] except WindowsError, err: pass except WindowsError, err: pass def CTL_CODE(self, device_type, function, method, access): return (device_type << 16) | (access << 14) | (function << 2) | method; def TAP_CONTROL_CODE(self, request, method): return self.CTL_CODE(34, request, method, 0)
import hexdump from pytun import TunTapDevice, IFF_TAP tun = TunTapDevice(name='rfc6214') with open("captured_in.hex", "r") as the_file: hex = the_file.readline() buf = hexdump.dehex(hex) tun.write(buf) buf = tun.read(tun.mtu) hex = hexdump.dump(buf, 2, '') print(hex) with open('captured_out.hex', 'w') as the_file: the_file.write(hex)
print x if args.debug: def debug(x): print x log("Debug mode entered.") else: debug = lambda x: None # ---------- config crypto functions crypto = Crypto(args.key) encrypt, decrypt = crypto.encrypt, crypto.decrypt # ---------- config TUN device tun = TunTapDevice() if "client" == args.role: log("Running as client.") tun.addr = args.client_ip #"10.1.0.2" tun.dstaddr = args.server_ip #"10.1.0.1" else: log("Running as server.") tun.addr = args.server_ip #"10.1.0.1" tun.dstaddr = args.client_ip #"10.1.0.2" tun.netmask = "255.255.255.0" tun.mtu = MTU log(\ """%s: mtu %d addr %s netmask %s dstaddr %s""" % \ (tun.name, tun.mtu, tun.addr, tun.netmask, tun.dstaddr) ) tun.up()
from socket import * from fcntl import ioctl from select import select import getopt, struct from scapy.all import * from pytun import TunTapDevice, IFF_TUN, IFF_NO_PI def change_dst_ip(packet, new_ip): new_packet = packet.copy() new_packet[IP].dst = new_ip return new_packet tun0 = TunTapDevice(name='tun0', flags=IFF_TUN + IFF_NO_PI) #'127.0.0.1' tun0.addr = '10.1.8.82' tun0.dstaddr = '10.1.8.83' tun0.netmask = '255.255.255.0' tun0.mtu = 1500 ip = IP(src="192.168.1.2", dst="192.168.1.1") udp = UDP(sport=4444, dport=4444) payload = Raw(load="Hi! I'm UDP-packet") packet = ip / udp / payload packet.show() new_packet = change_dst_ip(packet, "192.168.1.3")
from chips.api.api import Component, Chip, Input, Output, Stimulus, Response from chips.compiler.exceptions import C2CHIPError from demo.rundemo import build_xst, compile_user_design, download_digilent from pytun import TunTapDevice, IFF_TAP, IFF_NO_PI import sys import os import select tap = TunTapDevice(flags=IFF_TAP|IFF_NO_PI, name="tap0") tap.addr = '192.168.1.0' tap.netmask = '255.255.255.0' tap.mtu = 1500 tap.up() class ConsoleOut(Output): def __init__(self, chip, name): Output.__init__(self, chip, name) def data_sink(self, data): sys.stdout.write(chr(data)) sys.stdout.flush() class Leds(Output): def __init__(self, chip, name): Output.__init__(self, chip, name) def data_sink(self, data): print "leds:", bin(data) class NetworkOut(Output): def __init__(self, chip, name): Output.__init__(self, chip, name) self.packet_len=0