def __init__(self, callback, interface='tun0', ip_addr=None, netmask='255.255.255.0', logname='cb.tcphijack', tunowner=None): """ Constructor Creates the TUN device, sets the file descriptor, and registers itself with the Twisted reactor Parameters: callback: The callback function (that takes a single pkt argument) to call when a packet has been read ip: The IP address to give the interface netmask: The netmask to configure for the interface logname: The name of the logger for this instance """ self.log = logging.getLogger('cb.util.twistedtun') guid = get_device_guid() interface = get_interface_from_guid(guid) self.log.debug("TUN Interface = %s" % interface) print interface 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, win32file.FILE_SHARE_READ) win32file.DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, '\x01\x00\x00\x00', None) network = net(ip_addr, netmask) args = '' args += socket.inet_aton(ip_addr) args += socket.inet_aton(network) args += socket.inet_aton(netmask) win32file.DeviceIoControl(handle, TAP_IOCTL_CONFIG_TUN, args, None) self.handle = handle # Okay we have a Tun device up, now we need to set the IP os.popen("netsh int ip set address \"%s\" static %s %s" % (interface, ip_addr, netmask)) # Now we need to create the socket to communicate between the Tun reading thread # and Twisted # First the socket listener tunreadfactory = Factory() tunreadfactory.protocol = TunReadProtocol tunreadfactory.cb = callback endpoint = endpoints.TCP4ServerEndpoint(reactor, TUN_S_PORT) endpoint.listen(tunreadfactory) # Now the producer that reads TUN and writes to the socket t = Thread(target=read_win_tun, args=(handle, TUN_S_PORT)) # t = Process(target=read_win_tun, args=(guid, TUN_S_PORT)) t.daemon = True t.start()