Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python
- import os, sys
- from socket import *
- from fcntl import ioctl
- from select import select
- import getopt, struct
- MAGIC_WORD = "EknathVenkataramani"
- TUNSETIFF = 0x400454ca
- IFF_TUN = 0x0001
- IFF_TAP = 0x0002
- TUNMODE = IFF_TUN
- MODE = 0
- DEBUG = 0
- def usage(status=0):
- print "Usage: tunproxy [-s port|-c targetip:port] [-e]"
- sys.exit(status)
- opts = getopt.getopt(sys.argv[1:],"s:c:ehd")
- for opt,optarg in opts[0]:
- if opt == "-h":
- usage()
- elif opt == "-d":
- DEBUG += 1
- elif opt == "-s":
- '''Server Mode> So get pinged by client and then send data'''
- MODE = 1
- PORT = int(optarg)
- elif opt == "-c":
- '''CLient Mode. So ping the server and receive the data'''
- MODE = 2
- IP,PORT = optarg.split(":")
- PORT = int(PORT)
- peer = (IP,PORT)
- elif opt == "-e":
- TUNMODE = IFF_TAP
- if MODE == 0:
- usage(1)
- f = os.open("/dev/net/tun", os.O_RDWR)
- '''tun is the interface which processes IP packets'''
- ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "eknathtun%d", TUNMODE))
- '''Create the TUN interface'''
- ifname = ifs[:16].strip("\x00")
- '''Get the interface name'''
- print "Allocated interface %s!" % ifname
- s = socket(AF_INET, SOCK_DGRAM)
- '''Open socket for communication'''
- try:
- if MODE == 1:'''Used while receiving data (ping packet)'''
- s.bind(("", PORT))
- while 1:
- word,peer = s.recvfrom(1500)
- '''_1500_ is the buffer size, indicating the maxmum size of data to be received at once
- _word_ is a string representing the data received and _peer_ is the address of the socket sending the data'''
- if word == MAGIC_WORD:
- break
- print "Bad magic word for %s:%i" % peer
- s.sendto(MAGIC_WORD, peer)
- '''peer is the name of the destination '''
- else:'''Used while sending data (ping packet)'''
- s.sendto(MAGIC_WORD, peer)
- '''peer is the destination to send the data. In this case this comes from the command line arg and is a tuple containing the (destinationIP,port#)'''
- word,peer = s.recvfrom(1500)
- '''_1500_ is the buffer size, indicating the maxmum size of data to be received at once'''
- '''_word_ is a string representing the data received and _peer_ is the address of the socket sending the data'''
- if word != MAGIC_WORD:
- print "Bad magic word for %s:%i" % peer
- sys.exit(2)
- print "Connection with %s:%i established" % peer
- while 1:
- r = select([f,s],[],[])[0][0]
- '''wait until _f_ or _s_ is ready for reading '''
- if r == f:
- if DEBUG: os.write(1,">")
- s.sendto(os.read(f,1500),peer)
- else:
- buf,p = s.recvfrom(1500)
- if p != peer:
- print "Got packet from %s:%i instead of %s:%i" % (p+peer)
- continue
- if DEBUG: os.write(1,"<")
- os.write(f, buf)
- except KeyboardInterrupt:
- print "Exitting....!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement