forked from emily404/442VPN
/
main.py
384 lines (300 loc) · 15.8 KB
/
main.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import kivy
kivy.require('1.9.0')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from functools import partial
import socket
import threading
import sys
import md5
import time
import cbc as CBC
import hmac_gen
from mutual_auth import MutualAuth
from diffie_hellman import DiffieHellman
MSG_TYPE_DH = 'D'
MSG_TYPE_REGULAR = 'R'
SESSION_REFRESH_TIMER_S = 60
TERMINATORS = '\0\0\0\0\0'
class InitScreen(FloatLayout):
def __init__(self, **kwargs):
super(InitScreen, self).__init__(**kwargs)
self.add_widget(Label(text='Shared Secret Value', size_hint=(None, None), pos_hint={'top':0.95, 'right':0.3}))
self.shared_secret_value = TextInput(password=False, multiline=False, size_hint=(0.46, 0.10), pos_hint={'top':0.88, 'right':0.5})
self.add_widget(self.shared_secret_value)
send_secret_button = Button(text='Use Secret', size_hint=(.46, .05), pos_hint={'top':0.75, 'right':0.5}, disabled='true')
self.add_widget(send_secret_button)
self.add_widget(Label(text='Mode', size_hint=(0.5, 0.05), pos_hint={'top':0.65, 'right':0.5}))
client_button = ToggleButton(text='Client', group='Mode', size_hint=(.22, .05), pos_hint={'top':0.60, 'right':0.25})
server_button = ToggleButton(text='Server', group='Mode', state='down', size_hint=(.22, .05), pos_hint={'top':0.60, 'right':0.5})
self.add_widget(client_button)
self.add_widget(server_button)
self.add_widget(Label(text='TCP Connection', size_hint=(.5, .05), pos_hint={'top':0.50, 'right':0.5}))
open_connection_button = Button(text='Open Connection', size_hint=(.22, .05), pos_hint={'top':0.40, 'right':0.25})
close_connection_button = Button(text='Close Connection', size_hint=(.22, .05), pos_hint={'top':0.40, 'right':0.5}, disabled='true')
self.add_widget(open_connection_button)
self.add_widget(close_connection_button)
self.add_widget(Label(text='Data To Be Sent', size_hint=(.5, .05), pos_hint={'top':0.30, 'right':0.5}))
self.data_to_send = TextInput(password=False, multiline=True, size_hint=(.46, .15), pos_hint={'top':0.25, 'right':0.5})
self.add_widget(self.data_to_send)
send_data_button = Button(text='Send Data', size_hint=(.46, .05), pos_hint={'top':0.07, 'right':0.5}, disabled='true')
self.add_widget(send_data_button)
self.add_widget(Label(text='Console', size_hint=(.4, .05), pos_hint={'top':0.95, 'right':0.95}))
self.console = TextInput(password=False, multiline=True, size_hint=(.40, .9), pos_hint={'top':0.90, 'right':0.95})
self.add_widget(self.console)
self.server_button = server_button
self.send_data_button = send_data_button
self.open_connection_button = open_connection_button
self.close_connection_button = close_connection_button
self.send_secret_button = send_secret_button
# bind event handlers
open_connection_button.bind(on_press=partial(self.connectionPrompt))
close_connection_button.bind(on_press=self.closeConnection)
send_secret_button.bind(on_press=self.useSharedSecret)
send_data_button.bind(on_press=self.sendData)
# build UI prompt for connecting
def connectionPrompt(self, obj):
prompt = BoxLayout(size=(250,250),orientation="vertical",spacing=20,padding=20)
self.mode = 'server' if self.server_button.state == 'down' else 'client'
if self.mode == 'client':
self.host_input = TextInput(size_hint=(.8,.15))
prompt.add_widget(Label(text='Host:',size_hint=(.7,.1)))
prompt.add_widget(self.host_input)
self.port_input = TextInput(size_hint=(.8,.15))
prompt.add_widget(Label(text='Port:',size_hint=(.7,.1)))
prompt.add_widget(self.port_input)
connect_button = Button(text='Connect',size_hint=(.4,.1),pos_hint={'right':.7})
self.connect_button= connect_button
prompt.add_widget(connect_button)
popup = Popup(title='Connect',content=prompt, size_hint=(.5,.5))
self.connection_popup = popup
popup.open()
connect_button.bind(on_press=self.connect)
def preventDismiss(self, obj):
return True
# thread for establishing connection
def connectThread(self):
try:
port = int(self.port_input.text)
except ValueError as e:
print e
self.console.text = self.console.text + "\nERROR: Invalid port"
self.connection_popup.unbind(on_dismiss=self.preventDismiss)
self.connection_popup.dismiss()
return
if self.mode == 'client':
sock = self.clientConnect(self.host_input.text, port)
else:
sock = self.serverConnect(port)
self.connection_popup.unbind(on_dismiss=self.preventDismiss)
self.connection_popup.dismiss()
# if connection was not successful do not continue
if not sock:
return
self.console.text = self.console.text + "\nConnected successfully!"
self.socket = sock
self.open_connection_button.disabled = True
self.close_connection_button.disabled = False
self.send_secret_button.disabled = False
# reads in data until it encounters TERMINATORS
def receiveData(self):
data = ''
newchar = ''
last_five = 'abcde'
while last_five != TERMINATORS:
newchar = self.socket.recv(1)
data = data + newchar
if(len(data) > 5):
last_five = data[len(data)-5:]
else:
last_five = 'abcde'
return data[:len(data)-5]
# exchange nonce and establish session key
def mutualAuthentication(self):
bits = 16
nonce = self.mutual_auth.generate_nonce(bits)
self.dh = DiffieHellman.defaultInstance()
if self.mode == 'client':
# send client challenge
self.socket.sendall('im alice,' + str(nonce) + TERMINATORS)
print '[MutualAuthentication] client sent: im alice,' + str(nonce)
# receive challenge response from client
server_response = self.receiveData()
server_nonce = server_response.split(',',1)[0]
server_encrypted = server_response.split(',',1)[1]
print '[MutualAuthentication] client received nonce from server: ' + server_nonce
print '[MutualAuthentication] client received encrypted text: ' + server_encrypted
plaintext = self.mutual_auth.decrypt_ciphertext(server_encrypted)
print '[MutualAuthentication] client decrypted plaintext: ' + plaintext
# check that nonce is correct and you weren't the one to encrypt it
if(not self.mutual_auth.check_name(plaintext) and self.mutual_auth.check_nonce(plaintext)):
# extract partial key sent by server
server_partial_session_key = self.mutual_auth.get_partner_dh_value(plaintext)
print '[MutualAuthentication] extracted server partial key: ' + str(server_partial_session_key)
# generate client partial key
client_partial_session_key = self.dh.partialSessionKeyGen()[0]
# compute the session key
self.total_session_key = self.dh.computeTotalSessionKey(server_partial_session_key)
# encrypt server nonce and client partial key with shared secret and send
encrypted = self.mutual_auth.encrypt_nonce(server_nonce, client_partial_session_key)
self.socket.sendall(encrypted + TERMINATORS)
print '[MutualAuthentication] client sending encrypted text: ' + encrypted
print '[MutualAuthentication] success in authenticating server'
return True
else:
print '[MutualAuthentication] cannot authenticate server, check falied'
return False
# server mode
else:
#server
# wait to receive nonce from client
client_response = self.receiveData()
client_nonce = client_response.split(',')[1]
print '[MutualAuthentication] received client_nonce:'+str(client_nonce)
# generate server partial key
server_partial_session_key = self.dh.partialSessionKeyGen()[0]
# encrypt client nonce and server partial key with shared secret
encrypted = self.mutual_auth.encrypt_nonce(client_nonce, server_partial_session_key)
# send server nonce along with encrypter message
self.socket.sendall(str(nonce) + ',' + encrypted + TERMINATORS)
print '[MutualAuthentication] server sending nonce: ' + str(nonce)
print '[MutualAuthentication] server sending encrypted text: ' + encrypted
# receive client challenge response
client_second_response = self.receiveData()
print '[MutualAuthentication] server received client response: ' + str(client_second_response)
# decrypt client response
plaintext = self.mutual_auth.decrypt_ciphertext(client_second_response)
print '[MutualAuthentication] server decrypted plaintext: ' + plaintext
# check that nonce is correct and you weren't the one to encrypt it
if(not self.mutual_auth.check_name(plaintext) and self.mutual_auth.check_nonce(plaintext)):
# extract client partial key
client_partial_session_key = self.mutual_auth.get_partner_dh_value(plaintext)
print '[MutualAuthentication] extracted the client partial key: ' + str(client_partial_session_key)
# compute session key
self.total_session_key = self.dh.computeTotalSessionKey(client_partial_session_key)
print '[MutualAuthentication] success in authenticating client'
return True
else:
print '[MutualAuthentication] cannot authenticate client, check falied'
return False
# triggers mutual authentication
def useSharedSecret(self, obj):
# validate shared secret input
if(self.shared_secret_value.text != ''):
self.shared_secret_value.disabled = True
# use hashed shared secret as key for mutual authentication
self.shared_secret_hash = md5.new(self.shared_secret_value.text).digest()
self.mutual_auth = MutualAuth(self.shared_secret_hash, self.mode)
else:
self.console.text = self.console.text + "\nERROR: Please enter a shared secret."
print "ERROR: Please enter a shared secret."
return
# on success
if(self.mutualAuthentication()):
self.key_estabilshment_inprogress = False
self.send_data_button.disabled = False
self.send_secret_button.disabled = True
# initialize the CBC cipher
key = md5.new(str(self.total_session_key)).digest()
self.cipher = CBC.generateCBC(key)
# start up thread for receiving incoming messages
threading.Thread(target=self.messageReceivingService).start()
# in server, start up thread to periodically refresh session key
if(self.mode == 'server'):
threading.Thread(target=self.updateSessionKeyService).start()
def connect(self, obj):
self.connect_button.text = "Connecting..."
self.connect_button.disabled = True
self.connection_popup.bind(on_dismiss=self.preventDismiss)
threading.Thread(target=self.connectThread).start()
def closeConnection(self, obj):
self.socket.close()
self.send_data_button.disabled = True
self.data_to_send.text = ''
self.open_connection_button.disabled = False
self.close_connection_button.disabled = False
# sends user inputted messages
def sendData(self, obj):
plaintext = self.data_to_send.text
ciphertext = CBC.encrypt(self.cipher, plaintext)
self.console.text = self.console.text + '\n' + 'Text to be sent: ' + self.data_to_send.text
hmacVal = hmac_gen.genHmac(self.shared_secret_hash, plaintext)
print "[Outgoing] encrypted ciphertext to send: " + ciphertext
print "[Outgoing] hmac value " + hmacVal
self.socket.sendall(MSG_TYPE_REGULAR + hmacVal + ciphertext + TERMINATORS)
self.data_to_send.text = ''
def messageReceivingService(self):
while True:
received = self.receiveData()
print "[Incoming] received raw message: " + received
# special message for exchanging Diffie Hellman keys
if(received[0] == MSG_TYPE_DH):
partial_session_key_received = int(received[1:])
if(self.mode == 'client'):
partial_session_key_generated = self.dh.partialSessionKeyGen()[0]
self.socket.sendall(MSG_TYPE_DH + str(partial_session_key_generated) + TERMINATORS)
self.total_session_key = self.dh.computeTotalSessionKey(partial_session_key_received)
self.key_estabilshment_inprogress = False
# regular messages sent by user
else:
received = received[1:]
# HMAC is first 16 bytes (32 hex digits)
receivedHmac = received[:32]
ciphertext = received[32:]
print "[Incoming] hmac received: "+ receivedHmac
print "[Incoming] ciphertext received: " + ciphertext
plaintext = CBC.decrypt(self.cipher, ciphertext)
print "[Incoming] plaintext decrypted: " + plaintext
self.console.text = self.console.text + "\nReceived: " + plaintext
generatedHmac = hmac_gen.genHmac(self.shared_secret_hash, plaintext)
print "[Incoming] hmac to compare with: " + generatedHmac
if(receivedHmac != generatedHmac):
print "ERROR: Message integrity compromised!"
def updateSessionKeyService(self):
while True:
time.sleep(SESSION_REFRESH_TIMER_S)
# do not generate new partial key if previous exchange has not been completed
if(self.key_estabilshment_inprogress):
continue
partial_session_key = self.dh.partialSessionKeyGen()[0]
msg = MSG_TYPE_DH + str(partial_session_key) + TERMINATORS
self.socket.sendall(msg)
self.key_estabilshment_inprogress = True
# returns socket or nothing on failure
def clientConnect(self, host, port):
# create the client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to given ip and port
try:
client_socket.connect((host, port))
except socket.error, msg:
print msg
return
return client_socket
# returns socket or nothing on failure
def serverConnect(self, port):
# create the server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print socket.gethostname()
# bind the socket to host and port
try:
server_socket.bind((socket.gethostname(), port))
except socket.error, msg:
print msg
return
# listen for a connection
server_socket.listen(1)
sock, addr = server_socket.accept()
return sock
class MyApp(App):
def build(self):
init = InitScreen()
return init
if __name__ == '__main__':
MyApp().run()