-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
1131 lines (950 loc) · 47.7 KB
/
client.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import select, socket, sys, json, getpass, time, base64, os, time, logging
from os import listdir
from os.path import isfile, join
from Crypto.Hash import SHA512, HMAC, SHA256
from Crypto.Random import random
from Crypto.PublicKey import RSA
from secure import Secure
from citizencard import citizencard
from random import randint
secure = Secure() # secure functions
cc = citizencard()
HOST = "localhost" # All available interfaces
PORT = 8080 # The server port
TERMINATOR = "\r\n"
MAX_BUFSIZE = 64 * 1024
# Connection status
NOT_CONNECTED = 10000
CONNECTING = 20000
CONNECTED = 30000
# Mathematics for session key / diffie helman
PRIMITIVE_ROOT = 5
MODULUS_PRIME = 0xeb8d2e0bfda29137c04f5a748e88681e87038d2438f1ae9a593f620381e58b47656bf5386f7880da383788a35d3b4a6991d3634b149b3875e0dccff21250dccc0bf865a5b262f204b04e38b2385c7f4fb4e2058f73a8f65252e556b667b1570465b2f6d1beeab215b05cd0e28b9277f3f48c01b1619b30147fcfc87b5b6903e70078babb45c2ee6a6bd4099ab87b01ba09a38c36279b46309ef0df5e45e15df9ba5cb296baa535c60bb0065669fd8078269eb759416d9b27229f9cb6e5f60f7d8756f6f621ad519745f914e81a7c8d09b3c7a764863dd5d5f2bcab5ef283aa3781c985d07f2b1aafb2e7747b3217dbbfea2e91484c31a00e22467c0c7f9d40f73d392594c516b302aa7c1aa6ca5a0b346cc6bfc1cd201dfe78aabf717f6c69f30a896567b07090e352e87fd698128da0594916d27203e22b7bb1f7f860842fd0aee2e532a077629451ef86163fdf567048266050a473d4db27e85a33bc985b16569afddaa9a94a5b9155b32b78c84b261ce7acf7d8d0ef23d4e1d028104aff6a77cab79ecdf7dd19468f67d3cb9b86835cce1a87dbf4b2d3100a9bd7a9e251272bf4e2fed2c2f7535e556b8cc1fc6fcfc1a2ca188c02ea9298bb4a7f12afd4164ad9211f7935f51be3d9d932e835a1fd322e7db75ba587021f8c730d7f021905e89a0ddb80bf8ea53b8f1603cf08c734aadfe7f9184e0de9e91651c3d88deb68fd1bc0188e479747caab9a157ef6ec68295a1bfb6391973364987cda6c7817dfee2ab9d4e0eaefb29154f23eafedcab06d67fbcc5d1788a20315c50f9c6471dbb45419b07ddec0d507c16a0b7e2d79290d3115edcdc2996897015dfa430389a1d63533e52aa6309c76e7069e0a99af65702036e7829bc8e86ad3e23983debf72c82d8e3a2e9d767cccfb2abed6b0b0c9f217bb496ea816ea3c32111f60916d91f8a97cfa38b163ca1261733cd98cb2ff77a7ee9290bda74be8dc206489d06abca4e5ae82ae4923fa43b451fa419da06d74f15e4efc4852bf5edf37e581edeaaefd28a8b3c672bb76068439635adecebaf8311d4018fe8e62892f784d7a44747178c4cb540c58e5e2a660a3f02c873d12b43f0643d3794d8b310fe9fa6d798e0724d38c85c9e4d5c8c9ba645f3411dd4645ef1ef1dad9ba60325b12def1bd706d11386045e450fee2a60c88cf6387dea0521acc4d869fb146a47ef4e34480d30f84ffa0e0e0a4a4c7f1b0a8e642223e8bec4d1c8effd98ba235dc5c5f7e296ecd7476595ef17371a1aec3a38c3e7f7e08e7b5e7c927f5843062f753e5ee85f7e64164dd0ccb7261d4ca3a35058ca88f87275a292e96100005c025742f85be7a2598406b9c792f2ba2a496f8074d899821110effb184e3c679330b182a8c14ba1699f3761168d64e838829c0250c6be87bc8dc2b29954bf6cb450ba7bed793cf97
pubNum = lambda x,y,z: int(pow(x,y,z))
def privateNumber():
secret = random.getrandbits(256)
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'
# Client class
class Client:
def __str__(self):
""" Converts object into string.
"""
return "Client(id=%r addr:%s)" % (self.id, str(self.addr))
# Inicializacao
def __init__(self, host, port):
self.ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.ss.connect((host, port))
logging.info(colors.INFO+"Client listening on"+colors.END+"%s", self.ss.getsockname())
self.inputs = [] # Sockets from which we expect to read
# Login stuff
self.uuid = None
self.passphrase = None
self.id = None
self.name = None
self.certificate = None
self.serialnumber = None
self.myDirPath = None
# Buffers
self.bufin = ""
self.bufout = ""
self.mail = {} # inbox
self.outmail= {} # outbox
self.Users = [] # user id, uuid, pubkeys
# Key Pairs
self.pubKey, self.privKey = None, None
# Server
self.serverPubKey = None
self.serverPubNum = None
# Connection
self.pubNum = None
self.privNum = None
self.modulus_prime = MODULUS_PRIME
self.primitive_root = PRIMITIVE_ROOT
self.state = NOT_CONNECTED
self.sharedKey = None
# Flags auxiliares
self.requestBuffer = []
self.nextRequest = 0
self.to_receipt = False
self.requests = 0
self.requestsNumber = randint(10, 20)
#################################################################################################################################################################################
################################################################################### Aux Functions ###############################################################################
def getKeyDir(self, timestamp, mypath):
# searches key in dirs by timestamp
directories = [f for f in listdir(mypath) if os.path.isdir(mypath+"/"+f)]
for d in directories:
period = d.split("_")
not_before = int(period[0])
if period[1] != "":
not_after = int(period[1])
if int(timestamp) >= not_before and int(timestamp) < not_after:
return mypath+"/"+d
else:
not_after = str(period[1])
if int(timestamp) >= not_before:
return mypath+"/"+d
def putKeyDir(self, timestamp, mypath=None):
# organize and creates dirs by timestamp,
# dirname = notbefore_notafter for past keys
# dirname = notbefore_ for last key in use
# mypath = client keys path
directories = [f for f in listdir(mypath) if os.path.isdir(mypath+"/"+f)]
if len(directories) > 0:
for d in directories:
# parsing dir name
period = d.split("_")
if period[1] == "": #found dir to rename and mkdir new one
if (int(timestamp) > int(period[0])):
dir_path = mypath+"/"+d
# changes
os.rename(dir_path, dir_path+str(timestamp))
os.mkdir(mypath+"/"+str(timestamp)+"_")
return mypath+"/"+str(timestamp)+"_"
else:
os.mkdir(mypath+"/"+str(timestamp)+"_")
return mypath+"/"+str(timestamp)+"_"
def getKeyByValue(self, value):
for k, v in self.mail.items():
if str(value) == v or isinstance(v, list) and str(value) in v:
return k
return None
def loadKeys(self, timestamp):
# processo de escolha correcta do par de chaves
keypath = self.getKeyDir(timestamp=timestamp, mypath= self.myDirPath)
# user path to keys
path = keypath + "/key.pem"
try:
with open(path, "rb") as f:
key = RSA.importKey(f.read(), self.passphrase) # import with passphrase
self.pubKey, self.privKey = key.publickey().exportKey(format='PEM'),key.exportKey(format='PEM', passphrase=self.passphrase)
#print colors.INFO+ "Keys Sucessfully Loaded!" + colors.END
return True
except:
#print colors.ERROR+ "Error! Wrong Passphrase! Aborting..." + colors.END
return False
return False
def saveKeys(self):
# save do par de chaves, utilizado no refresh
self.pubKey, self.privKey = secure.get_keys(self.passphrase)
try:
os.mkdir(self.myDirPath)
except:
pass
# actual time
timestamp= str(int(time.time() * 1000))
keypath = self.putKeyDir(timestamp= timestamp, mypath= self.myDirPath)
# into file, client dir
path = keypath + "/key.pem"
data = self.privKey # PEM already
with open(path, "wb") as f:
f.write(data)
return True
return False
def checkUser(self, user):
for x in self.Users:
y = dict(x)
if y['description']['uuid'] == str(user):
return True
return False
def getUUID(self, idd):
"""
Translation between id to uuid,
give an id, returns respective uuid
"""
for x in self.Users:
y = dict(x)
if y['id'] == int(idd):
return str(y['description']['uuid'])
def getID(self, idd):
"""
Translation between uuid to id,
give an id, returns respective uuid
"""
for x in self.Users:
y = dict(x)
if y['description']['uuid'] == str(idd):
return str(y['id'])
def getCert(self, username):
"""
Translation between uuid to id,
give an id, returns respective uuid
"""
for x in self.Users:
y = dict(x)
if y['description']['uuid'] == str(username):
return str(y['description']['auth_certificate'])
def retrieveCCData(self):
"""
Obter dados dos smartcard, certificados, nova sessao, nome, serialNumber e validacao do estado
"""
try:
self.auth_certificate, self.session = cc.certificate(mode="AUTHENTICATION")
self.sign_certificate, self.session = cc.certificate(mode="SIGNATURE")
self.name, self.serialnumber = cc.getUserDetails(self.auth_certificate)
print colors.INFO + "Citizen Card loaded!" + colors.END
if not (cc.retrieveStatus(cert= self.auth_certificate, mode="AUTHENTICATION") or cc.retrieveStatus(cert= self.sign_certificate, mode="SIGNATURE")):
print colors.ERROR + "Citizen Card revoked!" + colors.END
return False
print colors.INFO + "Citizen Card not revoked!" + colors.END
time.sleep(1)
return True
except:
print colors.ERROR + "Error while loading Citizen Card!" + colors.END
return False
return False
def hybrid(self, operation, data, data_key=None, timestamp=None):
"""
Function used to cipher/decipher requests, generates symetric
key and ciphers with pubKey of dst or deciphers with my privKey
"""
if operation == 'cipher':
#update to atual key
actual_timestamp= str(int(time.time() * 1000))
self.loadKeys(actual_timestamp)
symKey = secure.symmetricKey(256)
instance = RSA.importKey(data_key)
a = secure.AES(message=data, key=symKey)
b = secure.rsaCipher(message=symKey, key=instance)
return a, b # data ciphered with symKey, symKey ciphered with server pubKey
if operation == 'decipher':
self.loadKeys(timestamp)
instance = RSA.importKey(self.privKey, self.passphrase)
b = secure.rsaDecipher(message=data_key, key=instance)
a = secure.D_AES(symKey=b, message=data)
return a
#################################################################################################################################################################################
################################################################################ Client Messages ################################################################################
# Refrescamento das chaves
def refreshKeys(self):
#save old key pair and generates new one
if self.saveKeys():
self.loadKeys(timestamp= str(int(time.time() * 1000)))
# nova sessao
self.primitive_root = PRIMITIVE_ROOT
self.modulus_prime = MODULUS_PRIME
self.privNum = privateNumber()
self.pubNum = pubNum(self.primitive_root, self.privNum, self.modulus_prime)
data = {
"type" : "refresh",
"publickey" : base64.b64encode(self.pubKey),
"primitive_root" : self.primitive_root,
"modulus_prime" : self.modulus_prime,
"Client_pubNum" : int(self.pubNum),
}
print colors.INFO + "Refreshing Keys..." + colors.END
self.send(data)
# Start DiffieHelman key exchange / Session
def startDH(self, phase):
self.primitive_root = PRIMITIVE_ROOT
self.modulus_prime = MODULUS_PRIME
self.privNum = privateNumber()
self.pubNum = pubNum(self.primitive_root, self.privNum, self.modulus_prime)
passphrase = secure.SHA256(self.passphrase)
data = {
"type" : "dh",
"phase": int(phase),
"uuid" : base64.b64encode(self.uuid),
"passphrase": base64.b64encode(passphrase),
"primitive_root" : self.primitive_root,
"modulus_prime" : self.modulus_prime,
"Client_pubNum" : int(self.pubNum),
}
self.send(data)
# Message status
def status(self, msgNr):
try:
msgid = self.outmail[msgNr]
except:
print colors.ERROR + colors.BOLD + "Wrong Message ID! Try again" + colors.END
return
data = {
"type" : "status",
"id" : base64.b64encode(self.uuid),
"msg" : base64.b64encode(msgid),
}
self.send(data)
# Message receipt
def receipt(self, msgNr, receipt):
data = {
"type" : "receipt",
"id" : base64.b64encode(self.uuid),
"msg" : base64.b64encode(self.mail[int(msgNr)]),
"receipt": receipt,
}
#print colors.INFO + "Receipt Sent Sucessfully!" + colors.END
self.send(data)
# Create User Message Box
def createUserMsgBox(self):
if self.retrieveCCData():
try:
# dir
os.makedirs(os.getcwd() + '/clients/')
except:
pass
#user details
os.system('clear')
print " -----------------------"
print colors.TITLE + colors.BOLD + " Register" + colors.END
print " -----------------------"
self.uuid = str(raw_input(colors.TITLE + colors.INFO + " Username: "+ colors.END))
self.passphrase = str(getpass.getpass(colors.TITLE + colors.INFO + ' Password: '+ colors.END))
#update path name
self.myDirPath = "clients/" + str(self.uuid)
self.saveKeys()
# build dict
data = {
"type": "create",
"uuid": self.uuid,
"name": self.name,
"Client_pubKey" : self.pubKey,
"auth_certificate" : self.auth_certificate,
"sign_certificate" : self.sign_certificate,
"serialnumber" : self.serialnumber,
"passphrase": base64.b64encode(secure.SHA256(self.passphrase))
}
self.send(data)
# Read a message
def recvMessage(self, msgNr):
try:
msgid = self.mail[int(msgNr)]
if msgid in self.newMails:
self.to_receipt = True
else:
self.to_receipt = False
except:
print colors.ERROR + colors.BOLD + "Wrong Message ID! Try again" + colors.END
return
data = {
"type": "recv",
"uuid" : base64.b64encode(self.uuid),
"msg" : base64.b64encode(msgid),
}
self.send(data)
# List all messages in boxes, sent and recvd
def listAllMessages(self):
data = {
"type": "all",
"uuid": self.uuid,
}
self.send(data)
# List users with details
def listUserMsgBox(self):
data = {
"type": "list",
}
self.send(data)
# sync
def sync(self):
data = {
"type": "sync",
}
self.send(data)
# Send a message to another user/client
def sendMessage(self, dst, txt):
sending = ""
for t in txt:
sending += (str(t))
sending += " "
dstId = int(self.getID(dst)) - 1 # dict comeca em 0
# respectiva public key
dstPubKey = self.Users[dstId]['description']['Client_pubKey']
#print self.Users[dstId]['description']
# cifra hibrida destino
messageCiphered, symKeyCiphered = self.hybrid('cipher', sending, dstPubKey)
# cifra hibrida para mim
messageCiphered2, symKeyCiphered2 = self.hybrid('cipher', sending, self.pubKey)
# registar envio
timestamp = str(int(time.time() * 1000))
# Verificar estado do certificado
#self.auth_certificate, self.session = cc.certificate(mode="AUTHENTICATION")
if not cc.retrieveStatus(cert= self.auth_certificate, mode="AUTHENTICATION"):
print "Your Certificate is revoked! Sorry, aborting ..."
return
if not cc.signatureValidity(cert=self.auth_certificate, timestamp=timestamp):
print "Your Signature isn't valid!"
return
# assinar
signature, cleartext = cc.sign(data=messageCiphered, session=self.session, mode="AUTHENTICATION")
# signed stuff
signed = json.dumps({
"signature": base64.b64encode(signature),
"cleartext" : base64.b64encode(cleartext),
})
# encapsulamento destino
dstMessage = json.dumps({
"messageCiphered": base64.b64encode(messageCiphered),
"symKeyCiphered" : base64.b64encode(symKeyCiphered),
"timestamp": base64.b64encode(timestamp),
"signature": base64.b64encode(signed),
})
# encapsulamento para mim
srcMessage = json.dumps({
"messageCiphered2": base64.b64encode(messageCiphered2),
"symKeyCiphered2" : base64.b64encode(symKeyCiphered2),
"timestamp": base64.b64encode(timestamp),
})
data = {
"type": "send",
"src": self.uuid,
"dst": dst,
"msg": dstMessage,
"copy": srcMessage, # para mim, receipt
}
self.send(data)
##################################################################################################################################################################################
######################################################################## Funcoes Base do Cliente #################################################################################
def parseReqs(self, data):
"""Parse a chunk of data from this client.
Return any complete requests in a list.
Leave incomplete requests in the buffer.
This is called whenever data is available from client socket."""
if len(self.bufin) + len(data) > MAX_BUFSIZE:
self.bufin = ""
self.bufin += data
reqs = self.bufin.split('\n\n')
self.bufin = reqs[-1]
return reqs[:-1]
def handleRequest(self, request):
"""
Faz o devido handle dos requests do servidor,
tratando dos dados enviados e processando
de forma logica
"""
self.inbox=[]
self.newMails=[]
self.mailBox=[]
self.outbox=[]
try:
try:
req = json.loads(request)
except:
return
if not isinstance(req, dict):
return
if 'error' in req:
# error enviado pelo servidor
print colors.ERROR+req['error']+colors.END
return
if 'resultSend' in req:
self.requests += 1
# mensagem enviada correctamente
print colors.INFO + "Message Sent Sucessfully!" + colors.END
return
if 'resultRefresh' in req:
self.requests = 0
# connect to server, calculate shared/session key
self.serverPubNum = int(req['resultRefresh']['Server_pubNum'])
self.serverPubKey = req['server_pubkey']
self.sharedKey = int(pow(self.serverPubNum,self.privNum, self.modulus_prime))
print colors.INFO + "Keys Updated" + colors.END
return
if 'resultAll' in req:
self.requests += 1
# Parsing e organizacao da MessageBox
i=0
os.system('clear')
# Parsing messages
for x in req['resultAll'][0]:
if x[0] == '_':
if x not in self.inbox:
self.inbox.append(x)
else:
if x not in self.newMails:
self.newMails.append(x)
for y in req['resultAll'][1]:
if y not in self.outbox:
self.outbox.append(y)
# ordered mail, new messages first
self.mailBox = self.newMails + self.inbox
############################################ GUID ############################################
print colors.VALID + colors.BOLD + " Mensagens (Inbox/Outbox): \n" + colors.END
print colors.WARNING + str(len(self.mailBox)) + " Received Messages: " + colors.END
if len(self.mailBox) == 0:
print "You didnt received any message yet.\n"
for mail in self.mailBox:
if mail[0] == '_':
i = i + 1
aux = mail.split('_')
print str(i) + "- Message " + str(aux[2]) + " from " + self.getUUID(str(aux[1]))
else:
i = i + 1
aux = mail.split('_')
print str(i) + "- Message " + str(aux[1]) + " from " + self.getUUID(str(aux[0])) + colors.ERROR +" (NEW!)"+colors.END
print "\n"
print colors.WARNING + str(len(self.outbox)) + " Sent Messages: " + colors.END
if len(self.outbox) == 0:
print "You didnt send any message yet.\n"
i = 0
for mail in self.outbox:
aux = mail.split('_')
i = i + 1
print str(i) +"- Message " + str(aux[1]) + " sent to user " + self.getUUID(str(aux[0]))
print "\n"
print "\n"
print " ------------------------------------------------"
print colors.TITLE + colors.BOLD + " Commands: " + colors.END
print colors.WARNING +" (/send <user> <text>)" + colors.END + " Send a Message"
print colors.WARNING +" (/recv <msg_number>)" + colors.END + " Read message"
print colors.WARNING +" (/status <msg_number>)" + colors.END + " Check Receipt Status"
print colors.WARNING +" (<) " + colors.END + " Main Menu"
print " ------------------------------------------------"
##############################################################################################
# inbox, outbox, sync
self.mail = dict(zip(range(1,len(self.mailBox)+1), self.mailBox))
self.outmail = dict(zip(range(1,len(self.outbox)+1), self.outbox))
return
if 'resultStatus' in req:
self.requests += 1
os.system('clear')
msg = req['resultStatus']['msg']
msg = json.loads(msg)
# parsing arguments to decipher message content, real text
messageCiphered2 = base64.b64decode(msg['messageCiphered2'])
symKeyCiphered2 = base64.b64decode(msg['symKeyCiphered2'])
timestamp_mine = base64.b64decode(msg['timestamp'])
# parse signed receipt, se existir, ou seja, se ja foi lida a mensagem em principio
try:
receiptDict = json.loads(req['resultStatus']['receipts'][0]['receipt'])
receiptSigned = base64.b64decode(receiptDict['receiptSigned'])
receiptCleartext = base64.b64decode(receiptDict['receiptCleartext'])
message = base64.b64decode(receiptDict['message'])
# source username, certificate
source_rec = self.getUUID(req['resultStatus']['receipts'][0]['id'])
source_cert = self.getCert(username=source_rec)
# timestamp
timestamp = req['resultStatus']['receipts'][0]['date']
msg = self.hybrid(operation='decipher', data=str(messageCiphered2), data_key=str(symKeyCiphered2), timestamp=str(timestamp))
except:
# decipher msg
msg = self.hybrid(operation='decipher', data=str(messageCiphered2), data_key=str(symKeyCiphered2), timestamp = str(timestamp_mine))
pass
#sent to..
source = self.getUUID(req['id'][0])
############################################ GUID ############################################
print colors.TITLE + colors.BOLD + " Receipt Status " + colors.END
if req['resultStatus']['receipts'] != []: # mensagem lida
# messagem foi lida
print colors.VALID + colors.BOLD + "Sent to: " + colors.END + str(source)
print colors.WARNING + colors.BOLD + "Your Message: " + colors.END
print str(msg)
print "\n"
# Verificar assinatura/certificado, e validade da assinatura
if cc.verify(cert=source_cert, data= message, sign= receiptSigned) and cc.signatureValidity(cert=source_cert, timestamp=timestamp):
# validated
print colors.VALID + colors.BOLD + "Signed and Verified! (Read at "+ str(time.ctime(int(timestamp) / 1000)) +")\n" + colors.END
print colors.WARNING + colors.BOLD + "Signature: " +colors.END
print str(receiptCleartext)
print "\n"
else:
# not validated
print colors.ERROR + colors.BOLD + "Unreliable Message! (Forging attempt at "+ str(time.ctime(int(timestamp) / 1000)) +")\n" + colors.END
else:
# mensagem ainda nao foi lida
print colors.VALID + colors.BOLD + "Sent to: " + colors.END + str(source)
print colors.WARNING + colors.BOLD + "Your Message: " + colors.END
print str(msg)
print "\n"
print colors.WARNING + colors.ERROR + "The message has not been read yet! " +colors.END
# commands
print "\n"
print " ------------------------------------------------"
print colors.TITLE + colors.BOLD + " Commands: " + colors.END
print colors.WARNING +" (/all) " + colors.END + "Return to Message Box"
print colors.WARNING +" (<) " + colors.END + "Main Menu"
print " ------------------------------------------------"
##############################################################################################
return
if 'resultDH' in req:
self.requests += 1
phase = int(req['resultDH']['phase'])
if phase == 2:
# conexao com o servidor, calcular shared/session key para estabelecer nova sessao
self.id = req['id']
self.name = req['name']
self.serverPubNum = int(req['resultDH']['Server_pubNum'])
self.serverPubKey = req['server_pubkey']
self.sharedKey = int(pow(self.serverPubNum,self.privNum, self.modulus_prime))
passphrase = secure.SHA256(self.passphrase)
try:
# Verificar estado do certificado
self.auth_certificate, self.session = cc.certificate(mode="AUTHENTICATION")
# Marcar tempo de leitura
timestamp = str(int(time.time() * 1000))
# Verificar estado do cc
if not cc.retrieveStatus(cert= self.auth_certificate, mode="AUTHENTICATION"):
print "Your Certificate is revoked! Sorry, aborting ..."
return
# Verificar validade da assinatura
if not cc.signatureValidity(cert=self.auth_certificate, timestamp=timestamp):
print "Your Signature isn't valid!"
return
# Assinar
#if cc.loginSession(self.session):
signed_passphrase, cleartext = cc.sign(data=passphrase, session=self.session, mode="AUTHENTICATION")
data = {
"type" : "dh",
"phase" : int(phase)+1,
"passphrase" : base64.b64encode(passphrase),
"signed_passphrase" : base64.b64encode(signed_passphrase),
}
self.send(data)
except:
return
if phase == 4:
# load keys and data registered on server(id, name), passphrase is checked
if self.loadKeys(timestamp= str(int(time.time() * 1000))):
# state changed to connected
self.state = CONNECTED
print colors.INFO+" Sucessfully Connected!"+colors.END
# synchronizing users details
self.sync()
time.sleep(1)
os.system('clear')
self.show_menu()
else:
# connection ERROR, session failed
# passphrase errada probably (loadKeys), double check servidor-cliente
self.state = NOT_CONNECTED
print colors.ERROR+" Connection Denied!"+colors.END
return
if 'resultRecv' in req:
self.requests += 1
os.system('clear')
source = req['resultRecv'][0]
msg = req['resultRecv'][1]
msg = json.loads(msg)
# Parsing dos args para decifrar mensagem
# hybrid
messageCiphered = base64.b64decode(msg['messageCiphered'])
symKeyCiphered = base64.b64decode(msg['symKeyCiphered'])
# timestamp
sent_timestamp = base64.b64decode(msg['timestamp'])
# signature
signature_dict = json.loads(base64.b64decode(msg['signature']))
signature = base64.b64decode(signature_dict['signature'])
sign_cleartext = base64.b64decode(signature_dict['cleartext'])
# id mensagem
msg_nr = str(req['resultRecv'][2])
try:
# decipher msg
msg = self.hybrid(operation='decipher', data=str(messageCiphered), data_key=str(symKeyCiphered), timestamp=str(sent_timestamp))
if self.to_receipt: # mandar receipt se for primeira leitura
# Marcar tempo de leitura
receipt_timestamp = str(int(time.time() * 1000))
# Verificar estado do cc
if not cc.retrieveStatus(cert= self.auth_certificate, mode="AUTHENTICATION"):
print "Your Certificate is revoked! Sorry, aborting ..."
return
# Verificar validade da assinatura
if not cc.signatureValidity(cert=self.auth_certificate, timestamp=receipt_timestamp):
print "Your Signature isn't valid!"
return
# Assinar
try:
receipt_signature, receipt_cleartext = cc.sign(data=msg, session=self.session, mode="AUTHENTICATION")
except:
print colors.ERROR + colors.BOLD + "You ain't the owner. Aborting ...\n" + colors.END
return
# receipt composto por assinatura, assinatura.toChar, mensagem real (nao necessario)
receipt = json.dumps({
"receiptSigned": base64.b64encode(receipt_signature),
"receiptCleartext": base64.b64encode(receipt_cleartext),
"message" : base64.b64encode(msg),
})
dict_id = self.getKeyByValue(msg_nr) # indicates message in self.mail
# Envio do receipt
self.receipt(int(dict_id), receipt)
except:
print colors.ERROR + colors.BOLD + "You cannot read this message! Aborting... \n" + colors.END
return
# username and cert
source = self.getUUID(str(source))
source_cert = self.getCert(username=source)
############################################ GUID ############################################
print colors.TITLE + colors.BOLD + " Message "+ msg_nr[-1] + colors.END
print colors.VALID + colors.BOLD + "Source: " + colors.END + str(source)
print colors.WARNING + colors.BOLD + "Message: " +colors.END
print msg
print "\n"
# Verificar assinatura com o certificado da source e validade da assinatura
if cc.verify(cert=source_cert, data= messageCiphered, sign= signature) and cc.signatureValidity(cert=source_cert, timestamp=sent_timestamp):
print colors.VALID + colors.BOLD + "Signed and Verified!\n" + colors.END
else:
print colors.ERROR + colors.BOLD + "Unreliable Message!\n" + colors.END
print "\n"
print " ------------------------------------------------"
print colors.TITLE + colors.BOLD + " Commands: " + colors.END
print colors.WARNING +" (/all) " + colors.END + " Return to Message Box"
print colors.WARNING +" (<) " + colors.END + " Main Menu"
print " ------------------------------------------------"
##############################################################################################
return
if 'resultList' in req:
self.requests += 1
arrayAux = []
os.system('clear')
############################################ GUID ############################################
print colors.TITLE + colors.BOLD + " Available Users \n" + colors.END
for x in req['resultList']:
aux = {}
aux['id'] = x['id']
aux['description'] = x['description']
arrayAux.append(aux)
if (x['description']['uuid'] != (self.uuid)):
print colors.WARNING +' Username: ' +colors.END + str(x['description']['uuid']) + "\t\t\t" + colors.WARNING +'Nome: ' +colors.END+(x['description']['name']).encode('utf-8')
print "\n"
print " --------------------------------------"
print colors.TITLE + colors.BOLD + " Commands: " + colors.END
print colors.WARNING +" (<) " + colors.END + "Main Menu"
print " --------------------------------------"
############################################ GUID ############################################
self.Users = arrayAux
return
if 'resultSync' in req:
self.requests += 1
arrayAux = []
for x in req['resultSync']:
aux = {}
aux['id'] = x['id']
aux['description'] = x['description']
arrayAux.append(aux)
self.Users = arrayAux
return
if 'resultCreate' in req:
self.requests += 1
# Conta criada com sucesso
# guardar id da messagebox
self.id = req['resultCreate']
print colors.VALID + " You may connect now! (/connect)" + colors.END
return
if 'type' not in req:
return
except Exception, e:
logging.exception("Could not handle request")
def handleInput(self, input):
"""
Faz o handle do input(teclado)
e redireciona para a funcao correcta
de modo a fazer um pedido correcto ao servidor
"""
fields = input.split()
if fields[0] == '/list':
self.listUserMsgBox()
return
if fields[0] == '/create':
if self.id != None:
print "You already created at least one MessageBox"
return
self.createUserMsgBox()
return
if fields[0] == '/all':
self.listAllMessages()
return
if fields[0] == '/send':
usernameDst = str(fields[1])
if self.checkUser(usernameDst):
self.sendMessage(str(fields[1]), fields[2:])
return
print colors.ERROR + "Username not found! Try another one ..." + colors.END
return
if fields[0] == '/recv':
try:
self.recvMessage(int(fields[1]))
except:
print colors.ERROR + "Please insert <message_id>!" + colors.END
return
if fields[0] == 'r':
self.refreshKeys()
return
if fields[0] == '<':
os.system('clear')
self.show_menu()
return
if fields[0] == '/connect':
if self.state == NOT_CONNECTED:
os.system('clear')
print " -----------------------"
print colors.TITLE + colors.BOLD + " Log in" + colors.END
print " -----------------------"
self.uuid = str(raw_input(colors.TITLE + colors.INFO + " Username: "+ colors.END))
self.passphrase = str(getpass.getpass(colors.TITLE + colors.INFO + ' Password: '+ colors.END))
self.myDirPath = "clients/" + str(self.uuid)
#start connection
self.startDH(1)
else:
print " You are already Connected!"
return
return
if fields[0] == '/status':
try:
self.status(int(fields[1]))
except:
print colors.ERROR + "Please insert <message_id>!" + colors.END
return
return
else:
logging.error("Invalid input")
return
def processSecure(self, req):
"""
Decifrar com chave deriada de sessao, secure channel e verificacao de integridade
"""
req = json.loads(req)
salt = base64.b64decode(req['salt'])
kdf_key = secure.kdf(str(self.sharedKey), salt, 32, 4096, lambda p, s: HMAC.new(p, s, SHA512).digest())
content = req['content'] #mensagem
content_decoded = base64.b64decode(content)
msgControl = base64.b64decode(req['msgControl'])
if not msgControl == self.requestBuffer[self.nextRequest-1]:
print colors.ERROR + "This messages is not the answer for the previews request." + colors.END
return
# Read HMAC
HMAC_msg = base64.b64decode(req['HMAC'])
# Conteudo da mensagem
dataFinal = secure.D_AES(message= content_decoded, symKey= kdf_key)
# Creating new HMAC
# Criar novo HMAC com o texto recebido e comparar integridade
HMAC_new = (HMAC.new(key=kdf_key, msg=dataFinal, digestmod=SHA512)).hexdigest()
# Checking Integrity
if (HMAC_new == HMAC_msg) :
#print colors.INFO + "Integrity Checked Sucessfully" + colors.END
return dataFinal
else:
#print colors.ERROR + "Message forged! Sorry! Aborting ..." + colors.END
return
# Verificacao do tipo de mensagem e envio (socket.send)
def send(self, dict_):
if self.state == NOT_CONNECTED:
if dict_['type'] == 'dh' or dict_['type'] == 'create': # Connect e Create
try:
self.ss.send((json.dumps(dict_))+TERMINATOR)
except Exception:
pass
else:
print "Error! Not connected!"
if self.state == CONNECTED:
# Secure Messages with Session Key
if dict_['type'] == 'list' or dict_['type'] == 'send' \
or dict_['type'] == 'getMyId' or dict_['type'] == 'all' or dict_['type'] == 'new' \
or dict_['type'] == 'recv' or dict_['type'] == 'status' \
or dict_['type'] == 'receipt' or dict_['type'] == 'refresh' or dict_['type'] == 'sync':
try:
"""
Cifrar com chave deriada de sessao, secure channel, inclusao integridade (HMAC)
"""
# Pronto para encapsular
message = (json.dumps(dict_))
# Calcular nova chave derivada
# salt