-
Notifications
You must be signed in to change notification settings - Fork 0
/
startCzar.py
364 lines (329 loc) · 13.3 KB
/
startCzar.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
import os
from time import time
import threading
import datetime
import shutil
import platform
import ctypes
from hashlib import sha256
import argparse
import logging
from cryptography.exceptions import InvalidTag
from tabulate import tabulate
from more_itertools import chunked_even
from ioUtils.readFromShell import (
readChoice,
readPassId,
readUserName,
readPassword,
readMode,
readBackupFileName,
)
from crypto.aes import encrypt, decrypt, generateSalt, generateKey
from ioUtils.clipboardUtils import copyToClipboard, clearClipboard
from ioUtils.ioUtilities import (
readfromFile,
writetoFile,
deleteFile,
appendToTextFile,
readfromTextFile,
)
from crypto.randomPwd import generatePassword
argParser = argparse.ArgumentParser(description="CZar Password manager CLI startup")
argParser.add_argument(
"-m",
"--mode",
type=str,
dest="cZarMode",
help="CZar startup mode; set (s): to create new password; \
get (g): to retrieve password; del (d): to delete a password; \
export (e): to export a backup compressed file;\
import (i): to import passwords from a backup compressed file.",
default="",
)
# Get arguments from user through CLI
args = argParser.parse_args()
class CZar:
def __init__(self, args):
try:
os.mkdir("Czar_logs")
except FileExistsError:
pass
logging.basicConfig(
filename="Czar_logs/czar.log",
format="%(levelname)s | %(asctime)s | %(message)s",
datefmt="%m/%d/%Y %H:%M",
level=logging.ERROR,
)
self.cZarMode = args.cZarMode.lower()
# Init master key
self.mPassword = readPassword("Master")
# Create data directory
self.dataDir = None
self.currentOS = platform.system()
self.makeDataDirectory()
# generating master key
mSaltFileName = sha256(self.mPassword.encode("utf-8")).hexdigest()
try:
mSalt = readfromFile(mSaltFileName, self.currentOS)
except FileNotFoundError:
mSalt = generateSalt()
writetoFile(mSalt, mSaltFileName, self.currentOS)
self.mKey = generateKey(mSalt, self.mPassword.encode("utf-8"))
self.timerThread = None
def makeDataDirectory(self):
try:
if self.currentOS == "Windows":
self.dataDir = "data"
os.mkdir("data")
ctypes.windll.kernel32.SetFileAttributesW("data", 0x02)
elif self.currentOS == "Linux":
self.dataDir = ".data"
os.mkdir(".data")
except FileExistsError:
pass # Directory already exists
def clipboardTimer(self):
start_time = time()
while time() - start_time < 60:
pass
clearClipboard()
def displayPassIds(self):
# Display list pf IDs.
passIdFile = sha256(self.mKey).hexdigest()
passIdList = readfromTextFile(passIdFile, self.currentOS)
passIdList.sort()
print("Here are lists of saved password IDs")
passIdRows = list(chunked_even(passIdList, 5))
headers = [f"List {i + 1}" for i in range(5)]
print(tabulate(passIdRows, headers=headers, tablefmt="grid"))
def savePassId(self, passId):
passIdFile = sha256(self.mKey).hexdigest()
passIdList = readfromTextFile(passIdFile, self.currentOS)
if passId in passIdList:
return False
else:
appendToTextFile(passId, passIdFile, self.currentOS)
return True
def removePassId(self, passId):
passIdFile = sha256(self.mKey).hexdigest()
passIdList = readfromTextFile(passIdFile, self.currentOS)
if passId in passIdList:
passIdList.remove(passId)
# Delete PassID File and Create a new one.
deleteFile(passIdFile, self.currentOS)
for pId in passIdList:
if len(pId) != 0:
appendToTextFile(pId, passIdFile, self.currentOS)
def savePassword(self):
self.displayPassIds()
print("=== Set/Update Password ===")
# password ID must be unique
passId = readPassId()
updatePassword = False
while not self.savePassId(passId):
print("This Password ID exists.")
if readChoice(f"Do you want to update the password of '{passId}'?") == "y":
updatePassword = True
break
else:
passId = readPassId()
usrName = readUserName(passId)
# Ask user if he wants to get new password
if (
readChoice("Do you want Czar to choose a new secure password for you?")
== "y"
):
password = generatePassword().encode("utf-8")
else:
Password_1 = readPassword(passId).encode("utf-8")
print("Please, re-enter your password")
password_2 = readPassword(passId).encode("utf-8")
if password_2 != Password_1:
print("Error: Passwords don't match ..")
return
password = password_2
baseNonce = sha256(passId.encode("utf-8")).hexdigest()[:24].encode("utf-8")
usrAad = passId.encode("utf-8")
encUsrName, key, nonce = encrypt(
usrName.encode("utf-8"), usrAad, key=self.mKey, nonce=baseNonce
)
passIdHash = sha256(passId.encode("utf-8")).hexdigest()
passNonceString = passIdHash + self.mPassword
passNonce = (
sha256(passNonceString.encode("utf-8")).hexdigest()[:24].encode("utf-8")
)
passAad = (passId + usrName).encode("utf-8")
encPassword, passKey, nonce = encrypt(
password, passAad, key=self.mKey, nonce=passNonce
)
# write data to files
aadHash = sha256(passAad).hexdigest()
if updatePassword:
try:
deleteFile(passIdHash, self.currentOS)
except FileNotFoundError:
logging.error("File I/O Error")
print("Error: Try again!")
return
try:
deleteFile(aadHash, self.currentOS)
except FileNotFoundError:
pass # Username updated
writetoFile(encUsrName, passIdHash, self.currentOS)
writetoFile(encPassword, aadHash, self.currentOS)
print("\nPassword saved successfully!\n")
def getPassword(self):
self.displayPassIds()
print("=== Get Password ===")
# Retrieving password
passId = readPassId()
passIdHash = sha256(passId.encode("utf-8")).hexdigest()
try:
encUsrName = readfromFile(passIdHash, self.currentOS)
except FileNotFoundError:
logging.error("Incorrect Password ID.")
print("Error: Incorrect Input.")
return
# Decrypting username
usrAad = passId.encode("utf-8")
baseNonce = sha256(passId.encode("utf-8")).hexdigest()[:24].encode("utf-8")
try:
usrName = decrypt(self.mKey, encUsrName, usrAad, baseNonce).decode("utf-8")
except InvalidTag:
print("Error: Incorrect Input.")
return
# decrypting password
passAad = (passId + usrName).encode("utf-8")
aadHash = sha256(passAad).hexdigest()
# Read Encrypted password
try:
encPassword = readfromFile(aadHash, self.currentOS)
except FileNotFoundError:
logging.error("Cannot read password file {}".format(aadHash))
print("Error: Something went wrong. Try again!")
return
passIdHash = sha256(passId.encode("utf-8")).hexdigest()
passNonceString = passIdHash + self.mPassword
passNonce = (
sha256(passNonceString.encode("utf-8")).hexdigest()[:24].encode("utf-8")
)
password = decrypt(self.mKey, encPassword, passAad, passNonce)
copyToClipboard(password.decode("utf-8"))
print("Your account username is: {}".format(usrName))
print("\nPassword copied successfully!\n")
def deletePassword(self):
self.displayPassIds()
print("=== Delete Password ===")
passId = readPassId()
if readChoice(f"Are you sure you want to delete '{passId}'?") == "n":
return
passIdHash = sha256(passId.encode("utf-8")).hexdigest()
try:
encUsrName = readfromFile(passIdHash, self.currentOS)
deleteFile(passIdHash, self.currentOS)
except FileNotFoundError:
logging.error("Incorrect Password ID.")
print("Error: Incorrect Input.")
return
# Decrypting username
usrAad = passId.encode("utf-8")
baseNonce = sha256(passId.encode("utf-8")).hexdigest()[:24].encode("utf-8")
try:
usrName = decrypt(self.mKey, encUsrName, usrAad, baseNonce).decode("utf-8")
except InvalidTag:
print("Error: Incorrect Input.")
return
passAad = (passId + usrName).encode("utf-8")
aadHash = sha256(passAad).hexdigest()
# Delete password file
try:
deleteFile(aadHash, self.currentOS)
self.removePassId(passId)
except FileNotFoundError:
logging.error(f"Cannot find password file {aadHash}")
print("Error: Something went wrong. Try again!")
return
print("\nPassword Deleted successfully!\n")
def exportData(self):
currentDateTime = str(datetime.datetime.now()).split(".")[0].replace(":", "").replace(" ", "-")
try:
if self.currentOS == "Windows":
shutil.make_archive(currentDateTime, "zip", self.dataDir)
return currentDateTime + ".zip"
elif self.currentOS == "Linux":
shutil.make_archive(currentDateTime, "gztar", self.dataDir)
return currentDateTime + ".tar.gz"
else:
return None
except Exception:
return None
return None
def importData(self, backupFileName):
shutil.rmtree(self.dataDir + '/')
self.makeDataDirectory()
shutil.unpack_archive(backupFileName, self.dataDir + '/')
def start(self):
stillRunning = True
if self.cZarMode:
mode = self.cZarMode
else:
mode = readMode()
while stillRunning:
if mode in ("set", "s"):
self.savePassword()
if readChoice("Do you want to continue using CZar?") == "n":
stillRunning = False
elif mode in ("get", "g"):
self.getPassword()
self.timerThread = threading.Thread(target=self.clipboardTimer)
self.timerThread.start()
if readChoice("Do you want to continue using CZar?") == "n":
stillRunning = False
elif mode in ("del", "d"):
self.deletePassword()
if readChoice("Do you want to continue using CZar?") == "n":
stillRunning = False
else:
mode = readMode()
elif mode in ("export", "e"):
if readChoice("All encrypted files will be exported to current directory. Continue?") == "y":
fileName = self.exportData()
if fileName is not None:
print(f"***Successful backup saved to: {fileName}")
print("***You should save this file on another secured device.")
else:
print("Error: Unable to save a new backup file")
if readChoice("Do you want to continue using CZar?") == "n":
stillRunning = False
else:
mode = readMode()
elif mode in ("import", "i"):
fileName = readBackupFileName()
if readChoice(f"Password data will be imported from {fileName}. Current data could be lost or replaced. Continue?") == "y":
try:
self.importData(fileName)
print(f"***Successful backup import")
except Exception:
print("Error: Unable to import from backup file")
while readChoice("Shutdown CZar and start it again. Confirm?") == "n":
pass
stillRunning = False
else:
logging.error("Undefined input mode!")
print("Undefined input mode!")
stillRunning = False
# Clear clipboard before shutting down CZar
copyToClipboard("")
logging.info("Shutting down CZar ...")
print("\nShutting down CZar ...")
def main(args):
try:
cZar = CZar(args)
# Start Czar
cZar.start()
except KeyboardInterrupt:
copyToClipboard("")
logging.info("Shutting down CZar ...")
print("\nShutting down CZar ...")
if __name__ == "__main__":
main(args)