-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrouter.py
334 lines (298 loc) · 11.9 KB
/
router.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
import sys
import socket
import threading
import pickle
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Util import Padding
from Crypto.Random import get_random_bytes
from Crypto.Random.random import getrandbits
from hashlib import sha256
from threading import Thread, Lock
from select import select
class Router:
ip = None
port = None
dirIP = None
dirPort = None
priKey = None
pubKey = None
def __init__(self, ip, port):
self.ip = ip
self.port = int(port)
self.dirIP = 'localhost'
self.dirPort = 9001
def generateRSAKeys(self):
# generate keys
key = RSA.generate(2048)
pem = key.export_key(format='PEM', passphrase='dees')
pub = key.publickey()
pub_pem = pub.export_key(format='PEM')
# save in state
self.priKey = pem
self.pubKey = pub_pem
return None
def createSocket(self, ip, port):
ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssocket.bind((ip, port))
ssocket.listen()
return ssocket
def connectSocket(self, ip, port):
ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssocket.connect((ip, port))
return ssocket
def register(self):
ssocket = self.connectSocket(self.dirIP, self.dirPort)
data = {
'ip': self.ip,
'port': self.port,
'pubKey': self.pubKey
}
msg = b'R' + pickle.dumps(data)
ssocket.send(msg)
ssocket.close()
return None
def decryptRSA(self, data):
priKey = RSA.importKey(self.priKey, passphrase='dees')
cipher = PKCS1_OAEP.new(priKey)
plainText = cipher.decrypt(data)
return plainText.decode()
def encryptAES(self, hsk, nonce, data):
key = bytes.fromhex(hsk.hexdigest())
nonce = nonce.digest()[0:8]
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
ct_bytes = cipher.encrypt(data)
return ct_bytes
def decryptAES(self, hsk, nonce, data):
key = bytes.fromhex(hsk.hexdigest())
nonce = nonce.digest()[0:8]
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
return cipher.decrypt(data)
def padData(self, length, data):
return data.ljust(length, b'\0')
def unpadData(self, data):
return data.rstrip(b'\0')
def closeSockets(self, sockets):
for x in sockets:
x.close()
return None
def handleClient(self, connection, address):
print('New connection - {}'.format(address))
p = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485
g = 2
y = getrandbits(1024)
hsk = None
hnonce = None
circID = None
nextRouter = None
nextCircID = None
sockets = [connection]
exitRouter = False
while True:
try:
r, w, e = select(sockets, [], [])
except ValueError:
sockets.remove(nextRouter)
# -->
if connection in r:
try:
msg = connection.recv(512)
except ConnectionResetError:
break
# if len(msg) <= 0: continue
cmd = msg[2:3]
data = msg[3:]
# create
if cmd == b'\x01':
circID = msg[0:2]
# unpad
data = self.unpadData(data)
nonce = data[0:8]
hnonce = sha256(nonce)
egx = data[8:]
# calc shared key
gx = int(self.decryptRSA(egx))
sk = pow(gx, y, p)
hsk = sha256(str(sk).encode())
# calc gy to send back
gy = pow(g, y, p)
data = self.padData(509, str(gy).encode())
# send back to sender
msg = circID + b'\x02' + data
connection.send(msg)
# relay
elif cmd == b'\x03':
# decrypt layer
relayHeader = self.decryptAES(hsk, hnonce, data)
streamID = relayHeader[0:2]
digest = relayHeader[2:8]
length = int.from_bytes(relayHeader[8:10], sys.byteorder)
cmd = relayHeader[10:11]
data = relayHeader[11:length+11]
# check if digest is valid
if hsk.digest()[0:6] == digest:
# update digest
hsk.update(relayHeader)
hnonce.update(relayHeader)
# extend
if cmd == b'\x04':
# send create to next router
nonce = data[0:8]
router = self.unpadData(data[8:29]).decode()
ip, port = tuple(router.split(':'))
try:
nextRouter = self.connectSocket(ip, int(port))
sockets.append(nextRouter)
except Exception as inst:
print(inst)
# send create
nextCircID = get_random_bytes(2)
ex = data[29:]
data = nonce + ex
paddedData = self.padData(509, data)
msg = (nextCircID
+ b'\x01'
+ paddedData)
nextRouter.send(msg)
# begin
elif cmd == b'\x06':
address = data.decode()
ip, port = tuple(address.split(':'))
# create tcp connection
nextRouter = self.connectSocket(ip, int(port))
sockets.append(nextRouter)
exitRouter = True
# build msg
streamID = get_random_bytes(2)
digest = hsk.digest()[0:6]
length = get_random_bytes(2)
relayHeader = (streamID
+ digest
+ length
+ b'\x07'
+ self.padData(498, b''))
cipherText = self.encryptAES(hsk, hnonce, relayHeader)
# send relay back to connection
msg = (circID
+ b'\x03'
+ cipherText)
connection.send(msg)
# data
elif cmd == b'\x08':
request = self.unpadData(data)
# send request
nextRouter.send(request)
# end
elif cmd == b'\x09':
# build msg
streamID = get_random_bytes(2)
digest = hsk.digest()[0:6]
length = get_random_bytes(2)
relayHeader = (streamID
+ digest
+ length
+ b'\x09'
+ self.padData(498, b''))
cipherText = self.encryptAES(hsk, hnonce, relayHeader)
# send relay back to connection
msg = (circID
+ b'\x03'
+ cipherText)
connection.send(msg)
# close nextRouter
nextRouter.close()
else:
# forward to next router
msg = (nextCircID
+ b'\x03'
+ relayHeader)
nextRouter.send(msg)
# <--
if nextRouter in r:
if exitRouter:
try:
msg = nextRouter.recv(498)
except OSError:
nextRouter.close()
continue
streamID = get_random_bytes(2)
digest = hsk.digest()[0:6]
length = len(msg).to_bytes(2, sys.byteorder)
paddedData = self.padData(498, msg)
relayHeader = (streamID
+ digest
+ length
+ b'\x08'
+ paddedData)
cipherText = self.encryptAES(hsk, hnonce, relayHeader)
# send relay back to connection
msg = (circID
+ b'\x03'
+ cipherText)
connection.send(msg)
else:
try:
msg = nextRouter.recv(512)
except ConnectionResetError:
break
# if len(msg) <= 0: continue
cmd = msg[2:3]
data = msg[3:]
# created
if cmd == b'\x02':
# unpad
gy = self.unpadData(data)
# create relay message
streamID = get_random_bytes(2)
digest = hsk.digest()[0:6]
length = len(gy).to_bytes(2, sys.byteorder)
relayHeader = (streamID
+ digest
+ length
+ b'\x05'
+ self.padData(498, gy))
cipherText = self.encryptAES(hsk, hnonce, relayHeader)
# send relay back to connection
msg = (circID
+ b'\x03'
+ cipherText)
connection.send(msg)
# relay
elif cmd == b'\x03':
# add layer
cipherText = self.encryptAES(hsk, hnonce, data)
# send relay back to connection
msg = (circID
+ b'\x03'
+ cipherText)
connection.send(msg)
self.closeSockets(sockets)
print('Connection {} closed.'.format(address))
return None
def listen(self):
# create server socket
ip = self.ip
port = self.port
ssocket = self.createSocket(ip, port)
print('Server is listening on {}:{}'.format(ip, port))
while True:
connection, address = ssocket.accept()
thread = threading.Thread(target=self.handleClient, args=(connection, address))
thread.start()
print('Number of connections: {}'.format(threading.activeCount() - 1))
ssocket.close()
return None
def main(ip, port):
# create router obj
router = Router(ip, port)
# create RSA keypair
router.generateRSAKeys()
# register with directory
router.register()
# start listening
router.listen()
return None
if __name__ == '__main__':
ip = sys.argv[1]
port = sys.argv[2]
main(ip, port)