-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathciphra.py
More file actions
4860 lines (4399 loc) · 162 KB
/
ciphra.py
File metadata and controls
4860 lines (4399 loc) · 162 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ciphra.py
# CLI entry point for Ciphra.
# Defines click commands: verify, hash, config, completions.
import datetime
import hashlib
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import time
from logging.handlers import RotatingFileHandler
from pathlib import Path
import click
import questionary
from questionary import Style as QStyle
from rich.console import Console
from rich.progress import BarColumn, DownloadColumn, Progress, TransferSpeedColumn
from config import (
ERROR_LOG,
LOG_FOLDER,
SUPPORTED_SIG_EXTENSIONS,
VERSION,
get_config_path,
get_vt_key,
get_vt_tier,
get_vt_upload_limit,
remove_vt_key as _remove_vt_key,
save_credentials,
set_vt_key,
set_vt_tier,
)
from utils.crypto_tools import (
encrypt_file as _crypto_encrypt_file,
decrypt_file as _crypto_decrypt_file,
detect_format as _detect_format,
calibrate_argon2_params,
derive_key,
_read_kdf_params,
)
from utils.gpg_tools import (
GPG_BIN,
gpg_available,
verify_signature,
fetch_gpg_key,
import_and_trust_key,
extract_key_id,
list_encryption_keys,
encrypt_file_asymmetric,
decrypt_file_asymmetric,
get_encrypted_for_key_id,
import_public_key_file,
generate_key_pair,
list_signing_keys,
list_signing_keys_without_encryption_subkey,
list_secret_keys_with_encryption_subkey,
sign_file_detached,
export_public_key,
export_private_key,
add_encryption_subkey,
rotate_encryption_subkey,
extend_subkey_expiry,
verify_key_passphrase,
delete_key_pair,
extend_key_expiry,
)
from utils.hash_tools import compute_hash
from utils.log_tools import write_scan_log, write_operation_log
from utils.verdict_tools import (
compute_verdict,
VERDICT_CLEAN,
VERDICT_FLAGGED,
VERDICT_REVIEW,
VERDICT_LIKELY_SAFE,
VERDICT_UNVERIFIED,
VERDICT_CHECKED,
)
from utils.vt_tools import check_file as vt_check_file
_no_color = os.environ.get("NO_COLOR", "") != ""
console = Console(no_color=_no_color)
ACCENT = "#c9dff0"
GOOD = "#4caf50"
CAUTION = "#e8a838"
BAD = "#e05c5c"
PROGRESS_THRESHOLD = 10 * 1024 * 1024 # 10 MB
_BANNER_SHOWN = False
_IN_OPERATION = False
BANNER_LINES = [
" ██████╗██╗██████╗ ██╗ ██╗██████╗ █████╗ ",
" ██╔════╝██║██╔══██╗██║ ██║██╔══██╗██╔══██╗",
" ██║ ██║██████╔╝███████║██████╔╝███████║",
" ██║ ██║██╔═══╝ ██╔══██║██╔══██╗██╔══██║",
" ╚██████╗██║██║ ██║ ██║██║ ██║██║ ██║",
" ╚═════╝╚═╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝",
]
BANNER_LINES_ASCII = [
" CIPHRA ",
" ------ ",
]
def _supports_unicode() -> bool:
try:
encoding = sys.stdout.encoding or ""
if encoding.lower() in ("ascii", "ansi", ""):
return False
"─".encode(encoding)
return True
except (UnicodeEncodeError, LookupError, AttributeError):
return False
UNICODE_OK = _supports_unicode()
def _translate_error(raw: str, context: str = "") -> str:
if not raw:
return "An unexpected error occurred. Details in logs/ciphra.log."
logging.error("Raw error: %s", raw)
r = raw.lower()
if "no valid" in r:
msg = "That file does not contain a GPG key."
elif "keyserver receive failed: no name" in r:
msg = "Keyserver did not respond."
elif "keyserver receive failed" in r:
msg = "Could not reach the keyserver."
elif "connection timed out" in r or "timed out" in r:
msg = "The request timed out."
elif "http_401" in r:
msg = "API key rejected. Check your key in Configure settings."
elif "http_429" in r:
msg = "Rate limit reached. Free API allows 4 lookups per minute."
elif "http_500" in r or "http_502" in r or "http_503" in r:
msg = "VirusTotal is temporarily unavailable."
elif "http_" in r:
msg = "VirusTotal returned an unexpected error."
elif "network_error" in r:
msg = "No network connection or server did not respond."
elif "not_in_db" in r:
msg = "File not found in VirusTotal database."
elif "file_too_large" in r:
msg = "File is too large to upload. Hash lookup only."
elif "no_key" in r:
msg = "No VirusTotal API key configured."
elif "invalid tag" in r or "invalidtag" in r:
msg = "Wrong password or the file was tampered with."
elif "bad passphrase" in r:
msg = "Wrong passphrase."
elif "no secret key" in r:
msg = "The private key for this file is not in your keyring."
elif "permission denied" in r:
msg = "Permission denied. Check file permissions."
elif "no such file" in r or "file not found" in r:
msg = "File not found."
elif "is a directory" in r:
msg = "That is a folder. Select a file inside it."
elif "unusable public key" in r:
msg = "That key cannot encrypt files. It may be expired, revoked, or signing-only."
elif "key_not_created" in r or "key not created" in r:
msg = "Key generation failed. Check that GPG is correctly installed."
elif "invalid algorithm" in r or "invalid algo" in r:
msg = "Key algorithm not supported by your GPG version."
elif "already exists" in r and "gnupg" in r:
msg = "A key with this identity already exists in your keyring."
elif "signing failed" in r:
msg = "Signing failed. Check your passphrase and try again."
elif "export failed" in r or "nothing exported" in r:
msg = "Export failed. The key may not exist in your keyring."
elif "key not changed" in r or "no update needed" in r:
msg = "No change was made. The expiry date may already be set to that value."
else:
msg = "An unexpected error occurred. Details in logs/ciphra.log."
return f"{context}: {msg}" if context else msg
CIPHRA_STYLE = QStyle([
("qmark", "fg:#c9dff0 bold"),
("question", "fg:#c9dff0 bold"),
("answer", "fg:#c9dff0 bold"),
("pointer", "fg:#c9dff0 bold"),
("highlighted", "fg:#c9dff0 bold"),
("selected", "fg:#ffffff"),
("separator", "fg:#6c6c6c"),
("instruction", "fg:#6c6c6c"),
("text", "fg:#ffffff"),
("disabled", "fg:#6c6c6c italic"),
])
def _outcome_recoverable(msg: str, choices: list[str]) -> str | None:
console.print(f" [{CAUTION}][WARN] {msg}[/{CAUTION}]")
return questionary.select(
"What do you want to do?", choices=choices, style=CIPHRA_STYLE
).ask()
def _outcome_degraded(msg: str) -> None:
console.print(f" [dim]{msg}[/dim]")
def _outcome_hard_stop(msg: str) -> bool:
console.print(f" [{BAD}][ERROR] {msg}[/{BAD}]")
retry = questionary.confirm(
" Try again?", default=True, style=CIPHRA_STYLE
).ask()
return bool(retry)
# --- helpers ---
def _norm(s):
return re.sub(r'[^a-z0-9]', '', s.lower())
def _resolve_path(raw: str) -> str:
if not raw:
return raw
return os.path.abspath(os.path.expanduser(raw.strip()))
def _prompt_for_file(prompt_text, start_dir=None):
"""Prompt for a file path with tab completion, starting in start_dir."""
display_dir = start_dir or os.path.expanduser("~")
default_val = display_dir.rstrip("/") + "/" if display_dir else "/"
fp = questionary.path(
prompt_text,
default=default_val,
style=CIPHRA_STYLE,
).ask()
if fp is None:
return None
fp = fp.strip()
if not fp:
return None
return _resolve_path(fp)
def setup_logging():
os.makedirs(LOG_FOLDER, exist_ok=True)
handler = RotatingFileHandler(
ERROR_LOG,
maxBytes=1_000_000,
backupCount=3,
)
handler.setLevel(logging.ERROR)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
logging.getLogger().setLevel(logging.ERROR)
def _get_master_key_fp(subkey_id: str) -> str | None:
if not subkey_id or GPG_BIN is None:
return None
try:
proc = subprocess.run(
[GPG_BIN, "--list-keys", "--with-colons", subkey_id],
capture_output=True,
text=True,
timeout=10,
)
master_fp = None
for line in proc.stdout.splitlines():
if line.startswith("fpr:"):
parts = line.split(":")
if len(parts) >= 10 and parts[9]:
if master_fp is None:
master_fp = parts[9].strip()
return master_fp
except (subprocess.TimeoutExpired, subprocess.SubprocessError, OSError):
return None
def _hash_with_progress(fp: str, algo: str) -> str:
chunk_size = 1048576
h = hashlib.new(algo)
file_size = os.path.getsize(fp)
with Progress(
"[progress.description]{task.description}",
BarColumn(),
DownloadColumn(),
TransferSpeedColumn(),
console=console,
transient=False,
) as progress:
task = progress.add_task(
f" Hashing ({algo.upper()})...",
total=file_size,
)
try:
with open(fp, "rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
h.update(chunk)
progress.advance(task, len(chunk))
except (PermissionError, OSError, IOError):
raise
return h.hexdigest()
def _gpg_install_hint() -> str:
system = platform.system()
if system == "Linux":
if shutil.which("apt"):
return " sudo apt install gnupg"
elif shutil.which("dnf"):
return " sudo dnf install gnupg2"
elif shutil.which("pacman"):
return " sudo pacman -S gnupg"
elif shutil.which("apk"):
return " apk add gnupg"
elif shutil.which("zypper"):
return " sudo zypper install gpg2"
return " Install gnupg using your package manager"
elif system == "Darwin":
return " brew install gnupg"
return " Download Gpg4win: https://gpg4win.org"
def check_dirs():
for d, name in [
(LOG_FOLDER, "logs"),
]:
os.makedirs(d, exist_ok=True)
if not os.access(d, os.W_OK):
logging.error("Directory not writable: %s", d)
console.print(f" [{BAD}][ERROR] {name} directory is not writable: {d}[/{BAD}]")
sys.exit(1)
def _validate_vt_key(key: str) -> bool:
return bool(re.match(r'^[0-9a-fA-F]{64}$', key.strip()))
def _set_vt_key_flow() -> str | None:
"""Full VT key setup flow. Returns 'free', 'premium', or None if cancelled."""
# Preamble — shown once before the first prompt
console.print()
console.print(" [dim]VirusTotal scans files against 70+ antivirus engines.[/dim]")
console.print(" [dim]Get a free API key at: https://virustotal.com/gui/my-apikey[/dim]")
console.print()
# Password loop
while True:
key = questionary.password(
"VirusTotal API key:",
style=CIPHRA_STYLE,
).ask()
# Ctrl+C or ESC
if key is None:
console.print(" [dim]Cancelled.[/dim]")
return None
# Blank or whitespace — silently re-ask, no warning
if not key.strip():
continue
# Invalid format
if not _validate_vt_key(key):
console.print(
f"\n [{CAUTION}][WARN] That is not a valid API key."
f" Keys are exactly 64 hex characters.[/{CAUTION}]\n"
)
retry = questionary.confirm(
"Try again?",
default=True,
style=CIPHRA_STYLE,
).ask()
if not retry or retry is None:
console.print(" [dim]Cancelled.[/dim]")
return None
continue
# Valid key — ask tier
break
# Tier selection
tier_choice = questionary.select(
"Is this a premium VirusTotal account?",
choices=[
"No, standard free account",
"Yes, I have a paid premium account",
],
style=CIPHRA_STYLE,
).ask()
if tier_choice is None:
console.print(" [dim]Cancelled. Key not saved.[/dim]")
return None
tier = "premium" if tier_choice.startswith("Yes") else "free"
# Save key and tier
set_vt_key(key.strip())
set_vt_tier(tier)
if tier == "premium":
console.print(
f" [{GOOD}]Key saved. Tier: premium. Upload limit: 650 MB.[/{GOOD}]"
)
else:
console.print(
f" [{GOOD}]Key saved. Tier: free. Upload limit: 32 MB.[/{GOOD}]"
)
console.print(
" [dim]Free API is for personal use only."
" Commercial use requires a paid license.[/dim]"
)
return tier
def _show_banner(animate: bool = True) -> None:
lines_to_use = BANNER_LINES if UNICODE_OK else BANNER_LINES_ASCII
for line in lines_to_use:
console.print(f"[{ACCENT}]{line}[/{ACCENT}]")
if animate:
time.sleep(0.04)
def first_run_check() -> None:
config_path = get_config_path()
if config_path.exists():
return
click.clear()
_show_banner(animate=True)
console.print(
f"\n [{ACCENT}]ciphra[/{ACCENT}] [dim]know what protects you.[/dim]"
)
console.print(
" [dim]Hash, GPG signature, and VirusTotal checks. Runs locally.[/dim]"
)
console.print(
" [dim]To add a VirusTotal API key, go to Configure settings.[/dim]\n"
)
save_credentials({})
def _show_faq():
_old_less = os.environ.get("LESS", "")
os.environ["LESS"] = "-R -+F"
try:
faq_text = (
f"\n"
f" [bold {ACCENT}]FAQ[/bold {ACCENT}]\n"
f" [dim]{'─' * 54 if UNICODE_OK else '-' * 54}[/dim]\n"
f"\n"
f" [bold {ACCENT}]What do the verdicts mean?[/bold {ACCENT}]\n"
f"\n"
f" [{GOOD}]CLEAN[/{GOOD}] signature verified, nothing failed.\n"
f"\n"
f" [{GOOD}]LIKELY SAFE[/{GOOD}] VirusTotal found zero threats. No signature checked.\n"
f"\n"
f" [{CAUTION}]REVIEW[/{CAUTION}] a few engines flagged it. Possible false positive.\n"
f" Check the full VirusTotal report before opening.\n"
f"\n"
f" [{BAD}]FLAGGED[/{BAD}] hard failure. Invalid signature, 10 or more detections,\n"
f" or hash mismatch. Do not open the file.\n"
f" Download it again from the official source.\n"
f"\n"
f" [dim]CHECKED[/dim] hash computed. Everything else was skipped.\n"
f"\n"
f" [dim]UNVERIFIED[/dim] not in VirusTotal database. Common for new or niche files.\n"
f"\n"
f"\n"
f" [bold {ACCENT}]Symmetric vs asymmetric encryption[/bold {ACCENT}]\n"
f"\n"
f" [dim]Symmetric[/dim] password-based. You encrypt it, you decrypt it with the\n"
f" same password. Good for files you keep yourself.\n"
f" Produces a [dim].ciphra[/dim] file. Only ciphra can decrypt it.\n"
f"\n"
f" [dim]Asymmetric[/dim] public key-based. Only the person with the matching\n"
f" private key can open it. Good for sending to someone.\n"
f" Produces a [dim].gpg[/dim] file. Any GPG tool can decrypt it.\n"
f"\n"
f"\n"
f" [bold {ACCENT}]Lost your .ciphra password?[/bold {ACCENT}]\n"
f"\n"
f" No recovery. AES-256-GCM with Argon2id means the file cannot be\n"
f" decrypted without the correct password. No backdoor, no reset.\n"
f" Keep passwords somewhere safe.\n"
f"\n"
f"\n"
f" [bold {ACCENT}]Key expired vs subkey expired[/bold {ACCENT}]\n"
f"\n"
f" Your key pair has two expiry dates.\n"
f"\n"
f" [dim]Primary key[/dim] your signing identity. Cannot sign files if expired.\n"
f" Fix: Digital Signatures > Extend key expiry\n"
f"\n"
f" [dim]Encryption subkey[/dim] others use this to encrypt files to you.\n"
f" Fix: Manage subkeys > Extend subkey expiry\n"
f"\n"
f" When in doubt, extend both.\n"
f"\n"
f"\n"
f" [bold {ACCENT}]How do I receive encrypted files from someone?[/bold {ACCENT}]\n"
f"\n"
f" Share your public key. Digital Signatures > Export public key.\n"
f" Send them the .asc file. They import it and encrypt files to you\n"
f" using ciphra or any GPG tool. Your private key never leaves your machine.\n"
f"\n"
f"\n"
f" [bold {ACCENT}]What gets sent to VirusTotal?[/bold {ACCENT}]\n"
f"\n"
f" The file hash. Always.\n"
f" If not found and the file is under your upload limit, ciphra uploads it.\n"
f" Files over the limit are never uploaded.\n"
f" The result line tells you which path ran.\n"
f"\n"
f" To keep everything local, skip VirusTotal when prompted or remove\n"
f" your API key in Configure settings.\n"
f"\n"
f"\n"
f" [bold {ACCENT}]CLI commands[/bold {ACCENT}] [dim](skip the menu)[/dim]\n"
f"\n"
f" [{ACCENT}]ciphra verify file.iso[/{ACCENT}]\n"
f" [{ACCENT}]ciphra verify file.iso --sig file.iso.sig[/{ACCENT}]\n"
f" [{ACCENT}]ciphra verify file.iso --sig file.iso.sig --no-vt[/{ACCENT}]\n"
f" [{ACCENT}]ciphra verify file.iso --expected a1b2c3... --algo sha256[/{ACCENT}]\n"
f" [{ACCENT}]ciphra verify file.iso --algo sha512[/{ACCENT}]\n"
f"\n"
f" [{ACCENT}]ciphra hash file.iso[/{ACCENT}]\n"
f" [{ACCENT}]ciphra hash file.iso --algo sha512[/{ACCENT}]\n"
f"\n"
f" [{ACCENT}]ciphra config --vt-key YOUR_KEY[/{ACCENT}]\n"
f" [{ACCENT}]ciphra config --show[/{ACCENT}]\n"
f" [{ACCENT}]ciphra config --remove-vt-key[/{ACCENT}]\n"
f"\n"
f" [{ACCENT}]ciphra --version[/{ACCENT}]\n"
f"\n"
f" [dim]Tab completion: ciphra completions --shell bash[/dim]\n"
f" [dim]Also works with zsh and fish.[/dim]\n"
f"\n"
f"\n"
f" [bold {ACCENT}]Is my passphrase stored anywhere?[/bold {ACCENT}]\n"
f"\n"
f" No. ciphra uses a masked prompt and never writes passphrases to disk.\n"
f"\n"
f" [dim]Press q to return to the menu.[/dim]\n"
)
with console.pager(styles=True):
console.print(faq_text)
finally:
if _old_less:
os.environ["LESS"] = _old_less
else:
os.environ.pop("LESS", None)
console.print(" [dim]Returned to menu.[/dim]")
def _validate_sig_input(sig: str, fp: str) -> str | None:
"""Check a manually entered sig path and return None with a warning if invalid."""
sig_ext = os.path.splitext(sig)[1].lower()
key_extensions = [".key", ".pem", ".pub"]
if sig == fp:
console.print(
f"\n [{CAUTION}][WARN] Signature file cannot be the same as "
f"the verified file.[/{CAUTION}]"
)
return None
if sig_ext in key_extensions:
console.print(
f"\n [{CAUTION}][WARN] {os.path.basename(sig)} is a public key file, "
f"not a signature.\n"
f" Import this key using a GPG tool.\n"
f" Then find the .sig file from the developer's download page.[/{CAUTION}]"
)
return None
if sig_ext not in [".sig", ".asc", ".gpg"]:
console.print(
f"\n [{CAUTION}][WARN] Unsupported file type: {sig_ext}\n"
f" Signature files use: .sig .asc .gpg[/{CAUTION}]"
)
return None
return sig
def show_launch_screen():
try:
_show_launch_screen_inner()
except (KeyboardInterrupt, click.Abort):
if not _IN_OPERATION:
console.print(" [dim]Goodbye.[/dim]")
sys.exit(0)
console.print(" [dim]Cancelled.[/dim]")
show_launch_screen()
def _configure_settings_loop(ctx, first_entry: bool = True) -> None:
"""Configure settings menu loop."""
console.print()
sub = questionary.select(
"Configure settings",
choices=[
"Set VirusTotal API key",
"Remove VirusTotal API key",
"Show current config",
"Back",
],
style=CIPHRA_STYLE,
).ask()
if sub is None or sub == "Back":
return
if sub == "Set VirusTotal API key":
existing = get_vt_key()
if existing is not None and _validate_vt_key(existing):
confirmed = questionary.confirm(
" A key is already set. Overwrite?",
default=False,
style=CIPHRA_STYLE,
).ask()
if not confirmed:
console.print(" [dim]Key unchanged.[/dim]")
_configure_settings_loop(ctx, first_entry=False)
return
_set_vt_key_flow()
elif sub == "Remove VirusTotal API key":
ctx.invoke(config, vt_key=None, show=False, remove_vt_key=True)
elif sub == "Show current config":
ctx.invoke(config, vt_key=None, show=True, remove_vt_key=False)
_configure_settings_loop(ctx, first_entry=False)
def _show_launch_screen_inner():
global _BANNER_SHOWN, _IN_OPERATION
if not _BANNER_SHOWN:
# Step 1 -- separate from previous terminal output
console.print()
# Step 2 -- animate banner line by line
_show_banner(animate=True)
# Step 3 -- typewriter tagline
tagline = " know what protects you."
console.print()
for char in tagline:
console.print(char, end="", style="dim")
time.sleep(0.03)
console.print(f"\n v{VERSION}", style="dim")
console.print()
_BANNER_SHOWN = True
# Step 4 -- interactive menu
choices = [
"Verify a file",
"Hash a file",
"Encrypt & Decrypt",
"Digital Signatures",
questionary.Separator("─" * 18 if UNICODE_OK else "-" * 18),
"Configure settings",
"What is this? (FAQ)",
"Exit",
]
answer = questionary.select(
"What do you want to do?",
choices=choices,
style=CIPHRA_STYLE,
).ask()
if answer is None:
console.print(" [dim]Goodbye.[/dim]")
sys.exit(0)
if answer == "Exit":
console.print("\n [dim]Goodbye.[/dim]")
sys.exit(0)
if answer == "What is this? (FAQ)":
_show_faq()
show_launch_screen()
return
ctx = click.get_current_context()
if answer == "Verify a file":
# STEP 1 -- File selection with retry loop
console.print(
" [dim]Check a file's integrity, scan for threats,"
" or verify a developer's signature.[/dim]"
)
console.print(" [dim]Start with / or ~, Tab to complete, Ctrl+C to cancel.[/dim]")
console.print()
fp = _prompt_for_file("File path:", start_dir="/")
if fp is None:
console.print(" [dim]Cancelled.[/dim]")
show_launch_screen()
return
while True:
if os.path.isdir(fp):
if not _outcome_hard_stop("That is a folder. Select a file inside it."):
show_launch_screen()
return
fp = _prompt_for_file("File path:", start_dir="/")
if fp is None:
show_launch_screen()
return
continue
if not os.path.exists(fp):
if not _outcome_hard_stop("File not found."):
show_launch_screen()
return
fp = _prompt_for_file("File path:", start_dir="/")
if fp is None:
show_launch_screen()
return
continue
if os.path.getsize(fp) == 0:
if not _outcome_hard_stop("The file is empty."):
show_launch_screen()
return
fp = _prompt_for_file("File path:", start_dir="/")
if fp is None:
show_launch_screen()
return
continue
try:
with open(fp, "rb") as f:
f.read(1)
except PermissionError:
console.print(f" [{BAD}][ERROR] Cannot read that file. Check file permissions.[/{BAD}]")
show_launch_screen()
return
except OSError as e:
console.print(f" [{BAD}][ERROR] {_translate_error(str(e))}[/{BAD}]")
show_launch_screen()
return
break # validation passed
fp = os.path.abspath(fp)
size_mb = os.path.getsize(fp) / (1024 * 1024)
console.print(f"\n [{ACCENT}]{os.path.basename(fp)}[/{ACCENT}] [dim]{size_mb:.1f} MB[/dim]")
# STEP 2 -- Expected hash (early, near file selection)
console.print(
" [dim]Paste the expected hash from the developer's page,"
" or press Enter to skip.[/dim]"
)
expected_raw = questionary.text(
"Expected hash:",
style=CIPHRA_STYLE,
).ask()
if expected_raw:
expected_raw = expected_raw.strip() or None
else:
expected_raw = None
# STEP 3 -- Algorithm selection
algo_choice = questionary.select(
"Hash algorithm:",
choices=[
"sha256 standard. use this if unsure",
"sha512 stronger. some developers publish sha512 checksums",
"sha1 legacy. only if the developer specifically requires it",
"md5 legacy. only if the developer specifically requires it",
],
default="sha256 standard. use this if unsure",
style=CIPHRA_STYLE,
).ask()
algo = algo_choice.split()[0] if algo_choice else "sha256"
expected_lengths = {"sha256": 64, "sha512": 128, "sha1": 40, "md5": 32}
if expected_raw and len(expected_raw) != expected_lengths.get(algo, 0):
_outcome_degraded(
f"That does not look like a {algo.upper()} hash. "
f"{algo.upper()} hashes are {expected_lengths[algo]} characters. Continuing."
)
# STEP 4 -- Auto-detect sig file
sig_dir = os.path.dirname(fp)
base = os.path.basename(fp)
auto_sig = None
for _ext in [".sig", ".asc", ".gpg"]:
candidate = os.path.join(sig_dir, base + _ext)
if os.path.isfile(candidate):
# Reject .asc files that are actually public keys
if _ext == ".asc":
try:
with open(candidate, "r", errors="ignore") as f:
first_line = f.readline().strip()
if "BEGIN PGP PUBLIC KEY BLOCK" in first_line:
console.print(
f" [{CAUTION}][WARN] Found {os.path.basename(candidate)}"
f" but it is a public key, not a signature. Skipping.[/{CAUTION}]"
)
continue
except OSError:
pass
auto_sig = candidate
break
# STEP 5 -- Offer sig file with three options
sig = None
key_choice = None
if auto_sig:
console.print(
f"\n [dim]Found signature file: {os.path.basename(auto_sig)}[/dim]"
)
sig_choice = questionary.select(
"Use this signature file?",
choices=[
"Yes, use it",
"No, enter a different path",
"Skip signature check",
],
style=CIPHRA_STYLE,
).ask()
if sig_choice is None:
sig = None
elif sig_choice == "Skip signature check":
sig = None
elif sig_choice == "Yes, use it":
sig = auto_sig
else:
sig_input = _prompt_for_file(
"Signature file path:",
start_dir=sig_dir,
)
if sig_input and os.path.isfile(sig_input):
sig = _validate_sig_input(sig_input, fp)
# Extra content check for manually entered .asc
if sig and sig.lower().endswith(".asc"):
try:
with open(sig, "r", errors="ignore") as f:
first_line = f.readline().strip()
if "BEGIN PGP PUBLIC KEY BLOCK" in first_line:
console.print(
f" [{CAUTION}][WARN] That file is a public key,"
f" not a signature. Skipping.[/{CAUTION}]"
)
sig = None
except OSError:
pass
else:
console.print()
sig_choice = questionary.select(
"Signature file:",
choices=[
"Enter path",
"Skip signature check",
],
style=CIPHRA_STYLE,
).ask()
if sig_choice is None:
sig = None
elif sig_choice == "Enter path":
sig_input = _prompt_for_file(
"Signature file path:",
start_dir=sig_dir,
)
if sig_input and os.path.isfile(sig_input):
sig = _validate_sig_input(sig_input, fp)
# Extra content check for manually entered .asc
if sig and sig.lower().endswith(".asc"):
try:
with open(sig, "r", errors="ignore") as f:
first_line = f.readline().strip()
if "BEGIN PGP PUBLIC KEY BLOCK" in first_line:
console.print(
f" [{CAUTION}][WARN] That file is a public key,"
f" not a signature. Skipping.[/{CAUTION}]"
)
sig = None
except OSError:
pass
# STEP 5b -- GPG availability check
if sig is not None:
if GPG_BIN is None:
_outcome_degraded(
f"GPG is not installed. Signature check skipped.\n"
f"{_gpg_install_hint()}\n"
f" Hash and VirusTotal checks will still run."
)
sig = None
# STEP 6 -- Extract key ID from sig silently
sig_key_id = None
if sig and os.path.isfile(sig):
with console.status(
" Reading signature...",
spinner="dots",
spinner_style=ACCENT,
):
try:
_tmp = verify_signature(fp, sig)
sig_key_id = _tmp.get("key_id")
if not sig_key_id:
if GPG_BIN:
_proc = subprocess.run(
[GPG_BIN, "--batch", "--verify", sig, fp],
capture_output=True,
text=True,
timeout=30,
)
sig_key_id = extract_key_id(
_proc.stdout + "\n" + _proc.stderr
)
except subprocess.TimeoutExpired:
_outcome_degraded("Could not read key ID from signature. Continuing.")
sig_key_id = None
except subprocess.SubprocessError:
_outcome_degraded("Could not read key ID from signature. Continuing.")
sig_key_id = None
except (OSError, ValueError):
sig_key_id = None
if sig is not None:
# STEP 7 -- Auto-detect key file
auto_key = None
file_norm = _norm(os.path.splitext(os.path.basename(fp))[0])
try:
for _f in sorted(os.listdir(sig_dir)):
_f_lower = _f.lower()
_f_path = os.path.join(sig_dir, _f)
if not os.path.isfile(_f_path):
continue
is_key_ext = (
_f_lower.endswith(".key") or
(_f_lower.endswith(".asc") and
any(word in _f_lower for word in ["sign", "key", "pub", "pgp", "gpg"]))
)
if not is_key_ext:
continue
_f_norm = _norm(os.path.splitext(_f_lower)[0])
if (
file_norm[:4] == _f_norm[:4] or
_f_norm in file_norm or
file_norm in _f_norm
):
auto_key = _f_path
break
except PermissionError:
pass
# STEP 8 -- Offer key file with options
key_file = None
if auto_key:
console.print(
f"\n [dim]Found key file: {os.path.basename(auto_key)}[/dim]"
)
key_choice = questionary.select(
"Use this key file?",
choices=[
"Yes",
"No, enter a different path",
"Fetch from keyserver instead",
"Skip key import",
],
style=CIPHRA_STYLE,
).ask()
if key_choice is None:
key_choice = "Skip key import"
if key_choice == "Yes":
key_file = auto_key
elif key_choice == "No, enter a different path":
key_input = _prompt_for_file(
"Key file path:",
start_dir=sig_dir,
)
if key_input and os.path.isfile(key_input):
key_file = key_input
elif key_choice == "Fetch from keyserver instead":
key_file = None