-
Notifications
You must be signed in to change notification settings - Fork 1
/
vlt.py
1854 lines (1584 loc) · 81.8 KB
/
vlt.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
# Version used for auto-updater
__version__="1.9.6"
import sys
import os
from base64 import b64encode, b64decode
import hashlib
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from os.path import exists
import pwinput
import colorama
from colorama import init
from colorama import Fore, Back, Style
import zlib
import json
import pwd
import re
import readline
import secrets
import string
import base64
from datetime import datetime
import humanize
import csv
buffer_size = 65536 # 64kb
init()
BLOCK_SIZE = 16
salt = b'\x8a\xfe\x1f\xa7aY}\xa3It=\xc3\xccT\xc8\x94\xc11%w]A\xb7\x87G\xd8\xba\x9e\xf8\xec&\xf0'
PASSWORD_ALPHABET = string.ascii_lowercase + string.digits
PASSWORD_LENGTH = 16
vaultPassword = ""
vaultData = []
configData = []
currentVault = 0
vaultName = ""
ORIGINALCOMMANDS = ['encrypt', 'decrypt', 'exit', 'quit', 'list', 'ls', 'new', 'create', 'append', 'remove', 'addfile', 'passrefresh', 'passcreate', 'printeverything', 'newvault', 'edit', 'clear', 'cls', 'help', 'rename', 'dbencrypt', 'importcsv', 'search', 'searchcontents']
commands = ORIGINALCOMMANDS
RE_SPACE = re.compile('.*\s+$', re.M)
startScreenLogo = """
██╗ ██╗ █████╗ ██╗ ██╗██╗ ████████╗
██║ ██║██╔══██╗██║ ██║██║ ╚══██╔══╝
╚██╗ ██╔╝██╔══██║██║ ██║██║ ██║
╚████╔╝ ██║ ██║╚██████╔╝███████╗██║
╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝
"""
print("Vault version v" + __version__)
# Class to auto-complete the user's input
class Completer(object):
def _listdir(self, root):
"List directory 'root' appending the path separator to subdirs."
res = []
for name in os.listdir(root):
path = os.path.join(root, name)
if os.path.isdir(path):
name += os.sep
res.append(name)
return res
def _complete_path(self, path=None):
"Perform completion of filesystem path."
if not path:
return self._listdir('.')
dirname, rest = os.path.split(path)
tmp = dirname if dirname else '.'
res = [os.path.join(dirname, p)
for p in self._listdir(tmp) if p.startswith(rest)]
# more than one match, or single match which does not exist (typo)
if len(res) > 1 or not os.path.exists(path):
return res
# resolved to a single directory, so return list of files below it
if os.path.isdir(path):
return [os.path.join(path, p) for p in self._listdir(path)]
# exact file match terminates this completion
return [path + ' ']
def complete_extra(self, args):
"Completions for the 'extra' command."
if not args:
return self._complete_path('.')
# treat the last arg as a path and complete it
return self._complete_path(args[-1])
def complete(self, text, state):
"Generic readline completion entry point."
buffer = readline.get_line_buffer()
line = readline.get_line_buffer()
# show all commands
if not line:
return [c + ' ' for c in commands][state]
cmd = line.strip()
if cmd in commands:
impl = getattr(self, 'complete_%s' % cmd)
args = line.split()
if args:
return (impl(args) + [None])[state]
return [cmd + ' '][state]
results = [c + ' ' for c in commands if c.startswith(cmd)] + [None]
return results[state]
# Function to AES encrypt and compress data with a password
def encrypt(data, password):
key = PBKDF2(password, salt, dkLen=32) # Your key that you can encrypt with
cipher = AES.new(key, AES.MODE_CFB) # CFB mode
ciphered_data = cipher.encrypt(data) # Only need to encrypt the data, no padding required for this mode
# Compress ciphered data with zlib
compressed_data = zlib.compress(cipher.iv + ciphered_data)
return compressed_data
# Function to decompress and AES decrypt ciphered data with a password
def decrypt(enc, password):
# Decompress ciphered data with zlib
decompressed_data = zlib.decompress(enc)
# Now to get all the data for decryption:
key = PBKDF2(password, salt, dkLen=32) # Your key that you can decrypt with
iv = decompressed_data[0:16] # read iv from beginning of decompressed data bytes
ciphered_data = decompressed_data[16:len(decompressed_data)] # separate encrypted data from iv
cipher = AES.new(key, AES.MODE_CFB, iv)
original_data = cipher.decrypt(ciphered_data) # Decrypt ciphered data
return original_data
def refreshCommands():
global commands
commands = []
for cc in ORIGINALCOMMANDS:
for h in vaultData['files']:
commands.append(cc+" "+h['title'])
for h in vaultData['files']:
commands.append(h['title'])
def ListToString(l):
strout = ""
for ob in l:
strout += ob
if l.index(ob) < len(l)-1:
strout += "\n"
return strout
###########################################################
# This is the interactive text editor for encrypted files #
###########################################################
# Credit: https://github.com/maksimKorzh/code
import curses
import sys
editedContent = ""
contentToEdit = ""
class Editor:
def __init__(self):
self.screen = curses.initscr()
self.screen.keypad(True)
self.screen.nodelay(1)
self.ROWS, self.COLS = self.screen.getmaxyx()
self.ROWS -= 1
curses.raw()
curses.noecho()
# self.lexers = {"py": PythonLexer, "c": CLexer}
def reset(self):
self.curx = 0
self.cury = 0
self.offx = 0
self.offy = 0
self.buff = []
self.total_lines = 0
self.filename = "Untitled"
self.modified = 0
self.search_results = []
self.search_index = 0
def insert_char(self, c):
self.buff[self.cury].insert(self.curx, c)
self.curx += 1
self.modified += 1
def delete_char(self):
if self.curx:
self.curx -= 1
del self.buff[self.cury][self.curx]
elif self.curx == 0 and self.cury:
oldline = self.buff[self.cury][self.curx :]
del self.buff[self.cury]
self.cury -= 1
self.curx = len(self.buff[self.cury])
self.buff[self.cury] += oldline
self.total_lines -= 1
self.modified += 1
def insert_line(self):
oldline = self.buff[self.cury][self.curx :]
self.buff[self.cury] = self.buff[self.cury][: self.curx]
self.cury += 1
self.curx = 0
self.buff.insert(self.cury, [] + oldline)
self.total_lines += 1
self.modified += 1
def delete_line(self):
if len(self.buff) == 1:
return
try:
del self.buff[self.cury]
self.curx = 0
self.total_lines -= 1
except:
pass
self.modified += 1
if self.cury >= self.total_lines:
self.cury = self.total_lines - 1
def move_cursor(self, key):
row = self.buff[self.cury] if self.cury < self.total_lines else None
if key == curses.KEY_LEFT:
if self.curx != 0:
self.curx -= 1
elif self.cury > 0:
self.cury -= 1
self.curx = len(self.buff[self.cury])
elif key == curses.KEY_RIGHT:
if row is not None and self.curx < len(row):
self.curx += 1
elif (
row is not None
and self.curx == len(row)
and self.cury != self.total_lines - 1
):
self.cury += 1
self.curx = 0
elif key == curses.KEY_UP:
if self.cury != 0:
self.cury -= 1
else:
self.curx = 0
elif key == curses.KEY_DOWN:
if self.cury < self.total_lines - 1:
self.cury += 1
else:
self.curx = len(self.buff[self.cury])
row = self.buff[self.cury] if self.cury < self.total_lines else None
rowlen = len(row) if row is not None else 0
if self.curx > rowlen:
self.curx = rowlen
def skip_word(self, key):
if key == 545:
self.move_cursor(curses.KEY_LEFT)
try:
if self.buff[self.cury][self.curx] != ord(" "):
while self.buff[self.cury][self.curx] != ord(" "):
if self.curx == 0:
break
self.move_cursor(curses.KEY_LEFT)
elif self.buff[self.cury][self.curx] == ord(" "):
while self.buff[self.cury][self.curx] == ord(" "):
if self.curx == 0:
break
self.move_cursor(curses.KEY_LEFT)
except:
pass
if key == 560:
self.move_cursor(curses.KEY_RIGHT)
try:
if self.buff[self.cury][self.curx] != ord(" "):
while self.buff[self.cury][self.curx] != ord(" "):
self.move_cursor(curses.KEY_RIGHT)
elif self.buff[self.cury][self.curx] == ord(" "):
while self.buff[self.cury][self.curx] == ord(" "):
self.move_cursor(curses.KEY_RIGHT)
except:
pass
def scroll_end(self):
while self.cury < self.total_lines - 1:
self.scroll_page(curses.KEY_NPAGE)
def scroll_home(self):
while self.cury:
self.scroll_page(curses.KEY_PPAGE)
def scroll_page(self, key):
count = 0
while count != self.ROWS:
if key == curses.KEY_NPAGE:
self.move_cursor(curses.KEY_DOWN)
if self.offy < self.total_lines - self.ROWS:
self.offy += 1
elif key == curses.KEY_PPAGE:
self.move_cursor(curses.KEY_UP)
if self.offy:
self.offy -= 1
count += 1
def scroll_buffer(self):
if self.cury < self.offy:
self.offy = self.cury
if self.cury >= self.offy + self.ROWS:
self.offy = self.cury - self.ROWS + 1
if self.curx < self.offx:
self.offx = self.curx
if self.curx >= self.offx + self.COLS:
self.offx = self.curx - self.COLS + 1
def print_status_bar(self):
status = "\x1b[7m"
status += self.filename + " - " + str(self.total_lines) + " lines"
status += " modified" if self.modified else " saved"
status += " Ctrl+S | Save Ctrl+Q | Quit "
status += "\x1b[0m"
status += Fore.WHITE + Back.RED + "Not saved"+Style.RESET_ALL if self.modified else Fore.BLACK + Back.GREEN + "Saved"+Style.RESET_ALL
status += "\x1b[7m"
pos = "Row " + str(self.cury + 1) + ", Col " + str(self.curx + 1)
while len(status)-22 < self.COLS - len(pos) + 3:
status += " "
status += pos + " "
status += "\x1b[m"
status += (
"\x1b["
+ str(self.cury - self.offy + 1)
+ ";"
+ str(self.curx - self.offx + 1)
+ "H"
)
status += "\x1b[?25h"
return status
def print_buffer(self):
print_buffer = "\x1b[?25l"
print_buffer += "\x1b[H"
for row in range(self.ROWS):
buffrow = row + self.offy
if buffrow < self.total_lines:
rowlen = len(self.buff[buffrow]) - self.offx
if rowlen < 0:
rowlen = 0
if rowlen > self.COLS:
rowlen = self.COLS
print_buffer += "".join(
[
chr(c)
for c in self.buff[buffrow][self.offx : self.offx + rowlen]
]
)
print_buffer += "\x1b[K"
print_buffer += "\r\n"
return print_buffer
def update_screen(self):
self.scroll_buffer()
print_buffer = self.print_buffer()
status_bar = self.print_status_bar()
sys.stdout.write(print_buffer + status_bar)
sys.stdout.flush()
def resize_window(self):
self.ROWS, self.COLS = self.screen.getmaxyx()
self.ROWS -= 1
self.screen.refresh()
self.update_screen()
def read_keyboard(self):
def ctrl(c):
return (c) & 0x1F
c = -1
while c == -1:
c = self.screen.getch()
if c == ctrl(ord("q")):
return True
# self.exit()
elif c == 9:
[self.insert_char(ord(" ")) for i in range(4)]
elif c == 353:
[self.delete_char() for i in range(4) if self.curx]
# elif c == ctrl(ord("n")):
# self.new_file()
elif c == ctrl(ord("s")):
self.save_file()
elif c == ctrl(ord("f")):
self.search()
elif c == ctrl(ord("g")):
self.find_next()
elif c == ctrl(ord("d")):
self.delete_line()
# elif c == ctrl(ord("t")):
# self.indent()
elif c == curses.KEY_RESIZE:
self.resize_window()
elif c == curses.KEY_HOME:
self.curx = 0
elif c == curses.KEY_END:
self.curx = len(self.buff[self.cury])
elif c == curses.KEY_LEFT:
self.move_cursor(c)
elif c == curses.KEY_RIGHT:
self.move_cursor(c)
elif c == curses.KEY_UP:
self.move_cursor(c)
elif c == curses.KEY_DOWN:
self.move_cursor(c)
elif c == curses.KEY_BACKSPACE:
self.delete_char()
elif c == curses.KEY_NPAGE:
self.scroll_page(c)
elif c == curses.KEY_PPAGE:
self.scroll_page(c)
elif c == 530:
self.scroll_end()
elif c == 535:
self.scroll_home()
elif c == 560:
self.skip_word(560)
elif c == 545:
self.skip_word(545)
elif c == ord("\n"):
self.insert_line()
elif ctrl(c) != c:
self.insert_char(c)
def clear_prompt(self, line):
command_line = "\x1b[" + str(self.ROWS + 1) + ";" + "0" + "H"
command_line += "\x1b[7m" + line
pos = "Row " + str(self.cury + 1) + ", Col " + str(self.curx + 1)
while len(command_line) < self.COLS - len(pos) + 10:
command_line += " "
command_line += pos + " "
command_line += "\x1b[" + str(self.ROWS + 1) + ";" + "9" + "H"
sys.stdout.write(command_line)
sys.stdout.flush()
def command_prompt(self, line):
self.clear_prompt(line)
self.screen.refresh()
word = ""
c = -1
pos = 0
while c != 0x1B:
c = -1
while c == -1:
c = self.screen.getch()
if c == 10:
break
if c == curses.KEY_BACKSPACE:
pos -= 1
if pos < 0:
pos = 0
continue
sys.stdout.write("\b")
sys.stdout.write(" ")
sys.stdout.write("\b")
sys.stdout.flush()
word = word[: len(word) - 1]
if c != curses.KEY_BACKSPACE:
pos += 1
sys.stdout.write(chr(c))
sys.stdout.flush()
word += chr(c)
self.update_screen()
self.screen.refresh()
return word
def indent(self):
indent = self.command_prompt("indent:")
try: # format: [rows] [cols] [+/-]
start_row = self.cury
end_row = self.cury + int(indent.split()[0])
start_col = self.curx
end_col = self.curx + int(indent.split()[1])
dir = indent.split()[2]
try:
char = indent.split()[3]
except:
char = ""
for row in range(start_row, end_row):
for col in range(start_col, end_col):
if dir == "+":
self.buff[row].insert(col, ord(char if char != "" else " "))
if dir == "-":
del self.buff[row][self.curx]
self.modified += 1
except:
pass
def search(self):
self.search_results = []
self.search_index = 0
word = self.command_prompt("search:")
for row in range(len(self.buff)):
buffrow = self.buff[row]
for col in range(len(buffrow)):
if "".join([chr(c) for c in buffrow[col : col + len(word)]]) == word:
self.search_results.append([row, col])
if len(self.search_results):
self.cury, self.curx = self.search_results[self.search_index]
self.search_index += 1
def find_next(self):
if len(self.search_results):
if self.search_index == len(self.search_results):
self.search_index = 0
try:
self.cury, self.curx = self.search_results[self.search_index]
except:
pass
self.search_index += 1
def open_file(self, filecontent):
global editedContent
global editedTitle
self.reset()
print("filecontent: " + editedContent)
content = editedContent.split("\n")
for row in content:
self.buff.append([ord(c) for c in row])
self.buff.append([])
self.filename = editedTitle
self.highlight = False
self.total_lines = len(self.buff)
self.update_screen()
def save_file(self):
global editedContent
# with open(self.filename, "w") as f:
editedContent = ""
for row in self.buff:
editedContent += "".join([chr(c) for c in row])+"\n"
# editedContent = content
# f.write(content)
self.modified = 0
# def new_file(self):
# self.reset()
# self.buff.append([])
# self.total_lines = 1
def exit(self):
curses.endwin()
# sys.exit(0)
def start(self):
self.update_screen()
while True:
if self.read_keyboard() == True:
return
self.update_screen()
def texteditor(stdscr):
editor = Editor()
editor.open_file(contentToEdit)
editor.start()
def editableInput(strinput, title):
global editedContent
global editedTitle
editedContent = strinput
editedTitle = title
curses.wrapper(texteditor)
return editedContent
# import urllib
import urllib.request
import re
from subprocess import call
def compare_versions(vA, vB):
"""
Compares two version number strings
@param vA: first version string to compare
@param vB: second version string to compare
@return negative if vA < vB, zero if vA == vB, positive if vA > vB.
"""
if vA == vB: return 0
def num(s):
if s.isdigit(): return int(s)
return s
splitVA = vA.split(".")
splitVB = vB.split(".")
vaNum = (num(splitVA[0])*100)+(num(splitVA[1])*10)+(num(splitVA[2]))
vbNum = (num(splitVB[0])*100)+(num(splitVB[1])*10)+(num(splitVB[2]))
if vaNum<vbNum: return -1
if vaNum>vbNum: return 1
# Function to get the current version of this script from the server, and prompt
# to update if a newer one is available.
def update(dl_url, force_update=False):
"""
Attempts to download the update url in order to find if an update is needed.
If an update is needed, the current script is backed up and the update is
saved in its place.
"""
# dl the first 256 bytes and parse it for version number
try:
http_stream = urllib.request.urlopen(dl_url)
update_file = str(http_stream.read(256))
http_stream.close()
except (Exception) as e:
print("Unable to retrieve version data: " + str(e))
# print("Error %s: %s" % (errno, strerror))
return
match_regex = re.search(r'__version__ *= *"(\S+)"', update_file)
if not match_regex:
print("No version info could be found")
return
update_version = match_regex.group(1)
if not update_version:
print("Unable to parse version data")
return
if force_update:
print("Forcing update, downloading version %s..." \
% update_version)
else:
cmp_result = compare_versions(__version__, update_version)
# Prompt user if they want to update if it is available
if cmp_result < 0:
print("Newer version v%s available, do you want to update?" % update_version)
while True:
ans = input("Y/n: ")
if ans.upper() == "Y":
break
elif ans.upper() == "N":
print("Skipping update...")
return
if cmp_result < 0:
print("Downloading version %s..." % update_version)
elif cmp_result > 0:
# print("Local version %s newer then available %s, not updating." \
# % (__version__, update_version))
return
else:
print("You have the latest version of Vault.")
return
# dl, backup, and save the updated script
app_path = os.path.realpath(sys.argv[0])
if not os.access(app_path, os.W_OK):
print("Cannot update -- unable to write to %s" % app_path)
dl_path = app_path + ".new"
backup_path = app_path + ".old"
try:
dl_file = open(dl_path, 'wb')
http_stream = urllib.request.urlopen(dl_url)
total_size = None
bytes_so_far = 0
chunk_size = 8192
try:
total_size = int(http_stream.info().getheader('Content-Length').strip())
except:
# The header is improper or missing Content-Length, just download
dl_file.write(http_stream.read())
while total_size:
chunk = http_stream.read(chunk_size)
dl_file.write(chunk)
bytes_so_far += len(chunk)
if not chunk:
break
percent = float(bytes_so_far) / total_size
percent = round(percent*100, 2)
sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" %
(bytes_so_far, total_size, percent))
if bytes_so_far >= total_size:
sys.stdout.write('\n')
http_stream.close()
dl_file.close()
except (Exception) as e:
print("Download failed: " + str(e))
# print("Error %s: %s" % (errno, strerror))
return
try:
os.rename(app_path, backup_path)
except:
print("Unable to rename %s to %s" \
% (app_path, backup_path))
return
try:
os.rename(dl_path, app_path)
except:
print("Unable to rename %s to %s" \
% (dl_path, app_path))
return
try:
import shutil
shutil.copymode(backup_path, app_path)
except:
os.chmod(app_path, 755)
print(Fore.GREEN + "New version installed as %s" % app_path)
print(Fore.GREEN+"(previous version backed up to %s)" % (backup_path))
# Restart script so newer update is the current process
print(Fore.GREEN + "Restarting with newer update..." + Style.RESET_ALL)
print()
arglist = []
arglist.append(sys.argv[0])
os.execl(sys.executable, os.path.abspath(__file__), *arglist)
# Make sure vault is correctly formatted and the newest version
def upgradeVault(jDat):
outJ = json.loads('{"files":[],"version":""}')
# print(json.dumps(jDat, sort_keys=True, indent=4))
# 1.5.0 Update
# This update I started storing the version in the vault file
try:
vv = jDat['version']
outJ['version'] = vv
except:
jDat['version'] = "1.4.0"
outJ['version'] = "1.4.0"
print("vault file version " + jDat['version'])
# 1.5.0 Update
# This checks if the vault is older than the .Json update 1.5.0,
# where I converted each entry to a more organized json object
if compare_versions(jDat['version'], "1.5.0") < 0:
for i, fle in enumerate(jDat['files']):
# If normal entry
if fle.split("\n")[0].__contains__("-=password=") == False:
outJ["files"].append({"title":fle.split("\n")[0],"type":"normal","content":ListToString(fle.split("\n")[1:]),"encryption":"normal"})
# If password entry
else:
outJ["files"].append({"title":fle.split("\n")[0].split("-=password=")[0],"type":"password","content":ListToString(fle.split("\n")[1:]),"encryption":"normal"})
outJ['version'] = "1.5.0" # increase the version, because the file is now updated to at least this version
# Otherwise, the vault is compatable so just load it normally
else:
outJ = jDat
# By this point the version should be the same so just make sure
outJ['version'] = __version__
return outJ
# Make sure vault configuration file is correctly formatted and the newest version
def upgradeConfig(jDat):
outJ = json.loads('{"vaults":[],"version":"","updatedTime":""}')
# 1.6.0 Update
# This update I started storing the version in the config file
try:
vv = jDat['version'] # If the version is accessed then there is no problem
outJ['version'] = vv
except:
jDat['version'] = "0.0.0" # If the version can't be accessed, it could be any version before 1.6.0 so just default to 0
outJ['version'] = "0.0.0"
# If a version cannot be determined, then at least figure out if it is the old vault config format:
try:
v2 = jDat['vault'] # If this test succeeds, then it is the oldest version of the config
jDat['version'] = "0.0.0"
except:
jDat['version'] = "1.0.0" # Otherwise, it is at least version 1 and doesn't need old processing done first
outJ['version'] = "1.0.0"
# 0.0.0 Update
# This checks if the config is older than the update 0.0.0,
# where I started allowing multiple vault paths to be in
# the config file
if compare_versions(jDat['version'], "0.0.0") <= 0:
outJ['vaults'].append(jDat['vault'])
jDat['version'] = "1.0.0"
# Otherwise, the config is compatable so just load it normally
else:
outJ = jDat
# 1.6.1 Update
# This update was when I added date checking to the config and updater
if compare_versions(jDat['version'], "1.6.1") < 0:
try:
oT = jDat['updatedTime']
outJ['updatedTime'] = oT
except:
outJ['updatedTime'] = datetime.now().strftime("%d/%m/%y %H:%M:%S")
jDat['version'] = "1.6.1"
# By this point the version should be the same so just make sure
outJ['version'] = __version__
return outJ
def ListVaultDirectory():
print(Fore.BLACK + Back.GREEN + "Files in Vault: " + Style.RESET_ALL)
print(" "+Fore.BLACK+Back.WHITE+"Title: "+Back.RESET+" " + Back.WHITE+"Type: "+Back.RESET+" " + Back.WHITE+"Encryption Lvl:" + Style.RESET_ALL)
print(" ------------------------- ---------- ---------------")
vaultData['files'] = sorted(vaultData['files'], key=lambda k: k['title'])
for fle in vaultData['files']:
if fle['type'] == "password":
icon = "🔑"
elif fle['type'] == "file":
icon = "💾"
else:
icon = "📝"
encryptionLvl = fle['encryption'] if fle['encryption'] == "double" else "-"
encryptionLvlIcon = "🔐x2" if fle['encryption'] == "double" else " "
print(("{:3s}{:25s} {:10s} {:7s}{:3s}").format(icon, fle['title'], fle['type'], encryptionLvl, encryptionLvlIcon))
print()
try:
# Make sure config folder exists
if os.path.isdir("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault") == False:
os.mkdir("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault")
# Make sure config file exists, if it doesn't then enter setup
if exists("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault/va.conf") == False:
# Prompt user for vault directory
validDirectory = ""
while validDirectory == "":
dir = input("\nEnter directory to store existing or new vaults\n(ex. \"/home/vault/\")\n > ")
if os.path.isdir(dir):
if not (dir.endswith("/") and dir.endswith("\\")):
dir += "/"
validDirectory = os.path.abspath(dir)
else:
print(Fore.RED + "Not a valid directory"+Style.RESET_ALL)
mke = input("\nThis directory does not exist. Create it?\nY/n > ")
if mke.upper() == "Y":
try:
os.mkdirs(dir)
if os.path.isdir(dir):
validDirectory = os.path.abspath(dir)
except OSError as error:
print("Directory '%s' can not be created: %s" % (dir, error))
# Check if any vaults are present in the directory
vaultFiles = []
for filename in os.listdir(validDirectory):
if filename.endswith(".vlt"):
vaultFiles.append(os.path.join(validDirectory, filename))
# If there are no existing vaults, create one
if len(vaultFiles) == 0:
# Prompt user for vault name
nam = input("\nEnter name of new vault\n(ex. \"MyVault\")\n > ")
if len(nam)>0:
if nam.endswith(".vlt"):
validDirectory += "./"+nam
else:
validDirectory += "./"+nam+".vlt"
else:
validDirectory += "./MyVault.vlt"
vaultFiles.append(os.path.abspath(validDirectory))
# Create vault file
passwordAccepted = False
while passwordAccepted == False:
password = pwinput.pwinput(Fore.BLACK + Back.WHITE + "Create vault password: " + Style.RESET_ALL)
confirmedPassword = pwinput.pwinput(Fore.BLACK + Back.WHITE + "Confirm password: " + Style.RESET_ALL)
if password == "":
print(Fore.RED + "Password is invalid")
elif password == confirmedPassword:
passwordAccepted = True
elif password != confirmedPassword:
print(Fore.RED + "Passwords don't match")
dataIn = {'files':[],'version':__version__}
fw = open(os.path.abspath(validDirectory), 'wb')
fw.write(encrypt(bytes(json.dumps(dataIn), "utf-8"), password))
fw.close()
vaultPassword = password
vaultName = nam
vaultData = upgradeVault(dataIn)
data = {'vaults' : vaultFiles, 'version' : __version__, 'updatedTime' : datetime.now().strftime("%d/%m/%y %H:%M:%S")}
with open("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault/va.conf", 'w') as outfile:
json.dump(data, outfile)
with open("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault/va.conf") as json_file:
# Load config file data
configData = upgradeConfig(json.load(json_file))
# Check if the user needs update by comparing last updated time to now
currentTime = datetime.now()
difference = currentTime-datetime.strptime(configData['updatedTime'], "%d/%m/%y %H:%M:%S")
print("Last checked for updates " + Fore.YELLOW+humanize.naturaltime(datetime.now() - difference) + Style.RESET_ALL)
if difference.seconds//3600 >= 3: # If it has been at leat 3 hours since the last update, then try updating again.
print(" Checking now... ")
update("https://raw.githubusercontent.com/sam-astro/vault/main/vlt.py")
configData['updatedTime'] = datetime.now().strftime("%d/%m/%y %H:%M:%S") # Update last time to now
# Save updated config data
with open("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault/va.conf", 'w') as outfile:
json.dump(configData, outfile)
# If there are no arguments specified, enter interactive mode
if len(sys.argv) <= 1:
# List all known vaults, and ask which one the user wants to load
print("\nVaults:")
for i, vaultDir in enumerate(configData['vaults']):
if exists(configData['vaults'][i]):
print(Fore.BLACK + Back.GREEN +"\t" + str(i) + "." + Back.RESET+Fore.GREEN+" " + os.path.basename(vaultDir)+" "+Fore.CYAN+ os.path.dirname(vaultDir)+"/"+ Style.RESET_ALL)
else:
print(Fore.YELLOW + Back.RED +"\t" + str(i) + ". " + os.path.basename(vaultDir) + Style.RESET_ALL + " not found at "+Fore.CYAN+ os.path.dirname(vaultDir)+"/"+ Style.RESET_ALL)
# If the number of vaults is more than 1, ask user which one they want to use this time
if len(configData['vaults'])>1:
valAccepted = False
while valAccepted == False:
g = input("\nWhich vault do you want to load?\n(0-"+str(len(configData['vaults'])-1)+") > ")
try:
ii = int(g)
if ii < len(configData['vaults']) and ii >= 0:
currentVault = ii
valAccepted = True
else:
print(Fore.RED + "Invalid value, please enter valid index" + Style.RESET_ALL)
except:
print(Fore.RED + "Invalid value, please enter valid index" + Style.RESET_ALL)
else:
print("\nYou only have 1 vault file, automatically loading it: " + Fore.GREEN+os.path.basename(configData['vaults'][0])+Fore.RESET)
# If the vault file specified in the config is invalid, ask to create new one
if exists(configData['vaults'][currentVault]) == False:
print("Vault file at '%s' could not be found. Create new one?" % configData['vaults'][currentVault])
cnoA = input("Y/n > ")
if cnoA.upper() == "Y" or cnoA.upper() == "YES":
passwordAccepted = False
while passwordAccepted == False:
vaultPassword = pwinput.pwinput(Fore.BLACK + Back.WHITE + "Create vault password: " + Style.RESET_ALL)
confirmedPassword = pwinput.pwinput(Fore.BLACK + Back.WHITE + "Confirm password: " + Style.RESET_ALL)
if vaultPassword == "":
print(Fore.RED + "Password is invalid")
elif vaultPassword == confirmedPassword:
passwordAccepted = True
elif vaultPassword != confirmedPassword:
print(Fore.RED + "Passwords don't match")
dataIn = {'files':[],'version':__version__}
fw = open(os.path.abspath(configData['vaults'][currentVault]), 'wb')
fw.write(encrypt(bytes(json.dumps(dataIn), "utf-8"), vaultPassword))
fw.close()
vaultName = configData['vaults'][currentVault]
vaultData = upgradeVault(dataIn)
elif cnoA.upper() == "N" or cnoA.upper() == "NO":
print(Fore.YELLOW + "Would you like to remove this vault from your configuration then?" + Style.RESET_ALL)
cnoA = input("Y/n > ")
if cnoA.upper() == "Y" or cnoA.upper() == "YES":
configData['vaults'].remove(configData['vaults'][currentVault])
# Save updated config data
with open("/home/"+pwd.getpwuid(os.getuid()).pw_name+"/vault/va.conf", 'w') as outfile:
json.dump(configData, outfile)
exit()
else:
exit()