-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathToyVpnClient.py
215 lines (189 loc) · 7.03 KB
/
ToyVpnClient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/python
# coding:utf-8
"""
__version__ = '1.0'
__date__ = '2013-07-29'
__author__ = "[email protected]"
"""
from __future__ import with_statement
import sys
if sys.version_info < (2, 6):
import simplejson as json
else:
import json
import os
import hashlib
import getopt
import fcntl
import time
import struct
import socket, select
import traceback
import signal
import logging
#SHARED_PASSWORD = hashlib.sha1("xiaoxia").digest()
TUNSETIFF = 0x400454ca
IFF_TUN = 0x0001
IFF_NO_PI = 0x1000
TIMEOUT = 60*10 # seconds
DEBUG = 0
BUFFER_SIZE = 32767
MAX_COUNT = 50
class Tunnel():
def __init__(self):
self.mParameters = None
self.tfd = None
def create(self):
logging.info("create the interface")
try:
self.tfd = os.open("/dev/net/tun", os.O_RDWR)
except:
self.tfd = os.open("/dev/tun", os.O_RDWR)
ifs = fcntl.ioctl(self.tfd, TUNSETIFF, struct.pack("16sH", "tun%d", IFF_TUN|IFF_NO_PI))
self.tname = ifs[:16].strip("\x00")
def close(self):
os.close(self.tfd)
def config(self, ip):
logging.info("Configuring interface %s with ip %s" %(self.tname, ip))
os.system("ip link set %s up" % (self.tname))
os.system("ip addr add %s dev %s" % (ip, self.tname))
os.system("ip link set %s mtu %s" % (self.tname,self.mtu))
os.system("ifconfig %s netmask 255.255.255.0" %self.tname)
def config_routes(self):
logging.info("Setting up new gateway ...")
# Look for default route
routes = os.popen("ip route show").readlines()
defaults = [x.rstrip() for x in routes if x.startswith("default")]
if not defaults:
raise Exception("Default route not found, maybe not connected!")
self.prev_gateway = defaults[0]
self.new_gateway = "default dev %s metric 1" % (self.tname)
self.tun_gateway = self.prev_gateway.replace("default", SERVER)
self.old_dns = file("/etc/resolv.conf", "rb").read()
# Remove default gateway
os.system("ip route del " + self.prev_gateway)
# Add route for gateway
os.system("ip route add " + self.tun_gateway)
# Add new default gateway
os.system("ip route add " + self.new_gateway)
# Set new DNS to 8.8.8.8
file("/etc/resolv.conf", "wb").write("nameserver %s" %self.dns)
def restore_routes(self):
logging.info("Restoring previous gateway ...")
os.system("ip route del " + self.new_gateway)
os.system("ip route del " + self.tun_gateway)
os.system("ip route add " + self.prev_gateway)
file("/etc/resolv.conf", "wb").write(self.old_dns)
def handshake(self,tunnel):
logging.info("handshake with the server ...")
for i in xrange(3):
tunnel.sendto(chr(0) + KEY,(SERVER,PORT))
#tunnel.shutdown(1)
logging.info("start to recv ")
signal.signal(signal.SIGALRM, onRecvParamTimeout)
signal.alarm(5)
packet,src = tunnel.recvfrom(1024)
signal.alarm(0)
logging.info("recv finished == %s" %str(packet).strip())
if (len(packet) > 0 and packet[0] == chr(0)):
if 'WRONG PASSWORD' in packet:
raise Exception("password is wrong")
self.configure(str(packet[1:]).strip())
return
raise Exception("Failed to login server.")
def configure(self,parameters):
logging.info("config the parameters")
if self.tfd and parameters == self.mParameters:
logging.info('Using the previous interface')
return
for parameter in parameters.split(" "):
fields = parameter.split(",")
if fields[0][0] == 'm':
self.mtu = int(fields[1])
elif fields[0][0] == 'a':
self.address = fields[1]
elif fields[0][0] == 'd':
self.dns = fields[1]
self.mParameters = parameters
try:
if self.tfd:
self.close()
except:
logging.error("close interface failed")
self.create()
self.config(self.address)
self.config_routes()
logging.info("configurate finished...")
def run(self):
logging.info("start to run ...")
self.udpfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udpfd.bind(("", 0))
self.handshake(self.udpfd)
logging.info("connected successful")
#maxlentfd = 0
#maxlenudpfd = 0
alive_count = 0
while True:
rset = select.select([self.udpfd, self.tfd], [], [], 1)[0]
if self.tfd in rset:
if DEBUG: os.write(1,'>')
data = os.read(self.tfd, BUFFER_SIZE)
if len(data):
self.udpfd.sendto(data,(SERVER,PORT))
alive_count += 1
if alive_count > MAX_COUNT:
logging.info("recieve data from the tunnel timeout")
#print 'the len of data read from interface is %d' %len(data)
#maxlentfd = maxlentfd > len(data) and maxlentfd or len(data)
#print 'the max lenth of data recv from interface is ',maxlentfd
if self.udpfd in rset:
if DEBUG: os.write(1,'<')
data,src = self.udpfd.recvfrom(BUFFER_SIZE)
if data[0] != chr(0):
os.write(self.tfd, data)
alive_count = 0
#self.run()
#print 'the len of data read from udp tunnel is %d' %len(data)
#maxlenudpfd = maxlenudpfd > len(data) and maxlenudpfd or len(data)
#print 'the max lenth of data recv from udp tunnel is ',maxlenudpfd
def usage(status = 0):
print "Usage: %s [-s server|-p port|-k passord|-h help|-d debug] " % (sys.argv[0])
sys.exit(status)
def on_exit(no, info):
raise Exception("TERM or TSTP signal caught!" )
def onRecvParamTimeout(no, info):
raise Exception("Recieve parameters timeout!" )
if __name__=="__main__":
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
with open('config.json', 'rb') as f:
config = json.load(f)
SERVER = config['server']
PORT = config['server_port']
KEY = config['password']
opts = getopt.getopt(sys.argv[1:],"s:p:k:hd")
for opt,optarg in opts[0]:
if opt == "-h":
usage()
elif opt == "-s":
SERVER = socket.gethostbyname(optarg)
elif opt == "-p":
PORT = int(optarg)
elif opt == "-k":
KEY = optarg
elif opt == "-d":
DEBUG = True
if False == (SERVER and PORT and KEY):
usage(1)
tun = Tunnel()
signal.signal(signal.SIGTERM, on_exit)
signal.signal(signal.SIGTSTP, on_exit)
try:
tun.run()
except KeyboardInterrupt:
pass
except:
print traceback.format_exc()
finally:
tun.restore_routes()
tun.close()