termvault 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- termvault/__init__.py +3 -0
- termvault/cli.py +397 -0
- termvault/clipboard.py +72 -0
- termvault/crypto.py +78 -0
- termvault/passphrase.py +37 -0
- termvault/vault.py +232 -0
- termvault/wordlist.txt +7776 -0
- termvault-0.1.1.dist-info/METADATA +158 -0
- termvault-0.1.1.dist-info/RECORD +12 -0
- termvault-0.1.1.dist-info/WHEEL +4 -0
- termvault-0.1.1.dist-info/entry_points.txt +2 -0
- termvault-0.1.1.dist-info/licenses/LICENSE +21 -0
termvault/__init__.py
ADDED
termvault/cli.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
"""The `vault` command.
|
|
2
|
+
|
|
3
|
+
vault init create a new vault
|
|
4
|
+
vault add NAME generate (or type) a password and save it
|
|
5
|
+
vault get NAME copy a password to the clipboard
|
|
6
|
+
vault list show the names of saved entries
|
|
7
|
+
|
|
8
|
+
The vault lives at ~/.termvault/vault.json unless the TERMVAULT_PATH
|
|
9
|
+
environment variable says otherwise.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import getpass
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import pyperclip
|
|
20
|
+
|
|
21
|
+
from .passphrase import generate as generate_passphrase
|
|
22
|
+
from .vault import VaultError
|
|
23
|
+
from .vault import create as create_vault
|
|
24
|
+
from .vault import load as load_vault
|
|
25
|
+
from .vault import save as save_vault
|
|
26
|
+
from .clipboard import DEFAULT_CLEAR_AFTER, schedule_clear
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class DataWithSuccess:
|
|
31
|
+
success: bool
|
|
32
|
+
data: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
MASTER_PASSWORD_PROMPT = "Master password for your vault: "
|
|
36
|
+
CANNOT_OPEN_MESSAGE = "Wrong master password (or the vault file is damaged)."
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def vault_path() -> Path:
|
|
40
|
+
return Path(os.environ.get("TERMVAULT_PATH", Path.home() / ".termvault" / "vault.json"))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def error(message: str) -> int:
|
|
44
|
+
"""Print an error message to stderr and return the exit code for failure."""
|
|
45
|
+
print(message, file=sys.stderr)
|
|
46
|
+
return 1
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _copy_to_clipboard(password: str, clear: bool) -> str:
|
|
50
|
+
"""Copy `password` to the clipboard and, unless `clear` is False, schedule
|
|
51
|
+
it to be cleared. Returns a sentence describing what happened."""
|
|
52
|
+
pyperclip.copy(password)
|
|
53
|
+
if not clear:
|
|
54
|
+
return "It will stay on the clipboard until you copy something else."
|
|
55
|
+
schedule_clear(password)
|
|
56
|
+
return f"It will be cleared in {DEFAULT_CLEAR_AFTER} seconds."
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class OpenVault:
|
|
61
|
+
"""An unlocked vault: where it is, the master password that opened it,
|
|
62
|
+
and its entries (name -> password)."""
|
|
63
|
+
|
|
64
|
+
path: Path
|
|
65
|
+
master_password: str
|
|
66
|
+
entries: dict[str, str]
|
|
67
|
+
|
|
68
|
+
def save(self) -> None:
|
|
69
|
+
"""Write the entries back to the vault file. Raises VaultError."""
|
|
70
|
+
save_vault(self.path, self.master_password, self.entries)
|
|
71
|
+
|
|
72
|
+
def change_master_password(self, new_master_password: str) -> None:
|
|
73
|
+
"""Change the master password of the vault."""
|
|
74
|
+
temp_path = self.path.with_suffix(".tmp")
|
|
75
|
+
temp_path.unlink(missing_ok=True)
|
|
76
|
+
try:
|
|
77
|
+
create_vault(temp_path, new_master_password)
|
|
78
|
+
save_vault(temp_path, new_master_password, self.entries)
|
|
79
|
+
except BaseException:
|
|
80
|
+
temp_path.unlink(missing_ok=True)
|
|
81
|
+
raise
|
|
82
|
+
|
|
83
|
+
temp_path.replace(self.path)
|
|
84
|
+
self.master_password = new_master_password
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _open_vault() -> OpenVault | None:
|
|
88
|
+
"""Ask for the master password and unlock the vault.
|
|
89
|
+
|
|
90
|
+
Prints an error and returns None if there's no vault yet, or if it
|
|
91
|
+
can't be opened.
|
|
92
|
+
"""
|
|
93
|
+
path = vault_path()
|
|
94
|
+
|
|
95
|
+
if not path.exists():
|
|
96
|
+
error(f"No vault found at {path}. Run `vault init` to create one.")
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
master_password = getpass.getpass(MASTER_PASSWORD_PROMPT)
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
entries = load_vault(path, master_password)
|
|
103
|
+
except VaultError:
|
|
104
|
+
error(CANNOT_OPEN_MESSAGE)
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
return OpenVault(path, master_password, entries)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
111
|
+
path = vault_path()
|
|
112
|
+
|
|
113
|
+
if path.exists():
|
|
114
|
+
return error(f"A vault already exists at {path}.")
|
|
115
|
+
|
|
116
|
+
master_password_result = _get_master_password(
|
|
117
|
+
args, "Choose a master password for your new vault: ", "Nothing was created.")
|
|
118
|
+
if not master_password_result.success:
|
|
119
|
+
return error(master_password_result.data)
|
|
120
|
+
|
|
121
|
+
master_password = master_password_result.data
|
|
122
|
+
|
|
123
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
create_vault(path, master_password)
|
|
127
|
+
except FileExistsError:
|
|
128
|
+
return error(f"A vault already exists at {path}.")
|
|
129
|
+
|
|
130
|
+
print(f"Created a new vault at {path}.")
|
|
131
|
+
return 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def cmd_add(args: argparse.Namespace) -> int:
|
|
135
|
+
vault = _open_vault()
|
|
136
|
+
if vault is None:
|
|
137
|
+
return 1
|
|
138
|
+
|
|
139
|
+
name = args.name
|
|
140
|
+
|
|
141
|
+
if name in vault.entries:
|
|
142
|
+
return error(f"{name} already exists in the vault.")
|
|
143
|
+
|
|
144
|
+
result = _generate_password(args)
|
|
145
|
+
|
|
146
|
+
if not result.success:
|
|
147
|
+
return error(result.data)
|
|
148
|
+
|
|
149
|
+
if not result.data:
|
|
150
|
+
return error("Failed to generate a new password.")
|
|
151
|
+
|
|
152
|
+
passphrase = result.data
|
|
153
|
+
|
|
154
|
+
vault.entries[name] = passphrase
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
vault.save()
|
|
158
|
+
except VaultError:
|
|
159
|
+
return error("Couldn't save the vault: the file may have been changed or damaged.")
|
|
160
|
+
|
|
161
|
+
clipboard_note = _copy_to_clipboard(passphrase, clear=not args.no_clear)
|
|
162
|
+
print(
|
|
163
|
+
f"Added {name} and copied its password to the clipboard. {clipboard_note}")
|
|
164
|
+
return 0
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def cmd_get(args: argparse.Namespace) -> int:
|
|
168
|
+
vault = _open_vault()
|
|
169
|
+
if vault is None:
|
|
170
|
+
return 1
|
|
171
|
+
|
|
172
|
+
name: str = args.name
|
|
173
|
+
|
|
174
|
+
if name not in vault.entries:
|
|
175
|
+
return error(f"{name} isn't in the vault. Run `vault list` to see what is.")
|
|
176
|
+
|
|
177
|
+
passphrase = vault.entries[name]
|
|
178
|
+
clipboard_note = _copy_to_clipboard(passphrase, clear=not args.no_clear)
|
|
179
|
+
print(f"Copied {name}'s password to the clipboard. {clipboard_note}")
|
|
180
|
+
return 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
184
|
+
vault = _open_vault()
|
|
185
|
+
if vault is None:
|
|
186
|
+
return 1
|
|
187
|
+
|
|
188
|
+
if not vault.entries:
|
|
189
|
+
print("The vault is empty. Add a password with `vault add NAME`.")
|
|
190
|
+
return 0
|
|
191
|
+
|
|
192
|
+
for name in sorted(vault.entries):
|
|
193
|
+
print(name)
|
|
194
|
+
|
|
195
|
+
return 0
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def cmd_remove(args: argparse.Namespace) -> int:
|
|
199
|
+
|
|
200
|
+
vault = _open_vault()
|
|
201
|
+
if vault is None:
|
|
202
|
+
return 1
|
|
203
|
+
|
|
204
|
+
name: str = args.name
|
|
205
|
+
|
|
206
|
+
if name not in vault.entries:
|
|
207
|
+
return error(f"{name} isn't in the vault. Run `vault list` to see what is.")
|
|
208
|
+
|
|
209
|
+
if not args.yes:
|
|
210
|
+
confirm = input(f"Are you sure you want to remove {name}? [y/N] ")
|
|
211
|
+
if confirm.lower() != "y":
|
|
212
|
+
print("Aborted.")
|
|
213
|
+
return 0
|
|
214
|
+
|
|
215
|
+
del vault.entries[name]
|
|
216
|
+
|
|
217
|
+
try:
|
|
218
|
+
vault.save()
|
|
219
|
+
except VaultError:
|
|
220
|
+
return error("Couldn't save the vault: the file may have been changed or damaged.")
|
|
221
|
+
|
|
222
|
+
print(f"Removed {name} from the vault.")
|
|
223
|
+
return 0
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cmd_edit(args: argparse.Namespace) -> int:
|
|
227
|
+
|
|
228
|
+
vault = _open_vault()
|
|
229
|
+
if vault is None:
|
|
230
|
+
return 1
|
|
231
|
+
|
|
232
|
+
name: str = args.name
|
|
233
|
+
|
|
234
|
+
if name not in vault.entries:
|
|
235
|
+
return error(f"{name} isn't in the vault. Run `vault list` to see what is.")
|
|
236
|
+
|
|
237
|
+
if not args.yes:
|
|
238
|
+
confirm = input(f"Are you sure you want to edit {name}? [y/N] ")
|
|
239
|
+
if confirm.lower() != "y":
|
|
240
|
+
print("Aborted.")
|
|
241
|
+
return 0
|
|
242
|
+
|
|
243
|
+
result = _generate_password(args)
|
|
244
|
+
|
|
245
|
+
if not result.success:
|
|
246
|
+
return error(result.data)
|
|
247
|
+
|
|
248
|
+
passphrase = result.data
|
|
249
|
+
|
|
250
|
+
vault.entries[name] = passphrase
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
vault.save()
|
|
254
|
+
print(f"Updated {name} in the vault.")
|
|
255
|
+
except VaultError:
|
|
256
|
+
return error("Couldn't save the vault: the file may have been changed or damaged.")
|
|
257
|
+
|
|
258
|
+
clipboard_note = _copy_to_clipboard(passphrase, clear=not args.no_clear)
|
|
259
|
+
print(
|
|
260
|
+
f"Edited {name} and copied its password to the clipboard. {clipboard_note}")
|
|
261
|
+
|
|
262
|
+
return 0
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def cmd_passwd(args: argparse.Namespace) -> int:
|
|
266
|
+
vault = _open_vault()
|
|
267
|
+
|
|
268
|
+
if vault is None:
|
|
269
|
+
return 1
|
|
270
|
+
|
|
271
|
+
if not args.yes:
|
|
272
|
+
confirm = input(
|
|
273
|
+
f"Are you sure you want to change the master password? [y/N] ")
|
|
274
|
+
if confirm.lower() != "y":
|
|
275
|
+
print("Aborted.")
|
|
276
|
+
return 0
|
|
277
|
+
|
|
278
|
+
new_master_password_result = _get_master_password(
|
|
279
|
+
args, "New master password: ", "The master password wasn't changed.")
|
|
280
|
+
|
|
281
|
+
if not new_master_password_result.success:
|
|
282
|
+
return error(new_master_password_result.data)
|
|
283
|
+
|
|
284
|
+
new_master_password = new_master_password_result.data
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
vault.change_master_password(new_master_password)
|
|
288
|
+
print("Master password changed successfully.")
|
|
289
|
+
except VaultError:
|
|
290
|
+
return error("Couldn't save the vault: the file may have been changed or damaged.")
|
|
291
|
+
|
|
292
|
+
return 0
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
296
|
+
parser = argparse.ArgumentParser(
|
|
297
|
+
prog="vault", description="A password manager for your terminal.")
|
|
298
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
299
|
+
|
|
300
|
+
commands.add_parser(
|
|
301
|
+
"init", help="create a new vault").set_defaults(func=cmd_init)
|
|
302
|
+
|
|
303
|
+
add = commands.add_parser("add", help="add a new entry")
|
|
304
|
+
add.add_argument("name")
|
|
305
|
+
add.add_argument("--words", type=int, default=5,
|
|
306
|
+
help="number of words in a generated passphrase")
|
|
307
|
+
add.add_argument("--manual", action="store_true",
|
|
308
|
+
help="type the password yourself")
|
|
309
|
+
add.add_argument("--no-clear", action="store_true",
|
|
310
|
+
help="don't clear the clipboard afterwards")
|
|
311
|
+
add.set_defaults(func=cmd_add)
|
|
312
|
+
|
|
313
|
+
get = commands.add_parser(
|
|
314
|
+
"get", help="copy an entry's password to the clipboard")
|
|
315
|
+
get.add_argument("name")
|
|
316
|
+
get.add_argument("--no-clear", action="store_true",
|
|
317
|
+
help="don't clear the clipboard afterwards")
|
|
318
|
+
get.set_defaults(func=cmd_get)
|
|
319
|
+
|
|
320
|
+
commands.add_parser(
|
|
321
|
+
"list", help="list entry names").set_defaults(func=cmd_list)
|
|
322
|
+
|
|
323
|
+
remove = commands.add_parser(
|
|
324
|
+
"remove", help="remove an entry from the vault")
|
|
325
|
+
remove.add_argument("name")
|
|
326
|
+
remove.add_argument("--yes", action="store_true",
|
|
327
|
+
help="Remove without prompting")
|
|
328
|
+
remove.set_defaults(func=cmd_remove)
|
|
329
|
+
|
|
330
|
+
edit = commands.add_parser(
|
|
331
|
+
"edit", help="edit an entry in the vault")
|
|
332
|
+
edit.add_argument("name")
|
|
333
|
+
edit.add_argument("--yes", action="store_true",
|
|
334
|
+
help="Edit without prompting")
|
|
335
|
+
edit.add_argument("--words", type=int, default=5,
|
|
336
|
+
help="number of words in a generated passphrase")
|
|
337
|
+
edit.add_argument("--manual", action="store_true",
|
|
338
|
+
help="type the password yourself")
|
|
339
|
+
edit.add_argument("--no-clear", action="store_true",
|
|
340
|
+
help="don't clear the clipboard afterwards")
|
|
341
|
+
edit.set_defaults(func=cmd_edit)
|
|
342
|
+
|
|
343
|
+
passwd = commands.add_parser(
|
|
344
|
+
"passwd", help="change the master password of the vault")
|
|
345
|
+
passwd.add_argument("--yes", action="store_true",
|
|
346
|
+
help="Edit without prompting")
|
|
347
|
+
passwd.set_defaults(func=cmd_passwd)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
return parser
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _generate_password(args: argparse.Namespace) -> DataWithSuccess:
|
|
354
|
+
name = args.name
|
|
355
|
+
if not name:
|
|
356
|
+
return DataWithSuccess(success=False, data="Name cannot be empty")
|
|
357
|
+
if args.manual:
|
|
358
|
+
password_1 = getpass.getpass(f"Password for {name}: ")
|
|
359
|
+
|
|
360
|
+
if not password_1:
|
|
361
|
+
return DataWithSuccess(success=False, data="Password cannot be empty")
|
|
362
|
+
|
|
363
|
+
password_2 = getpass.getpass("Type it again to confirm: ")
|
|
364
|
+
|
|
365
|
+
if password_1 != password_2:
|
|
366
|
+
return DataWithSuccess(success=False, data="Passwords do not match")
|
|
367
|
+
|
|
368
|
+
passphrase = password_1
|
|
369
|
+
else:
|
|
370
|
+
try:
|
|
371
|
+
passphrase = generate_passphrase(args.words)
|
|
372
|
+
except ValueError:
|
|
373
|
+
return DataWithSuccess(success=False, data="Unable to generate passphrase")
|
|
374
|
+
return DataWithSuccess(success=True, data=passphrase)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _get_master_password(args: argparse.Namespace, prompt: str, nothing_happened: str) -> DataWithSuccess:
|
|
378
|
+
master_password_1 = getpass.getpass(prompt)
|
|
379
|
+
|
|
380
|
+
if not master_password_1:
|
|
381
|
+
return DataWithSuccess(success=False, data="The master password can't be empty")
|
|
382
|
+
|
|
383
|
+
master_password_2 = getpass.getpass("Type it again to confirm: ")
|
|
384
|
+
|
|
385
|
+
if master_password_1 != master_password_2:
|
|
386
|
+
return DataWithSuccess(success=False, data=f"The passwords didn't match. {nothing_happened}")
|
|
387
|
+
|
|
388
|
+
return DataWithSuccess(success=True, data=master_password_1)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def main(argv: list[str] | None = None) -> int:
|
|
392
|
+
args = build_parser().parse_args(argv)
|
|
393
|
+
return args.func(args)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
if __name__ == "__main__":
|
|
397
|
+
sys.exit(main())
|
termvault/clipboard.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Clearing the clipboard a while after a password is copied.
|
|
2
|
+
|
|
3
|
+
`vault get` copies the password, then calls schedule_clear(). That starts
|
|
4
|
+
this module as a separate background process (python -m termvault.clipboard),
|
|
5
|
+
which waits, then clears the clipboard only if it still holds that password.
|
|
6
|
+
|
|
7
|
+
The background process never sees the password itself, only its SHA-256 hash,
|
|
8
|
+
sent through stdin (not on the command line, where `ps` would show it).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
import pyperclip
|
|
17
|
+
|
|
18
|
+
DEFAULT_CLEAR_AFTER = 30 # seconds
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def fingerprint(text: str) -> str:
|
|
22
|
+
"""The SHA-256 hash of `text`, as a hex string."""
|
|
23
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def should_clear(current_clipboard: str, expected_fingerprint: str) -> bool:
|
|
27
|
+
"""True if the clipboard still holds the password we copied.
|
|
28
|
+
|
|
29
|
+
This is the bit to unit-test: no waiting and no real clipboard needed.
|
|
30
|
+
"""
|
|
31
|
+
return fingerprint(current_clipboard) == expected_fingerprint
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def schedule_clear(password: str, after: int = DEFAULT_CLEAR_AFTER) -> None:
|
|
35
|
+
"""Start the background process that will clear the clipboard later.
|
|
36
|
+
|
|
37
|
+
Returns straight away.
|
|
38
|
+
"""
|
|
39
|
+
proc = subprocess.Popen([sys.executable, "-m", "termvault.clipboard", str(after)],
|
|
40
|
+
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
41
|
+
start_new_session=True)
|
|
42
|
+
|
|
43
|
+
if proc.stdin:
|
|
44
|
+
proc.stdin.write(fingerprint(password).encode())
|
|
45
|
+
proc.stdin.close()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _run_in_background(after: int) -> None:
|
|
49
|
+
"""Wait, then clear the clipboard if it hasn't changed."""
|
|
50
|
+
expected = sys.stdin.read().strip()
|
|
51
|
+
|
|
52
|
+
time.sleep(after)
|
|
53
|
+
|
|
54
|
+
if should_clear(pyperclip.paste(), expected):
|
|
55
|
+
pyperclip.copy("")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
if __name__ == "__main__":
|
|
59
|
+
|
|
60
|
+
if len(sys.argv) < 2:
|
|
61
|
+
print("Usage: python -m termvault.clipboard <seconds>")
|
|
62
|
+
sys.exit(1)
|
|
63
|
+
|
|
64
|
+
number_of_seconds_wrapper = sys.argv[1]
|
|
65
|
+
|
|
66
|
+
if not number_of_seconds_wrapper.isdigit():
|
|
67
|
+
print("Usage: python -m termvault.clipboard <seconds>")
|
|
68
|
+
sys.exit(1)
|
|
69
|
+
|
|
70
|
+
number_of_seconds = int(number_of_seconds_wrapper)
|
|
71
|
+
|
|
72
|
+
_run_in_background(number_of_seconds)
|
termvault/crypto.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Key derivation and encryption.
|
|
2
|
+
|
|
3
|
+
Two building blocks, both from the `cryptography` library:
|
|
4
|
+
|
|
5
|
+
- Argon2id turns the master password and a random salt into a 32-byte key.
|
|
6
|
+
It's deliberately slow and memory-hungry, which makes guessing passwords
|
|
7
|
+
expensive: cryptography.hazmat.primitives.kdf.argon2.Argon2id
|
|
8
|
+
|
|
9
|
+
- AES-256-GCM encrypts the vault with that key. GCM is "authenticated":
|
|
10
|
+
decrypting with the wrong key, or after any byte has been changed,
|
|
11
|
+
raises cryptography.exceptions.InvalidTag instead of returning garbage:
|
|
12
|
+
cryptography.hazmat.primitives.ciphers.aead.AESGCM
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
import secrets
|
|
17
|
+
from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
|
|
18
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
19
|
+
|
|
20
|
+
KEY_LENGTH = 32 # bytes, for AES-256
|
|
21
|
+
SALT_LENGTH = 16 # bytes
|
|
22
|
+
NONCE_LENGTH = 12 # bytes, the standard size for AES-GCM
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class KdfParams:
|
|
27
|
+
"""Argon2id settings. They're saved in the vault file, so the vault can
|
|
28
|
+
always be opened with the settings it was created with."""
|
|
29
|
+
|
|
30
|
+
iterations: int
|
|
31
|
+
lanes: int
|
|
32
|
+
memory_cost: int # in KiB
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# RFC 9106's second recommended option: 3 passes, 4 lanes, 64 MiB of memory.
|
|
36
|
+
DEFAULT_KDF = KdfParams(iterations=3, lanes=4, memory_cost=64 * 1024)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def new_salt() -> bytes:
|
|
40
|
+
"""Return SALT_LENGTH random bytes (use `secrets` or `os.urandom`)."""
|
|
41
|
+
return secrets.token_bytes(SALT_LENGTH)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def derive_key(password: str, salt: bytes, params: KdfParams = DEFAULT_KDF) -> bytes:
|
|
45
|
+
"""Turn the master password into a KEY_LENGTH-byte key with Argon2id.
|
|
46
|
+
|
|
47
|
+
The same password, salt and params must always give the same key.
|
|
48
|
+
"""
|
|
49
|
+
kdf = Argon2id(
|
|
50
|
+
iterations=params.iterations,
|
|
51
|
+
memory_cost=params.memory_cost,
|
|
52
|
+
salt=salt,
|
|
53
|
+
length=KEY_LENGTH,
|
|
54
|
+
lanes=params.lanes
|
|
55
|
+
)
|
|
56
|
+
return kdf.derive(password.encode())
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def encrypt(key: bytes, plaintext: bytes, associated_data: bytes | None = None) -> tuple[bytes, bytes]:
|
|
60
|
+
"""Encrypt with AES-256-GCM and return (nonce, ciphertext).
|
|
61
|
+
|
|
62
|
+
Use a new random NONCE_LENGTH-byte nonce on every call. Reusing a nonce
|
|
63
|
+
with the same key breaks GCM's security.
|
|
64
|
+
|
|
65
|
+
`associated_data` isn't encrypted, but it is authenticated: decrypt() fails
|
|
66
|
+
unless it's given exactly the same bytes. Useful for protecting a header.
|
|
67
|
+
"""
|
|
68
|
+
nonce = secrets.token_bytes(NONCE_LENGTH)
|
|
69
|
+
aesgcm = AESGCM(key)
|
|
70
|
+
ciphertext = aesgcm.encrypt(nonce, plaintext, associated_data)
|
|
71
|
+
return nonce, ciphertext
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def decrypt(key: bytes, nonce: bytes, ciphertext: bytes, associated_data: bytes | None = None) -> bytes:
|
|
75
|
+
"""Reverse encrypt(). Raises cryptography.exceptions.InvalidTag if the key
|
|
76
|
+
is wrong or anything was tampered with."""
|
|
77
|
+
aesgcm = AESGCM(key)
|
|
78
|
+
return aesgcm.decrypt(nonce, ciphertext, associated_data)
|
termvault/passphrase.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Memorable passphrases made from the EFF large wordlist.
|
|
2
|
+
|
|
3
|
+
The wordlist (wordlist.txt) is the EFF's "large wordlist" for passphrases:
|
|
4
|
+
7,776 words, one per line. It's published by the Electronic Frontier
|
|
5
|
+
Foundation under a Creative Commons Attribution licence (CC BY 3.0 US):
|
|
6
|
+
https://www.eff.org/dice
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from importlib.resources import files
|
|
10
|
+
import secrets
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_words() -> list[str]:
|
|
14
|
+
"""Return the 7,776 words in the EFF large wordlist."""
|
|
15
|
+
text = files("termvault").joinpath("wordlist.txt").read_text(encoding="utf-8")
|
|
16
|
+
return text.split()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def generate(words: int = 5, separator: str = "-") -> str:
|
|
20
|
+
"""Return a random passphrase such as "guitar-clever-orbit-pancake-ample".
|
|
21
|
+
|
|
22
|
+
Rules:
|
|
23
|
+
- `words` words, picked independently from the wordlist (repeats allowed).
|
|
24
|
+
- Joined with `separator`.
|
|
25
|
+
- Must use the `secrets` module, never `random`: `random` is predictable.
|
|
26
|
+
- Raise ValueError if `words` is less than 1.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
if words < 1:
|
|
30
|
+
raise ValueError("Number of words must be at least 1")
|
|
31
|
+
|
|
32
|
+
wordlist = load_words()
|
|
33
|
+
|
|
34
|
+
if len(wordlist) == 0:
|
|
35
|
+
raise ValueError("Wordlist is empty")
|
|
36
|
+
|
|
37
|
+
return separator.join(secrets.choice(wordlist) for _ in range(words))
|