-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmdaclient.py
More file actions
1296 lines (1073 loc) · 52.7 KB
/
mdaclient.py
File metadata and controls
1296 lines (1073 loc) · 52.7 KB
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
# -*- coding: utf-8 -*-
# MDA Network Project
# Ring decentralized P2P network for secure instance-messaging
# By Amr Abdelbari C&E Engineer, Qatar
# Begin in 14/9/2015 04:23 PM
# Changed from Python2.7 to Python3.7 on 10/5/2022 10:18 AM
# This file contains the NodeClient - GUI of the program
from datetime import datetime
from mdanetwork import mda, mdaconnection
from encryption import mda_encryption
import tkinter as tk
#import tkMessageBox
from tkinter import messagebox, filedialog, ttk
#import tkFileDialog
#import ttk
import threading
import socket
import subprocess
import time
import webbrowser
import sys
import os
import ast
import unicodedata
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_PSS
from Crypto.Hash import SHA512
# The AES key ( for large data )
from Crypto.Cipher import AES
from Crypto import Random
import json
import base64
import db_dht as db
# The GUI of the program (chat) using TK library
class mdachat(ttk.Frame, mda):
"""
The GUI of the chat program that works on the MDA Network.
"""
mda = mda()
connectionlist = {} # Tracking connections with other nodes (contact-ID : connection obj)
openwin = {} # Tracking chat windows with other nodes (contact-ID : open or not)
# Set Options
options = [['0', '0'] for _ in range(7)] # User custom options { [ state, *info ], .. }
options[6].append('0')
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
mda.__init__(self)
self.parent = parent
self.parent.configure(background='white')
self.initUI()
self.antispam = 0 # prevent user from broadcast and sending spam messages !!
# Get options
self.mycontactid, self.weight, opt = self.get_config()
if opt == 0:
pass
else:
self.options = opt
if self.options[1][0]:
self.checkarchive()
self.newidvar = tk.StringVar()
self.genkey = None
self.person = {} # Names of connected friends
# Execute the NodeServer from inside the Nodeclient !
cmd = "python mdaserver.py"
self.p = subprocess.Popen(cmd, shell=True)
# Crypto keys of the ( Node Server <---> Node Client Connection )
self.RSAKey = None
self.nodeserver_pup = None # for verifying the messages from Node server
self.AESKey = None
self.iv = None
if not self.p.pid:
time.sleep(10)
self.nodeclient()
thread = threading.Thread(target=self.rcvconnection)
thread.start()
#thread.join()
def nodeclient(self):
'''
Make a connection with the node server to exchange connections keys and other info
about the messages and contacts meta-data
:return: nothing
'''
#try:
# Generate the AES key and send a request to connect to the Node server
request = "Req4444"
self.AESKey = Random.new().read(32)
self.iv = Random.new().read(AES.block_size)
cipher = AES.new(self.AESKey, AES.MODE_CFB, self.iv)
realmsg = request
realmsg2 = realmsg.encode("utf8")
#print ("Node client side: ", realmsg2)
msg = self.iv + cipher.encrypt(realmsg2)
# Generate Client-side RSA key
go, self.RSAKey = mda_encryption.generateRSAkey()
host = socket.gethostbyname(socket.gethostname())# '127.0.0.1'
# %%%%%%%%%%%Change to test%%%%%%%%%%%%%%%%%%%
port = mda.PORT
#print(port)
# %%%%%%%%%%%Change to test%%%%%%%%%%%%%%%%%%%
# Make a new connection when open the program
self.ctrlsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# host = socket.gethostbyname(socket.gethostname())
self.ctrlsock.connect((host, port))
# Wait until Server-side send the first packet...
# Receive Server-side RSA public key (for sending msg to server and verify received ones)
rcstring = self.ctrlsock.recv(5000)
# Send Client-side RSA public key (server can send msg and verify received ones)
self.ctrlsock.send(go.encode())
# Decode the Server-side RSA public key
self.nodeserver_pup, buf = mda_encryption.receive_RSAkey(rcstring)
#print "Node client side: ", rcstring
rsakey = PKCS1_OAEP.new(self.nodeserver_pup)
# Signing the msg with SHA512 using Client-side RSA private key
print('self.RSAKey', self.RSAKey, type(self.RSAKey))
signer = PKCS1_PSS.new(self.RSAKey)
h = SHA512.new()
h.update(msg)
signature = signer.sign(h)
# Encrypt the AES key with RSA key
secretText = rsakey.encrypt(self.AESKey)
# encoding and send
race2 = base64.b64encode(secretText)
race3 = base64.b64encode(msg)
race4 = base64.b64encode(signature)
#print "node client side: ", " The secretText : ", race4
#print(type(race2), type(race3), type(race4))
final_race = race2.decode() + ':' + race3.decode() + ':' + race4.decode()
self.ctrlsock.sendall(final_race.encode())
self.ctrlsock.close()
#except Exception as e:
# print ("Cleint ERROR: ", e)
#self.nodeclient()
#finally:
#self.ctrlsock.close()
def rcvconnection(self):
'''
Make a loop of connections between Node Server and Client sides
to request and receive any new messages from other MDA nodes.
:return: nothing
'''
try:
while 1:
# make a new connection to this node Server-side
self.ctrlsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
# %%%%%%%%%%%Change to test%%%%%%%%%%%%%%%%%%%
port = mda.PORT
# %%%%%%%%%%%Change to test%%%%%%%%%%%%%%%%%%%
self.ctrlsock.connect((host, port))
# Send a request for new received packets
# Generate a AES key and encrypt the message
request = "Req0000"
cipher = AES.new(self.AESKey, AES.MODE_CFB, self.iv)
realmsg = request
realmsg2 = realmsg.encode("utf8")
#print( "node client side: ", realmsg2)
msg = self.iv + cipher.encrypt(realmsg2)
# Sign the request message with Client-side RSA private key
signer = PKCS1_PSS.new(self.RSAKey)
h = SHA512.new()
h.update(msg)
signature = signer.sign(h)
# encoding and send
race3 = base64.b64encode(msg)
race4 = base64.b64encode(signature)
#print ("node client side: "," The secretText : ", race4)
self.ctrlsock.sendall(race3 + ':' + race4)
# Receiving the packets (files names containing messages)
while 1:
rcstring = ''
buf = self.ctrlsock.recv(10000)
rcstring += buf
if not len(rcstring):
break
packet = self.decryptmsg(rcstring)
#print("node client side: ", "Receive new connection or message", packet)
# Dealing with the packet received
if packet.startswith("00"): # ----- Begin connection
ctrl , senderid, sender, aeskey, rsakey, msg = packet.split('$', 5)
ha = db.get_node('7', senderid)
if self.isreal(msg):
# If user does not want to show any messages from unknown nodes
wmsg = "This connection is not secure !!"
if self.options[4][0] == '1': # Check for the option
if db.check_contact(ha): # Check in the list of contacts
newchat = mdaconnection()
# if this is the first connection with this node ever, ...
# ... then the the AES key will be your friend verifier later :)
newchat.contactid = senderid
newchat.nodeid = sender
newchat.AESkey = aeskey
newchat.RSAkey = rsakey
self.openwin.update({newchat.contactid: "close 000"})
newchat.isreal = True
newchat.mcounter = 1
# Here we can show the first msg from new chat finally !!
mdaprotocol, now, mcounter, contactid, chatmsg = msg.split('@@', 4)
if now > 20 or mcounter > newchat.mcounter:
if db.check_contact(senderid):
self.notification(wmsg, "warning", db.get_contact(senderid))
else:
self.notification(wmsg, "warning", senderid)
else:
self.notification(chatmsg, "msg", senderid)
self.connectionlist.update({senderid: newchat})
else:
self.notification(wmsg, "warning", senderid)
else:
# show any message coming from any MDA node
newchat = mdaconnection()
# if this is the first connection with this node ever, ...
# ... then the the AES key will be your friend verifier later :)
newchat.contactid = senderid
newchat.nodeid = sender
newchat.AESkey = aeskey
newchat.RSAkey = rsakey
self.openwin.update({newchat.contactid: "close 000"})
newchat.isreal = True
newchat.mcounter = 1
# Here we can show the first msg from new chat finally !!
mdaprotocol, now, mcounter, contactid, chatmsg = msg.split('@@', 4)
if now > 20 or mcounter > newchat.mcounter:
self.notification(wmsg, "warning", senderid)
else:
self.notification(chatmsg, "msg", senderid)
self.connectionlist.update({senderid: newchat})
elif packet.startswith("m0"): # ______ an income message within a working connection
msgconn = mda_encryption()
# Extract the message
decmsg = msgconn.decrypt_f(packet, self.AESKey)
senderid, sender, msg = decmsg.split('$', 2)
# Check for it's connection
for x in self.connectionlist.keys():
var = self.connectionlist[x]
if var.contactid == senderid:
# Decrypt it with the connection Keys
plaintxt = mda_encryption.aesdecrypt(msg, var.AESKey, var.othernode_pup)
if self.isreal(plaintxt): # Real message will be shown
var.mcounter += 1
var.rcvfile = packet + ".enc"
mdaprotocol, now, mcounter, contactid, chatmsg = plaintxt.split('@@', 4)
if self.openwin[var.contactid] == "close 000": # A Chat windows is not opened yet !
# Show the message ( If it is Real message !! )
if now > 20 or mcounter > var.mcounter:
if db.check_contact(ha):
self.notification(wmsg, "warning", db.get_contact(senderid))
else:
self.notification(wmsg, "warning", senderid)
else:
self.notification(chatmsg, "msg", senderid)
var.messages.append(plaintxt) # Save received messages
else: # Fake message will be deleted
del var
del self.connectionlist[x]
self.ctrlsock.close()
except Exception as e:
print("Client ERROR", e)
finally:
self.ctrlsock.close()
@staticmethod
def isreal(msg):
if msg.startwith("fa"):
real = False
else:
real = True
return real
def decryptmsg(self, rcstring):
'''
Decrypt the message (packets received from node sever-side)
:param rcstring:
:return:
'''
# getting the AES key to decrypt the msg
# print( " Received total message : ", rcstring)
encmessage, secretsign = rcstring.split(':', 1)
#secretkey = rcstring.split(':')
#secretsign = rcstring.split(':')
encmsg = base64.b64decode(encmessage)
signature = base64.b64decode(secretsign)
# Verifing the msg with the node server RSA public key before decrypt it !
h = SHA512.new()
h.update(encmsg)
verifier = PKCS1_PSS.new(self.nodeserver_pup)
plaintxt2 = ''
if verifier.verify(h, signature):
iv = encmsg[:16]
encmsg = encmsg[16:]
cipher = AES.new(self.AESKey, AES.MODE_CFB, iv)
plaintxt = cipher.decrypt(encmsg)
plaintxt2 = plaintxt.decode("utf8")
else:
print ("The signature is not authentic.")
return plaintxt2
# ----------------------------------------------------------------------------------
# ----------------------- GUI of The MDA Program -----------------------------------
# ----------------------------------------------------------------------------------
# Node menu functions
def joinmda(self):
msg = ""
file_name = self.join_net()
if not file_name:
messagebox.showwarning("Warning", "You did not select any MDA network file !\n")
return 0
msg = self.mda.join(file_name)
if msg != "":
messagebox.showinfo(message=msg)
return 0
time.sleep(60)
if self.mycontactid:
msg = " Congratulation, You are a MDA member !"
messagebox.showinfo(message=msg)
self.notification(msg, "msg", "")
self.showid()
my = "MDA Contact-ID: {}".format(self.mycontactid)
self.lbl3.configure(text=my)
else:
msg = " Sorry,, try again in few minutes :( We hope you come back soon."
messagebox.showinfo(message=msg)
def join_net(self):
filename = filedialog.askopenfile(title = "Select Network file",filetypes = (("MDA files","*.mdar"),("all files","*.*")))
# show an "Open" dialog box and return the path to the selected file
return filename
def leave(self):
msg = " You have left MDA member :( "
if messagebox.askyesno(message='Are you sure you want to leave MDA Network ?', icon='question', title='Leave MDA') == "Yes":
# Remove from nodelist first ( function in mda )
self.mda.leavemda()
# Second delete my info
db.del_node(self.mynodeid)
del self.mda.mycontactid
self.connectionlist.clear()
self.notification(msg, "warning", "")
messagebox.showinfo(message=msg)
def newkey(self):
top = tk.Toplevel()
top.title("New Contact-ID")
top.configure(bg="white")
frame = ttk.Frame(top)
frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
frame.columnconfigure(0, weight=3)
frame.columnconfigure(1, weight=3)
frame.columnconfigure(2, weight=3)
frame.rowconfigure(0, weight=3)
# The Name, id label
oldkeylbl = ttk.Label(frame, text="Old Contact-ID :")
newkeylbl = ttk.Label(frame, text="New Contact-ID :")
# Enter your friend name and id
oldkey = ttk.Label(frame, text=self.mycontactid)
newkey = ttk.Entry(frame, textvariable=self.newidvar)
oldkeylbl.grid(row=0, column=0, sticky=tk.E+tk.W+tk.S+tk.N, pady=3)
oldkey.grid(row=0, column=1, sticky=tk.E+tk.W+tk.S+tk.N, padx=3)
newkeylbl.grid(row=1, column=0, columnspan=2, sticky=tk.E+tk.W+tk.S+tk.N, pady=3)
newkey.grid(row=1, column=1, columnspan=2, sticky=tk.E+tk.W+tk.S+tk.N, padx=3)
# Action Buttons
frame2 = ttk.Frame(frame)
frame2.grid(row=2, column=2, columnspan=2, sticky=tk.E)
button1 = ttk.Button(frame2, text="Generate", command=self.b1genkey)
# Update button delete old key from nodelist and show a warning message
button2 = ttk.Button(frame2, text="Update", command=self.up)
button3 = ttk.Button(frame2, text="Cancel", command=top.destroy)
button1.grid(row=0, column=0,padx=3, pady=3,sticky=tk.W+tk.N)
button2.grid(row=0, column=1,padx=3, pady=3,sticky=tk.W+tk.N)
button3.grid(row=0, column=2,padx=3, pady=3, sticky=tk.E+tk.N)
top.grab_set()
def b1genkey(self): # need changes ****
me = mda()
self.genkey = me.generatecontactkey() # change to generatecontactkey function for checking
self.newidvar.set(self.genkey)
def up(self):
# Update the new Contact-ID to the nodelist
ha = db.get_node('6', self.mycontactid)
if db.check_node(ha) or ha:
self.mycontactid = self.newidvar
db.update_node(ha, self.mycontactid)
self.showid()
else:
msg = "You have to be MDA member first to change your Contact-ID" \
"Please click \'Join\' from \'Node\' menu to be a MDA member :)"
messagebox.showwarning("Warning", "You are not a MDA Network member !\n")
self.notification(msg, "hint", "")
# -----------------------------------------------------------------------------------
# MDA porgram options
def mdaoptions(self):
'''
[0][] open the program in OS start-up
[1][] cash messages
[2][] show new messages in new win
[3][] iconify
[4][] do not receive from unknown member
[5][] language
[6][] use verify question
'''
self.optop = tk.Toplevel()
self.optop.title("Options")
self.optop.configure(bg="white")
frame = ttk.Frame(self.optop)
frame.pack(fill=tk.BOTH, expand=True, pady=5, padx=5)
frame.columnconfigure(0, weight=3)
frame.columnconfigure(1, weight=3)
frame.rowconfigure(0, weight=3)
# General options
lbl = ttk.Label(frame, text="General")
lbl.grid(row=0, column=0, sticky=tk.N+tk.W)
self.lanvar = tk.IntVar()
self.cashvar = tk.IntVar()
self.showvar = tk.StringVar()
self.iconvar = tk.StringVar()
self.unkvar = tk.StringVar()
box1 = ttk.Checkbutton(frame, text='Launch MDA Private Messanger on start-up', variable=self.lanvar, command=self.launch)
box1.grid(row=1, column=0, sticky=tk.N+tk.W)
box2 = ttk.Checkbutton(frame, text='Cash messages for (in days)', variable=self.cashvar, command=self.cashf)
box2.grid(row=2, column=0, sticky=tk.N+tk.W)
self.cash = tk.IntVar()
self.cashspin = tk.Spinbox(frame, from_=0, to=100, width=3, state='disabled', textvariable=self.cash)
self.cashspin.grid(row=2, column=1, sticky=tk.W+tk.N)
box3 = ttk.Checkbutton(frame, text='Show new messages in new windows', variable=self.showvar)
box4 = ttk.Checkbutton(frame, text='Iconify the program windows when minimize it.', variable=self.iconvar)
box5 = ttk.Checkbutton(frame, text='Do not receive from unknown members', variable=self.unkvar)
box3.grid(row=3, column=0, columnspan=2, sticky=tk.N+tk.W)
box4.grid(row=4, column=0, columnspan=2, sticky=tk.N+tk.W)
box4.grid(row=4, column=0, columnspan=2, sticky=tk.N+tk.W)
box5.grid(row=5, column=0, columnspan=2, sticky=tk.N+tk.W)
lbl1 = ttk.Label(frame, text='program language: ')
self.drop = ttk.Combobox(frame, state='readonly', width="8")
self.drop['values'] = ('English', 'Arabic')
self.drop.current(0)
self.drop.grid(row=6, column=1, sticky=tk.W+tk.N)
lbl1.grid(row=6, column=0, sticky=tk.N+tk.W)
# Security options
se = ttk.Separator(frame)
se.grid(row=7, column=0, columnspan=2,pady=5, sticky=tk.E+tk.W)
lbl3 = ttk.Label(frame, text='Security')
lbl3.grid(row=8, column=0, sticky=tk.N+tk.W)
self.qvar = tk.IntVar()
box6 = ttk.Checkbutton(frame, text='Use verify question', variable=self.qvar, command=self.check)
lbl4 = ttk.Label(frame, text='Enter the verify question: ')
lbl5 = ttk.Label(frame, text='Enter the answer: ')
self.question = tk.StringVar()
self.answer = tk.StringVar()
self.quesent = ttk.Entry(frame, textvariable=self.question, state='disabled')
self.ansent = ttk.Entry(frame, textvariable=self.answer, state='disabled')
box6.grid(row=9, column=0, sticky=tk.N+tk.W)
lbl4.grid(row=10, column=0, sticky=tk.N+tk.W)
lbl5.grid(row=11, column=0, sticky=tk.N+tk.W)
self.quesent.grid(row=10, column=1, pady=3, sticky=tk.N+tk.W+tk.E)
self.ansent.grid(row=11, column=1, sticky=tk.N+tk.W+tk.E)
# Action Buttons
frame2 = ttk.Frame(frame)
frame2.grid(row=12, column=1, columnspan=2, sticky=tk.E)
b1 = ttk.Button(frame2, text='Save', command=self.saveop)
b2 = ttk.Button(frame2, text='Cancel', command=self.optop.destroy)
b1.grid(row=0, column=0, padx=5, pady=3, sticky=tk.W+tk.N)
b2.grid(row=0, column=1, pady=3, sticky=tk.E+tk.N)
# Set the values
try:
if self.options[0][0] == '1': # use password
self.lanvar.set(1)
if self.options[1][0] == '1': # cash messages
self.cashvar.set(1)
self.cash.set(int(self.options[1][1]))
self.cashspin.configure(state='normal')
if self.options[2][0] == '1': # messages in new window
self.showvar.set('1')
if self.options[3][0] == '1': # iconify the porgram
self.iconvar.set('1')
if self.options[4][0] == '1': # not receive from unknown
self.unkvar.set('1')
if self.options[5][0]: # language
self.drop.current(int(self.options[5][0]))
if self.options[6][0] == '1': # verify question
self.qvar.set(1)
self.question.set(self.options[6][1])
self.answer.set(self.options[6][2])
self.quesent.configure(state='normal')
self.ansent.configure(state='normal')
except IndexError:
pass
def launch(self):
pass
def cashf(self):
if self.cashvar.get() == 0:
self.cashspin.configure(state='disabled')
else:
self.cashspin.configure(state='normal')
def check(self):
if self.qvar.get() == 0:
self.quesent.configure(state='disabled')
self.ansent.configure(state='disabled')
else:
self.quesent.configure(state='normal')
self.ansent.configure(state='normal')
def saveop(self): # Save user option
if self.lanvar.get() == 1:
self.options[0][0] = '1'
elif self.lanvar.get() == 0:
self.options[0][0] = '0'
if self.cashvar.get() == 1 and self.cash.get():
self.options[1][0] = '1'
self.options[1][1] = str(self.cash.get())
elif self.cashvar.get() == 0:
self.options[1][0] = '0'
self.cashspin.configure(state='disabled')
if self.showvar.get() == '1':
self.options[2][0] = '1'
elif self.showvar.get() == '0':
self.options[2][0] = '0'
if self.iconvar.get() == '1':
self.options[3][0] = '1'
elif self.iconvar.get() == '0':
self.options[3][0] = '0'
if self.unkvar.get() == '1':
self.options[4][0] = '1'
elif self.unkvar.get() == '0':
self.options[4][0] = '0'
self.options[5][0] = str(self.drop['values'].index(self.drop.get()))
if self.qvar.get() == 1 and self.question.get() and self.answer.get():
self.options[6][0] = '1'
self.options[6][1] = self.question.get()
self.options[6][2] = self.answer.get()
elif self.qvar.get() == 0:
self.options[6][0] = '0'
self.optop.destroy()
# ------------------------------------------------------------------------------------
# Help menu functions
def mdanews(self):
self.showinbrowser2()
def offlinehelp(self):
hel = ''
@staticmethod
def about():
top = tk.Toplevel()
top.title("About")
top.configure(bg="white")
frame = ttk.Frame(top)
frame.pack(fill=tk.BOTH, expand=True, pady=5, padx=5)
frame.columnconfigure(0, weight=3)
frame.columnconfigure(1, weight=3)
frame.rowconfigure(0, weight=3)
we = "MDA Private Messenger Edition 1.0\n"
we2 = "Free, Secure and Anonymous Instant-Messaging Network\n\n"
me = "Created by Amr Abdelnaser, 20/03/2016 04:00PM, Doha, Qatar\n"
me2 = "Follow me in twitter: "
me3 = "@AmrBsheer\n"
us = "For more info, see MDA-Network blog: "
us2 = "mdanetwork.wordpress.com\n\n"
ack = "Acknowledgments\n"
ack2 = "Abdallah Elsamman, Mohammed Elsayed"
about = '{}{}{}{}{}{}{}{}{}'.format(we, we2, me, me2, me3, us, us2, ack, ack2)
msg = ttk.Label(frame, text=about, justify=tk.CENTER, font=('arial', '12', 'bold'))
msg.grid(row=0, column=0, columnspan=2, padx=7, pady=7, sticky=tk.N+tk.W)
button = ttk.Button(frame, text="Dismiss", command=top.destroy)
button.grid(row=1, column=1, sticky=tk.N+tk.E)
top.grab_set()
# ------------------------------------------------------------------------------
# The Buttons functions
def chat(self):
if self.antispam < 15:
self.antispam += 1
else:
msg = "Maximum opened secure chats is 15 at the same time !!\n"
messagebox.showwarning("Warning", msg)
return
# GUI-Design
chat = None
per, ii = self.detectselection()
if per:
contactid = db.get_name(per)
if contactid in self.connectionlist: # Open income chat ( old connection )
chat = chatwin(per, contactid, self.connectionlist[contactid])
else: # Start a new chat ( new connection )
newconnection = mdaconnection()
self.connectionlist.update({contactid: newconnection})
chat = chatwin(per, contactid, newconnection)
self.openwin.update({contactid: "open 111"}) # Indicate that a Chat windows is opened !!
# Not Begin the connection But Begin the MDA protocol :)
else:
wmsg = "If you want to connect to more than one friend, select one by one from \'Contact\' list " \
"at the right and then click \'Chat\' button !"
self.notification(wmsg, "hint", "")
try:
chat
except NameError:
del self.connectionlist[db.get_name(per)]
def newcontact(self):
self.newtop = tk.Toplevel()
self.newtop.title("New Contact")
self.newtop.configure(bg="white")
frame = ttk.Frame(self.newtop)
frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
frame.columnconfigure(0, weight=3)
frame.columnconfigure(1, weight=3)
#frame.columnconfigure(2, weight=3)
frame.rowconfigure(0, weight=3)
# The Name, id label
namelbl = ttk.Label(frame, text="Name :")
idlbl = ttk.Label(frame, text="Contact-ID :")
# Enter your friend name and id
self.namevar = tk.StringVar()
self.idvar = tk.StringVar()
name = ttk.Entry(frame, textvariable=self.namevar)
id = ttk.Entry(frame, textvariable=self.idvar)
namelbl.grid(row=0, column=0, sticky=tk.E+tk.W+tk.S+tk.N, pady=3)
name.grid(row=0, column=1, sticky=tk.E+tk.W+tk.S+tk.N, padx=3, pady=3)
idlbl.grid(row=1, column=0, sticky=tk.E+tk.W+tk.S+tk.N, pady=3)
id.grid(row=1, column=1, sticky=tk.E+tk.W+tk.S+tk.N, padx=3)
# Action Buttons
frame2 = ttk.Frame(frame)
frame2.grid(row=2, column=1, columnspan=2, sticky=tk.E)
b1 = ttk.Button(frame2, text='Add', command=self.addnew)
b2 = ttk.Button(frame2, text='Cancel', command=self.newtop.destroy)
b1.grid(row=0, column=0, padx=3, pady=3, sticky=tk.W+tk.N)
b2.grid(row=0, column=1, padx=3, pady=3, sticky=tk.E+tk.N)
self.newtop.grab_set()
def addnew(self): # need changes ( function in mda ) ***
# To check if the contact id in nodelist or not then add it
try:
if db.get_node('7', self.idvar.get()):
self.listinsert()
self.newtop.destroy()
else:
msg = "The Contact-ID is not correct! Or the person you want to add is not a member of MDA Network." \
" Please write the correct one."
messagebox.showwarning("Warning", "The Contact-ID is not correct!\n")
self.notification(msg, "hint", "")
except Exception:
messagebox.showwarning("Warning", "Please enter the Contact-ID and the name!\n")
def listinsert(self):
query = db.enter_contact(self.namevar.get(), self.idvar.get())
if query:
messagebox.showinfo(title="Duplicate Contact", message="{} already exist !".format(self.idvar.get()))
else:
self.contactslist.insert(tk.END, self.namevar.get())
def delcontact(self):
# for deleting more than one person
item, item_inx = self.detectselection()
#print (item_inx, " ", item)
if item:
if messagebox.askyesno(message='Are you sure you want to delete {} ?'.format(item), icon='question', title='Delete Contact') == True:
self.contactslist.delete(item_inx)
db.del_contact(item)
messagebox.showinfo(title="Delete Contact", message="{} deleted successfully !".format(item))
def detectselection(self):
items_inx = self.contactslist.curselection()
items = None
#print (items_inx[0], " ", str(items), " ", len(items_inx))
if not items_inx:
msg = "Please select one friend at least!\n"
messagebox.showwarning("Warning", msg)
return False, False
else:
items = self.contactslist.get(items_inx)
return str(items), items_inx[0]
# Status and contact list update functions
def notification(self, msg, tag, name): # need changes ***
self.txt.configure(state="normal") # To enable editing the text obviously !!
if msg == "":
self.getdate()
msg = "Warning[{}]: Do not miss with me !".format(self.now)
tag = "warning"
self.txt.insert(tk.END, msg, tag)
else:
self.formatmsg = ""
self.getdate()
if tag == "warning":
self.formatmsg = "Warning[{}]: {}".format(self.now, msg)
self.txt.insert(tk.END, self.formatmsg, tag)
elif tag == "msg":
self.txt.insert(tk.END, name, "name") # The name of sender and receiver
self.formatmsg = "[{}]".format(self.now)
self.txt.insert(tk.END, self.formatmsg, "date")
self.formatmsg = ": {}".format(msg)
self.txt.insert(tk.END, self.formatmsg, 'message')
elif tag == "hint":
self.formatmsg = "Hint: {} {}".format(name, msg)
self.txt.insert(tk.END, self.formatmsg, 'hint')
self.txt.insert(tk.END, '\n', tag)
self.txt.see(tk.END)
self.txt.configure(state="disabled") # To prevent editing the text (Read-only)
def getdate(self):
self.now = str(datetime.now())
def initUI(self):
self.parent.title("MDA Private Messenger")
self.pack(fill=tk.BOTH, expand=True)
s = ttk.Style()
s.configure('TLabel', background='white', foreground="#000000")
s2 = ttk.Style()
s2.configure('TText', background='white', foreground="#000000")
s3 = ttk.Style()
s3.configure('TFrame', background='white', foreground="#000000")
s4 = ttk.Style()
s4.configure('TCheckbutton', background='white', foreground="#000000")
# the style of the program need changes ***
#self.style = ttk.Style()
#self.style.theme_use("default")
menubar = tk.Menu(self.parent) # The top level menu (Node - Help)
nodemenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Node", menu=nodemenu)
nodemenu.add_command(label="Join", command=self.joinmda)
nodemenu.add_command(label="My Contact-ID", command=self.showid)
nodemenu.add_command(label="New Contact-ID", command=self.newkey)
nodemenu.add_command(label="Options", command=self.mdaoptions)
nodemenu.add_separator()
nodemenu.add_command(label="Leave", command=self.leave)
nodemenu.add_separator()
nodemenu.add_command(label="Quit", command=self.quit)
helpmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="help", menu=helpmenu)
helpmenu.add_command(label="News", command=self.mdanews)
helpmenu.add_command(label="Offline help", command=self.offlinehelp)
helpmenu.add_command(label="About", command=self.about)
self.parent.config(menu=menubar)
frame = ttk.Frame(self, style='TFrame')
frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
#frame.grid(row=0, column=0, padx=7, pady=7, sticky=(N, S, E, W))
frame2 = ttk.Frame(frame, style='TFrame')
frame2.grid(row=1, column=3)
frame.columnconfigure(0, weight=3)
frame.columnconfigure(1, weight=3)
frame.columnconfigure(2, weight=5)
#frame.columnconfigure(3, weight=3)
frame.columnconfigure(4, weight=1)
frame.columnconfigure(5, weight=1)
#frame.columnconfigure(6, weight=1)
frame.columnconfigure(3, pad=7)
frame.rowconfigure(1, weight=1)
#frame.rowconfigure(2, weight=1)
#frame.rowconfigure(5, pad=7)
lbl1 = ttk.Label(frame, text="Status")
lbl1.grid(row=0, column=0, sticky=tk.W+tk.N, pady=5)
# The updates, new messages, warnings Screen
self.txt = tk.Text(frame, wrap=tk.WORD)
txtscroll = ttk.Scrollbar(frame, command=self.txt.yview)
self.txt.configure(yscrollcommand=txtscroll.set)
# for different use in the program
self.txt.tag_configure('name',foreground='#2200ff', font=('Cambria', 12)) # blue
self.txt.tag_configure('date',foreground='#818181', font=('Cambria', 12)) # gray
self.txt.tag_configure('hint',foreground='#006400', font=('Cambria', 12)) # green
self.txt.tag_configure('warning', foreground='#FF0000', font=('Cambria', 12)) # red
self.txt.tag_configure('message', foreground='#000000', font=('Cambria', 12)) # black
# for Welcome screen only
self.txt.tag_configure('tw',foreground='#2200ff', justify='center', font=('Cambria', 14), underline=1) # blue
self.txt.tag_configure('blog',foreground='#2200ff', justify='center', font=('Cambria', 14), underline=1) # blue
self.txt.tag_configure('date1',foreground='#818181', justify='center', font=('Cambria', 14)) # gray
self.txt.tag_configure('hint1',foreground='#006400', justify='center', font=('Cambria', 14)) # green
self.txt.tag_configure('warning1', foreground='#FF0000', justify='center', font=('Cambria', 14)) # red
self.txt.tag_configure('message1', foreground='#000000', justify='center', font=('Cambria', 14)) # black
self.txt.tag_bind('tw', "<Button-1>", self.showinbrowser)
self.txt.tag_bind('blog', "<Button-1>", self.showinbrowser2)
self.txt.config(cursor="arrow")
self.txt.grid(row=1, column=0, columnspan=2, sticky=tk.E+tk.W+tk.S+tk.N)
txtscroll.grid(row=1, column=2, sticky=tk.W+tk.N+tk.S)
# Contacts list and it's Buttons (New - Del - Chat - Options)
lbl2 = ttk.Label(frame, text="Contacts", width=10)
lbl2.grid(row=0, column=4, sticky=tk.N+tk.W, pady=5)
# The user contact list to deal with
self.contactslist = tk.Listbox(frame)
listscroll = ttk.Scrollbar(frame, orient=tk.VERTICAL)
self.contactslist.config(yscrollcommand=listscroll.set)
listscroll.config(command=self.contactslist.yview)
self.contactslist.grid(row=1, column=4, columnspan=2, sticky=tk.W+tk.N+tk.S+tk.E)
listscroll.grid(row=1, column=6, sticky=tk.W+tk.N+tk.S)
chatbutton = ttk.Button(frame, text="Secure Chat", command=self.chat)
chatbutton.grid(row=2, column=4, columnspan=2, ipadx=3, ipady=3, pady=3, sticky=tk.N+tk.W+tk.E)
newbutton = ttk.Button(frame, text="New", command=self.newcontact)
newbutton.grid(row=3, column=4, sticky=tk.N+tk.W)
delbutton = ttk.Button(frame, text="Delete", command=self.delcontact)
delbutton.grid(row=3, column=5, sticky=tk.N+tk.W)
self.lbl3 = ttk.Label(frame, text="MDA Contact-ID: ")
self.lbl3.grid(row=2, column=0, sticky=tk.N+tk.W, pady=5)
if self.mycontactid:
self.lbl3.configure(text=self.mycontactid)
else:
my = "MDA Contact-ID not assigned yet, please join the MDA Network !"
self.lbl3.configure(text=my)
self.welcome()
def welcome(self):
we = "\n\nWelcome to MDA Private Messenger Edition 1.0 !\n"
we2 = "A free, secure and anonymous Instant-Messaging network\n"
me = " Created by Amr Abdelnaser\n"
me2 = "Follow me in twitter: "
me3 = "@AmrBsheer\n"
us = "For more info, see MDA-Network blog: "
us2 = "mdanetwork.wordpress.com\n" # not created yet **************
us3 = "--------------------------------------------------------------------------------------------------\n" \
"---------------------------------------------------------------------------------------------------\n\n"
self.txt.insert(tk.END, we, 'message1')
self.txt.insert(tk.END, we2, 'hint1')
self.txt.insert(tk.END, me, 'hint1')
self.txt.insert(tk.END, me2, 'hint1')
self.txt.insert(tk.END, me3, 'tw')
self.txt.insert(tk.END, us, 'warning1')
self.txt.insert(tk.END, us2, 'blog')
self.txt.insert(tk.END, us3, 'date1')
self.txt.configure(state="disabled") # To prevent editing the text (Read-only)
self.contact_show()
def contact_show(self):
query = db.get_all_contacts()
for i in query:
self.contactslist.insert(tk.END, i)
def showinbrowser(self):
webbrowser.open("https://www.twitter.com/AmrBsheer")
def showinbrowser2(self):
webbrowser.open("https://www.google.com")
def showid(self):
if not self.mycontactid:
my = "not assigned yet, please join the MDA Network first !"
elif self.mycontactid == '0':
my = "Config files is corrupted or deleted !"
else:
my = self.mycontactid
self.notification(my, 'hint', "MDA Contact-ID")
def checkarchive(self):
path = '/bin/'
file = 'db.enc'
arch = self.getarchive(path, file)
if arch:
for key, item in arch.iteritems():
tic = int(key[8:])
self.getdate()
kick = int(self.now) - tic
if kick >= self.options[1][1]:
del arch[key]
@staticmethod
def savearchive(path, File, archive):
go, rsa = mda_encryption.generateRSAkey('m93ihGlk3J50pHo')
rsakey = PKCS1_OAEP.new(rsa)
aeskey = Random.new().read(32)
encryptedkey = rsakey.encrypt(aeskey)