18 ipbytes = map(ord,ip.decode("hex"))
19 return '.'.join(map(str,ipbytes))
25 '8863' : 'PPPoE discover',
29 def etherProto(packet, len=len):
31 if packet[12] == "\x81" and packet[13] == "\x00":
39 def formatPacket(packet, ether_mode):
41 stripped_packet = etherStrip(packet)
42 if not stripped_packet:
43 packet = packet.encode("hex")
45 return "malformed eth " + packet.encode("hex")
47 if packet[24:28] == "8100":
49 ethertype = tagtype.get(packet[32:36], 'eth')
50 return ethertype + " " + ( '-'.join( (
51 packet[0:12], # MAC dest
52 packet[12:24], # MAC src
53 packet[24:32], # VLAN tag
54 packet[32:36], # Ethertype/len
55 packet[36:], # Payload
59 ethertype = tagtype.get(packet[24:28], 'eth')
60 return ethertype + " " + ( '-'.join( (
61 packet[0:12], # MAC dest
62 packet[12:24], # MAC src
63 packet[24:28], # Ethertype/len
64 packet[28:], # Payload
67 packet = stripped_packet
68 packet = packet.encode("hex")
70 return "malformed ip " + packet
72 return "ip " + ( '-'.join( (
74 packet[1:2], #header length
75 packet[2:4], #diffserv/ECN
76 packet[4:8], #total length
78 packet[12:16], #flags/fragment offs
80 packet[18:20], #ip-proto
81 packet[20:24], #checksum
82 ipfmt(packet[24:32]), # src-ip
83 ipfmt(packet[32:40]), # dst-ip
84 packet[40:48] if (int(packet[1],16) > 5) else "", # options
85 packet[48:] if (int(packet[1],16) > 5) else packet[40:], # payload
88 def _packetReady(buf, ether_mode=False, len=len):
99 _,totallen = struct.unpack('HH',buf[0][:4])
100 totallen = socket.htons(totallen)
101 rv = len(buf[0]) >= totallen
102 if not rv and len(buf) > 1:
110 def _pullPacket(buf, ether_mode=False, len=len):
114 _,totallen = struct.unpack('HH',buf[0][:4])
115 totallen = socket.htons(totallen)
116 if len(buf[0]) < totallen:
117 rv = buf[0][:totallen]
118 buf[0] = buf[0][totallen:]
126 if buf[12:14] == '\x08\x10' and buf[16:18] == '\x08\x00':
127 # tagged ethernet frame
129 elif buf[12:14] == '\x08\x00':
130 # untagged ethernet frame
135 def etherWrap(packet):
137 "\x00"*6*2 # bogus src and dst mac
140 "\x00"*4, # bogus crc
143 def piStrip(buf, len=len):
149 def piWrap(buf, ether_mode, etherProto=etherProto):
151 proto = etherProto(buf)
155 "\x00\x00", # PI: 16 bits flags
156 proto, # 16 bits proto
160 _padmap = [ chr(padding) * padding for padding in xrange(127) ]
163 def encrypt(packet, crypter, len=len, padmap=_padmap):
165 padding = crypter.block_size - len(packet) % crypter.block_size
166 packet += padmap[padding]
169 return crypter.encrypt(packet)
171 def decrypt(packet, crypter, ord=ord):
174 packet = crypter.decrypt(packet)
177 padding = ord(packet[-1])
178 if not (0 < padding <= crypter.block_size):
180 raise RuntimeError, "Truncated packet"
181 packet = packet[:-padding]
187 fl = fcntl.fcntl(fd, fcntl.F_GETFL)
189 fcntl.fcntl(fd, fcntl.F_SETFL, fl)
192 traceback.print_exc(file=sys.stderr)
196 def tun_fwd(tun, remote, with_pi, ether_mode, cipher_key, udp, TERMINATE, stderr=sys.stderr, reconnect=None, rwrite=None, rread=None, tunqueue=1000, tunkqueue=1000,
197 cipher='AES', accept_local=None, accept_remote=None, slowlocal=True, queueclass=None, bwlimit=None,
198 len=len, max=max, min=min, OSError=OSError, select=select.select, selecterror=select.error, os=os, socket=socket,
199 retrycodes=(os.errno.EWOULDBLOCK, os.errno.EAGAIN, os.errno.EINTR) ):
204 if cipher_key and cipher:
207 __import__('Crypto.Cipher.'+cipher)
210 cipher = getattr(Crypto.Cipher, cipher)
211 hashed_key = hashlib.sha256(cipher_key).digest()
212 if getattr(cipher, 'key_size'):
213 hashed_key = hashed_key[:cipher.key_size]
214 elif ciphername == 'DES3':
215 hashed_key = hashed_key[:24]
216 crypter = cipher.new(
221 traceback.print_exc(file=sys.stderr)
225 if stderr is not None:
227 print >>stderr, "Packets are transmitted in CIPHER"
229 print >>stderr, "Packets are transmitted in PLAINTEXT"
231 if hasattr(remote, 'fileno'):
232 remote_fd = remote.fileno()
234 def rwrite(remote, packet, os_write=os.write):
235 return os_write(remote_fd, packet)
237 def rread(remote, maxlen, os_read=os.read):
238 return os_read(remote_fd, maxlen)
240 rnonblock = nonblock(remote)
241 tnonblock = nonblock(tun)
243 # Pick up TUN/TAP writing method
248 # We have iovec, so we can skip PI injection
249 # and use iovec which does it natively
251 twrite = iovec.ethpiwrite
252 tread = iovec.piread2
254 twrite = iovec.ippiwrite
255 tread = iovec.piread2
257 # We have to inject PI headers pythonically
258 def twrite(fd, packet, oswrite=os.write, piWrap=piWrap, ether_mode=ether_mode):
259 return oswrite(fd, piWrap(packet, ether_mode))
261 # For reading, we strip PI headers with buffer slicing and that's it
262 def tread(fd, maxlen, osread=os.read, piStrip=piStrip):
263 return piStrip(osread(fd, maxlen))
265 # No need to inject PI headers
273 if accept_local is not None:
274 def tread(fd, maxlen, _tread=tread, accept=accept_local):
275 packet = _tread(fd, maxlen)
276 if accept(packet, 0):
281 if accept_remote is not None:
283 def decrypt_(packet, crypter, decrypt_=decrypt_, accept=accept_remote):
284 packet = decrypt_(packet, crypter)
285 if accept(packet, 1):
290 def rread(fd, maxlen, _rread=rread, accept=accept_remote):
291 packet = _rread(fd, maxlen)
292 if accept(packet, 1):
297 maxbkbuf = maxfwbuf = max(10,tunqueue-tunkqueue)
298 tunhurry = max(0,maxbkbuf/2)
300 if queueclass is None:
301 queueclass = collections.deque
305 maxfwbuf = maxbkbuf = 2000000000
314 if ether_mode or udp:
316 pullPacket = queueclass.popleft
317 reschedule = queueclass.appendleft
319 packetReady = _packetReady
320 pullPacket = _pullPacket
321 reschedule = queueclass.appendleft
327 maxbwfree = bwfree = 1500 * tunqueue
335 if packetReady(bkbuf):
337 if remoteok and packetReady(fwbuf) and (not bwlimit or bwfree > 0):
341 if len(fwbuf) < maxfwbuf:
343 if remoteok and len(bkbuf) < maxbkbuf:
352 rdrdy, wrdy, errs = select(rset,wset,eset,1)
353 except selecterror, e:
354 if e.args[0] == errno.EINTR:
358 traceback.print_exc(file=sys.stderr)
363 if reconnect is not None and remote in errs and tun not in errs:
365 if hasattr(remote, 'fileno'):
366 remote_fd = remote.fileno()
367 elif udp and remote in errs and tun not in errs:
368 # In UDP mode, those are always transient errors
369 # Usually, an error will imply a read-ready socket
370 # that will raise an "Connection refused" error, so
371 # disable read-readiness just for now, and retry
380 # check to see if we can write
381 #rr = wr = rt = wt = 0
386 for x in xrange(maxbatch):
387 packet = pullPacket(fwbuf)
390 packet = encrypt_(packet, crypter)
392 sent += rwrite(remote, packet)
395 if not rnonblock or not packetReady(fwbuf):
398 # This except handles the entire While block on PURPOSE
399 # as an optimization (setting a try/except block is expensive)
400 # The only operation that can raise this exception is rwrite
401 if e.errno in retrycodes:
403 reschedule(fwbuf, packet)
407 if reconnect is not None:
408 # in UDP mode, sometimes connected sockets can return a connection refused.
409 # Give the caller a chance to reconnect
411 if hasattr(remote, 'fileno'):
412 remote_fd = remote.fileno()
414 # in UDP mode, we ignore errors - packet loss man...
416 #traceback.print_exc(file=sys.stderr)
422 for x in xrange(maxtbatch):
423 packet = pullPacket(bkbuf)
424 twrite(tunfd, packet)
427 # Do not inject packets into the TUN faster than they arrive, unless we're falling
428 # behind. TUN devices discard packets if their queue is full (tunkqueue), but they
429 # don't block either (they're always ready to write), so if we flood the device
430 # we'll have high packet loss.
431 if not tnonblock or (slowlocal and len(bkbuf) < tunhurry) or not packetReady(bkbuf):
435 # Give some time for the kernel to process the packets
438 # This except handles the entire While block on PURPOSE
439 # as an optimization (setting a try/except block is expensive)
440 # The only operation that can raise this exception is os_write
441 if e.errno in retrycodes:
443 reschedule(bkbuf, packet)
447 # check incoming data packets
450 for x in xrange(maxbatch):
451 packet = tread(tunfd,2000) # tun.read blocks until it gets 2k!
457 if not tnonblock or len(fwbuf) >= maxfwbuf:
460 # This except handles the entire While block on PURPOSE
461 # as an optimization (setting a try/except block is expensive)
462 # The only operation that can raise this exception is os_read
463 if e.errno not in retrycodes:
468 for x in xrange(maxbatch):
469 packet = rread(remote,2000)
474 packet = decrypt_(packet, crypter)
478 if not udp and packet == "":
479 # Connection broken, try to reconnect (or just die)
480 raise RuntimeError, "Connection broken"
486 if not rnonblock or len(bkbuf) >= maxbkbuf:
489 # This except handles the entire While block on PURPOSE
490 # as an optimization (setting a try/except block is expensive)
491 # The only operation that can raise this exception is rread
492 if e.errno not in retrycodes:
495 if reconnect is not None:
496 # in UDP mode, sometimes connected sockets can return a connection refused
497 # on read. Give the caller a chance to reconnect
499 if hasattr(remote, 'fileno'):
500 remote_fd = remote.fileno()
502 # in UDP mode, we ignore errors - packet loss man...
504 traceback.print_exc(file=sys.stderr)
508 delta = tnow - lastbwtime
510 delta = int(bwlimit * delta)
512 bwfree = min(bwfree+delta, maxbwfree)
515 #print >>sys.stderr, "rr:%d\twr:%d\trt:%d\twt:%d" % (rr,wr,rt,wt)
517 def udp_connect(TERMINATE, local_addr, local_port, peer_addr, peer_port):
518 rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
521 # TERMINATE is a array. An item can be added to TERMINATE, from
522 # outside this function to force termination of the loop
524 raise OSError, "Killed"
526 rsock.bind((local_addr, local_port))
529 # wait a while, retry
530 print >>sys.stderr, "%s: Could not bind. Retrying in a sec..." % (time.strftime('%c'),)
531 time.sleep(min(30.0,retrydelay))
534 rsock.bind((local_addr, local_port))
535 print >>sys.stderr, "Listening UDP at: %s:%d" % (local_addr, local_port)
536 print >>sys.stderr, "Connecting UDP to: %s:%d" % (peer_addr, peer_port)
537 rsock.connect((peer_addr, peer_port))
540 def udp_handshake(TERMINATE, rsock):
543 while not endme and not TERMINATE:
553 keepalive_thread = threading.Thread(target=keepalive)
554 keepalive_thread.start()
558 raise OSError, "Killed"
560 heartbeat = rsock.recv(10)
563 time.sleep(min(30.0,retrydelay))
566 heartbeat = rsock.recv(10)
568 keepalive_thread.join()
570 def udp_establish(TERMINATE, local_addr, local_port, peer_addr, peer_port):
571 rsock = udp_connect(TERMINATE, local_addr, local_port, peer_addr,
573 udp_handshake(TERMINATE, rsock)
576 def tcp_connect(TERMINATE, stop, rsock, peer_addr, peer_port):
579 # The peer has a firewall that prevents a response to the connect, we
580 # will be forever blocked in the connect, so we put a reasonable timeout.
587 raise OSError, "Killed"
589 rsock.connect((peer_addr, peer_port))
593 # wait a while, retry
594 print >>sys.stderr, "%s: Could not connect. Retrying in a sec..." % (time.strftime('%c'),)
595 time.sleep(min(30.0,retrydelay))
598 rsock.connect((peer_addr, peer_port))
601 print >>sys.stderr, "tcp_connect: TCP sock connected to remote %s:%s" % (peer_addr, peer_port)
605 def tcp_listen(TERMINATE, stop, lsock, local_addr, local_port):
608 # We try to bind to the local virtual interface.
609 # It might not exist yet so we wait in a loop.
614 raise OSError, "Killed"
616 lsock.bind((local_addr, local_port))
619 # wait a while, retry
620 print >>sys.stderr, "%s: Could not bind. Retrying in a sec..." % (time.strftime('%c'),)
621 time.sleep(min(30.0,retrydelay))
624 lsock.bind((local_addr, local_port))
626 print >>sys.stderr, "tcp_listen: TCP sock listening in local sock %s:%s" % (local_addr, local_port)
627 # Now we wait until the other side connects.
628 # The other side might not be ready yet, so we also wait in a loop for timeouts.
633 raise OSError, "Killed"
634 rlist, wlist, xlist = select.select([lsock], [], [], timeout)
638 sock,raddr = lsock.accept()
639 print >>sys.stderr, "tcp_listen: TCP connection accepted in local sock %s:%s" % (local_addr, local_port)
644 def tcp_handshake(rsock, listen, hand):
645 # we are going to use a barrier algorithm to decide wich side listen.
646 # each side will "roll a dice" and send the resulting value to the other
652 peer_hand = rsock.recv(1)
653 print >>sys.stderr, "tcp_handshake: hand %s, peer_hand %s" % (hand, peer_hand)
657 elif hand > peer_hand:
660 except socket.timeout:
665 def tcp_establish(TERMINATE, local_addr, local_port, peer_addr, peer_port):
666 def listen(stop, hand, lsock, lresult):
668 rsock = tcp_listen(TERMINATE, stop, lsock, local_addr, local_port)
670 win = tcp_handshake(rsock, True, hand)
672 lresult.append((win, rsock))
674 def connect(stop, hand, rsock, rresult):
676 rsock = tcp_connect(TERMINATE, stop, rsock, peer_addr, peer_port)
678 win = tcp_handshake(rsock, False, hand)
680 rresult.append((win, rsock))
684 for i in xrange(0, 50):
688 raise OSError, "Killed"
689 hand = str(random.randint(1, 6))
693 lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
694 rsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
695 listen_thread = threading.Thread(target=listen, args=(stop, hand, lsock, lresult))
696 connect_thread = threading.Thread(target=connect, args=(stop, hand, rsock, rresult))
697 connect_thread.start()
698 listen_thread.start()
699 connect_thread.join()
701 (lwin, lrsock) = lresult[0]
702 (rwin, rrsock) = rresult[0]
703 if not lrsock or not rrsock:
709 # both socket are connected
719 raise OSError, "Error: tcp_establish could not establish connection."