-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforge-keys.sh
More file actions
executable file
·1387 lines (1169 loc) · 63.2 KB
/
Copy pathforge-keys.sh
File metadata and controls
executable file
·1387 lines (1169 loc) · 63.2 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 bash
# ═══════════════════════════════════════════════════════════════════════════════
# forge-keys.sh v1.1
# Distributed LUKS key storage with wear-leveled RAW partition
#
# ARCHITECTURE (per device):
# ┌────────────────────────────┬─────────────────────────────────────────────┐
# │ p1: LUKS2 + ext4 (50%) │ p2: RAW (50%) │
# │ (regular files) │ [~~urandom noise (baseline)~~] │
# │ │ [INDEX @ IDX_OFFSET — hardcoded] │
# │ │ [~~noise~~] [chunk_0] [~~noise~~] │
# │ │ [chunk_1..4 @ dynamic offsets] [~~noise~~] │
# └────────────────────────────┴─────────────────────────────────────────────┘
#
# SHAMIR 2-of-3: 3 drives, any 2 reconstruct master LUKS key.
# ANTI-CONFLICT: MIN_GAP guard zones around every layout element.
# WEAR LEVELING: `rotate` moves chunks to new random positions.
#
# COMMANDS:
# setup — Format 3 USB/SD drives, write keys
# open DEV1 DEV2 [LUKS_PART [MAPPER]]
# — Reconstruct key, open LUKS
# rotate DEV — Move chunks to new offsets (wear leveling)
# inspect DEV — Show current RAW layout
#
# EXAMPLE:
# sudo ./forge-keys.sh setup
# sudo ./forge-keys.sh open /dev/sdb /dev/sdc /dev/sdd1 my-vault
# sudo ./forge-keys.sh rotate /dev/sdb
# sudo ./forge-keys.sh inspect /dev/sdb
# ═══════════════════════════════════════════════════════════════════════════════
set -uo pipefail
# NOTE: set -e is intentionally omitted — arithmetic (( )) returns non-zero
# for false, which would kill the script. We handle errors explicitly.
# ═══════════════════════════════════════════════════════════════════════════════
# CONSTANTS — do NOT change after initial setup on any drive
# ═══════════════════════════════════════════════════════════════════════════════
readonly VERSION="1.1"
readonly NUM_CHUNKS=5 # key fragments stored per device
readonly CHUNK_SLOT=256 # bytes reserved per chunk slot (actual key data + padding)
readonly ALIGN=4096 # all offsets sector-aligned to this
# Index block: HARDCODED fixed position in the RAW partition.
# Stores NUM_CHUNKS × 8-byte big-endian uint64 offset values (+ noise pad).
readonly IDX_OFFSET=8192 # bytes from start of p2 — NEVER changes
readonly IDX_SIZE=512 # bytes (holds 5×8=40 bytes + 472 noise bytes)
# Minimum gap (bytes) between any two layout elements (index block or chunk slot).
# With ALIGN=4096 this equals 32 sectors — substantial deniability buffer.
readonly MIN_GAP=131072 # 128 KiB guard zones
# LUKS parameters
readonly LUKS_KEY_BYTES=64 # 512-bit master key
readonly SHAMIR_T=2 # threshold (minimum shares needed)
readonly SHAMIR_N=3 # total shares
# ═══════════════════════════════════════════════════════════════════════════════
# COLORS
# ═══════════════════════════════════════════════════════════════════════════════
R=$(printf "\e[0;31m"); G=$(printf "\e[0;32m"); Y=$(printf "\e[1;33m")
C=$(printf "\e[0;36m"); B=$(printf "\e[0;34m"); NC=$(printf "\e[0m")
# ═══════════════════════════════════════════════════════════════════════════════
# LOGGING
# ═══════════════════════════════════════════════════════════════════════════════
log() { printf "${C}[%s]${NC} %s\n" "$(date +%H:%M:%S)" "$*"; }
ok() { printf "${G}[ ✓ ]${NC} %s\n" "$*"; }
warn() { printf "${Y}[ ! ]${NC} %s\n" "$*"; }
die() { printf "${R}[ERR]${NC} %s\n" "$*" >&2; exit 1; }
banner(){ printf "\n${B}════ %s ════${NC}\n" "$*"; }
# ═══════════════════════════════════════════════════════════════════════════════
# DEPENDENCY MANAGEMENT
# ═══════════════════════════════════════════════════════════════════════════════
declare -A DEP_PKG=(
[cryptsetup]=cryptsetup
[parted]=parted
[partprobe]=parted
[blockdev]=util-linux
[xxd]=xxd
[shred]=coreutils
[lsblk]=util-linux
[gpg]=gnupg
)
readonly SSSS_CMDS=(ssss-split ssss-combine)
_pkg_install() {
local pkgs=("$@")
if command -v apt-get &>/dev/null; then apt-get update -qq && apt-get install -y "${pkgs[@]}"
elif command -v pacman &>/dev/null; then pacman -Sy --noconfirm "${pkgs[@]}"
elif command -v dnf &>/dev/null; then dnf install -y "${pkgs[@]}"
elif command -v zypper &>/dev/null; then zypper install -y "${pkgs[@]}"
else die "No package manager found. Install manually: ${pkgs[*]}"; fi
}
_build_ssss_from_source() {
command -v pacman &>/dev/null && pacman -Sy --noconfirm base-devel gmp 2>/dev/null || true
command -v apt-get &>/dev/null && apt-get install -y build-essential libgmp-dev 2>/dev/null || true
local tmp; tmp=$(mktemp -d /tmp/ssss.XXXXXX)
trap "rm -rf '$tmp'" RETURN
local url="http://point-at-infinity.org/ssss/ssss-0.5.3.tar.gz"
log "Downloading ssss source from $url ..."
if command -v curl &>/dev/null; then
curl -fsSL "$url" -o "$tmp/ssss.tar.gz" || die "curl download failed"
elif command -v wget &>/dev/null; then
wget -q "$url" -O "$tmp/ssss.tar.gz" || die "wget download failed"
else
die "Neither curl nor wget available to download ssss."
fi
tar -xzf "$tmp/ssss.tar.gz" -C "$tmp" --strip-components=1
( cd "$tmp" && make -j"$(nproc)" ) || ( cd "$tmp" && gcc -O2 -o ssss-split ssss.c -lgmp )
[[ -f "$tmp/ssss-split" ]] || die "ssss build failed."
install -m755 "$tmp/ssss-split" /usr/local/bin/ssss-split
cp /usr/local/bin/ssss-split /usr/local/bin/ssss-combine
ok "ssss built from source and installed to /usr/local/bin."
}
_install_ssss() {
command -v ssss-split &>/dev/null && command -v ssss-combine &>/dev/null && return 0
log "ssss not found — installing..."
# Debian/Ubuntu/Fedora: in official repos
if command -v apt-get &>/dev/null; then
apt-get update -qq && apt-get install -y ssss && return 0
fi
if command -v dnf &>/dev/null; then
dnf install -y ssss && return 0
fi
# Arch: AUR only — try helpers, then build from source
if command -v pacman &>/dev/null; then
local aur_user="${SUDO_USER:-}"
[[ -z "$aur_user" || "$aur_user" == "root" ]] && aur_user=$(awk -F: '$3>=1000 && $3<65534{print $1; exit}' /etc/passwd)
if [[ -n "$aur_user" ]]; then
if command -v yay &>/dev/null; then
sudo -u "$aur_user" yay -S --noconfirm ssss && command -v ssss-split &>/dev/null && { ok "ssss installed via yay."; return 0; }
fi
if command -v paru &>/dev/null; then
sudo -u "$aur_user" paru -S --noconfirm ssss && command -v ssss-split &>/dev/null && { ok "ssss installed via paru."; return 0; }
fi
fi
warn "No AUR helper (yay/paru) found. Building ssss from source..."
_build_ssss_from_source
return 0
fi
die "Cannot install ssss. Please install it manually."
}
install_deps() {
[[ $EUID -ne 0 ]] && die "Must run as root."
# 1. ssss (AUR on Arch — special handling)
_install_ssss
# 3. All other deps
local missing_cmds=() missing_pkgs=()
for cmd in "${!DEP_PKG[@]}"; do
command -v "$cmd" &>/dev/null || { missing_cmds+=("$cmd"); missing_pkgs+=("${DEP_PKG[$cmd]}"); }
done
if [[ ${#missing_cmds[@]} -gt 0 ]]; then
warn "Missing: ${missing_cmds[*]}"
local -a upkgs
mapfile -t upkgs < <(printf '%s\n' "${missing_pkgs[@]}" | sort -u)
log "Installing: ${upkgs[*]}"
_pkg_install "${upkgs[@]}" || die "Install failed for: ${upkgs[*]}"
fi
# 4. Verify everything
local failed=()
for cmd in "${!DEP_PKG[@]}" "${SSSS_CMDS[@]}"; do
command -v "$cmd" &>/dev/null || failed+=("$cmd")
done
[[ ${#failed[@]} -gt 0 ]] && die "Still missing after install: ${failed[*]}"
ok "All dependencies verified."
}
# ═══════════════════════════════════════════════════════════════════════════════
# HELPER: safe 48-bit random integer (avoids bash signed-64 overflow)
# ═══════════════════════════════════════════════════════════════════════════════
rand48() {
# Returns a random integer in [0, 2^48)
local hex
hex=$(dd if=/dev/urandom bs=6 count=1 2>/dev/null | xxd -p | tr -d '\n')
printf '%d' "$(( 16#${hex} ))"
}
# ═══════════════════════════════════════════════════════════════════════════════
# HELPER: range overlap check
# overlaps A AL B BL → returns 0 (true) if [A, A+AL) ∩ [B, B+BL) ≠ ∅
# ═══════════════════════════════════════════════════════════════════════════════
overlaps() {
local a=$1 al=$2 b=$3 bl=$4
[[ $(( a < b + bl && a + al > b )) -ne 0 ]]
}
# ═══════════════════════════════════════════════════════════════════════════════
# OFFSET GENERATION
# Produces NUM_CHUNKS sector-aligned byte offsets within a RAW partition,
# with mutual MIN_GAP clearance and clearance from the index block.
#
# Arguments: part_size (bytes)
# Output: space-separated list of offsets (relative to partition start)
# ═══════════════════════════════════════════════════════════════════════════════
gen_offsets() {
local part_size=$1
local -a offs=()
local attempts=0
# A chunk at position C (size CHUNK_SLOT) conflicts with the index block if the
# inter-element gap is less than MIN_GAP in either direction.
# The earliest safe start for a chunk:
# C >= IDX_OFFSET + IDX_SIZE + MIN_GAP (chunk starts at least MIN_GAP after index end)
# The latest safe end:
# C + CHUNK_SLOT <= part_size (chunk fits in partition)
#
# For two chunks A < B: conflict if B - (A + CHUNK_SLOT) < MIN_GAP
# i.e. B < A + CHUNK_SLOT + MIN_GAP
local stride=$(( CHUNK_SLOT + MIN_GAP )) # minimum distance between chunk starts
# Earliest valid chunk start (2×MIN_GAP from index end — extra margin)
local earliest=$(( IDX_OFFSET + IDX_SIZE + 2 * MIN_GAP ))
earliest=$(( (earliest + ALIGN - 1) / ALIGN * ALIGN )) # align up
# Latest valid chunk start
local latest=$(( part_size - CHUNK_SLOT ))
[[ $earliest -ge $latest ]] && \
die "RAW partition too small for index + $NUM_CHUNKS chunks with guard zones."
# Max chunks that could possibly fit (upper bound sanity check)
local avail=$(( latest - earliest ))
local max_possible=$(( avail / stride ))
[[ $max_possible -lt $NUM_CHUNKS ]] && \
die "RAW partition too small: only fits ~$max_possible chunks, need $NUM_CHUNKS."
while [[ ${#offs[@]} -lt $NUM_CHUNKS ]]; do
attempts=$(( attempts + 1 ))
[[ $attempts -gt 300000 ]] && \
die "gen_offsets: cannot place $NUM_CHUNKS offsets without conflicts."
# Random ALIGN-aligned candidate in [earliest, latest]
local rnd; rnd=$(rand48)
local range=$(( (latest - earliest) / ALIGN + 1 ))
local cand=$(( earliest + ( rnd % range ) * ALIGN ))
# Bounds check
[[ $cand -lt $earliest || $(( cand + CHUNK_SLOT )) -gt $part_size ]] && continue
# Must not encroach on index block zone (double-check — earliest handles this,
# but guard against mis-alignment edge cases)
if [[ $cand -lt $(( IDX_OFFSET + IDX_SIZE + MIN_GAP )) ]]; then
continue
fi
# Must clear all already-placed offsets by at least MIN_GAP in both directions
# Conflict: |cand - ex| < CHUNK_SLOT + MIN_GAP
local conflict=0
for ex in "${offs[@]}"; do
local lo hi
if [[ $cand -le $ex ]]; then lo=$cand; hi=$ex
else lo=$ex; hi=$cand; fi
if [[ $(( hi - lo )) -lt $stride ]]; then
conflict=1; break
fi
done
[[ $conflict -eq 1 ]] && continue
offs+=("$cand")
done
printf '%s\n' "${offs[@]}"
}
# ═══════════════════════════════════════════════════════════════════════════════
# INDEX BLOCK — fixed position IDX_OFFSET in the RAW partition
#
# Format: [ offset_0 (8B BE) | offset_1 | ... | offset_4 | noise pad ]
# Total: IDX_SIZE bytes. First 40 bytes are data, rest is urandom noise.
# ═══════════════════════════════════════════════════════════════════════════════
write_index() {
local part=$1; shift
local -a offs=("$@")
# Build data section: NUM_CHUNKS × 8-byte BE uint64
local data_hex=""
for o in "${offs[@]}"; do
data_hex+=$(printf '%016x' "$o")
done
# Noise padding to fill IDX_SIZE
local data_bytes=$(( ${#data_hex} / 2 ))
local pad_bytes=$(( IDX_SIZE - data_bytes ))
local pad_hex
pad_hex=$(dd if=/dev/urandom bs=1 count="$pad_bytes" 2>/dev/null | xxd -p | tr -d '\n')
local full_hex="${data_hex}${pad_hex}"
printf '%s' "$full_hex" | xxd -r -p | \
dd of="$part" bs=1 seek="$IDX_OFFSET" count="$IDX_SIZE" conv=notrunc 2>/dev/null
}
read_index() {
local part=$1
local raw
raw=$(dd if="$part" bs=1 skip="$IDX_OFFSET" count="$(( NUM_CHUNKS * 8 ))" 2>/dev/null \
| xxd -p | tr -d '\n')
local -a offs=()
local _ci
for (( _ci=0; _ci<NUM_CHUNKS; _ci++ )); do
local hex_word="${raw:$(( _ci * 16 )):16}"
# Bash safe: split into two 32-bit halves to avoid signed overflow
local hi=$(( 16#${hex_word:0:8} ))
local lo=$(( 16#${hex_word:8:8} ))
offs+=("$(( hi * 0x100000000 + lo ))")
done
printf '%s\n' "${offs[@]}"
}
# ═══════════════════════════════════════════════════════════════════════════════
# KEY CHUNK I/O
# Each chunk slot is CHUNK_SLOT bytes. Actual key data occupies the front;
# the rest is urandom noise written during the baseline noise fill.
# ═══════════════════════════════════════════════════════════════════════════════
write_chunk() {
local part=$1 offset=$2 hex_data=$3
# Pad hex_data to exactly CHUNK_SLOT bytes
local max_hex=$(( CHUNK_SLOT * 2 ))
local padded
padded=$(printf "%-${max_hex}s" "$hex_data" | tr ' ' '0')
padded="${padded:0:$max_hex}"
printf '%s' "$padded" | xxd -r -p | \
dd of="$part" bs=1 seek="$offset" count="$CHUNK_SLOT" conv=notrunc 2>/dev/null
}
read_chunk() {
local part=$1 offset=$2
dd if="$part" bs=1 skip="$offset" count="$CHUNK_SLOT" 2>/dev/null \
| xxd -p | tr -d '\n'
}
# ═══════════════════════════════════════════════════════════════════════════════
# SHARE ↔ CHUNKS (split a Shamir share string into NUM_CHUNKS hex blobs)
#
# A ssss share looks like "2-a3f29b..." (ASCII, ~130 chars for 64B key).
# We ASCII→hex encode it so it's byte-clean, then split across NUM_CHUNKS slots.
# Total storage: NUM_CHUNKS × CHUNK_SLOT = 5 × 256 = 1280 bytes >> needed.
# ═══════════════════════════════════════════════════════════════════════════════
share_to_chunks() {
local share=$1
# ASCII share string → hex
local hex_share
hex_share=$(printf '%s' "$share" | xxd -p | tr -d '\n')
local per=$(( CHUNK_SLOT * 2 )) # hex chars per chunk
local total=$(( NUM_CHUNKS * per ))
# Zero-pad the full hex to total length
local padded
padded=$(printf "%-${total}s" "$hex_share" | tr ' ' '0')
padded="${padded:0:$total}"
local -a chunks=()
local _ci
for (( _ci=0; _ci<NUM_CHUNKS; _ci++ )); do
chunks+=("${padded:$(( _ci * per )):$per}")
done
printf '%s\n' "${chunks[@]}"
}
chunks_to_share() {
local -a chunks=("$@")
local combined=""
for c in "${chunks[@]}"; do
combined+="$c"
done
# hex → ASCII, strip null bytes and trailing whitespace
printf '%s' "$combined" | xxd -r -p | tr -d '\0' | sed 's/[[:space:]]*$//'
}
# ═══════════════════════════════════════════════════════════════════════════════
# SHAMIR WRAPPERS
# ═══════════════════════════════════════════════════════════════════════════════
shamir_split() {
# Input: master_key_hex
# Output: NUM_SHARES lines, one share per line
local key_hex=$1
printf '%s' "$key_hex" | \
ssss-split -t "$SHAMIR_T" -n "$SHAMIR_N" -x -q 2>/dev/null
}
shamir_combine() {
# Input: two share lines
local s1=$1 s2=$2
printf '%s\n%s\n' "$s1" "$s2" | \
ssss-combine -t "$SHAMIR_T" -x -q 2>/dev/null
}
# ═══════════════════════════════════════════════════════════════════════════════
# DEVICE SELECTION — pure CLI, numbered list
# Sets global: SELECTED_DEVS[0..2]
# ═══════════════════════════════════════════════════════════════════════════════
SELECTED_DEVS=()
# Print available block devices as a numbered list.
# Stores results in global DEVS array: index → /dev/sdX
# Returns 1 if nothing found.
DEVS=()
_list_devices() {
local -a exclude=("$@")
DEVS=()
local boot_dev=""
local src; src=$(findmnt -n -o SOURCE / 2>/dev/null | head -1)
[[ -n "$src" ]] && boot_dev="/dev/$(lsblk -no PKNAME "$src" 2>/dev/null | head -1)"
local n=0
printf "\n${Y} # %-14s %7s %-6s %s${NC}\n" "DEVICE" "SIZE" "BUS" "MODEL"
printf " %-4s %-14s %7s %-6s %s\n" "---" "---------" "------" "-----" "-----"
while IFS= read -r line; do
[[ -z "$line" ]] && continue
local dev size tran model
read -r dev size tran model <<< "$line"
# model may be empty or multi-word; re-extract
model=$(echo "$line" | awk '{for(i=4;i<=NF;i++) printf "%s%s",$i,(i<NF?" ":""); print ""}')
# skip non-root loop (snap etc)
[[ "$dev" =~ loop ]] && ! [[ "$dev" =~ ^/dev/loop[0-9]+$ ]] && continue
# skip already chosen
local skip=0
for ex in "${exclude[@]}"; do [[ "$dev" == "$ex" ]] && skip=1 && break; done
[[ $skip -eq 1 ]] && continue
n=$(( n + 1 ))
DEVS[$n]="$dev"
local note=""
[[ "$dev" == "$boot_dev" ]] && note="${R} [SYSTEM DISK]${NC}"
printf " ${G}%-3d${NC} %-14s %7s %-6s %s" "$n" "$dev" "$size" "${tran:--}" "$model"
[[ -n "$note" ]] && printf "%b" "$note"
printf "\n"
done < <(lsblk -dpno NAME,SIZE,TRAN,MODEL 2>/dev/null)
echo
[[ $n -eq 0 ]] && return 1
return 0
}
# Pick one device. Stores result in global _PICKED.
# $1 = label (e.g. "1 of 3"), $2..= already selected devs
_PICKED=""
_pick_device() {
local label=$1; shift
local -a exclude=("$@")
_PICKED=""
while true; do
printf "${C}─── Device slot %s ───${NC}\n" "$label"
[[ ${#exclude[@]} -gt 0 ]] && printf "Already selected: ${Y}%s${NC}\n" "${exclude[*]}"
if ! _list_devices "${exclude[@]}"; then
printf "No devices found. Insert USB/SD and press Enter to rescan (Ctrl-C to abort): "
read -r; continue
fi
local max=${#DEVS[@]}
printf "Enter number [1-%d], r=rescan, q=quit: " "$max"
local ans; read -r ans
[[ "$ans" == q ]] && die "Aborted."
[[ "$ans" == r ]] && continue
if ! [[ "$ans" =~ ^[0-9]+$ ]] || (( ans < 1 || ans > max )); then
warn "Bad input. Enter a number from 1 to $max."
continue
fi
local chosen="${DEVS[$ans]}"
local bytes; bytes=$(blockdev --getsize64 "$chosen" 2>/dev/null || echo 0)
local mib=$(( bytes / 1024 / 1024 ))
printf "\n → ${Y}%s${NC} (%d MiB) — ${R}ALL DATA WILL BE ERASED${NC}\n" "$chosen" "$mib"
printf " Confirm? [y/N]: "
local ok; read -r ok
[[ "${ok,,}" == y ]] || { echo " Re-selecting..."; continue; }
_PICKED="$chosen"
return 0
done
}
select_devices() {
SELECTED_DEVS=()
echo
log "Select 3 USB/SD devices. All data on them will be erased."
for (( slot=1; slot<=SHAMIR_N; slot++ )); do
_pick_device "$slot of $SHAMIR_N" "${SELECTED_DEVS[@]}"
SELECTED_DEVS+=("$_PICKED")
ok "Slot $slot → $_PICKED"
echo
done
printf "${Y}═══ FINAL CONFIRMATION ═══${NC}\n"
printf "These devices will be ${R}permanently erased${NC}:\n\n"
for i in "${!SELECTED_DEVS[@]}"; do
local b; b=$(blockdev --getsize64 "${SELECTED_DEVS[$i]}" 2>/dev/null || echo 0)
printf " Slot %d: ${Y}%s${NC} (%d MiB)\n" "$(( i+1 ))" "${SELECTED_DEVS[$i]}" "$(( b/1024/1024 ))"
done
echo
printf "Type ${G}YES${NC} to proceed, anything else to abort: "
local c; read -r c
[[ "$c" == YES ]] || die "Aborted."
echo
}
# ═══════════════════════════════════════════════════════════════════════════════
# DEVICE PREPARATION: wipe + GPT + 2 partitions (50% / 50%)
#
# Returns via stdout: "P1_PATH P2_PATH P2_SIZE_BYTES"
# ═══════════════════════════════════════════════════════════════════════════════
prepare_device() {
local dev=$1
# NOTE: called as geo=$(prepare_device "$dev"), so stdout is captured by the caller.
# All log/warn output MUST go to stderr (>&2) so it reaches the terminal.
# Only the final "p1 p2 p2_size" line goes to stdout.
log " Wiping signatures on $dev..." >&2
dd if=/dev/zero of="$dev" bs=1M count=4 conv=notrunc 2>/dev/null
sync; sleep 1
local total_bytes
total_bytes=$(blockdev --getsize64 "$dev")
log " Capacity: $total_bytes B ($(( total_bytes / 1024 / 1024 )) MiB)" >&2
local total_mib=$(( total_bytes / 1024 / 1024 ))
local half_mib=$(( total_mib / 2 ))
# Enforce minimum: 256 MiB per device
[[ $half_mib -lt 128 ]] && die "$dev: need >=256 MiB total, got ${total_mib} MiB."
log " Partitioning: p1=${half_mib}MiB (LUKS+ext4), p2=${half_mib}MiB (RAW)..." >&2
parted -s "$dev" -- \
mklabel gpt \
mkpart primary 1MiB "${half_mib}MiB" \
mkpart primary "${half_mib}MiB" "$(( total_mib - 1 ))MiB"
partprobe "$dev" 2>/dev/null || true
sleep 2
# Detect partition naming (sdX1 vs sdXp1 for MMC)
local p1 p2
if [[ -b "${dev}1" ]]; then p1="${dev}1"; p2="${dev}2"
elif [[ -b "${dev}p1" ]]; then p1="${dev}p1"; p2="${dev}p2"
else die "Cannot find partitions on $dev after partprobe. Try udevadm settle."; fi
# Wait for kernel to expose the block device (rename _ to _w to avoid set -u issues)
local _w
for _w in 1 2 3 4 5; do
[[ -b "$p2" ]] && break
sleep 1
done
[[ -b "$p2" ]] || die "Partition $p2 not available after 5s."
local p2_size
p2_size=$(blockdev --getsize64 "$p2")
# Only this line is captured by $() in the caller
printf '%s %s %s\n' "$p1" "$p2" "$p2_size"
}
# ═══════════════════════════════════════════════════════════════════════════════
# LUKS2 FORMAT + EXT4
# ═══════════════════════════════════════════════════════════════════════════════
setup_luks() {
local part=$1 key_hex=$2 mapper=$3
log " LUKS2 format: $part ..."
local kf
kf=$(mktemp /dev/shm/ukf-XXXXXX) || die "Cannot create temp key file in /dev/shm"
printf '%s' "$key_hex" | xxd -r -p > "$kf"
cryptsetup luksFormat \
--type luks2 \
--key-file "$kf" \
--key-size $(( LUKS_KEY_BYTES * 8 )) \
--cipher aes-xts-plain64 \
--hash sha512 \
--pbkdf argon2id \
--iter-time 2000 \
--batch-mode \
"$part" || { shred -zu "$kf"; die "luksFormat failed on $part"; }
cryptsetup luksOpen --key-file "$kf" "$part" "$mapper" || \
{ shred -zu "$kf"; die "luksOpen failed on $part"; }
log " Creating ext4 on /dev/mapper/$mapper ..."
mkfs.ext4 -q "/dev/mapper/$mapper" || { cryptsetup luksClose "$mapper"; shred -zu "$kf"; die "mkfs.ext4 failed"; }
udevadm settle 2>/dev/null || true
local _lc_try
for _lc_try in 1 2 3 4 5; do
cryptsetup luksClose "$mapper" 2>/dev/null && break
sleep 1
done
shred -zu "$kf"
}
# ═══════════════════════════════════════════════════════════════════════════════
# RAW PARTITION LAYOUT WRITER
#
# Step 1: noise-fill entire partition (baseline)
# Step 2: write index block at IDX_OFFSET (hardcoded)
# Step 3: write key chunks at generated dynamic offsets
# (gaps between elements remain as urandom noise from step 1)
# ═══════════════════════════════════════════════════════════════════════════════
write_raw_layout() {
local part=$1 p2_size=$2 share=$3
# Minimum required space sanity check
local min_needed=$(( IDX_OFFSET + IDX_SIZE + MIN_GAP \
+ NUM_CHUNKS * (CHUNK_SLOT + MIN_GAP) * 3 ))
[[ $p2_size -lt $min_needed ]] && \
die "RAW partition too small: ${p2_size}B < ${min_needed}B required."
# Step 1 — noise baseline
log " [RAW] Noise baseline ($(( p2_size / 1024 / 1024 )) MiB from /dev/urandom)..."
dd if=/dev/urandom of="$part" bs=65536 \
count=$(( p2_size / 65536 )) conv=notrunc status=progress 2>&1 || true
echo
# Handle remainder bytes
local rem=$(( p2_size % 65536 ))
[[ $rem -gt 0 ]] && \
dd if=/dev/urandom of="$part" bs=1 \
seek=$(( p2_size - rem )) count="$rem" conv=notrunc 2>/dev/null || true
sync
# Step 2 — generate conflict-free offsets
log " [RAW] Generating $NUM_CHUNKS conflict-free offsets..."
local -a offs=()
while IFS= read -r line; do offs+=("$line"); done < <(gen_offsets "$p2_size")
[[ ${#offs[@]} -ne $NUM_CHUNKS ]] && die "gen_offsets returned ${#offs[@]} offsets (expected $NUM_CHUNKS)"
log " [RAW] Offsets (bytes): ${offs[*]}"
# Step 3 — write index block
log " [RAW] Writing index @ offset $IDX_OFFSET (hardcoded)..."
write_index "$part" "${offs[@]}"
# Step 4 — split share into chunks and write
log " [RAW] Splitting share and writing $NUM_CHUNKS chunks..."
local -a chunk_hexes=()
while IFS= read -r line; do chunk_hexes+=("$line"); done < <(share_to_chunks "$share")
[[ ${#chunk_hexes[@]} -ne $NUM_CHUNKS ]] && die "share_to_chunks returned wrong count"
local _ci
for (( _ci=0; _ci<NUM_CHUNKS; _ci++ )); do
write_chunk "$part" "${offs[$_ci]}" "${chunk_hexes[$_ci]}"
done
sync
ok " [RAW] Layout written: index + $NUM_CHUNKS chunks, surrounded by noise."
}
# ═══════════════════════════════════════════════════════════════════════════════
# READBACK VERIFICATION
# ═══════════════════════════════════════════════════════════════════════════════
verify_raw_layout() {
local part=$1 expected_share=$2
log " [VERIFY] Reading back layout from $part..."
local -a offs=()
while IFS= read -r line; do offs+=("$line"); done < <(read_index "$part")
local -a chunks=()
for o in "${offs[@]}"; do
chunks+=("$(read_chunk "$part" "$o")")
done
local got_share
got_share=$(chunks_to_share "${chunks[@]}")
if [[ "$got_share" == "$expected_share" ]]; then
ok " [VERIFY] Readback OK."
else
warn " [VERIFY] MISMATCH!"
warn " Expected: ${expected_share:0:32}..."
warn " Got: ${got_share:0:32}..."
die "Readback verification failed on $part"
fi
}
# ═══════════════════════════════════════════════════════════════════════════════
# PARTITION RESOLVER (sdX1 vs sdXp1 naming)
# ═══════════════════════════════════════════════════════════════════════════════
get_p2() {
local dev=$1
if [[ -b "${dev}2" ]]; then printf '%s' "${dev}2"
elif [[ -b "${dev}p2" ]]; then printf '%s' "${dev}p2"
else die "Cannot find partition 2 on $dev"; fi
}
get_p1() {
local dev=$1
if [[ -b "${dev}1" ]]; then printf '%s' "${dev}1"
elif [[ -b "${dev}p1" ]]; then printf '%s' "${dev}p1"
else die "Cannot find partition 1 on $dev"; fi
}
# ═══════════════════════════════════════════════════════════════════════════════
# COMMAND: setup
# ═══════════════════════════════════════════════════════════════════════════════
cmd_setup() {
[[ $EUID -ne 0 ]] && die "setup must run as root."
banner "KEY GENERATION"
# 1 — Master LUKS key (512-bit, /dev/urandom)
local master_hex
master_hex=$(dd if=/dev/urandom bs="$LUKS_KEY_BYTES" count=1 2>/dev/null \
| xxd -p | tr -d '\n')
ok "Master key: ${LUKS_KEY_BYTES}B ($(( LUKS_KEY_BYTES * 8 )) bits)"
# 2 — Shamir 2-of-3
log "Running Shamir split (t=$SHAMIR_T, n=$SHAMIR_N)..."
local raw_shares
raw_shares=$(shamir_split "$master_hex") || die "ssss-split failed"
local -a shares=()
while IFS= read -r s; do [[ -n "$s" ]] && shares+=("$s"); done <<< "$raw_shares"
[[ ${#shares[@]} -ne $SHAMIR_N ]] && \
die "Shamir split returned ${#shares[@]} shares, expected $SHAMIR_N."
ok "3 shares generated. Any 2 of 3 reconstruct the master key."
# 3 — Process each device one at a time (select → write → swap → repeat)
SELECTED_DEVS=()
for (( i=0; i<SHAMIR_N; i++ )); do
local share="${shares[$i]}"
local mapper="ukf-setup-$$-${i}"
echo
log "Insert device $((i+1)) of $SHAMIR_N and select it below."
_pick_device "$((i+1)) of $SHAMIR_N" "${SELECTED_DEVS[@]+"${SELECTED_DEVS[@]}"}"
local dev="$_PICKED"
SELECTED_DEVS+=("$dev")
ok "Slot $((i+1)) → $dev"
banner "DEVICE $((i+1))/$SHAMIR_N — $dev"
local geo
geo=$(prepare_device "$dev")
local p1 p2 p2_size
p1=$(awk '{print $1}' <<< "$geo")
p2=$(awk '{print $2}' <<< "$geo")
p2_size=$(awk '{print $3}' <<< "$geo")
# Write RAW layout: noise + index + chunks
write_raw_layout "$p2" "$p2_size" "$share"
# Verify readback
verify_raw_layout "$p2" "$share"
# LUKS2 + ext4 on p1
setup_luks "$p1" "$master_hex" "$mapper"
ok "Device $((i+1)) complete ✓"
# Prompt to swap before next device (skip after last)
if (( i < SHAMIR_N - 1 )); then
printf "\n${Y}Remove this device and insert device $((i+2)) of $SHAMIR_N.${NC}\n"
printf "Press Enter when ready... "
read -r
fi
done
# ════════════════════════════════════════════════════════════════════════
# MASTER KEY BACKUP
# ════════════════════════════════════════════════════════════════════════
echo
printf "${Y}Would you like to create an encrypted master key backup?${NC}\n"
printf "This will save your data if you lose 2 of the 3 USB keys.\n"
printf "Create backup? [y/N]: "
local make_backup
read -r make_backup
if [[ "${make_backup,,}" == "y" ]]; then
# Save to the folder from which the script is run
local backup_file="$PWD/ukf-master-key-backup.gpg"
log "Creating backup (GPG will prompt for passphrase)..."
# Encrypt the master key hex string with AES256 symmetric cipher
if printf '%s' "$master_hex" | gpg --symmetric --cipher-algo AES256 --output "$backup_file" 2>/dev/null; then
ok "Backup successfully created: $backup_file"
warn "MAKE SURE to save this file in a secure cloud or storage!"
else
warn "Error creating GPG backup."
fi
fi
# ════════════════════════════════════════════════════════════════════════
# Wipe master key from bash variable
master_hex=$(dd if=/dev/urandom bs="${#master_hex}" count=1 2>/dev/null \
| xxd -p | tr -d '\n' | head -c "${#master_hex}")
unset master_hex shares raw_shares
echo
printf "${G}"
echo "════════════════════════════════════════════════"
echo " All 3 devices configured successfully."
echo " 2-of-3 Shamir scheme active."
echo "════════════════════════════════════════════════"
printf "${NC}"
echo
echo " Unlock: sudo $0 open /dev/sdX /dev/sdY /dev/sdZ1 [mapper]"
echo " Rotate: sudo $0 rotate /dev/sdX"
echo " Inspect: sudo $0 inspect /dev/sdX"
echo
}
# ═══════════════════════════════════════════════════════════════════════════════
# COMMAND: restore
# Decrypts the GPG backup file and sets up the Shamir scheme on 3 new drives
# ═══════════════════════════════════════════════════════════════════════════════
cmd_restore() {
[[ $EUID -ne 0 ]] && die "restore must be run as root."
local backup_file="${1:-$PWD/ukf-master-key-backup.gpg}"
if [[ ! -f "$backup_file" ]]; then
printf "${Y}[ ! ] Backup file not found at: $backup_file${NC}\n"
printf "Enter the full path to your .gpg backup file: "
read -r backup_file
[[ -f "$backup_file" ]] || die "Backup file does not exist: $backup_file"
fi
banner "RECOVERY FROM BACKUP"
log "Decrypting file $backup_file (enter password in the prompt)..."
# Decrypt key hex string via GPG
local master_hex
master_hex=$(gpg --decrypt "$backup_file" 2>/dev/null)
if [[ -z "$master_hex" || ${#master_hex} -ne $(( LUKS_KEY_BYTES * 2 )) ]]; then
die "Failed to decrypt key or file is corrupted (invalid master key length)."
fi
ok "Master key successfully extracted from backup!"
# Run Shamir split for the recovered key
log "Running Shamir split (t=$SHAMIR_T, n=$SHAMIR_N)..."
local raw_shares
raw_shares=$(shamir_split "$master_hex") || die "ssss-split failed."
local -a shares=()
while IFS= read -r s; do [[ -n "$s" ]] && shares+=("$s"); done <<< "$raw_shares"
[[ ${#shares[@]} -ne $SHAMIR_N ]] && \
die "Shamir split returned ${#shares[@]} shares, expected $SHAMIR_N."
ok "3 new shares generated. Any 2 of 3 will reconstruct the master key."
# Write to 3 new USB drives (similar to setup)
SELECTED_DEVS=()
for (( i=0; i<SHAMIR_N; i++ )); do
local share="${shares[$i]}"
local mapper="ukf-restore-$$-${i}"
echo
log "Insert device $((i+1)) of $SHAMIR_N and select it below."
_pick_device "$((i+1)) of $SHAMIR_N" "${SELECTED_DEVS[@]+"${SELECTED_DEVS[@]}"}"
local dev="$_PICKED"
SELECTED_DEVS+=("$dev")
ok "Slot $((i+1)) → $dev"
banner "DEVICE $((i+1))/$SHAMIR_N — $dev"
local geo
geo=$(prepare_device "$dev")
local p1 p2 p2_size
p1=$(awk '{print $1}' <<< "$geo")
p2=$(awk '{print $2}' <<< "$geo")
p2_size=$(awk '{print $3}' <<< "$geo")
# Write RAW layout (noise + index + share)
write_raw_layout "$p2" "$p2_size" "$share"
# Verify readback
verify_raw_layout "$p2" "$share"
# Format LUKS2 and ext4 under our old recovered master key
setup_luks "$p1" "$master_hex" "$mapper"
ok "Device $((i+1)) complete ✓"
# Prompt to swap device
if (( i < SHAMIR_N - 1 )); then
printf "\n${Y}Remove this device and insert device $((i+2)) of $SHAMIR_N.${NC}\n"
printf "Press Enter when ready... "
read -r
fi
done
# Wipe master key from bash variable for safety
master_hex=$(dd if=/dev/urandom bs="${#master_hex}" count=1 2>/dev/null \
| xxd -p | tr -d '\n' | head -c "${#master_hex}")
unset master_hex shares raw_shares
echo
printf "${G}"
echo "═════════════════════════════════════════════════════"
echo " All 3 devices successfully reconstructed from backup!"
echo " Your encrypted partitions match the old key."
echo " Shamir 2-of-3 scheme is active again."
echo "═════════════════════════════════════════════════════"
printf "${NC}"
echo
}
# ═══════════════════════════════════════════════════════════════════════════════
# COMMAND: open
# Reads shares from 2 drives, reconstructs master key, opens LUKS partition.
# ═══════════════════════════════════════════════════════════════════════════════
cmd_open() {
[[ $EUID -ne 0 ]] && die "open must run as root."
[[ $# -lt 2 ]] && { usage; exit 1; }
local dev1=$1 dev2=$2
local luks_part="${3:-}"
local mapper="${4:-ukf-volume}"
banner "OPEN — reconstruct key from 2 drives"
local -a shares=()
for dev in "$dev1" "$dev2"; do
local p2; p2=$(get_p2 "$dev")
log "Reading from $dev ($p2)..."
local -a offs=()
while IFS= read -r line; do offs+=("$line"); done < <(read_index "$p2")
log " Offsets: ${offs[*]}"
local -a chunks=()
for o in "${offs[@]}"; do
chunks+=("$(read_chunk "$p2" "$o")")
done
local share; share=$(chunks_to_share "${chunks[@]}")
[[ -z "$share" ]] && die "Empty share from $dev — wrong device or corrupted."
shares+=("$share")
ok "Share read from $dev: ${share:0:20}..."
done
log "Combining Shamir shares..."
local master_hex
master_hex=$(shamir_combine "${shares[0]}" "${shares[1]}") || \
die "ssss-combine failed. Shares may be from wrong/mismatched drives."
[[ -z "$master_hex" ]] && die "Reconstructed key is empty."
ok "Master key reconstructed."
if [[ -n "$luks_part" ]]; then
log "Opening LUKS on $luks_part → /dev/mapper/$mapper ..."
local kf; kf=$(mktemp /dev/shm/ukf-XXXXXX)
printf '%s' "$master_hex" | xxd -r -p > "$kf"
cryptsetup luksOpen --key-file "$kf" "$luks_part" "$mapper" || \
{ shred -zu "$kf"; die "luksOpen failed."; }
shred -zu "$kf"
ok "Volume open: /dev/mapper/$mapper"
echo
echo " Mount: mount /dev/mapper/$mapper /mnt/vault"
echo " Close: cryptsetup luksClose $mapper"
else
warn "No LUKS partition specified — key reconstructed but not used."
warn "Pass the LUKS partition as 3rd arg: $0 open DEV1 DEV2 /dev/sdZ1 [mapper]"
fi
master_hex=$(dd if=/dev/urandom bs="${#master_hex}" count=1 2>/dev/null \
| xxd -p | tr -d '\n' | head -c "${#master_hex}")
unset master_hex shares
}
# ═══════════════════════════════════════════════════════════════════════════════
# COMMAND: backup_existing
# Reads shares from 2 drives, reconstructs master key, and creates an encrypted
# GPG backup of it.
# ═══════════════════════════════════════════════════════════════════════════════
cmd_backup_existing() {
[[ $EUID -ne 0 ]] && die "open must run as root."
[[ $# -lt 2 ]] && { usage; exit 1; }
local dev1=$1 dev2=$2
local luks_part="${3:-}"
local mapper="${4:-ukf-volume}"
banner "OPEN — reconstruct key from 2 drives"
local -a shares=()
for dev in "$dev1" "$dev2"; do
local p2; p2=$(get_p2 "$dev")
log "Reading from $dev ($p2)..."