-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrednb-verify.py
More file actions
4530 lines (4016 loc) · 196 KB
/
Copy pathrednb-verify.py
File metadata and controls
4530 lines (4016 loc) · 196 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
#!/usr/bin/env python3
"""
rednb-verify
Version: 0.12.0
RedNotebook integrity verification tool.
Creates and verifies cryptographic manifests for notebook directories.
CLI/Commands:
rednb-verify.py [options] [notebook_directory]
Manifest creation:
"-m", "--month-only" : Hashes only month files
"-D", "--per-day" : Hash individual day entries within month files (requires PyYAML)
"-j", "--jobs N" : Parallel hashing workers (0 = auto, default: 1)
"-o", "--output" : Output dir for manifest (create) or report (verify; requires --report)
"--manifest-type txt|json" : Manifest creation format (default: txt)
"--no-bullets" : Text manifest: don't prefix per-file hash lines with '- '
"--hash ALGO[:LEN][,ALGO...]" : Hash algorithm(s); comma-separate for multi-hashing
"--hash-list" : Print available hash algorithms and exit
"--hash-merkle ALGO[,...]" : Merkle algo (single: combiner; multi: select trees)
"--hash-merkle-concatenate [ALGO]" : One tree over per-file concatenated hashes
"--exclude PATTERN" : Exclude files matching glob (repeatable)
"--exclude-from FILE" : File of glob patterns to exclude (one literal pattern per line)
"--symlink-targets MODE" : Record symlink targets: none|full|hash[:ALGO[:LEN]] (default: hash = sha256 of target)
"--no-symlink-table" : Omit the symlink table (alias for --symlink-targets none)
"--privacy" : Minimise manifest disclosure (currently implies --no-symlink-table)
"--lock" : After writing, chmod the manifest (and any .asc/.sshsig/.sig/.tsr) read-only (best-effort, not true WORM)
Manifest chaining (each manifest links the previous one by hash — makes the SEQUENCE tamper-evident):
"--prev-manifest FILE|DIR" : Link to a previous manifest (a directory auto-selects its latest, like --verify)
"--prev-hash ALGO[:LEN][,...]" : Hash algorithm(s) for the link (default: sha256; comma-separate for multiple)
Signing:
"--gpg [FINGERPRINT]" : Sign with GPG; optional fingerprint pre-selects key
"--gpg-k FILE" : GPG armored key file; implies --gpg
"--ssh [FILE_OR_DIR]" : Sign with SSH key; optional .pub file or directory
"--ssh-fido [NAME]" : Prefer FIDO2/hardware-backed SSH keys; optional name filter
"--trust high|low" : Signing trust level (default: low)
"--no-sign" : Skip all signing
"--resign MANIFEST" : Re-sign an existing manifest (requires --gpg and/or --ssh)
Timestamping (RFC 3161 — strictly opt-in; --tsa is the tool's ONLY network operation):
"--tsa NAME|URL" : Request a trusted timestamp at create (detached hashes-....tsr by default)
"--tsa-embed" : With --tsa: embed ONE stamp over the placement root as tsa_stamp (1 request)
"--tsa-embed-separate" : With --tsa: embed placement + content stamps separately (2 requests)
"--tsa-cert CAFILE" : TSA CA certificate to verify tokens during --verify (local check)
"--ignore-tsa" : During --verify, skip all timestamp-token checks
"--tsa-list" : Print the built-in TSA registry and exit (no network)
"--offline" : Assert no network: refuses --tsa (offline is already the default)
Verification:
"--verify [FILE|DIR]" : Verify mode; optional manifest path/dir (auto-finds latest if omitted)
"--report txt|json" : Write a verify report file (txt|json). Omit = verdict only, no file. -o sets its location and requires this flag
"--ssh-verify" : Force SSH signature check during --verify
"--ignore-sig" : Verify integrity only; skip all signature checks
"--ignore-symlinks" : During --verify, skip the symlink-table comparison and symlink warnings
"--ignore-chain" : During --verify, skip manifest chain verification (--prev-manifest)
"--files-only" : During --verify, skip checks that aren't about the files themselves; shorthand for --ignore-sig --ignore-tsa --ignore-chain (symlinks still checked)
"--sig FILE[,FILE]" : Signature file(s) comma-separated (.asc=GPG, .sshsig/.sig=SSH)
"--warn-age DAYS" : Warn during verify if manifest is older than N days
"--schema-ignore" : Verify a newer-schema manifest anyway (risky)
Validation:
"--validate [FILE|DIR]" : Validate a manifest/report against the embedded JSON schema and exit (needs optional jsonschema)
"--dump-schema manifest|report" : Print the embedded JSON schema to stdout and exit
General:
"-V", "--version" : Print version and exit
"-v", "--verbose" : Print per-file hash timing and detailed progress
"--quiet" : Suppress non-error output; implies --no-sign unless signing is explicit
"-y", "--yes" : Assume yes to confirmation prompts
"--json" : Emit result as one JSON document on stdout (logs to stderr) for piping
"--install-opt" : Let the tool 'pip install' optional packages a command needs (the only path that runs pip)
Config management:
"--set-cf FIELD:VALUE" : Set a config field and exit (trust-gpg, trust-ssh, trust-level, dir)
"--set-cf-run FIELD:VALUE" : Like --set-cf but continue running
"--add-trust FIELD:VALUE" : Append fingerprints to a trust list (de-duplicated)
"--config-out" : Print the resulting config as JSON
"--no-config / --no-cf" : Ignore ~/.config/rednb-verify/config.json for this run
"--config FILE" : Load a specific config file instead of the default
Exit codes:
0 all checks passed / manifest created successfully
1 verification found issues (modified/missing/new files, invalid or untrusted signature)
2 usage or input error (bad arguments, missing files, unsupported algorithm)
3 signing refused (untrusted key under --trust high)
"""
import argparse
import base64
import fnmatch
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, Iterable, List, Optional
VERSION = "0.12.0"
HASH_ALGO = "sha256"
CONFIG_PATH = Path(os.path.expanduser("~/.config/rednb-verify/config.json"))
# Default parallel hashing workers: leave a couple of cores free for the OS
# and whatever else the user is doing, rather than defaulting to fully
# sequential. Floored at 1 so a 1-2 core machine (a budget laptop, a
# container, a VPS) never computes 0 or negative workers. cpu_count() can
# return None in some sandboxed environments, hence the "or 1".
DEFAULT_JOBS = max(1, (os.cpu_count() or 1) - 2)
# Manifest structural contract. Separate from VERSION (build identifier).
# Bump only on a BREAKING structural change (renamed/removed/retyped field),
# never for an optional addition. Manifests without this field = version 0.
MANIFEST_SCHEMA_VERSION = 3
# Set by main() before any output
_quiet: bool = False
_verbose: bool = False
# In --json mode, stdout is reserved for the machine-readable JSON document, so
# all human/log output is routed to stderr to keep stdout pipe-clean.
_json_mode: bool = False
def _log_stream():
return sys.stderr if _json_mode else sys.stdout
def _qprint(msg: str) -> None:
"""Print only when not in quiet mode."""
if not _quiet:
print(msg, file=_log_stream())
def _vprint(msg: str) -> None:
"""Print only in verbose mode (quiet still suppresses it)."""
if _verbose and not _quiet:
print(msg, file=_log_stream())
def _require_yaml():
"""Import and return the yaml module, or exit with a clear install message."""
try:
import yaml # type: ignore
return yaml
except ImportError:
_err("--per-day needs PyYAML, which is not installed.")
_err(" Install it with: pip install pyyaml")
sys.exit(2)
# ---------- Colour helpers ----------
# Applied only when stdout/stderr is a real TTY (no colour when piped/redirected).
_ANSI_RESET = "\033[0m"
_ANSI: Dict[str, str] = {
"INFO": "\033[33m", # yellow
"OK": "\033[97m", # bright white
"PASS": "\033[92m", # bright green
"WARN": "\033[91m", # light red
"FAIL": "\033[91m", # light red
"ERROR": "\033[91m", # light red
}
def _tag(label: str, *, stream=None) -> str:
"""Return a coloured [LABEL] tag. Falls back to plain text on non-TTY."""
tty = (stream or sys.stdout).isatty()
code = _ANSI.get(label.upper(), "")
if code and tty:
return f"{code}[{label}]{_ANSI_RESET}"
return f"[{label}]"
def _info(msg: str) -> None:
_qprint(f"{_tag('INFO', stream=_log_stream())} {msg}")
def _ok(msg: str) -> None:
_qprint(f"{_tag('OK', stream=_log_stream())} {msg}")
def _pass(msg: str) -> None:
_qprint(f"{_tag('PASS', stream=_log_stream())} {msg}")
def _warn(msg: str) -> None:
"""Cosmetic-tier warning: suppressed by --quiet."""
if not _quiet:
print(f"{_tag('WARN', stream=_log_stream())} {msg}", file=_log_stream())
def _warn_security(msg: str) -> None:
"""Security-tier warning: ALWAYS printed, ALWAYS to stderr, ignores --quiet."""
print(f"{_tag('WARN', stream=sys.stderr)} {msg}", file=sys.stderr)
def _err(msg: str) -> None:
print(f"{_tag('ERROR', stream=sys.stderr)} {msg}", file=sys.stderr)
# ---------- Config ----------
def load_config(path: Path = CONFIG_PATH) -> Dict:
"""Load a config JSON file if present. Empty files are silently ignored."""
if path.exists():
try:
text = path.read_text(encoding="utf-8").strip()
if not text:
return {}
return json.loads(text)
except (OSError, json.JSONDecodeError) as exc:
print(f"{_tag('WARN', stream=sys.stderr)} Could not load config {path}: {exc}",
file=sys.stderr)
return {}
def save_config(config: Dict, path: Path = CONFIG_PATH) -> None:
"""Write the config dict to disk as pretty JSON, creating parent dirs."""
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(config, indent=4, ensure_ascii=False) + "\n",
encoding="utf-8")
def _normalize_gpg_fpr(fpr: str) -> str:
"""GPG fingerprints compared case-insensitively, spaces stripped (D3)."""
return fpr.replace(" ", "").upper()
# --set-cf / --add-trust field → trust list key
_CF_TRUST_FIELDS = {"trust-gpg": "gpg", "trust-ssh": "ssh"}
def _parse_cf_token(token: str) -> tuple:
"""Parse 'field:value[,value...]' → (field, [values]).
Splits on the FIRST colon only (G5), so dir:C:\\path keeps its drive colon.
Returns (field, None) if no colon is present.
"""
field, sep, rest = token.partition(":")
if not sep:
return field.strip(), None
values = [v.strip() for v in rest.split(",") if v.strip()]
return field.strip(), values
def apply_set_cf(config: Dict, tokens: List[str]) -> None:
"""Apply --set-cf tokens to config in place (REPLACE semantics)."""
for token in tokens:
field, values = _parse_cf_token(token)
if values is None:
_err(f"--set-cf expects field:value, got: {token!r}")
sys.exit(2)
if field in _CF_TRUST_FIELDS:
kind = _CF_TRUST_FIELDS[field]
if kind == "gpg":
values = [_normalize_gpg_fpr(v) for v in values]
config.setdefault("trust", {})[kind] = list(dict.fromkeys(values))
elif field == "trust-level":
level = (values[0].lower() if values else "")
if level not in ("high", "low"):
_err(f"trust-level must be 'high' or 'low', got: {values!r}")
sys.exit(2)
config["trust_level"] = level
elif field == "dir":
config["dir"] = values[0] # single path; last wins if repeated
else:
_err(f"Unknown --set-cf field: {field!r} "
"(expected trust-gpg, trust-ssh, trust-level, dir)")
sys.exit(2)
def apply_add_trust(config: Dict, tokens: List[str]) -> None:
"""Apply --add-trust tokens to config in place (APPEND + de-dupe, order kept)."""
for token in tokens:
field, values = _parse_cf_token(token)
if values is None:
_err(f"--add-trust expects field:value, got: {token!r}")
sys.exit(2)
if field not in _CF_TRUST_FIELDS:
_err(f"--add-trust only supports trust-gpg / trust-ssh, got: {field!r}")
sys.exit(2)
kind = _CF_TRUST_FIELDS[field]
if kind == "gpg":
values = [_normalize_gpg_fpr(v) for v in values]
existing = config.get("trust", {}).get(kind, [])
config.setdefault("trust", {})[kind] = list(dict.fromkeys(existing + values))
# ---------- Utilities ----------
# Algorithms whose digest() / hexdigest() require an explicit byte-length argument.
_VARIABLE_LENGTH_ALGOS = {"shake_128", "shake_256"}
# Cryptographically broken hashes — unsafe as the SOLE integrity hash.
_WEAK_ALGOS = {"md5", "sha1"}
# Canonical manifest warning strings (stored in the manifest "warnings" field).
WARN_WEAK_HASH = "WEAK HASHING ALGORITHM(S) IN USE ALONE"
WARN_UNSIGNED = "MANIFEST UNSIGNED"
WARN_EXCLUDED = "FILES EXCLUDED FROM MANIFEST"
WARN_NO_FILES = "NO FILES FOUND IN NOTEBOOK DIRECTORY"
WARN_NO_DAYS = "NO DAY ENTRIES FOUND"
def _parse_algo_spec(spec: str) -> tuple:
"""Parse 'algo' or 'algo:length' → (algo_name, length_or_None).
shake_128 and shake_256 require a length, e.g. 'shake_128:32'.
All other algorithms ignore the length component even if provided.
"""
if ":" in spec:
algo, _, length_str = spec.partition(":")
try:
return algo.strip(), int(length_str.strip())
except ValueError:
return spec.strip(), None
return spec.strip(), None
def _hexdigest(h, length: Optional[int]) -> str:
"""Call h.hexdigest() with or without a length argument."""
return h.hexdigest(length) if length is not None else h.hexdigest()
def _validate_algo_spec_or_exit(spec: str, label: str) -> tuple:
"""Validate one algo spec against the registry; exit(2) with a clear message.
Returns (name, length) on success. Note: AVAILABLE_HASHES is defined just
below hash_file, so this is only called from main() after module load.
"""
name, length = _parse_algo_spec(spec)
if name not in AVAILABLE_HASHES:
if name in _OPTIONAL_PIP:
_err(f"{label} {name!r} needs an optional package: "
f"pip install {_OPTIONAL_PIP[name]}")
else:
_err(f"Unsupported algorithm for {label}: {spec!r}")
sys.exit(2)
if name in _VARIABLE_LENGTH_ALGOS and length is None:
_err(f"{name} requires a length: use {label} {name}:32")
sys.exit(2)
if name not in _VARIABLE_LENGTH_ALGOS and length is not None:
_err(f"{name} does not support a length parameter (remove :{length})")
sys.exit(2)
try:
_hexdigest(_new_hasher(name), length)
except TypeError as exc:
_err(f"Algorithm error for {label} {spec!r}: {exc}")
sys.exit(2)
return name, length
def utc_timestamp() -> str:
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
def _now_stamp() -> str:
"""Human-readable UTC stamp for per-file verbose log lines."""
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
# ---------- Hashing progress bar (normal mode only) ----------
# A hand-rolled \r-overwrite bar (no tqdm/rich dependency) shown ONLY in
# normal mode: --verbose already gives full per-file lines and shouldn't also
# fight the bar for the same terminal line; --quiet stays fully silent;
# --json keeps stdout pipe-clean; a non-TTY (piped/redirected) run gets no
# escape codes, mirroring _tag()'s own TTY check.
_SPINNER_FRAMES_BRAILLE = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
_SPINNER_FRAMES_ASCII = ["|", "/", "-", "\\"]
_spinner_frames_cache: Optional[List[str]] = None
def _spinner_frames() -> List[str]:
"""Braille spinner when the terminal's encoding can render it, else a
plain ASCII fallback. Windows consoles commonly default to cp1252, which
cannot encode these characters at all — printing them unconditionally
would crash the tool with a UnicodeEncodeError the first time the
progress bar ticks, not just render oddly. Checked once and cached."""
global _spinner_frames_cache
if _spinner_frames_cache is None:
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
try:
"".join(_SPINNER_FRAMES_BRAILLE).encode(encoding)
_spinner_frames_cache = _SPINNER_FRAMES_BRAILLE
except (UnicodeEncodeError, LookupError):
_spinner_frames_cache = _SPINNER_FRAMES_ASCII
return _spinner_frames_cache
def _progress_active() -> bool:
return not _quiet and not _verbose and not _json_mode and sys.stdout.isatty()
def _format_elapsed(seconds: float) -> str:
"""Milliseconds while under 1s (finer-grained, matches short hash times),
seconds with one decimal once elapsed reaches a full second."""
ms = seconds * 1000
if ms < 1000:
return f"{ms:.0f}ms"
return f"{seconds:.1f}s"
def _progress_tick(done: int, total: int, phase_start: float) -> None:
"""Redraw the hashing progress line in place. `done` also drives the
spinner frame, so it advances once per completed file rather than on a
separate wall-clock timer — simple, thread-safe, and proportional to
real progress (a single very large file just holds its frame until done)."""
if not _progress_active():
return
frames = _spinner_frames()
spinner = frames[done % len(frames)]
pct = round((done / total) * 100) if total else 100
elapsed = _format_elapsed(time.perf_counter() - phase_start)
text = f"{spinner} Hashing... {done}/{total} files ({pct}%) [Time Elapsed: {elapsed}]"
try:
sys.stdout.write("\r\x1b[2K" + text)
sys.stdout.flush()
except UnicodeEncodeError:
# Last-resort guard: the cached frame set already matches the
# encoding at cache time, but stdout can be reconfigured mid-run in
# rare cases. Never let a cosmetic progress update crash the tool.
pass
def _progress_clear() -> None:
"""Erase the progress line so the next normal print() starts fresh."""
if _progress_active():
sys.stdout.write("\r\x1b[2K")
sys.stdout.flush()
def hash_file(path: Path, algo_spec: str) -> str:
"""Hash a file using an algorithm spec ('algo' or 'algo:length')."""
algo, length = _parse_algo_spec(algo_spec)
h = hashlib.new(algo)
with path.open("rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return _hexdigest(h, length)
# Optional hash backends beyond hashlib's guaranteed set. Each entry maps an
# algorithm NAME to a zero-arg constructor returning an object with
# .update(bytes) and .hexdigest(). Populated once at import time.
AVAILABLE_HASHES: Dict[str, object] = {}
for _algo in hashlib.algorithms_guaranteed:
# bind _algo per-iteration via default arg
AVAILABLE_HASHES[_algo] = (lambda a: (lambda: hashlib.new(a)))(_algo)
try:
import blake3 as _blake3_mod
AVAILABLE_HASHES["blake3"] = _blake3_mod.blake3
except ImportError:
pass
try:
import xxhash as _xxhash_mod
AVAILABLE_HASHES["xxh3"] = _xxhash_mod.xxh3_128
except ImportError:
pass
# Known optional algorithms and the pip package that provides each.
_OPTIONAL_PIP = {"blake3": "blake3", "xxh3": "xxhash"}
def _new_hasher(name: str):
"""Return a fresh hasher for an algorithm name, or None if unavailable."""
ctor = AVAILABLE_HASHES.get(name)
return ctor() if ctor is not None else None
def hash_file_multi(path: Path, specs: List[str]) -> Dict[str, str]:
"""Hash a file with N algorithms in a SINGLE read pass.
Returns {spec: hexdigest} keyed by the original spec string
(e.g. 'sha256', 'shake_128:32'). Caller is responsible for having
validated the specs.
"""
parsed = [(spec, *_parse_algo_spec(spec)) for spec in specs]
hashers = {spec: _new_hasher(name) for spec, name, _ in parsed}
with path.open("rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
for h in hashers.values():
h.update(chunk)
return {spec: _hexdigest(hashers[spec], length) for spec, _, length in parsed}
def hash_bytes_multi(data: bytes, specs: List[str]) -> Dict[str, str]:
"""Hash an in-memory byte string with N algorithms. Returns {spec: hexdigest}."""
out: Dict[str, str] = {}
for spec in specs:
name, length = _parse_algo_spec(spec)
h = _new_hasher(name)
h.update(data)
out[spec] = _hexdigest(h, length)
return out
def is_month_file(path: Path) -> bool:
if path.suffix != ".txt":
return False
stem = path.stem
return (
len(stem) == 7
and stem[4] == "-"
and stem[0:4].isnumeric()
and stem[5:7].isnumeric()
and 1 <= int(stem[5:7]) <= 12
)
# ---------- Merkle ----------
def merkle_root(hashes: List[str], algo_spec: str) -> str:
"""RFC 6962-style Merkle root with domain separation.
Two hardening measures distinguish this from a naive Merkle tree, both
aimed at the same class of attack — making two different file sets collide
to the same root:
* Leaf nodes are hashed with a ``0x00`` prefix and internal nodes with
``0x01``. Without this, a leaf digest and an internal digest are computed
identically, so an attacker can present an internal node's two children
as if they were a single leaf (a second-preimage forgery of the tree
shape).
* Odd nodes are promoted to the next level unchanged rather than being
duplicated. Duplication is the CVE-2012-2459 weakness: a tree over
``[A, B, C]`` (with C duplicated) yields the same root as a real
four-file tree ``[A, B, C, C]``, so files can be silently added or
removed without changing the root.
See the "Merkle tree" section of the README for the worked example.
"""
if not hashes:
return ""
algo, length = _parse_algo_spec(algo_spec)
def _node(prefix: bytes, *parts: bytes) -> bytes:
h = hashlib.new(algo, prefix + b"".join(parts))
return h.digest(length) if length is not None else h.digest()
# Leaf level: domain-separate every file hash with a 0x00 prefix.
level = [_node(b"\x00", bytes.fromhex(h)) for h in hashes]
# Internal levels: pair with a 0x01 prefix; promote a trailing odd node.
while len(level) > 1:
next_level = [
_node(b"\x01", level[i], level[i + 1])
for i in range(0, len(level) - 1, 2)
]
if len(level) % 2 == 1:
next_level.append(level[-1])
level = next_level
return level[0].hex()
# ---------- GPG ----------
def gpg_available() -> bool:
try:
subprocess.run(
["gpg", "--version"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
return True
except Exception:
return False
def list_secret_keys() -> List[Dict]:
result = subprocess.run(
["gpg", "--list-secret-keys", "--with-colons"],
capture_output=True, text=True, check=True,
)
keys: List[Dict] = []
current: Optional[Dict] = None
for line in result.stdout.splitlines():
parts = line.split(":")
if parts[0] == "sec":
expires = parts[6]
current = {
"fingerprint": None,
"uid": "",
"expires": (
datetime.fromtimestamp(int(expires), tz=timezone.utc).strftime("%Y-%m-%d")
if expires.isdigit() and int(expires) > 0
else "never"
),
}
keys.append(current)
elif parts[0] == "fpr" and current and current["fingerprint"] is None:
current["fingerprint"] = parts[9].upper()
elif parts[0] == "uid" and current and not current["uid"]:
current["uid"] = parts[9]
return [k for k in keys if k["fingerprint"] and k["uid"]]
def choose_gpg_key(keys: List[Dict]) -> Optional[str]:
print("\nAvailable signing keys:\n")
for idx, key in enumerate(keys):
print(f" [{idx:02d}] {key['uid']}")
print(f" FPR: {key['fingerprint']}")
print(f" Expires: {key['expires']}")
choice = input("\nSelect key index (or Enter to cancel): ").strip()
if not choice:
return None
if not choice.isdigit():
_err("Invalid selection.")
return None
idx = int(choice)
if idx < 0 or idx >= len(keys):
_err("Selection out of range.")
return None
return keys[idx]["fingerprint"]
def gpg_detach_sign(manifest_path: Path, key_fpr: str) -> bool:
cmd = ["gpg", "--detach-sign", "--armor", "--local-user", key_fpr, manifest_path.name]
try:
subprocess.run(cmd, cwd=manifest_path.parent, check=True)
return True
except subprocess.CalledProcessError:
return False
def gpg_verify(manifest: Path, signature: Path) -> bool:
try:
subprocess.run(
["gpg", "--verify", str(signature.resolve()), str(manifest.resolve())],
check=True, capture_output=True,
)
return True
except subprocess.CalledProcessError:
return False
def _gpg_sign_with_keyfile(manifest_path: Path, key_file: Path) -> bool:
"""Sign using an armored GPG key export file via a temporary homedir."""
tmp_home = Path(tempfile.mkdtemp(prefix="rednb-gpg-"))
try:
os.chmod(tmp_home, 0o700)
subprocess.run(
["gpg", "--homedir", str(tmp_home), "--import", str(key_file.resolve())],
check=True, capture_output=True,
)
result = subprocess.run(
["gpg", "--homedir", str(tmp_home), "--list-secret-keys", "--with-colons"],
check=True, capture_output=True, text=True,
)
fpr = None
for line in result.stdout.splitlines():
parts = line.split(":")
if parts[0] == "fpr":
fpr = parts[9].upper()
break
if not fpr:
return False
subprocess.run(
["gpg", "--homedir", str(tmp_home),
"--detach-sign", "--armor", "--local-user", fpr,
manifest_path.name],
cwd=manifest_path.parent, check=True,
)
return True
except subprocess.CalledProcessError:
return False
finally:
shutil.rmtree(tmp_home, ignore_errors=True)
# ---------- SSH ----------
SSH_NAMESPACE = "rednotebook-manifest"
SSH_SIGNER_IDENTITY = "rednb-verify"
@dataclass(frozen=True)
class SshKeyCandidate:
pub_path: Path
priv_path: Optional[Path]
key_type: str
comment: str
filename: str
is_fido: bool
@dataclass(frozen=True)
class SshVerifyResult:
status: str
message: str
warnings: List[str]
def ssh_keygen_available() -> bool:
return shutil.which("ssh-keygen") is not None
def _parse_pubkey_line(line: str) -> Optional[tuple]:
parts = line.strip().split()
if len(parts) < 2:
return None
return parts[0], (parts[2] if len(parts) > 2 else "")
def scan_ssh_keys(directory: Path, require_private: bool) -> List[SshKeyCandidate]:
candidates = []
if not directory.exists():
return candidates
for pub_path in sorted(directory.glob("*.pub")):
try:
line = pub_path.read_text(encoding="utf-8").splitlines()[0]
except (OSError, IndexError):
continue
parsed = _parse_pubkey_line(line)
if not parsed:
continue
key_type, comment = parsed
priv_path = pub_path.with_suffix("")
if require_private and not priv_path.exists():
continue
candidates.append(SshKeyCandidate(
pub_path=pub_path,
priv_path=priv_path if priv_path.exists() else None,
key_type=key_type,
comment=comment,
filename=pub_path.name,
is_fido="sk-" in key_type,
))
return candidates
def _filter_ssh_candidates(
candidates: Iterable[SshKeyCandidate],
prefer_fido: bool,
keyname: Optional[str],
) -> List[SshKeyCandidate]:
filtered = list(candidates)
if keyname:
kl = keyname.lower()
filtered = [c for c in filtered if kl in c.pub_path.stem.lower() or kl in c.comment.lower()]
if prefer_fido:
fido = [c for c in filtered if c.is_fido]
if fido:
filtered = fido
return filtered
def choose_ssh_key(candidates: List[SshKeyCandidate]) -> Optional[SshKeyCandidate]:
if not candidates:
return None
if len(candidates) == 1:
return candidates[0]
print("\nAvailable SSH keys:\n")
for idx, key in enumerate(candidates):
fido_tag = " [FIDO2]" if key.is_fido else ""
print(f" [{idx:02d}] {key.filename}{fido_tag}")
print(f" Type: {key.key_type}")
if key.comment:
print(f" Comment: {key.comment}")
choice = input("\nSelect key index (or Enter to cancel): ").strip()
if not choice:
return None
if not choice.isdigit():
_err("Invalid selection.")
return None
idx = int(choice)
if idx < 0 or idx >= len(candidates):
_err("Selection out of range.")
return None
return candidates[idx]
def select_ssh_key(
ssh_key: Path,
require_private: bool,
prefer_fido: bool,
keyname: Optional[str],
) -> Optional[SshKeyCandidate]:
"""Resolve an SSH key from a direct .pub file or a directory to scan."""
if ssh_key.is_file():
try:
line = ssh_key.read_text(encoding="utf-8").splitlines()[0]
except (OSError, IndexError):
_warn(f"Could not read public key: {ssh_key}")
return None
parsed = _parse_pubkey_line(line)
if not parsed:
_warn(f"Could not parse public key: {ssh_key}")
return None
key_type, comment = parsed
priv_path = ssh_key.with_suffix("")
if require_private and not priv_path.exists():
_warn(f"Private key not found alongside {ssh_key.name}")
return None
return SshKeyCandidate(
pub_path=ssh_key,
priv_path=priv_path if priv_path.exists() else None,
key_type=key_type,
comment=comment,
filename=ssh_key.name,
is_fido="sk-" in key_type,
)
candidates = scan_ssh_keys(ssh_key, require_private=require_private)
candidates = _filter_ssh_candidates(candidates, prefer_fido=prefer_fido, keyname=keyname)
return choose_ssh_key(candidates)
def ssh_sign_manifest(manifest_path: Path, key_path: Path, sig_path: Path) -> bool:
# Resolve every path passed to ssh-keygen BEFORE the subprocess call: the
# child process's cwd is set to manifest_path.parent below, so any
# argument that's still relative gets re-interpreted against that NEW
# cwd rather than ours, silently doubling the directory prefix (e.g.
# ".testing/output" + cwd ".testing/output" -> looks for
# ".testing/output/.testing/output/..."). Matches the pattern
# gpg_verify() already uses (it resolves its paths and sets no cwd).
manifest_path = manifest_path.resolve()
key_path = key_path.resolve()
sig_path = sig_path.resolve()
default_sig = manifest_path.with_suffix(manifest_path.suffix + ".sig")
appended_sig = manifest_path.parent / f"{manifest_path.name}.sig"
for c in (default_sig, appended_sig):
if c.exists():
c.unlink()
try:
subprocess.run(
["ssh-keygen", "-Y", "sign", "-f", str(key_path),
"-n", SSH_NAMESPACE, str(manifest_path)],
cwd=manifest_path.parent, check=True,
)
except subprocess.CalledProcessError:
return False
generated = next((c for c in (default_sig, appended_sig) if c.exists()), None)
if generated is None:
return False
sig_path.parent.mkdir(parents=True, exist_ok=True)
generated.replace(sig_path)
return True
def _write_allowed_signers(pub_path: Path) -> Path:
line = pub_path.read_text(encoding="utf-8").splitlines()[0].strip()
tmp = tempfile.NamedTemporaryFile("w", suffix=".signers", delete=False)
tmp.write(f"{SSH_SIGNER_IDENTITY} {line}\n")
tmp.flush()
tmp.close()
return Path(tmp.name)
def ssh_verify_manifest(
manifest_path: Path,
sig_path: Path,
pub_path: Path,
multiple_signatures: bool,
) -> SshVerifyResult:
# The signature file's NAME carries no cryptographic weight -- ssh-keygen
# -Y verify checks the signature bytes against the data bytes via the
# allowed-signers key, never the filename. So a signature file located via
# an explicitly-given --sig (the documented, fully-supported way to point
# at one) used to trigger a "non-standard filename" [WARN] on every single
# use, even though nothing was wrong -- removed rather than kept as a
# lower-severity note, since it has no actionable signal either way.
warnings: List[str] = []
if multiple_signatures:
warnings.append("Multiple SSH signatures found; only the selected signature was verified.")
# Resolve BEFORE the subprocess call: its cwd is set to manifest_path.parent
# below, so a still-relative sig_path would get re-interpreted against that
# NEW cwd instead of ours, silently doubling the directory prefix (e.g.
# ".testing/output" + cwd ".testing/output" -> looks for the nonexistent
# ".testing/output/.testing/output/..."). This was a real bug: any --sig
# given as a relative path, or a manifest located via `--verify <dir>`
# (whose auto-selected path was itself left relative), failed verification
# with an opaque "signature verification failed" and no visible reason.
manifest_path = manifest_path.resolve()
sig_path = sig_path.resolve()
allowed_path = _write_allowed_signers(pub_path)
try:
# `ssh-keygen -Y verify` reads the signed data from STDIN (not a
# positional argument), so feed the manifest file on stdin.
with manifest_path.open("rb") as data_in:
result = subprocess.run(
["ssh-keygen", "-Y", "verify",
"-f", str(allowed_path),
"-I", SSH_SIGNER_IDENTITY,
"-n", SSH_NAMESPACE,
"-s", str(sig_path)],
stdin=data_in, cwd=manifest_path.parent,
capture_output=True, text=True,
)
finally:
Path(allowed_path).unlink(missing_ok=True)
if result.returncode != 0:
# Surface WHY (e.g. "Couldn't read signature file", a genuine bad
# signature, wrong key) instead of a bare, undiagnosable failure.
detail = (result.stderr or result.stdout or "").strip().splitlines()
reason = detail[-1] if detail else "unknown reason"
return SshVerifyResult("FAIL", f"SSH signature verification failed: {reason}", warnings)
return SshVerifyResult("OK", "SSH signature verified.", warnings)
def ssh_key_fingerprint(pub_path: Path) -> Optional[str]:
"""Return the SHA256:... fingerprint of an SSH public key, or None."""
if not ssh_keygen_available():
return None
try:
result = subprocess.run(
["ssh-keygen", "-lf", str(pub_path)],
capture_output=True, text=True, check=True,
)
except subprocess.CalledProcessError:
return None
for token in result.stdout.split():
if token.startswith("SHA256:"):
return token
return None
def gpg_verified_fingerprint(manifest: Path, signature: Path) -> Optional[str]:
"""Return the primary-key fingerprint that produced a VALID gpg signature.
Uses --status-fd so the result is the cryptographically verified signer,
not anything self-declared (defends against key substitution, C1).
"""
try:
result = subprocess.run(
["gpg", "--verify", "--status-fd", "1",
str(signature.resolve()), str(manifest.resolve())],
capture_output=True, text=True,
)
except OSError:
return None
for line in result.stdout.splitlines():
parts = line.split()
# [GNUPG:] VALIDSIG <fpr> <date> ...
if len(parts) >= 3 and parts[0] == "[GNUPG:]" and parts[1] == "VALIDSIG":
return _normalize_gpg_fpr(parts[2])
return None
def gpg_fingerprint_from_keyfile(key_file: Path) -> Optional[str]:
"""Import an armored GPG key into a temp homedir and return its fingerprint."""
tmp_home = Path(tempfile.mkdtemp(prefix="rednb-gpgfpr-"))
try:
os.chmod(tmp_home, 0o700)
subprocess.run(
["gpg", "--homedir", str(tmp_home), "--import", str(key_file.resolve())],
check=True, capture_output=True,
)
result = subprocess.run(
["gpg", "--homedir", str(tmp_home), "--list-secret-keys", "--with-colons"],
check=True, capture_output=True, text=True,
)
for line in result.stdout.splitlines():
parts = line.split(":")
if parts[0] == "fpr":
return _normalize_gpg_fpr(parts[9])
except subprocess.CalledProcessError:
return None
finally:
shutil.rmtree(tmp_home, ignore_errors=True)
return None
# ---------- Trust ----------
def resolve_trust_level(cli_trust: Optional[str], config: Dict) -> str:
"""CLI --trust overrides config trust_level; default 'low'."""
return cli_trust or config.get("trust_level") or "low"
def is_key_trusted(kind: str, fpr: str, config: Dict) -> bool:
"""kind = 'gpg' | 'ssh'. GPG compared normalized; SSH compared verbatim (D3)."""
trusted = config.get("trust", {}).get(kind, [])
if kind == "gpg":
norm = _normalize_gpg_fpr(fpr)
return any(_normalize_gpg_fpr(t) == norm for t in trusted)
return fpr in trusted
def trust_gate_signing(kind: str, fpr: Optional[str], trust_level: str,
config: Dict) -> bool:
"""Enforce trust policy before signing. Returns True to proceed.
high + untrusted → refuse (exit 3). low → always proceed, notify.
"""
label = kind.upper()
if fpr is None:
# Can't determine the key's fingerprint.
if trust_level == "high":
_err(f"Cannot determine {label} key fingerprint — refusing to sign "
"(--trust high).")