Exemple #1
2
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)	
Exemple #2
0
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)
Exemple #3
0
 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()
Exemple #4
0
 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()
Exemple #5
0
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)
Exemple #6
0
    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: ")
Exemple #7
0
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 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
Exemple #9
0
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 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
Exemple #11
0
def start_main(rec, loc, dst, passwd,ifname):
    tunnel = WhatsAppMessageTunnel()
    # Create TUN device for network capture and injections
    tun = TunTapDevice(name='socialtun')

    print(tun.name + ' has been created, information follows:')

    tun.addr = loc
    tun.dstaddr = dst
    tun.netmask = '255.255.255.0'
    tun.mtu = 40000
    password = passwd

    print('Address: ' + tun.addr)
    print('Dest.-Address: ' + tun.dstaddr)
    print('Netmask: ' + tun.netmask)
    print('MTU: ' + str(tun.mtu))


    # Start TUN device
    tun.up()
    up = True

    print('TUN is up')


    # Create the receive thread via our helper method
    # thread = threading.Thread(target=main_loop_starter)
    thread = threading.Thread(target=recv_loop, args=(tunnel, rec, password, tun))
    thread.start()
    thread = threading.Thread(target=ping_server, args=(loc,))
    thread.start()
    while True:
        # Continually read from the tunnel and write data in base64
        buf = tun.read(tun.mtu)
        rc4obj = ARC4.new(password)
        tunnel.send(rec+"@s.whatsapp.net", base64.b64encode(rc4obj.encrypt(buf)))
        #print (buf)

    # Cleanup and stop application
    up = False
    tun.down()
    receiver.stop()
Exemple #12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--source-addr', default='10.8.0.1')
    parser.add_argument('-d', '--dest-addr', default='10.8.0.2')
    parser.add_argument('-m', '--netmask', default='255.255.255.0')
    parser.add_argument('-l', '--mtu', default=1500, type=int)
    args = parser.parse_args()

    tun = TunTapDevice()
    try:
        tun.addr = args.source_addr
        tun.dstaddr = args.dest_addr
        tun.netmask = args.netmask
        tun.mtu = args.mtu
        while True:
            buf = tun.read(tun.mtu)
            print(buf)
            tun.write(buf)
    finally:
        tun.close()
Exemple #13
0
log.debug('Start: %s , Filename: %s', __name__, __file__)

print('Create TAP device. Name = <' + DEVICE_NAME + '>')
try:
    tap = TunTapDevice(name=DEVICE_NAME, flags=IFF_TAP | IFF_NO_PI)
    #    tun = TunTapDevice(name=DEVICE_NAME)
    print('Success')
except:
    print('TAP device create failure.')
    sys.exit(ERROR)

print('Setting TAP device IP addr, Netmask, MTU, MAC')
try:
    #   '''
    tap.addr = '10.20.1.1'
    tap.netmask = '255.255.255.0'
    tap.mtu = 1500
    tap.hwaddr = b'\x00\x11\x22\x33\x44\x55'
    '''
  tun.addr = '10.20.1.1'
  tun.netmask = '255.255.255.0'
  tun.mtu = 1500
  #tun.dstaddr = '10.20.1.10'
  #tun.hwaddr = b'\x00\x11\x22\x33\x44\x55'
  '''
    print('Success')
except:
    print('Settings failure')
    sys.exit(ERROR)
Exemple #14
0
from pytun import TunTapDevice, IFF_NO_PI, IFF_TUN

tun = TunTapDevice(name="tun", flags=(IFF_TUN | IFF_NO_PI))
tun.addr = '192.168.13.10'
tun.dstaddr = '192.168.13.1'
tun.netmask = '255.255.255.0'
tun.persist(True)
tun.mtu = 1500
buf = tun.read(tun.mtu)
tun.write(buf)
Exemple #15
0
from pytun import TunTapDevice
import discord
from discord.ext import tasks, commands

from threading import Thread
import os

import logging

from buffer import Buffer

logging.basicConfig(level=logging.INFO)

tun = TunTapDevice(name='discip')
tun.addr = os.environ['SRC_IP']
tun.dstaddr = os.environ['DST_IP']
tun.netmask = '255.255.255.0'
tun.mtu = 1500
tun.persist(True)
tun.up()


def terminate():
    tun.down()


signal.signal(signal.SIGINT, terminate)

TOKEN = os.environ["DISCORD_TOKEN"]
Exemple #16
0
#!/usr/bin/python
from pytun import TunTapDevice
from select import select
import time

tun1 = TunTapDevice()
tun2 = TunTapDevice()

print "Name %s" % tun1.name
tun1.addr = '10.8.0.1'
tun1.dstaddr = '10.8.0.2'
tun1.netmask = '255.255.255.0'
tun1.mtu = 1500
tun1.up()

print "Name %s" % tun2.name
tun2.addr = '10.8.0.2'
tun2.dstaddr = '10.8.0.1'
tun2.netmask = '255.255.255.0'
tun2.mtu = 1500
tun2.up()

while True:
    r = select([tun1, tun2], [], [])[0][0]
    try:
        buf = r.read(r.mtu)
        if r == tun1:
            read = tun1.name
            tun2.write("Hi tun1!")
        else:
            read = tun2.name
Exemple #17
0
        print(" sending " + " ".join(["%.2x" % x for x in pkt]))
        return pkt
    elif proto == 6:
        parsetcp(payload)
        return None
    elif proto == 17:
        parseudp(payload)
        return None


def parse6(pkt):
    return None


tun = TunTapDevice()
tun.addr = '192.168.210.1'
tun.dstaddr = '192.168.210.2'
tun.netmask = '255.255.255.252'
tun.mtu = 1500
tun.up()

while True:
    buf = tun.read(tun.mtu)
    # pkt = ["%.2x "%c for c in list(buf)]
    pkt = list(buf)
    ethertype = pkt[2] << 8 | pkt[3]
    flags = pkt[0] << 8 | pkt[1]
    payload = pkt[4:]
    if ethertype == 0x0800:
        print("Got IPv4 packet")
        ret = parse4(payload)
Exemple #18
0
    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()
log("%s: up now." % tun.name)

# ---------- open UDP sockets
Exemple #19
0
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"]
Exemple #20
0
    print 'Please enter a number in the above range!'
    exit(1)

# Print username
username = unicode(contacts[i]['print_name'])
peer_id = contacts[i]['peer_id']
print 'Connecting to partner: ' + username

# Create TUN device for network capture and injections
tun = TunTapDevice(name='teletun-device')

print tun.name + ' has been created, information follows:'

# Set IP address based on --server flag
if '--server' in sys.argv:
    tun.addr = '10.8.0.1'
    tun.dstaddr = '10.8.0.2'
else:
    tun.addr = '10.8.0.2'
    tun.dstaddr = '10.8.0.1'

tun.netmask = '255.255.255.0'
tun.mtu = 1500

print 'Address: ' + tun.addr
print 'Dest.-Address: ' + tun.dstaddr
print 'Netmask: ' + tun.netmask
print 'MTU: ' + str(tun.mtu)

# Start TUN device
tun.up()
Exemple #21
0
        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()
log("%s: up now." % tun.name)

# ---------- open UDP sockets
 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()
Exemple #23
0
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()
Exemple #24
0
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
Exemple #25
0
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")

new_packet.show()
Exemple #26
0
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)