-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPiVault.py
2222 lines (2043 loc) · 70.1 KB
/
PiVault.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
'''
Very simply secrets vault.
- Takes in a string, encrypts it and stores the encrypted string.
- Then retrieves the encrypted string and decrypts it for use
Author Siggi Bjarnason AUG 2022
Copyright 2022
Encrypt/decrypt functions copied from https://stackoverflow.com/a/44212550/8549454
Following packages need to be installed for base functionality
pip install pycryptodome
pip install maskpass
If you want to use clipboard feature
pip install pyperclip
If you are using Redis also:
pip install redis
If you are using TOTP feature
pip install pyotp
'''
# Import libraries
import os
import shutil
import time
import sys
import subprocess
import base64
import re
# Global constants
iDefShowTime = 30 # Default time show password in GUI
bDefAutoHide = True # Default to auto hide password after show time expires
bDefHide = False # Default hide password while typing
strDefValueColor = "red"
strDefStore = "files"
strDefVault = "VaultData"
strDefTable = "tblVault"
strCheckValue = "This is a simple secrets vault"
strCheckKey = "VaultInit"
lstDBTypes = ["sqlite", "mysql", "postgres", "mssql"]
lstStoreTypes = ["files","redis"]
bLoggedIn = False
dictComponents = {}
iTimer = 0
strICOFile = "PieLock.ico"
#functions
def CheckDependency(Module):
"""
Function that installs missing depedencies
Parameters:
Module : The name of the module that should be installed
Returns:
dictionary object without output from the installation.
if the module needed to be installed
code: Return code from the installation
stdout: output from the installation
stderr: errors from the installation
args: list object with the arguments used during installation
success: true/false boolean indicating success.
if module was already installed so no action was taken
code: -5
stdout: Simple String: {module} version {x.y.z} already installed
stderr: Nonetype
args: module name as passed in
success: True as a boolean
"""
global dictComponents
dictReturn = {}
strModule = Module
if len(dictComponents) == 0:
lstOutput = subprocess.run(
[sys.executable, "-m", "pip", "list"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
lstLines = lstOutput.stdout.decode("utf-8").splitlines()
for strLine in lstLines:
lstParts = strLine.split()
dictComponents[lstParts[0].lower()] = lstParts[1]
if strModule.lower() not in dictComponents:
lstOutput = subprocess.run(
[sys.executable, "-m", "pip", "install", strModule], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
dictReturn["code"] = lstOutput.returncode
dictReturn["stdout"] = lstOutput.stdout.decode("utf-8")
dictReturn["stderr"] = lstOutput.stderr.decode("utf-8")
dictReturn["args"] = lstOutput.args
if lstOutput.returncode == 0:
dictReturn["success"] = True
else:
dictReturn["success"] = False
return dictReturn
else:
dictReturn["code"] = -5
dictReturn["stdout"] = "{} version {} already installed".format(
strModule, dictComponents[strModule.lower()])
dictReturn["stderr"] = None
dictReturn["args"] = strModule
dictReturn["success"] = True
return dictReturn
if not CheckDependency("pycryptodome")["success"]:
print("failed to install pycryptodome. Please pip install pycryptodome as that is needed for all the crypto work.")
sys.exit(5)
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
if not CheckDependency("maskpass")["success"]:
print("failed to install maskpass. Please pip install maskpass to be able to mask the password input.")
sys.exit(5)
import maskpass
# End imports
def ShowGUI():
"""
Function that handles the whole GUI. All GUI functions and code are here
Parameters:
nothing
Returns:
nothing
"""
global iTimer
import os
try:
import tkinter as tk
from tkinter import messagebox as mb
except ImportError:
print("unable to start GUI")
return
def Config():
"""
Part of ShowGUI. Function that handles the Preferences Config Window
Parameters:
nothing
Returns:
nothing
"""
global iClippy
global iHideIn
global strStoreType
global iTOTP
global strColor
global objVaultText
global objConfWin
global objVaultLbl
global objVaultText
global objHostLbl
global objHostText
global objPortLbl
global objPortText
global objTableLbl
global objTableText
global objDatabaseLbl
global objDatabaseText
global objDBUserLbl
global objDBUserText
global objDBPassLbl
global objDBPassText
global objNoteLbl
lstStoreOptions = lstStoreTypes.copy()
lstStoreOptions += lstDBTypes.copy()
objConfWin = tk.Toplevel(objMainWin)
iWidth = 600
iHeight = 450
ixMargin = 50
iyMargin = 50
iScreenW = objConfWin.winfo_screenwidth()
iScreenH = objConfWin.winfo_screenheight()
ixMargin = int(iScreenW/2 - iWidth/2)
iyMargin = int(iScreenH/2 - iHeight/2)
objConfWin.resizable(width=False, height=False)
objConfWin.geometry(
"{}x{}+{}+{}".format(iWidth, iHeight, ixMargin, iyMargin))
objConfWin.title("Configuration")
objConfWin.iconbitmap(strICOFile)
objConfWin.columnconfigure(0, weight=1)
objConfWin.columnconfigure(3, weight=1)
objConfLbl = tk.Label(objConfWin,text="PiVault Configuration")
objConfLbl.grid(row=0, columnspan=5, sticky=tk.EW, padx=10,pady=10)
objConfLbl.config(font=("arial bold",24))
objStoreLbl = tk.Label(objConfWin,text="Store Type: ")
objStoreLbl.grid(row=1, column=1, sticky=tk.E)
strStoreType = tk.StringVar()
strStoreType.set(strStore)
cmbStore = tk.OptionMenu(objConfWin, strStoreType, *lstStoreOptions, command=UpdateView)
cmbStore.grid(row=1,column=2,sticky=tk.W)
objVaultLbl = tk.Label(objConfWin,text="Vault: ")
objVaultLbl.grid(row=2, column=1, sticky=tk.E)
objVaultText = tk.Entry(objConfWin,width=50)
objVaultText.grid(row=2, column=2)
objVaultText.insert(0,strVault)
objHostLbl = tk.Label(objConfWin, text="Host: ")
objHostLbl.grid(row=3, column=1, sticky=tk.E)
objHostText = tk.Entry(objConfWin, width=50)
objHostText.grid(row=3, column=2)
objHostText.insert(0, FetchEnv("HOST"))
objPortLbl = tk.Label(objConfWin, text="Port: ")
objPortLbl.grid(row=4, column=1, sticky=tk.E)
objPortText = tk.Entry(objConfWin, width=50)
objPortText.grid(row=4, column=2)
objPortText.insert(0, FetchEnv("PORT"))
strTable = FetchEnv("TABLE")
if strTable == "":
strTable = strDefTable
objTableLbl = tk.Label(objConfWin, text="Table: ")
objTableLbl.grid(row=5, column=1, sticky=tk.E)
objTableText = tk.Entry(objConfWin, width=50)
objTableText.grid(row=5, column=2)
objTableText.insert(0, strTable)
objDatabaseLbl = tk.Label(objConfWin, text="Database: ")
objDatabaseLbl.grid(row=6, column=1, sticky=tk.E)
objDatabaseText = tk.Entry(objConfWin, width=50)
objDatabaseText.grid(row=6, column=2)
objDatabaseText.insert(0, FetchEnv("DB"))
objDBUserLbl = tk.Label(objConfWin, text="Database User: ")
objDBUserLbl.grid(row=7, column=1, sticky=tk.E)
objDBUserText = tk.Entry(objConfWin, width=50)
objDBUserText.grid(row=7, column=2)
objDBUserText.insert(0, FetchEnv("DBUSER"))
objDBPassLbl = tk.Label(objConfWin, text="DB Password: ")
objDBPassLbl.grid(row=8, column=1, sticky=tk.E)
objDBPassText = tk.Entry(objConfWin, width=50)
objDBPassText.grid(row=8, column=2)
objDBPassText.insert(0, FetchEnv("DBPWD"))
objNoteLbl = tk.Label(
objConfWin, text="Don't Use, use Env Var instead", fg="red")
objNoteLbl.grid(row=8, column=3, padx=5, sticky=tk.W)
iHideIn = tk.IntVar()
objHideInLbl = tk.Label(objConfWin, text="Hide Input: ")
objHideInLbl.grid(row=9, column=1, sticky=tk.E)
objHideInChk = tk.Checkbutton(objConfWin, variable=iHideIn)
objHideInChk.grid(row=9, column=2, sticky=tk.W)
if bHideValueIn:
objHideInChk.select()
objSectionLbl = tk.Label(objConfWin,text="The following only impacts CLI")
objSectionLbl.grid(row=10, columnspan=5, sticky=tk.EW, padx=10, pady=10)
objSectionLbl.config(font=("arial bold", 14))
strValueColor = FetchEnv("VALUECOLOR")
if strValueColor == "":
strValueColor = strDefValueColor
objColorLbl = tk.Label(objConfWin, text="Value Color: ")
objColorLbl.grid(row=11, column=1, sticky=tk.E)
strColor = tk.StringVar()
strColor.set(strValueColor)
cmbColor = tk.OptionMenu(objConfWin, strColor,*dictColor.keys())
cmbColor.grid(row=11, column=2, sticky=tk.W)
iTOTP = tk.IntVar()
objTOTPLbl = tk.Label(objConfWin, text="Enable TOTP: ")
objTOTPLbl.grid(row=12, column=1, sticky=tk.E)
objTOTPChk = tk.Checkbutton(objConfWin,variable=iTOTP)
objTOTPChk.grid(row=12, column=2, sticky=tk.W)
if bTOTP:
objTOTPChk.select()
iClippy = tk.IntVar()
objClippyLbl = tk.Label(objConfWin, text="Enable Clippy: ")
objClippyLbl.grid(row=13, column=1, sticky=tk.E)
objClippyChk = tk.Checkbutton(objConfWin,variable=iClippy)
objClippyChk.grid(row=13, column=2, sticky=tk.W)
if bClippy:
objClippyChk.select()
btnSave = tk.Button(objConfWin, text="Save", width=15,
height=1, command=SaveConfig)
btnSave.grid(row=14, columnspan=5, padx=10, pady=10)
UpdateView(strStore)
def SaveConfig():
"""
Part of ShowGUI. Function that handles collecting data from Preference window
and passing it onto the create config file function in the main code
Parameters:
nothing
Returns:
nothing
"""
dictConfFile = {}
if iClippy.get() == 1:
dictConfFile["CLIPPYENABLE"] = "true"
else:
dictConfFile["CLIPPYENABLE"] = "false"
if iHideIn.get() == 1:
dictConfFile["HIDEINPUT"] = "true"
else:
dictConfFile["HIDEINPUT"] = "false"
if iTOTP.get() == 1:
dictConfFile["TOTPENABLE"] = FetchEnv("TOTPENABLE")
dictConfFile["DB"] = objDatabaseText.get()
dictConfFile["DBPWD"] = objDBPassText.get()
dictConfFile["DBUSER"] = objDBUserText.get()
dictConfFile["HOST"] = objHostText.get()
dictConfFile["PORT"] = objPortText.get()
dictConfFile["STORE"] = strStoreType.get()
dictConfFile["TABLE"] = objTableText.get()
dictConfFile["VALUECOLOR"] = strColor.get()
dictConfFile["VAULT"] = objVaultText.get()
CreateConfig(dictConfFile)
objConfWin.destroy()
def UpdateView(strTemp):
"""
Part of ShowGUI. Function that handles making the Preferences Config Window
dynamic based on what is selected in the Store dropdown box.
Parameters:
strTemp: String indicating the value selected
Returns:
nothing
"""
if strTemp == "files":
objVaultLbl.grid(row=2, column=1, sticky=tk.E)
objVaultText.grid(row=2, column=2)
objHostLbl.grid_remove()
objHostText.grid_remove()
objPortLbl.grid_remove()
objPortText.grid_remove()
objTableLbl.grid_remove()
objTableText.grid_remove()
objDatabaseLbl.grid_remove()
objDatabaseText.grid_remove()
objDBUserLbl.grid_remove()
objDBUserText.grid_remove()
objDBPassLbl.grid_remove()
objDBPassText.grid_remove()
objNoteLbl.grid_remove()
elif strTemp == "redis":
objVaultLbl.grid_remove()
objVaultText.grid_remove()
objHostLbl.grid(row=3, column=1, sticky=tk.E)
objHostText.grid(row=3, column=2)
objPortLbl.grid(row=4, column=1, sticky=tk.E)
objPortText.grid(row=4, column=2)
objTableLbl.grid_remove()
objTableText.grid_remove()
objDatabaseLbl.grid(row=6, column=1, sticky=tk.E)
objDatabaseText.grid(row=6, column=2)
objDBUserLbl.grid(row=7, column=1, sticky=tk.E)
objDBUserText.grid(row=7, column=2)
objDBPassLbl.grid(row=8, column=1, sticky=tk.E)
objDBPassText.grid(row=8, column=2)
objNoteLbl.grid(row=8, column=3, padx=5, sticky=tk.W)
elif strTemp == "sqlite":
objVaultLbl.grid(row=2, column=1, sticky=tk.E)
objVaultText.grid(row=2, column=2)
objHostLbl.grid_remove()
objHostText.grid_remove()
objPortLbl.grid_remove()
objPortText.grid_remove()
objTableLbl.grid(row=5, column=1, sticky=tk.E)
objTableText.grid(row=5, column=2)
objDatabaseLbl.grid_remove()
objDatabaseText.grid_remove()
objDBUserLbl.grid_remove()
objDBUserText.grid_remove()
objDBPassLbl.grid_remove()
objDBPassText.grid_remove()
objNoteLbl.grid_remove()
elif strTemp in lstDBTypes:
objVaultLbl.grid_remove()
objVaultText.grid_remove()
objHostLbl.grid(row=3, column=1, sticky=tk.E)
objHostText.grid(row=3, column=2)
objPortLbl.grid_remove()
objPortText.grid_remove()
objTableLbl.grid(row=5, column=1, sticky=tk.E)
objTableText.grid(row=5, column=2)
objDatabaseLbl.grid(row=6, column=1, sticky=tk.E)
objDatabaseText.grid(row=6, column=2)
objDBUserLbl.grid(row=7, column=1, sticky=tk.E)
objDBUserText.grid(row=7, column=2)
objDBPassLbl.grid(row=8, column=1, sticky=tk.E)
objDBPassText.grid(row=8, column=2)
objNoteLbl.grid(row=8, column=3, padx=5, sticky=tk.W)
else:
objVaultLbl.grid(row=2, column=1, sticky=tk.E)
objVaultText.grid(row=2, column=2)
objHostLbl.grid(row=3, column=1, sticky=tk.E)
objHostText.grid(row=3, column=2)
objPortLbl.grid(row=4, column=1, sticky=tk.E)
objPortText.grid(row=4, column=2)
objTableLbl.grid(row=5, column=1, sticky=tk.E)
objTableText.grid(row=5, column=2)
objDatabaseLbl.grid(row=6, column=1, sticky=tk.E)
objDatabaseText.grid(row=6, column=2)
objDBUserLbl.grid(row=7, column=1, sticky=tk.E)
objDBUserText.grid(row=7, column=2)
objDBPassLbl.grid(row=8, column=1, sticky=tk.E)
objDBPassText.grid(row=8, column=2)
objNoteLbl.grid(row=8, column=3, padx=5, sticky=tk.W)
def MyTimer():
"""
Part of ShowGUI. Function that handles counting down in the gui
Used by the show value to automatically hide the value after few seconds
Parameters:
nothing
Returns:
nothing
"""
global iTimer
iTimer -= 1
objCountdown.grid(row=2, column=1)
objCountdown.config(text="Auto hiding in {} seconds".format(iTimer))
if iTimer < iShowTime/3:
objCountdown.config(bg="pink", fg="black")
if btnShow.cget("text") == "Hide":
objMainWin.after(1000, MyTimer)
else:
objCountdown.config(text="", bg="lightgreen", fg="black")
objCountdown.grid_remove()
def Login():
"""
Part of ShowGUI. Function that make login fields visible
Parameters:
nothing
Returns:
nothing
"""
btnLogin.grid_remove
objPWDNote.grid_remove()
objPWDLabel.grid(row=0, column=6, padx=20)
objPWDText.grid(row=1, column=6, padx=20)
objPWDText.delete(0, tk.END)
objPWDText.insert(0, strPWD)
btnAuth.grid(row=2, column=6, padx=20)
def Auth():
"""
Part of ShowGUI. Function that collects the login info
and passess it to the userlogin function in main code
then hides the login fields if successful
Parameters:
nothing
Returns:
nothing
"""
if objPWDText.get() == "":
return
objPWDLabel.grid_remove()
objPWDText.grid_remove()
btnAuth.grid_remove()
if btnAuth.cget("text") == "Authenticate":
global strPWD
objPWDNote.grid(row=0, column=6)
strPWD = objPWDText.get()
if (UserLogin()):
objPWDNote.config(bg="lightgreen", fg="black", text="Logged in")
else:
objPWDNote.config(bg="pink", fg="black", text="Invalid Password")
elif btnAuth.cget("text") == "Change":
if(ChangePWD(objPWDText.get())):
strMsg = "Password change successful"
else:
strMsg = ("Password changed failed on {} of {} entries. "
"The following keys failed {}".format(
len(lstFailed), len(lstVault), (lstFailed)))
objMsg1.config(text=strMsg)
btnAuth.config(text="Authenticate")
btnChgPwd.grid(row=3, column=6, padx=0)
Auth()
else:
mb.showerror("Unexpected", "I have no idea how to deal with btnAuth having a text of {}".format(
btnAuth.cget("text")))
def CopyValue():
"""
Part of ShowGUI. Function that fetches value, decrypts it and places it on the clipboard.
Parameters:
nothing
Returns:
nothing
"""
lstSel = objItemsLB.curselection()
if len(lstSel) > 0:
strSel = objItemsLB.get(lstSel[0])
strValue = FetchItem(strSel)
objMainWin.clipboard_clear()
objMainWin.clipboard_append(strValue)
else:
strMsg = "Please select a value"
objMsg1.config(text=strMsg)
def ShowValue():
"""
Part of ShowGUI. Function that fetches value, decrypts it
and writes it in the right field on the window.
Parameters:
nothing
Returns:
nothing
"""
global iTimer
global objHide
if btnShow.cget("text") == "Show":
lstSel = objItemsLB.curselection()
if len(lstSel) > 0:
strSel = objItemsLB.get(lstSel[0])
strValue = FetchItem(strSel)
if strValue == False:
strValue = "Failed to fetch value"
objValueText.delete(0, tk.END)
objValueText.insert(0, strValue)
else:
strSel = "nothing"
btnAdd.config(text="Update")
btnShow.config(text="Hide")
objKeyText.delete(0, tk.END)
objKeyText.insert(0, strSel)
objValueText.config(show="")
if bAutoHide:
iTimer = iShowTime
objMainWin.after(1000, MyTimer)
objHide = objMainWin.after(iShowTime*1000, ShowValue)
else:
objMsg1.config(text=strMsg)
btnShow.config(text="Show")
btnAdd.config(text="Add")
objKeyText.delete(0, tk.END)
objValueText.delete(0, tk.END)
if bHideValueIn:
objValueText.config(show="*")
objCountdown.grid_remove()
objMainWin.after_cancel(objHide)
iTimer = 0
def ShTOTP():
"""
Part of ShowGUI. Function that fetches TOTP secret, decrypts it,
calculated the TOTP number and writes it in the right field on the window.
Parameters:
nothing
Returns:
nothing
"""
lstSel = objItemsLB.curselection()
if len(lstSel) > 0:
strSel = objItemsLB.get(lstSel[0])
else:
objCountdown.config(text="Please select a key!!")
objCountdown.config(bg="pink", fg="black")
objCountdown.grid(row=2, column=1)
return
strCode = ShowTOTP(strSel)
objCountdown.grid(row=2, column=1)
objCountdown.config(text="Your TOTP Code is: {}".format(strCode))
objCountdown.config(bg="lightgreen", fg="black")
objMainWin.clipboard_clear()
objMainWin.clipboard_append(strCode)
if bAutoHide:
objMainWin.after(iShowTime*1000, ClearTOTP)
def ClearTOTP():
"""
Part of ShowGUI. Function that clears the TOTP value from the screen
Parameters:
nothing
Returns:
nothing
"""
objCountdown.config(text="")
objCountdown.grid_remove()
def AddKey():
"""
Part of ShowGUI. Function that collects new key details from the UI
and passess it to the right functions in the main code.
Parameters:
nothing
Returns:
nothing
"""
bCont = True
bUpdate = False
strKey = objKeyText.get()
strValue = objValueText.get()
if strKey in lstVault and btnAdd.cget("text") == "Add":
strResp = mb.askquestion("Overwrite entry","key {} already exists. Overwrite it?".format(strKey))
if strResp != "yes":
bCont = False
bUpdate = True
if btnAdd.cget("text") == "Update" or strKey in lstVault:
bUpdate= True
if not bLoggedIn:
bCont = False
objMsg1.config(text="You are not logged in")
if bCont:
if AddItem(strKey, strValue, False):
lstVault.append(strKey)
strMsg ="key {} successfully created or updated".format(strKey)
if not bUpdate:
objItemsLB.insert(tk.END, strKey)
strLBCount = "There are {} entries".format(objItemsLB.size())
objLBMsg.config(text=strLBCount)
objKeyText.delete(0, tk.END)
objValueText.delete(0, tk.END)
else:
strMsg ="Failed to create key {}".format(strKey)
objMsg1.config(text=strMsg)
def ChgPWD():
"""
Part of ShowGUI. Function that handles collecting new password
and calls the right functions in the main code
Parameters:
nothing
Returns:
nothing
"""
objPWDLabel.config(text="New Password")
Login()
objPWDText.delete(0, tk.END)
btnAuth.config(text="Change")
btnChgPwd.grid_remove()
def ItemDel():
"""
Part of ShowGUI. Function that deletes the selected value
Parameters:
nothing
Returns:
nothing
"""
lstSel = objItemsLB.curselection()
if len(lstSel) > 0:
strSel = objItemsLB.get(lstSel[0])
if (DelItem(strSel)):
strMsg = "Deleted {} successfully".format(strSel)
objItemsLB.delete(lstSel)
strLBCount = "There are {} entries".format(objItemsLB.size())
objLBMsg.config(text=strLBCount)
else:
strMsg = "Deleting {} failed".format(strSel)
else:
strMsg = "Please select a key to delete"
objMsg1.config(text=strMsg)
def DBWipe():
"""
Part of ShowGUI. Function that wipes the current database clean
Parameters:
nothing
Returns:
nothing
"""
strReponse = mb.askquestion(
"Wipe the database", "Are you sure you want to completely nuke the database? \nTHIS ACTION IS IRREVERSABLE")
if strReponse == "yes":
ResetStore()
objMainWin.destroy()
def GUILayout():
"""
Part of ShowGUI. Main window layout function
Parameters:
nothing
Returns:
nothing
"""
global objMainWin
global objCountdown
global btnShow
global btnLogin
global objPWDNote
global objPWDLabel
global objPWDText
global btnAuth
global objItemsLB
global objMsg1
global objValueText
global btnAdd
global objKeyText
global strMsg
global objLBMsg
global btnChgPwd
objMainWin = tk.Tk()
objMainWin.title("PiVault")
iWidth = 670
iHeight = 320
ixMargin = 50
iyMargin = 50
iScreenW = objMainWin.winfo_screenwidth()
iScreenH = objMainWin.winfo_screenheight()
ixMargin = int(iScreenW/2 - iWidth/2)
iyMargin = int(iScreenH/2 - iHeight/2)
objMainWin.attributes("-alpha", 0.95)
objMainWin.resizable(width=False, height=False)
objMainWin.geometry(
"{}x{}+{}+{}".format(iWidth, iHeight, ixMargin, iyMargin))
objMenu = tk.Menu(objMainWin)
objMainWin.config(menu=objMenu)
objFileMenu = tk.Menu(objMenu,tearoff=False)
objFileMenu.add_command(label="Preferences",command=Config)
objFileMenu.add_separator()
objFileMenu.add_command(label="Exit",command=objMainWin.destroy)
objMenu.add_cascade(label="File", menu=objFileMenu)
objDBmenu = tk.Menu(objMenu,tearoff=False)
objDBmenu.add_command(label="Nuke the database",command=DBWipe)
objMenu.add_cascade(label="DataBase",menu=objDBmenu)
btnAdd = tk.Button(objMainWin, text="Add", width=8,
height=1, command=AddKey)
btnAdd.grid(row=0, column=3, rowspan=2, padx=10)
btnShow = tk.Button(objMainWin, text="Show", width=8,
height=1, command=ShowValue)
btnShow.grid(row=2, column=3, padx=10)
btnCopy = tk.Button(objMainWin, text="Copy", width=8,
height=1, command=CopyValue)
btnCopy.grid(row=3, column=3, padx=10)
btnTOTP = tk.Button(objMainWin, text="TOTP", width=8,
height=1, command=ShTOTP)
btnTOTP.grid(row=4, column=3, padx=10)
btnLogin = tk.Button(objMainWin, text="Login", width=8,
height=1, command=Login)
btnLogin.grid(row=2, column=6, padx=45)
btnAuth = tk.Button(objMainWin, text="Authenticate", width=10,
height=1, command=Auth)
btnChgPwd = tk.Button(objMainWin, text="Change Password", width=15,
height=1, command=ChgPWD)
btnChgPwd.grid(row=3, column=6, padx=0)
btnDel = tk.Button(objMainWin, text="Delete", width=8,
height=1, command=ItemDel)
btnDel.grid(row=5, column=3, padx=10)
objPWDLabel = tk.Label(objMainWin, text="Please enter your password")
objPWDText = tk.Entry(objMainWin, width=25, show="*")
tk.Label(objMainWin, text="Key").grid(row=0, column=0, padx=10, sticky=tk.E)
tk.Label(objMainWin, text="Value").grid(
row=1, column=0, padx=10, sticky=tk.E)
objKeyText = tk.Entry(objMainWin, width=50)
objKeyText.grid(row=0, column=1)
objValueText = tk.Entry(objMainWin, width=50)
if bHideValueIn:
objValueText.config(show="*")
objValueText.grid(row=1, column=1)
objSB_Items = tk.Scrollbar(objMainWin)
objSB_Items.grid(row=3, column=2, rowspan=6, sticky=tk.NS)
objItemsLB = tk.Listbox(objMainWin, yscrollcommand=objSB_Items.set, width=50)
for strItem in lstVault:
if strItem != strCheckKey:
objItemsLB.insert(tk.END, strItem)
objItemsLB.grid(row=3, column=1, rowspan=6)
objSB_Items.config(command=objItemsLB.yview)
strMsg = "Welcome to the PiVault GUI, a simple secrets vault encrytping with AES-256 using MODE_CBC"
strMsg += "\nThis is running under Python Version {} ".format(strVersion)
strMsg += "using {} ".format(strStore)
if strStore != "files":
strMsg += "on {}".format(FetchEnv("HOST"))
objMsg1 = tk.Message(objMainWin, text=strMsg, width=iWidth-50)
objMsg1.config(bg="lightblue", fg="black")
objMsg1.place(x=20, y=iHeight - 50)
objPWDNote = tk.Message(objMainWin, text="Please Log in", width=400)
objPWDNote.config(bg="pink", fg="black")
objPWDNote.grid(row=0, column=6)
strLBCount = "There are {} entries".format(objItemsLB.size())
objLBMsg = tk.Message(objMainWin, width=150, bg="white",
fg="black", text=strLBCount)
objLBMsg.grid(column=1,row=9,sticky=tk.W)
objCountdown = tk.Message(objMainWin, text="", width=200)
objCountdown.config(bg="lightgreen", fg="black")
if strPWD != "":
objPWDText.delete(0, tk.END)
objPWDText.insert(0, strPWD)
Auth()
if os.path.isfile(strICOFile):
objMainWin.iconbitmap(strICOFile)
else:
binIco = b'AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAABeOREAAAAAAMTExAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEiIiIiIiIiESIiICIgIiIRIiIgIiAiIhEiIiAiICIiESIiICIgIiIRIiAgIiAiIhEiIgAAAAIiESIiIiIiICIREiIiIiIiIRERIRERERIREREhEREREhERESERERESERERIRERERIREREhEREREhERESERERESEREREiIiIiERGAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAMADAADv9wAA7/cAAO/3AADv9wAA7/cAAO/3AADwDwAA'
objFileOut = open(strICOFile, "wb")
objFileOut.write(base64.b64decode(binIco))
objFileOut.close()
objMainWin.iconbitmap(strICOFile)
objMainWin.mainloop()
GUILayout()
def PrepConfig ():
"""
Function that Creates a dictionary of configuration items
for use by the configuration file creator
Parameters:
nothing
Returns:
dictionary object of all configuration items.
"""
dictConfFile = {}
dictConfFile["CLIPPYENABLE"] = FetchEnv("CLIPPYENABLE")
dictConfFile["DB"] = FetchEnv("DB")
dictConfFile["DBPWD"] = FetchEnv("DBPWD")
dictConfFile["DBUSER"] = FetchEnv("DBUSER")
dictConfFile["HIDEINPUT"] = FetchEnv("HIDEINPUT")
dictConfFile["HOST"] = FetchEnv("HOST")
dictConfFile["PORT"] = FetchEnv("PORT")
dictConfFile["STORE"] = strStore
dictConfFile["TABLE"] = FetchEnv("TABLE")
dictConfFile["TOTPENABLE"] = FetchEnv("TOTPENABLE")
dictConfFile["VALUECOLOR"] = FetchEnv("VALUECOLOR")
dictConfFile["VAULT"] = strVault
return dictConfFile
def CreateConfig(dictOut):
"""
Function that Creates a configuration file that can be customized
then used instead of environment variables
Parameters:
dictOut: Dictionary object of configuration items
Returns:
tru/false indicating success of failure
"""
tmpResponse = GetFileHandle(strConf_File, "w")
if isinstance(tmpResponse, str):
print(tmpResponse)
return False
else:
objFileOut = tmpResponse
objFileOut.write("CLIPPYENABLE={}\n".format(dictOut["CLIPPYENABLE"]))
objFileOut.write("DB={}\n".format(dictOut["DB"]))
objFileOut.write("DBPWD={}\n".format(dictOut["DBPWD"]))
objFileOut.write("DBUSER={}\n".format(dictOut["DBUSER"]))
objFileOut.write("HIDEINPUT={}\n".format(dictOut["HIDEINPUT"]))
objFileOut.write("HOST={}\n".format(dictOut["HOST"]))
objFileOut.write("PORT={}\n".format(dictOut["PORT"]))
objFileOut.write("STORE={}\n".format(dictOut["STORE"]))
objFileOut.write("TABLE={}\n".format(dictOut["TABLE"]))
objFileOut.write("TOTPENABLE={}\n".format(dictOut["TOTPENABLE"]))
objFileOut.write("VALUECOLOR={}\n".format(dictOut["VALUECOLOR"]))
objFileOut.write("VAULT={}\n".format(dictOut["VAULT"]))
objFileOut.close()
return True
def processConf(strConf_File):
"""
Function that processes a configuration file that can be customized
then used instead of environment variables
Parameters:
nothing
Returns:
Nothing
"""
MsgOut("Looking for configuration file: {}".format(strConf_File))
if os.path.isfile(strConf_File):
MsgOut("Configuration File exists")
else:
MsgOut("Can't find configuration file {}, make sure it is the same directory "
"as this script and named the same with ini extension".format(strConf_File))
sys.exit(9)
strLine = " "
dictConfig = {}
MsgOut("Reading in configuration")
objINIFile = open(strConf_File, "r")
strLines = objINIFile.readlines()
objINIFile.close()
for strLine in strLines:
strLine = strLine.strip()
iCommentLoc = strLine.find("#")
if iCommentLoc > -1:
strLine = strLine[:iCommentLoc].strip()
else:
strLine = strLine.strip()
if "=" in strLine:
strConfParts = strLine.split("=")
strVarName = strConfParts[0].strip()
strValue = strConfParts[1].strip()
dictConfig[strVarName] = strValue
if strVarName == "include":
MsgOut("Found include directive: {}".format(strValue))
strValue = strValue.replace("\\", "/")
if strValue[:1] == "/" or strValue[1:3] == ":/":
MsgOut("include directive is absolute path, using as is")
else:
strValue = strBaseDir + strValue
MsgOut("include directive is relative path,"
" appended base directory. {}".format(strValue))
if os.path.isfile(strValue):
MsgOut("file is valid")
objINIFile = open(strValue, "r")
strLines += objINIFile.readlines()
objINIFile.close()
else:
MsgOut("invalid file in include directive")
MsgOut("Done processing configuration, moving on")
return dictConfig
def isInt(CheckValue):
"""
Function checks if a value is an integer
Parameters:
CheckValue: String to be evaluated
Returns:
true/false
"""
if isinstance(CheckValue, int):
return True
elif isinstance(CheckValue, str):
if CheckValue.isnumeric():
return True
else:
return False
else:
return False
def isFloat(fValue):
"""
Function checks if a value is a floating point number
Parameters:
fValue: String to be evaluated
Returns:
true/false
"""
if isinstance(fValue, (float, int, str)):
try:
fTemp = float(fValue)
except ValueError:
fTemp = "NULL"
else:
fTemp = "NULL"
return fTemp != "NULL"
def DBClean(strText):
"""
Function that removes undesirables from a string to prevent SQL injection
Parameters:
strText: String to be cleaned
Returns:
Clean string that is safe to send to database query
"""
if strText.strip() == "":
return "NULL"
elif isInt(strText):
return strText # int(strText)
elif isFloat(strText):
return strText # float(strText)
else:
strTemp = strText.encode("ascii", "ignore")
strTemp = strTemp.decode("ascii", "ignore")
strTemp = strTemp.replace("\\", "")
strTemp = strTemp.replace("'", "")
strTemp = strTemp.replace(";", "")
return strTemp
def DBConnect(*, DBType, Server, DBUser="", DBPWD="", Database=""):
"""