-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_actions.py
executable file
·459 lines (358 loc) · 18.1 KB
/
server_actions.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import logging
from log import *
import time, base64
from server_registry import *
from server_client import *
from server import *
import json
import random
from Crypto.Hash import SHA512, HMAC
from Crypto.Random import random
from Crypto.PublicKey import RSA
from string import ascii_lowercase
from secure import Secure
from Crypto.Protocol.KDF import PBKDF1
from citizencard import citizencard
cc = citizencard()
secure = Secure()
HOST = "" # All available interfaces
PORT = 8080 # The server port
pubNum = lambda x,y,z: int(pow(x,y,z))
def privateNumber():
secret = int(random.randint(0,100))
return secret
# Colours
class colors:
TITLE = '\033[95m'
INFO = '\033[94m'
VALID = '\033[92m'
WARNING = '\033[93m'
ERROR = '\033[91m'
END = '\033[0m'
BOLD = '\033[1m'
class ServerActions:
def __init__(self):
self.messageTypes = {
'all': self.processAll,
'list': self.processList,
'new': self.processNew,
'send': self.processSend,
'recv': self.processRecv,
'create': self.processCreate,
'receipt': self.processReceipt,
'status': self.processStatus,
'dh': self.processAuthentication,
'secure': self.processSecure,
'refresh': self.processRefresh,
'sync': self.processSync,
}
# Registry
self.registry = ServerRegistry()
# Par de Chaves Assimetricas
self.pubKey, self.privKey = secure.get_keys()
def handleRequest(self, s, request, client):
"""Handle a request from a client socket.
"""
try:
#logging.info("HANDLING message from %s: %r" %
# (client, repr(request)))
try:
req = json.loads(request)
except:
logging.exception("Invalid message from client")
return
if not isinstance(req, dict):
log(logging.ERROR, "Invalid message format from client")
return
if 'type' not in req:
log(logging.ERROR, "Message has no TYPE field")
return
if req['type'] in self.messageTypes:
self.messageTypes[req['type']](req, client, None) # secure
else:
log(logging.ERROR, "Invalid message type: " +
str(req['type']) + " Should be one of: " + str(self.messageTypes.keys()))
client.sendResult({"error": "unknown request"})
except Exception, e:
logging.exception("Could not handle request")
def processRefresh(self, data, client, msgControl):
""" Refresh keys and session
"""
log(logging.INFO, colors.INFO + " Refreshing Keys" + colors.END)
client_pubkey = base64.b64encode(data['publickey'])
client.modulus_prime = data['modulus_prime']
client.primitive_root = data['primitive_root']
client.client_pubNum = int(data['Client_pubNum'])
client.svPrivNum = privateNumber()
# update pubkey
if not self.registry.updatePublicKey(client.uuid, client_pubkey):
log(logging.INFO, colors.ERROR + "Error while trying to update Public Key" + colors.END)
return
# Compute New Shared Key
client.svPubNum = int(pow(client.primitive_root, client.svPrivNum, client.modulus_prime))
new_sharedKey = int(pow(client.client_pubNum, client.svPrivNum, client.modulus_prime))
log(logging.INFO, colors.VALID + " Keys Updated" + colors.END)
client.sendResult({"resultRefresh":{
"Server_pubNum" : client.svPubNum,
},
"server_pubkey" : self.pubKey,
}, msgControl)
client.sharedKey = new_sharedKey
def processSecure(self, data, client, msgControl=None):
""" Process Message with type field "secure"
"""
msgControl = data['msgControl']
# flag de controlo
if not base64.b64decode(msgControl) == secure.SHA256(str(client.nextRequest)):
log(logging.INFO, colors.ERROR + "This messages is not the answer for the previews request." + colors.END)
return
# resposta a ser esperada pelo server
client.nextRequest += 1
print "\n"
log(logging.INFO, colors.INFO + " Expected Message!" + colors.END + " SEQ CODE: " + str(client.nextRequest-1))
log(logging.INFO, colors.INFO + " Secure Request " + colors.WARNING + " username: " + colors.END+ client.uuid +colors.WARNING + colors.END)
content = base64.b64decode(data['content'])
salt = base64.b64decode(data['salt'])
HMAC_msg = base64.b64decode(data['HMAC'])
# Compute Derivated key
kdf_key = secure.kdf(str(client.sharedKey), salt, 32, 4096, lambda p, s: HMAC.new(p, s, SHA512).digest())
# Decipher Request
dataFinal = secure.D_AES(message= content, symKey= kdf_key)
req = json.loads(dataFinal)
# Create HMAC
HMAC_new = (HMAC.new(key=kdf_key, msg=dataFinal, digestmod=SHA512)).hexdigest() # Criar novo HMAC com o texto recebido e comparar integridade
# Checking integrity
if (HMAC_new == HMAC_msg) :
log(logging.INFO, colors.VALID + " Integrity Checked Sucessfully" + colors.END)
else:
log(logging.INFO, colors.ERROR + " Message forged! Sorry! Aborting ..." + colors.END)
return
# Handling Request
if req['type'] in dataFinal:
self.messageTypes[req['type']](req, client, msgControl)
return
def processCreate(self, data, client, msgControl):
log(logging.INFO, colors.INFO + " Creating New Account" + colors.END)
if 'uuid' not in data.keys():
log(logging.ERROR, "No \"uuid\" field in \"create\" message: " +
json.dumps(data))
client.sendResult({"error": "wrong message format"}, msgControl)
return
uuid = data['uuid'] # username
publicKey = data['Client_pubKey'] # user publicKey
if self.registry.userExists(uuid):
log(logging.ERROR, colors.ERROR + "User already exists" + colors.END)
client.sendResult({"error": " User already exists"}, msgControl)
return
if self.registry.userDirExists(uuid):
log(logging.ERROR, colors.ERROR + "User already exists" + colors.END)
client.sendResult({"error": " User already exists"}, msgControl)
return
user_cert = data['auth_certificate'] # authentication certificate
# validade certificado
if not cc.retrieveStatus(cert= user_cert, mode="AUTHENTICATION"):
log(logging.ERROR, colors.ERROR + "Your Certificate is revoked!" + colors.END)
return
log(logging.ERROR, colors.VALID + "Certificate Not Revoked" + colors.END)
# registar envio
timestamp = str(int(time.time() * 1000))
# validade assinatura
if not cc.signatureValidity(cert=user_cert, timestamp=timestamp):
log(logging.ERROR, colors.ERROR + "Your Signature isn't valid!" + colors.END)
return
log(logging.ERROR, colors.VALID + "Valid Signature. Current Date: " + str(time.ctime(int(timestamp) / 1000)) + colors.END)
# Adiciona novo user
me = self.registry.addUser(data)
log(logging.INFO, colors.INFO + " User Added Sucessfully" + colors.END)
client.id = me.id
client.sendResult({"resultCreate": me.id}, msgControl)
def processAuthentication(self, data, client, msgControl):
""" Processo de Autenticacao
"""
phase = int(data['phase'])
if phase == 1:
log(logging.INFO, colors.INFO + " Authenticating Credentials" + colors.END)
client.uuid = base64.b64decode(data['uuid']) # username = uuid
client.id = self.registry.getId(base64.b64decode(data['uuid'])) # uuid -> traducao para ID
client.modulus_prime = data['modulus_prime']
client.primitive_root = data['primitive_root']
client.client_pubNum = int(data['Client_pubNum'])
client.svPrivNum = privateNumber()
passphrase = data['passphrase']
# check username
if not self.registry.userDirExists(client.uuid):
log(logging.ERROR, colors.ERROR +"Invalid Username" + colors.END)
client.sendResult({"error": " Invalid Username!"}, msgControl)
return
# check password
if not self.registry.checkPassphrase(client.uuid, passphrase):
log(logging.ERROR, colors.ERROR +"Authentication failed! Wrong passphrase!"+colors.END)
client.sendResult({"error": " Wrong password!"}, msgControl)
return
log(logging.DEBUG,colors.VALID + "Correct Passphrase" + colors.END)
# Compute Shared Key
client.svPubNum = pubNum(client.primitive_root, client.svPrivNum, client.modulus_prime)
client.sendResult({"resultDH":{
"Server_pubNum" : client.svPubNum,
"phase" : phase+1
},
"server_pubkey" : self.pubKey,
"id": client.id,
"name": self.registry.users[client.id].description["name"]
}, msgControl)
if phase == 3:
log(logging.INFO, colors.INFO + " Authenticating Challenge" + colors.END)
# passphrase
signed_passphrase = base64.b64decode(data['signed_passphrase'])
passphrase = data['passphrase']
# double check password/passphrase
if not self.registry.checkPassphrase(client.uuid, passphrase):
log(logging.ERROR, colors.ERROR +"Authentication failed! Wrong passphrase!"+colors.END)
client.sendResult({"error": " Wrong password!"}, msgControl)
return
# signature validity
timestamp= str(int(time.time() * 1000))
user_cert = self.registry.getUserCertificate(uuid= client.uuid ,mode='AUTHENTICATION')
if user_cert != None:
if not cc.verify(cert=user_cert, data= base64.b64decode(passphrase), sign= signed_passphrase) and cc.signatureValidity(cert=user_cert, timestamp=timestamp):
# Not valid
log(logging.ERROR, colors.ERROR +"Invalid Signature!"+colors.END)
client.sendResult({"error": " Invalid Signature!"}, msgControl)
return
# Valid Signature
log(logging.DEBUG,colors.VALID + "Valid Signature" + colors.END)
# Valid Challende
log(logging.DEBUG,colors.VALID + "Challenge Validated" + colors.END)
# shared key
new_sharedKey = int(pow(client.client_pubNum, client.svPrivNum, client.modulus_prime))
client.sharedKey = new_sharedKey
log(logging.DEBUG,colors.INFO + "Session Estabilished" + colors.END)
# connected
log(logging.DEBUG,colors.INFO + "User authenticated" + colors.END)
client.sendResult({"resultDH":{
"phase" : phase+1
}
}, msgControl)
# Change Client Status
client.status = CONNECTED
def processList(self, data, client, msgControl):
log(logging.INFO, colors.INFO + " Listing Users" + colors.END)
user = 0
userStr = "all users"
if 'id' in data.keys():
user = int(data['id'])
userStr = "user%d" % user
log(logging.DEBUG,colors.INFO + "Looking for all connected users" + colors.END)
userList = self.registry.listUsers(user)
client.sendResult({"resultList": userList}, msgControl)
def processSync(self, data, client, msgControl):
log(logging.INFO, colors.INFO + " Synchronizing User's related data" + colors.END)
user = 0
userStr = "all users"
if 'id' in data.keys():
user = int(data['id'])
userStr = "user%d" % user
userList = self.registry.listUsers(user)
client.sendResult({"resultSync": userList}, msgControl)
def processNew(self, data, client, msgControl):
log(logging.DEBUG, "%s" % json.dumps(data))
user = -1
if 'id' in data.keys():
user = int(data['id'])
if user < 0:
log(logging.ERROR,
"No valid \"id\" field in \"new\" message: " + json.dumps(data))
client.sendResult({"error": "wrong message format"}, msgControl)
return
client.sendResult(
{"resultNew": self.registry.userNewMessages(user)}, msgControl)
def processAll(self, data, client, msgControl):
log(logging.INFO, colors.INFO + " Message Box" + colors.END)
if not client.uuid == data['uuid']:
log(logging.INFO, colors.ERROR + " Wrong Message Box Owner!" + colors.END)
return
log(logging.INFO, colors.INFO + " Correct Message Box Owner!" + colors.END)
user = -1
# uuid -> traducao para ID
if 'uuid' in data.keys():
user = self.registry.getId((data['uuid']))
if user < 0:
log(logging.ERROR,
"No valid \"id\" field in \"new\" message: " + json.dumps(data))
client.sendResult({"error": "wrong message format"}, msgControl)
return
client.sendResult({"resultAll": [self.registry.userAllMessages(user), self.registry.userSentMessages(user)]}, msgControl)
def processSend(self, data, client, msgControl):
log(logging.INFO, colors.INFO + "Sending Message" + colors.END)
if not set(data.keys()).issuperset(set({'src', 'dst', 'msg', 'msg'})):
log(logging.ERROR,
"Badly formated \"send\" message: " + json.dumps(data))
client.sendResult({"error": "wrong message format"}, msgControl)
srcId = self.registry.getId((data['src'])) # uuid -> traducao para ID
dstId = self.registry.getId((data['dst'])) # uuid -> traducao para ID
msg = data['msg']
copy = data['copy']
if not self.registry.userExists(srcId):
log(logging.ERROR,
"Unknown source id for \"send\" message: " + json.dumps(data))
client.sendResult({"error": "wrong parameters"}, msgControl)
return
if not self.registry.userExists(dstId):
log(logging.ERROR,
"Unknown destination id for \"send\" message: " + json.dumps(data))
client.sendResult({"error": "wrong parameters"}, msgControl)
return
# Save message and copy
response = self.registry.sendMessage(srcId, dstId, msg, copy)
log(logging.INFO, colors.VALID + "Message Sent Sucessfully" + colors.END)
client.sendResult({"resultSend": response}, msgControl)
def processRecv(self, data, client, msgControl):
log(logging.INFO, colors.INFO + "Receiving Message" + colors.END)
if not set({'uuid', 'msg'}).issubset(set(data.keys())):
log(logging.ERROR, "Badly formated \"recv\" message: " +
json.dumps(data))
client.sendResult({"error": "wrong message format"}, msgControl)
fromId = self.registry.getId((base64.b64decode(data['uuid']))) # uuid -> traducao para ID
msg = str(base64.b64decode(data['msg']))
if not self.registry.userExists(fromId):
log(logging.ERROR,
"Unknown source id for \"recv\" message: " + json.dumps(data))
client.sendResult({"error": "wrong parameters"}, msgControl)
return
if not self.registry.messageExists(fromId, msg):
log(logging.ERROR,
"Unknown source msg for \"recv\" message: " + json.dumps(data))
client.sendResult({"error": "wrong parameters"}, msgControl)
return
# Read message
response = self.registry.recvMessage(fromId, msg)
client.sendResult({"resultRecv": response}, msgControl)
def processReceipt(self, data, client, msgControl):
log(logging.INFO, colors.INFO + "New Receipt" + colors.END)
if not set({'id', 'msg', 'receipt'}).issubset(set(data.keys())):
log(logging.ERROR, "Badly formated \"receipt\" message: " +
json.dumps(data))
client.sendResult({"error": "wrong request format"}, msgControl)
fromId = self.registry.getId(base64.b64decode((data["id"])))
msg = str(base64.b64decode(data['msg']))
receipt = data['receipt']
if not self.registry.messageWasRed(str(fromId), msg):
log(logging.ERROR, "Unknown, or not yet red, message for \"receipt\" request " + json.dumps(data))
client.sendResult({"error": "wrong parameters"}, msgControl)
return
log(logging.INFO, colors.INFO + " Receipt Stored" + colors.END)
self.registry.storeReceipt(fromId, msg, receipt)
def processStatus(self, data, client, msgControl):
log(logging.INFO, colors.INFO + " Message Status" + colors.END)
if not set({'id', 'msg'}).issubset(set(data.keys())):
log(logging.ERROR, "Badly formated \"status\" message: " +
json.dumps(data))
client.sendResult({"error": "wrong message format"}, msgControl)
fromId = self.registry.getId((base64.b64decode(data['id'])))
msg = base64.b64decode(data["msg"])
if(not self.registry.copyExists(fromId, msg)):
log(logging.ERROR, "Unknown message for \"status\" request: " + json.dumps(data))
client.sendResult({"error", "wrong parameters"}, msgControl)
return
response = self.registry.getReceipts(fromId, msg)
client.sendResult({"resultStatus": response, "id": msg}, msgControl)