Repository navigation
Expand file tree
/
Copy pathinstall.sh
More file actions
2582 lines (2429 loc) · 96.8 KB
/
Copy pathinstall.sh
File metadata and controls
2582 lines (2429 loc) · 96.8 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 sh
#
# KeyHog installer (Linux + macOS).
#
# This installer does NOT download from GitHub releases. KeyHog publishes to
# crates.io only; the signed binary-asset channel was retired. Install the
# current release with:
#
# cargo install keyhog --locked
#
# Use this script to install a binary you already have, such as a CI artifact,
# an air-gapped transfer, or a local build:
#
# sh install.sh --from-file=./keyhog
#
# Modes:
# (default) install or upgrade keyhog from --from-file
# --diagnose print full host + binary status, make no changes
# --calibrate rerun visible autoroute calibration for the installed binary
# --uninstall remove the binary plus installer-owned PATH and completions
#
# Common flags:
# --from-file=PATH REQUIRED to install. Verifies a sibling PATH.minisig and
# PATH.sha256 when present, then runs backup, atomic swap,
# keyhog doctor, and rollback on failure.
# --install-dir=PATH override the default install directory
# --yes / -y non-interactive: accept defaults, no prompts
# --no-prompt never prompt; treat every question as its default
# --insecure proceed when local proof files are absent; a mismatch
# still fails
# --no-calibrate install and verify without measuring autoroute
# --no-color disable ANSI colors
# --help / -h show this help and exit
#
# Env overrides:
# NO_COLOR
set -eu
# Refuse to run when SOURCED. This installer calls `exit` on many paths, and
# `exit` inside a sourced script terminates the caller's interactive shell, a
# nasty surprise for anyone who runs `. install.sh` / `source install.sh`. The
# guard is scoped to bash/zsh (the shells that expose a sourcing signal); under a
# plain POSIX `sh` the normal `sh install.sh` run path hits neither branch and is
# left completely unchanged. `if`/`then` (not `[ ] && …`) keeps it safe under the
# `set -e` above when the condition is false on the normal run path.
if [ -n "${BASH_SOURCE:-}" ]; then
if [ "${BASH_SOURCE}" != "$0" ]; then
printf '%s\n' "keyhog installer: run this script (sh install.sh), do not source it." >&2
return 1
fi
elif [ -n "${ZSH_EVAL_CONTEXT:-}" ]; then
case "$ZSH_EVAL_CONTEXT" in
*:file)
printf '%s\n' "keyhog installer: run this script (sh install.sh), do not source it." >&2
return 1
;;
esac
fi
REPO="santhreal/keyhog"
RELEASE_PUBLIC_KEY="RWTPnJ/p6xVJ3TJIxr+ZVHMD/MTHWZhsdE38Go/oD3DYBoi4bePR55go"
INSTALL_DIR="$HOME/.local/bin"
FROM_FILE=""
INSECURE_INSTALL=0
SKIP_CALIBRATION=0
GPU_LITERALS_FROM_BINARY=0
MODE="install"
INTERACTIVE=1
ASSUME_YES=0
USE_COLOR=1
# ============================================================
# colors / style
# ============================================================
if [ "${NO_COLOR:-}" != "" ] || [ ! -t 1 ]; then
USE_COLOR=0
fi
setup_colors() {
if [ "$USE_COLOR" = "1" ]; then
C_RESET=$(printf '\033[0m')
C_BOLD=$(printf '\033[1m')
C_DIM=$(printf '\033[2m')
C_RED=$(printf '\033[31m')
C_GREEN=$(printf '\033[32m')
C_YELLOW=$(printf '\033[33m')
C_CYAN=$(printf '\033[36m')
else
C_RESET='' C_BOLD='' C_DIM='' C_RED='' C_GREEN='' C_YELLOW='' C_CYAN=''
fi
}
say() { printf '%s\n' "$*"; }
status() {
kh_status_label="$1"
kh_status_color="$2"
shift 2
printf '%s%s%s %s\n' "$kh_status_color" "$kh_status_label" "$C_RESET" "$*"
}
status_err() {
kh_status_label="$1"
kh_status_color="$2"
shift 2
printf '%s%s%s %s\n' "$kh_status_color" "$kh_status_label" "$C_RESET" "$*" >&2
}
info() { status INFO "$C_CYAN" "$*"; }
ok() { status PASS "$C_GREEN" "$*"; }
warn() { status WARN "$C_YELLOW" "$*"; }
err() { status_err FAIL "$C_RED" "$*"; }
dim() { printf '%s%s%s\n' "$C_DIM" "$*" "$C_RESET"; }
now_ms() {
kh_now_ms="$(date +%s%3N 2>/dev/null || true)"
case "$kh_now_ms" in
''|*[!0123456789]*)
kh_now_s="$(date +%s 2>/dev/null || printf '0')"
printf '%s000\n' "$kh_now_s"
;;
*)
printf '%s\n' "$kh_now_ms"
;;
esac
}
elapsed_ms_since() {
kh_elapsed_start_ms="$1"
kh_elapsed_end_ms="$(now_ms)"
case "$kh_elapsed_start_ms:$kh_elapsed_end_ms" in
*[!0123456789:]*|:*|*:)
printf '0\n'
;;
*)
if [ "$kh_elapsed_end_ms" -ge "$kh_elapsed_start_ms" ]; then
printf '%s\n' "$((kh_elapsed_end_ms - kh_elapsed_start_ms))"
else
printf '0\n'
fi
;;
esac
}
banner() {
if [ "$INTERACTIVE" = "1" ]; then
printf '\n%s KeyHog installer%s %s(secret scanner, %s)%s\n\n' \
"$C_BOLD" "$C_RESET" "$C_DIM" "$REPO" "$C_RESET"
else
say "keyhog installer (non-interactive)"
fi
}
# Prompt the user with a default. Usage: prompt "Question?" "default" -> sets $REPLY
prompt() {
question="$1"
default="${2:-}"
if [ "$INTERACTIVE" != "1" ] || [ "$ASSUME_YES" = "1" ]; then
REPLY="$default"
return
fi
if [ -n "$default" ]; then
printf '%s %s[%s]%s: ' "$question" "$C_DIM" "$default" "$C_RESET"
else
printf '%s: ' "$question"
fi
if ! IFS= read -r REPLY < /dev/tty 2>/dev/null; then
REPLY="$default"
printf '\n'
return
fi
[ -z "$REPLY" ] && REPLY="$default"
}
# yes/no prompt. Usage: confirm "Question?" "Y" -> returns 0 if yes, 1 if no
confirm() {
question="$1"
default="${2:-Y}"
if [ "$ASSUME_YES" = "1" ]; then
case "$default" in Y|y) return 0 ;; *) return 1 ;; esac
fi
if [ "$INTERACTIVE" != "1" ]; then
case "$default" in Y|y) return 0 ;; *) return 1 ;; esac
fi
hint="[Y/n]"
if [ "$default" = "N" ] || [ "$default" = "n" ]; then
hint="[y/N]"
fi
while :; do
printf '%s %s%s%s ' "$question" "$C_DIM" "$hint" "$C_RESET"
if ! IFS= read -r ans < /dev/tty 2>/dev/null; then
ans="$default"
printf '\n'
fi
[ -z "$ans" ] && ans="$default"
case "$ans" in
y|Y|yes|YES) return 0 ;;
n|N|no|NO) return 1 ;;
*) warn "Please answer y or n." ;;
esac
done
}
# ============================================================
# argument parsing
# ============================================================
usage() {
# When invoked from a file (`sh install.sh --help`) the header comment IS
# the help, so reproduce it from $0. Take the comment block itself rather
# than a pinned line range: a range goes stale the next time a flag is
# documented. When $0 is not readable, fall back to a built-in synopsis so
# --help still works.
help_text=""
if [ -r "$0" ]; then
help_text=$(awk 'NR==1 {next} /^#/ {sub(/^# ?/, ""); print; next} {exit}' "$0" 2>/dev/null)
fi
if [ -n "$help_text" ]; then
printf '%s\n' "$help_text"
else
printf '%s\n' \
"KeyHog installer (Linux + macOS)." \
"" \
"This script installs a binary you already have. It does not download" \
"from GitHub releases. For the current release, run:" \
" cargo install keyhog --locked" \
"" \
"Install a local binary:" \
" sh install.sh --from-file=./keyhog" \
"" \
"Modes: (default) install/upgrade --diagnose --calibrate --uninstall" \
"Flags: --from-file=PATH --install-dir=PATH" \
" --yes/-y --no-prompt --no-calibrate --insecure" \
"Env: NO_COLOR"
fi
exit 0
}
while [ $# -gt 0 ]; do
case "$1" in
--diagnose) MODE="diagnose" ;;
--calibrate) MODE="calibrate" ;;
--uninstall) MODE="uninstall" ;;
--install-dir=*) INSTALL_DIR="${1#--install-dir=}" ;;
--from-file=*) FROM_FILE="${1#--from-file=}" ;;
--yes|-y) ASSUME_YES=1 ;;
--no-prompt) INTERACTIVE=0 ;;
--insecure) INSECURE_INSTALL=1 ;;
--no-calibrate) SKIP_CALIBRATION=1 ;;
--no-color) USE_COLOR=0 ;;
--help|-h) usage ;;
*)
printf 'Unknown argument: %s\n' "$1" >&2
printf "Try: %s --help\n" "$0" >&2
exit 1
;;
esac
shift
done
# stdin not a TTY (piped input, CI) means we can't prompt at all.
[ -t 0 ] || INTERACTIVE=0
setup_colors
# ============================================================
# detection
# ============================================================
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
current_binary() {
if [ -x "$INSTALL_DIR/keyhog" ]; then
printf '%s\n' "$INSTALL_DIR/keyhog"
elif command -v keyhog >/dev/null 2>&1; then
command -v keyhog
fi
}
current_version() {
bin=$(current_binary)
[ -z "$bin" ] && return
"$bin" --version 2>/dev/null | head -n 1
}
# ============================================================
# install flow
# ============================================================
allow_unverified_install() {
reason="$1"
if [ "$INSECURE_INSTALL" = "1" ]; then
warn " INSECURE: $reason"
warn " Proceeding without full release verification because --insecure is set."
return 0
fi
err "$reason"
err "Refusing to install an unverified keyhog binary."
case "$reason" in
*"minisign is not installed"*)
print_minisign_install_hint
;;
*)
err "Fix: ensure the .minisig and .sha256 files are published, minisign is installed, and sha256sum or shasum is available."
;;
esac
err "Only for emergency/local diagnostics, rerun with --insecure to accept an unverified binary."
return 1
}
print_minisign_install_hint() {
case "$OS" in
darwin)
if command -v brew >/dev/null 2>&1; then
err "Fix: install minisign with: brew install minisign"
else
err "Fix: install Homebrew, then run: brew install minisign"
err "Portable fallback: cargo install minisign"
fi
;;
linux)
if command -v apt-get >/dev/null 2>&1; then
err "Fix: install minisign with: sudo apt-get update && sudo apt-get install -y minisign"
elif command -v dnf >/dev/null 2>&1; then
err "Fix: install minisign with: sudo dnf install -y minisign"
elif command -v yum >/dev/null 2>&1; then
err "Fix: install minisign with: sudo yum install -y minisign"
elif command -v apk >/dev/null 2>&1; then
err "Fix: install minisign with: sudo apk add minisign"
elif command -v pacman >/dev/null 2>&1; then
err "Fix: install minisign with: sudo pacman -S --needed minisign"
else
err "Fix: install minisign with your distro package manager, or run: cargo install minisign"
fi
;;
*)
err "Fix: install minisign, then rerun this command."
;;
esac
}
# Verify a local artifact signature when a sibling `.minisig` is present.
# Offline checksum-only bundles remain compatible; prerelease requires both.
verify_local_signature_if_present() {
binary="$1"
sigfile="$2"
label="$3"
[ -f "$sigfile" ] || return 0
if [ ! -s "$sigfile" ]; then
err "Local Minisign signature is empty for $label: $sigfile"
return 1
fi
if ! command -v minisign >/dev/null 2>&1; then
err "minisign is required to verify the supplied local signature for $label."
print_minisign_install_hint
return 1
fi
if minisign -Vm "$binary" -P "$RELEASE_PUBLIC_KEY" -x "$sigfile" >/dev/null 2>&1; then
ok "Local Minisign signature verified for $label."
return 0
fi
err "Local Minisign signature verification failed for $label."
err "Refusing to install an artifact signed by the wrong key or modified after signing."
return 1
}
# Verify $1 against a LOCAL checksum file $2 (a `<sha256> <name>` line, as
# written by `sha256sum binary > binary.sha256` or shipped beside a release
# asset). Used by --from-file installs so an offline/CI install can still
# integrity-check the artifact. Returns 0 on match. Missing proof fails closed
# unless the operator explicitly chooses --insecure.
verify_local_checksum() {
binary="$1"
sumfile="$2"
expected=$(awk '{print $1}' "$sumfile" 2>/dev/null | head -n1)
if [ -z "$expected" ]; then
allow_unverified_install "Local checksum file $sumfile is empty or unreadable."
return $?
fi
if command -v sha256sum >/dev/null 2>&1; then
actual=$(sha256sum "$binary" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
actual=$(shasum -a 256 "$binary" | awk '{print $1}')
else
allow_unverified_install "No sha256sum or shasum tool is installed, so $binary cannot be verified against $sumfile."
return $?
fi
if [ "$expected" = "$actual" ]; then
ok "SHA256 verified ($expected)."
return 0
fi
err "SHA256 mismatch against $sumfile!"
err " Expected: $expected"
err " Got: $actual"
err "Refusing to install the local binary."
return 1
}
# Holds the path to the pre-upgrade binary backup so a failed verification can
# roll back to the previously-working binary instead of leaving the user with a
# broken one. Empty when there was nothing to back up (fresh install).
INSTALL_BACKUP=""
GPU_LITERAL_SIDECAR_TMP=""
GPU_PROGRAMS_CACHE_BACKUP=""
GPU_PROGRAMS_CACHE_WAS_MISSING=0
gpu_programs_cache_dir_for_install() {
if [ "$OS" = "darwin" ]; then
printf '%s/Library/Caches/keyhog/programs\n' "$HOME"
elif [ -n "${XDG_CACHE_HOME:-}" ]; then
printf '%s/keyhog/programs\n' "$XDG_CACHE_HOME"
else
printf '%s/.cache/keyhog/programs\n' "$HOME"
fi
}
cleanup_gpu_literal_sidecar_tmp() {
if [ -n "$GPU_LITERAL_SIDECAR_TMP" ]; then
rm -f "$GPU_LITERAL_SIDECAR_TMP" 2>/dev/null || true
GPU_LITERAL_SIDECAR_TMP=""
fi
}
clear_gpu_programs_cache_backup() {
if [ -n "$GPU_PROGRAMS_CACHE_BACKUP" ]; then
rm -rf "$GPU_PROGRAMS_CACHE_BACKUP" 2>/dev/null || true
GPU_PROGRAMS_CACHE_BACKUP=""
fi
GPU_PROGRAMS_CACHE_WAS_MISSING=0
}
backup_gpu_programs_cache_for_install() {
clear_gpu_programs_cache_backup
programs_dir="$(gpu_programs_cache_dir_for_install)"
backup_root=$(mktemp -d -t keyhog-gpu-programs-backup-XXXXXX)
if [ -z "$backup_root" ] || [ ! -d "$backup_root" ]; then
err "Could not create a temporary GPU literal cache backup directory."
return 1
fi
if [ -d "$programs_dir" ]; then
if ! cp -Rp "$programs_dir" "$backup_root/programs" 2>/dev/null; then
rm -rf "$backup_root"
err "Could not back up GPU literal cache directory at $programs_dir."
return 1
fi
GPU_PROGRAMS_CACHE_WAS_MISSING=0
else
GPU_PROGRAMS_CACHE_WAS_MISSING=1
fi
GPU_PROGRAMS_CACHE_BACKUP="$backup_root"
}
restore_gpu_programs_cache_backup() {
[ -n "$GPU_PROGRAMS_CACHE_BACKUP" ] || return 0
programs_dir="$(gpu_programs_cache_dir_for_install)"
if ! rm -rf "$programs_dir" 2>/dev/null; then
err "Could not remove GPU literal cache directory at $programs_dir during rollback."
return 1
fi
if [ "$GPU_PROGRAMS_CACHE_WAS_MISSING" != "1" ] && [ -d "$GPU_PROGRAMS_CACHE_BACKUP/programs" ]; then
if ! mkdir -p "$(dirname "$programs_dir")" || ! mv "$GPU_PROGRAMS_CACHE_BACKUP/programs" "$programs_dir"; then
err "Could not restore GPU literal cache directory at $programs_dir."
return 1
fi
fi
clear_gpu_programs_cache_backup
}
stage_local_gpu_literal_sidecar() {
local_sidecar="$FROM_FILE.gpu-literals.tar.gz"
local_sum="$local_sidecar.sha256"
local_sig="$local_sidecar.minisig"
sidecar_tmp=$(mktemp)
if [ ! -f "$local_sidecar" ] || [ ! -s "$local_sidecar" ]; then
# No sidecar ships with a locally built or `cargo install` binary, and
# `--from-file` is the only install mode, so requiring one here failed
# every install. The binary compiles its own matchers instead, after the
# swap, from the detector corpus embedded in it. Runtime compilation is
# still never acceptable: a failure to generate fails the install.
rm -f "$sidecar_tmp"
GPU_LITERALS_FROM_BINARY=1
return 0
fi
if ! verify_local_signature_if_present "$local_sidecar" "$local_sig" "GPU literal sidecar"; then
rm -f "$sidecar_tmp"
return 1
fi
if [ -f "$local_sum" ]; then
if ! verify_local_checksum "$local_sidecar" "$local_sum"; then
rm -f "$sidecar_tmp"
return 1
fi
else
if ! allow_unverified_install "No local checksum file found beside --from-file GPU literal sidecar: $local_sum"; then
rm -f "$sidecar_tmp"
return 1
fi
fi
if ! cp "$local_sidecar" "$sidecar_tmp" 2>/dev/null; then
rm -f "$sidecar_tmp"
err "--from-file: could not read GPU literal sidecar $local_sidecar"
return 1
fi
if ! validate_gpu_literal_sidecar_archive "$sidecar_tmp"; then
rm -f "$sidecar_tmp"
err "Refusing GPU literal sidecar with unsafe archive contents."
return 1
fi
cleanup_gpu_literal_sidecar_tmp
GPU_LITERAL_SIDECAR_TMP="$sidecar_tmp"
}
rollback_staged_install_after_sidecar_failure() {
target="$1"
cleanup_gpu_literal_sidecar_tmp
if [ -n "$INSTALL_BACKUP" ] && [ -e "$INSTALL_BACKUP" ]; then
mv -f "$INSTALL_BACKUP" "$target"
INSTALL_BACKUP=""
warn "Rolled back to your previous working keyhog at $target."
else
rm -f "$target" 2>/dev/null || true
warn "Removed the binary because shipped GPU literal artifacts could not be seeded."
fi
}
validate_gpu_literal_sidecar_archive() {
# Extract to an isolated temp dir and validate the real filesystem tree.
# Line-oriented `tar -tzf` can be spoofed by newline-bearing member names;
# find -print0 walks extracted names and cannot be split that way (KH-1312).
archive="$1"
stage=$(mktemp -d -t keyhog-gpu-val-XXXXXX) || {
err "Could not create temporary directory to validate GPU literal sidecar."
return 1
}
listing="$stage/.keyhog-archive-list"
if ! tar -tzPf "$archive" > "$listing" 2>/dev/null; then
rm -rf "$stage"
err "GPU literal artifact sidecar is not a readable tar.gz archive."
return 1
fi
unsafe_listing="$stage/.keyhog-archive-unsafe"
printf '0\n' > "$unsafe_listing"
while IFS= read -r entry || [ -n "$entry" ]; do
case "$entry" in
""|/*|../*|*/../*|*/..)
printf '1\n' > "$unsafe_listing"
break
;;
esac
done < "$listing"
if [ "$(cat "$unsafe_listing" 2>/dev/null || printf '1')" != "0" ]; then
rm -rf "$stage"
err "GPU literal artifact sidecar contains unsafe archive paths."
return 1
fi
verbose_listing="$stage/.keyhog-archive-types"
if ! tar -tvzf "$archive" > "$verbose_listing" 2>/dev/null; then
rm -rf "$stage"
err "GPU literal artifact sidecar is not a readable tar.gz archive."
return 1
fi
printf '0\n' > "$unsafe_listing"
while IFS= read -r detail || [ -n "$detail" ]; do
case "$detail" in
l*|h*)
printf '1\n' > "$unsafe_listing"
break
;;
esac
done < "$verbose_listing"
if [ "$(cat "$unsafe_listing" 2>/dev/null || printf '1')" != "0" ]; then
rm -rf "$stage"
err "GPU literal artifact sidecar contains link entries."
return 1
fi
if ! tar -xzf "$archive" -C "$stage" 2>/dev/null; then
rm -rf "$stage"
err "GPU literal artifact sidecar is not a readable tar.gz archive."
return 1
fi
# Defense in depth: reject any link the archive implementation materialized
# despite the pre-extraction member-type check.
if find "$stage" -type l -print -quit 2>/dev/null | grep -q .; then
rm -rf "$stage"
err "GPU literal artifact sidecar contains link entries."
return 1
fi
# Pass paths as `find -exec` arguments. POSIX `read` has no NUL-delimiter
# option, while shell positional arguments preserve every filename byte.
status_file="$stage/.keyhog-path-check"
printf '0\n' > "$status_file"
if ! find "$stage" -mindepth 1 -exec sh -c '
root=$1
status=$2
shift 2
for path do
case "$path" in
"$root"/*) ;;
*) printf "1\n" > "$status"; exit 1 ;;
esac
if [ -L "$path" ]; then
printf "1\n" > "$status"
exit 1
fi
rel=${path#"$root"/}
case "$rel" in
""|/*|../*|*/../*|*/..)
printf "1\n" > "$status"
exit 1
;;
esac
done
' sh "$stage" "$status_file" {} + 2>/dev/null; then
printf '1\n' > "$status_file"
fi
check_status=$(cat "$status_file" 2>/dev/null || printf '1')
if [ "$check_status" != "0" ]; then
rm -rf "$stage"
err "GPU literal artifact sidecar contains unsafe archive paths."
return 1
fi
rm -rf "$stage"
return 0
}
# Compile the shipped detector corpus into this host's GPU literal matchers
# using the binary that was just installed. Runs after the atomic swap, so the
# caller rolls the binary back when this fails.
generate_gpu_literals_from_installed_binary() {
programs_dir="$(gpu_programs_cache_dir_for_install)"
if ! mkdir -p "$programs_dir"; then
err "Could not create GPU literal cache directory at $programs_dir."
return 1
fi
say "Compiling GPU literal matchers for this host..."
if ! "$INSTALL_DIR/keyhog" compile-gpu-literals --output-dir "$programs_dir" >/dev/null 2>&1; then
err "Could not compile GPU literal matchers into $programs_dir."
err "Refusing to finish an install that would recompile shipped detector matchers at runtime."
return 1
fi
if [ ! -f "$programs_dir/manifest.json" ]; then
err "GPU literal compilation reported success but published no manifest in $programs_dir."
return 1
fi
return 0
}
install_verified_gpu_literal_sidecar() {
if [ -z "$GPU_LITERAL_SIDECAR_TMP" ]; then
[ "$GPU_LITERALS_FROM_BINARY" = "1" ] || return 0
generate_gpu_literals_from_installed_binary
return $?
fi
if ! validate_gpu_literal_sidecar_archive "$GPU_LITERAL_SIDECAR_TMP"; then
cleanup_gpu_literal_sidecar_tmp
err "Refusing GPU literal sidecar with unsafe archive paths."
return 1
fi
programs_dir="$(gpu_programs_cache_dir_for_install)"
extract_dir=$(mktemp -d -t keyhog-gpu-literals-XXXXXX)
if ! mkdir -p "$programs_dir"; then
rm -rf "$extract_dir"
cleanup_gpu_literal_sidecar_tmp
err "Could not create GPU literal cache directory at $programs_dir."
return 1
fi
if ! tar -xzf "$GPU_LITERAL_SIDECAR_TMP" -C "$extract_dir"; then
rm -rf "$extract_dir"
cleanup_gpu_literal_sidecar_tmp
err "Could not extract GPU literal artifact sidecar."
return 1
fi
find "$extract_dir" -type f -name '*.bin' | while IFS= read -r artifact; do
base=$(basename "$artifact")
tmp_target="$programs_dir/.$base.$$"
if ! cp "$artifact" "$tmp_target"; then
rm -f "$tmp_target"
exit 2
fi
if ! mv -f "$tmp_target" "$programs_dir/$base"; then
rm -f "$tmp_target"
exit 3
fi
installed=$(cat "$extract_dir/.installed-count" 2>/dev/null || printf '0')
printf '%s\n' "$((installed + 1))" > "$extract_dir/.installed-count"
done
install_status=$?
installed=$(cat "$extract_dir/.installed-count" 2>/dev/null || printf '0')
rm -rf "$extract_dir"
cleanup_gpu_literal_sidecar_tmp
if [ "$install_status" != "0" ]; then
err "Could not install GPU literal artifacts into $programs_dir."
return 1
fi
if [ "$installed" = "0" ]; then
err "GPU literal artifact sidecar contained no matcher .bin files."
return 1
fi
ok "Installed $installed GPU literal matcher artifact(s) into $programs_dir."
}
stage_and_install() {
tmp=$(mktemp)
staged=""
INSTALL_BACKUP=""
# shellcheck disable=SC2064
trap 'rm -f "$tmp" "$staged" 2>/dev/null' EXIT INT TERM
if [ -n "$FROM_FILE" ]; then
# Local-binary source: install a pre-built/pre-downloaded artifact
# instead of a GitHub release. Everything below (empty-file guard,
# backup, atomic swap, verify_install/doctor, rollback) is identical to
# the download path - only the origin of $tmp differs.
if [ ! -f "$FROM_FILE" ]; then
err "--from-file: no such file: $FROM_FILE"
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
if ! cp "$FROM_FILE" "$tmp" 2>/dev/null; then
err "--from-file: could not read $FROM_FILE"
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
else
err "--from-file=PATH is required."
err "This installer does not download release binaries."
err "Install the current release with: cargo install keyhog --locked"
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
# A zero-byte download means the asset 404'd into an empty file, the
# connection dropped before the first byte, or a proxy served an empty
# body. An empty file is still chmod-able and, with no shebang, executes
# as a no-op shell script that exits 0 - so verify_install would wave it
# through and "install" a binary that does nothing. Refuse up front.
# This happens BEFORE any backup/overwrite, so a pre-existing working
# binary is never touched.
if [ ! -s "$tmp" ]; then
err "Source binary $ASSET is empty (0 bytes)."
err "Check the file passed to --from-file."
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
# Release verification happens BEFORE we overwrite, so a corrupt or unsigned
# artifact can never replace a working binary. Downloads check the release's
# per-asset .minisig and .sha256; a --from-file install requires a sibling
# PATH.sha256 unless the operator explicitly accepts an unverified local
# artifact.
if [ -n "$FROM_FILE" ]; then
if ! verify_local_signature_if_present "$FROM_FILE" "$FROM_FILE.minisig" "binary"; then
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
if [ -f "$FROM_FILE.sha256" ]; then
if ! verify_local_checksum "$tmp" "$FROM_FILE.sha256"; then
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
else
if ! allow_unverified_install "No local checksum file found beside --from-file binary: $FROM_FILE.sha256"; then
rm -f "$tmp"
trap - EXIT INT TERM
exit 1
fi
fi
if ! stage_local_gpu_literal_sidecar; then
rm -f "$tmp"
cleanup_gpu_literal_sidecar_tmp
trap - EXIT INT TERM
exit 1
fi
fi
mkdir -p "$INSTALL_DIR"
target="$INSTALL_DIR/keyhog"
# Recoverability invariant: never destroy a working binary before the
# replacement has proven itself on THIS host. Back the current one up, stage
# the new one beside it (same filesystem, so the final swap is an atomic
# rename), then let finalize_install verify and roll back on failure.
if [ -e "$target" ]; then
INSTALL_BACKUP="$INSTALL_DIR/.keyhog.bak.$$"
if ! cp -p "$target" "$INSTALL_BACKUP" 2>/dev/null; then
err "Could not back up the existing binary at $target."
err "Refusing to overwrite it - your current install is left untouched."
rm -f "$tmp"
INSTALL_BACKUP=""
trap - EXIT INT TERM
exit 1
fi
fi
staged="$INSTALL_DIR/.keyhog.new.$$"
# $tmp may live on a different filesystem (TMPDIR), so copy (not rename)
# into the install dir; the atomic rename is the same-dir mv below.
if ! cp "$tmp" "$staged" 2>/dev/null; then
err "Could not stage the download into $INSTALL_DIR (directory not writable?)."
rm -f "$tmp" "$INSTALL_BACKUP"
INSTALL_BACKUP=""
trap - EXIT INT TERM
exit 1
fi
rm -f "$tmp"
chmod +x "$staged"
# Atomic same-directory replace: a concurrent `keyhog` exec sees either the
# old inode or the fully-written new one, never a half-copied file.
mv -f "$staged" "$target"
staged=""
trap - EXIT INT TERM
}
# Restore the pre-upgrade binary after a failed verification. On a fresh
# install (no backup) the broken download is removed unless it is merely
# missing a system library (then it is kept, because it is the correct binary
# and the user can fix the lib without re-downloading). Either way the host is
# never left strictly worse off than before the install ran.
finalize_install() {
vrc=0
verify_install || vrc=$?
if [ "$vrc" = "0" ]; then
# New binary works: drop the backup.
[ -n "$INSTALL_BACKUP" ] && rm -f "$INSTALL_BACKUP"
INSTALL_BACKUP=""
return 0
fi
if [ -n "$INSTALL_BACKUP" ] && [ -e "$INSTALL_BACKUP" ]; then
# Upgrade/repair over a binary that worked: the old one ran, the new
# one does not on this host - restore the one that worked.
mv -f "$INSTALL_BACKUP" "$INSTALL_DIR/keyhog"
INSTALL_BACKUP=""
warn "Rolled back to your previous working keyhog at $INSTALL_DIR/keyhog."
elif [ "$vrc" = "2" ]; then
# Fresh install, correct binary, missing system library: keep it so the
# user can install the lib (hint already printed) without re-downloading.
warn "Left the binary in place; install the library listed above, then run 'keyhog doctor' to confirm."
else
# Fresh install, non-runnable binary (wrong CPU / corrupt): leaving it
# on PATH would fail confusingly on every call - remove it.
rm -f "$INSTALL_DIR/keyhog"
warn "Removed the non-runnable download; no working keyhog was overwritten."
fi
return 1
}
# Verify the freshly-staged binary. Returns:
# 0 - healthy (ran --version cleanly)
# 2 - runs but a required system library is missing (binary is correct)
# 1 - non-runnable for any other reason (wrong CPU, corrupt, ...)
# Never exits the script: finalize_install owns rollback/cleanup decisions.
verify_install() {
# Capture stderr so we can decode the real reason --version refused to run.
# The previous "may be corrupt" message hid the most common failure mode:
# a missing shared library on Linux (Hyperscan, libssl, etc.).
verify_status=0
verify_err_file=$(mktemp -t keyhog-version-stderr.XXXXXX)
verify_out=$("$INSTALL_DIR/keyhog" --version 2>"$verify_err_file") || verify_status=$?
verify_err=$(cat "$verify_err_file" 2>/dev/null || true)
rm -f "$verify_err_file"
# Success is exit 0 from --version. A warning on stderr (deprecation note,
# config-load warning, locale grumble) is NOT a broken binary - the old
# `-z "$verify_err"` gate treated any such noise as a failure and would,
# post-rollback-fix, needlessly roll back a perfectly good upgrade.
if [ "$verify_status" = "0" ]; then
ok "Installed $(printf '%s\n' "$verify_out" | head -n 1)"
[ -n "$verify_err" ] && dim " (binary emitted a startup notice: $verify_err)"
# Native post-install health check. `keyhog doctor` reuses the same
# hw_probe the scanner uses (so there's no shell-side GPU detection to
# drift from runtime) and runs an end-to-end scan self-test: it plants
# a synthetic secret and confirms the freshly-installed binary actually
# detects it on THIS host. Per doctor's contract it exits 4
# (EXIT_HEALTH_FAILURE) iff it deems the binary UNHEALTHY - the planted
# secret was NOT detected, the detector corpus is missing, or (on a
# GPU-capable host) the fail-closed DEFAULT GPU scan route is dead - and
# exits 0 otherwise (PATH-only notices are exit-0 warnings, never a
# failure; GPU self-tests are skipped on no-GPU/headless hosts so CI
# stays green). A non-zero exit therefore means the binary we just
# installed cannot do its primary job on the route it will actually
# use. That is a disqualifying install condition, not a cosmetic
# warning: fail closed and let finalize_install roll back rather than
# leave a broken scanner reporting "installed" (Law 10 - no silent
# fallback past a failed self-test; and consistent with the autoroute
# gate immediately below, which already refuses a broken default route).
say ""
run_in_neutral_dir post_install_health_and_calibration "$INSTALL_DIR/keyhog"
return $?
fi
err "Installed binary at $INSTALL_DIR/keyhog could not run."
err " exit=$verify_status"
[ -n "$verify_err" ] && err " stderr: $verify_err"
# Surface dynamic-link failures on Linux. Distribution builds expose the
# same Hyperscan ABI as libhs, libhyperscan, or libvectorscan.
if [ "$OS" = "linux" ] && command -v ldd >/dev/null 2>&1; then
missing=$(ldd "$INSTALL_DIR/keyhog" 2>/dev/null | awk '/not found/ {print $1}' | sort -u | tr '\n' ' ')
if [ -n "$missing" ]; then
err " Missing shared libraries: $missing"
case "$missing" in
*libhs.so*|*libhyperscan*|*libvectorscan*)
err " Install Hyperscan runtime:"
err " Ubuntu/Debian: sudo apt-get install -y libhyperscan5"
err " Fedora/RHEL: sudo dnf install -y hyperscan"
err " Arch: sudo pacman -S vectorscan"
err " Or rebuild from source with no Hyperscan dep:"
err " cargo install --git https://github.com/santhreal/keyhog --no-default-features --features portable"
;;
*libssl*|*libcrypto*)
err " Install OpenSSL runtime:"
err " Ubuntu/Debian: sudo apt-get install -y libssl3 ca-certificates"
err " Fedora/RHEL: sudo dnf install -y openssl ca-certificates"
;;
esac
# The binary itself is correct; it just needs a runtime library.
return 2
fi
fi
err "The binary may be corrupt or built for a different CPU."
err " Source binary: $ASSET"
return 1
}
cleanup_autoroute_calibration() {
cleanup_tmpdir="$1"
cleanup_web_pid_file="$2"
cleanup_docker_bin="$3"
cleanup_docker_image="$4"
cleanup_docker_ready="$5"
cleanup_probe_pid="$6"
if [ -n "$cleanup_probe_pid" ]; then
kill "$cleanup_probe_pid" >/dev/null 2>&1 || true
wait "$cleanup_probe_pid" 2>/dev/null || true
fi
if [ -n "$cleanup_web_pid_file" ]; then
stop_calibration_web_server "$cleanup_web_pid_file"
fi
if [ "$cleanup_docker_ready" = "1" ] && [ -n "$cleanup_docker_bin" ] && [ -n "$cleanup_docker_image" ]; then
if ! "$cleanup_docker_bin" image rm -f "$cleanup_docker_image" >/dev/null 2>&1; then
dim " Docker calibration image cleanup failed for $cleanup_docker_image"
fi
fi
if [ -n "$cleanup_tmpdir" ]; then
if ! rm -rf "$cleanup_tmpdir" 2>/dev/null; then
dim " Autoroute calibration workspace cleanup failed for $cleanup_tmpdir"
fi
fi
}
docker_daemon_ready() {
docker_cmd="$1"
"$docker_cmd" info >/dev/null 2>&1
}
# Resolve the same per-user cache root the binary resolves with `dirs::cache_dir()`.
# A mismatch here publishes packs the scanner will never look at.
keyhog_cache_root() {
if [ "$OS" = "darwin" ] || [ "$OS" = "macos" ]; then
printf '%s\n' "$HOME/Library/Caches"
return 0
fi
if [ -n "${XDG_CACHE_HOME:-}" ]; then
printf '%s\n' "$XDG_CACHE_HOME"
return 0
fi
printf '%s\n' "$HOME/.cache"
}
# Compile and publish the host execution-pack generation.
#
# Without an installed generation every scan re-parses and re-compiles the
# embedded detector corpus: measured on a 16-core AVX-512 host, scan setup costs
# 284 ms wall and 1570 ms CPU with no packs against 132 ms and 170 ms with them.
# That work belongs to install, once, not to every scan. It must run BEFORE
# autoroute calibration, because the packs change the resolved detector and
# config digests calibration measures its buckets against.
publish_execution_packs() {
bin="$1"
# Capability probe, same contract as the --autoroute-calibrate probe below:
# a binary without the subcommand is not broken, it just predates packs.
if ! "$bin" compile-execution-packs --help >/dev/null 2>&1; then
warn " Execution packs not supported by this build; scans will compile detectors in-process."
return 0
fi
pack_root="$(keyhog_cache_root)/keyhog/execution-packs"
key_path="$pack_root/signing.key"
generation="$pack_root/current"