-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkekkai.sh
More file actions
executable file
·1457 lines (1320 loc) · 51.4 KB
/
Copy pathkekkai.sh
File metadata and controls
executable file
·1457 lines (1320 loc) · 51.4 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
# kekkai — one-script installer / updater / repair tool.
#
# Usage:
# bash kekkai.sh # auto-detect state and do the right thing
# bash kekkai.sh install # force first-time install
# bash kekkai.sh update # force update (pulls prebuilt release assets)
# bash kekkai.sh repair # force re-install of binaries + systemd unit
# bash kekkai.sh doctor # read-only health check (delegates to `kekkai doctor`)
# bash kekkai.sh uninstall # remove everything except config
#
# Flags (apply to any subcommand):
# --no-install skip apt dependency install
# --iface NAME force a specific interface in the default config
# --run launch the agent in foreground at the end (debugging)
#
# Update model: kekkai is distributed as prebuilt GitHub release binaries.
# `update.channel` may be `release` (default) or `pre-release`. There is no
# source-build mode — operators never need Go, git, clang, or this repo on
# the target host.
#
# Runtime note: kekkai CLI always runs under sudo (e.g. `sudo kekkai status`)
# because on Debian/Ubuntu/Pi OS the kernel sysctl
# `kernel.unprivileged_bpf_disabled` blocks non-root bpf() regardless of caps.
# The installer writes a sudoers drop-in (/etc/sudoers.d/kekkai-cli-<user>)
# so `sudo kekkai ...` won't prompt for a password. No shell alias is added —
# users should type literal `sudo kekkai` to build portable muscle memory.
#
# Auto-detect logic (no subcommand):
# - no binaries yet → install
# - binaries present but no systemd unit OR unit disabled → repair
# - otherwise → doctor (use `update` subcommand explicitly
# to check for a new release)
#
set -euo pipefail
# ROOT resolution:
# - normal: directory containing kekkai.sh on disk (/usr/local/bin or dev dir)
# - raw mode (`bash <(curl ...)`): fallback to ~/kekkai (or $KEKKAI_REPO)
# because $0 becomes /dev/fd/* and is not a writable project directory.
resolve_root() {
if [[ -n "${KEKKAI_REPO:-}" ]]; then
mkdir -p "$KEKKAI_REPO"
(cd "$KEKKAI_REPO" && pwd)
return
fi
local script_dir
script_dir="$(cd "$(dirname "$0")" && pwd)"
if [[ "$script_dir" == /dev/fd* ]] || [[ "$script_dir" == /proc/*/fd* ]]; then
local fallback="${HOME:-/tmp}/kekkai"
mkdir -p "$fallback"
(cd "$fallback" && pwd)
return
fi
echo "$script_dir"
}
ROOT="$(resolve_root)"
cd "$ROOT"
# Ensure a reusable local script copy exists for `kekkai update`.
# This is critical when running via process substitution:
# bash <(curl -fsSL .../kekkai.sh)
# where $0 is /dev/fd/* and no on-disk kekkai.sh exists by default.
persist_self_script() {
local target="$ROOT/kekkai.sh"
if [[ -f "$target" ]] && [[ -s "$target" ]]; then
return 0
fi
if [[ -r "$0" ]]; then
cat "$0" > "$target" 2>/dev/null || true
chmod +x "$target" 2>/dev/null || true
fi
}
persist_self_script
# ---------------------------------------------------------------------------
# Paths & constants
# ---------------------------------------------------------------------------
AGENT_BIN=/usr/local/bin/kekkai-agent
CLI_BIN=/usr/local/bin/kekkai
ROLLBACK_BIN=/usr/local/bin/kekkai-agent.prev
SCRIPT_INSTALL_PATH=/usr/local/bin/kekkai.sh
BASH_COMPLETION_DST=/usr/share/bash-completion/completions/kekkai
ZSH_COMPLETION_DST=/usr/share/zsh/vendor-completions/_kekkai
MOTD_DST=/etc/update-motd.d/98-kekkai
STATE_DIR=/var/lib/kekkai
STAGED_DIR=/var/lib/kekkai/staged
AUTO_UPDATE_ERROR_FILE=/var/lib/kekkai/auto_update_error.txt
CONFIG_DIR=/etc/kekkai
CONFIG_FILE="$CONFIG_DIR/kekkai.yaml"
STATS_DIR=/var/run/kekkai
BPFFS_DIR=/sys/fs/bpf/kekkai
UNIT_NAME=kekkai-agent.service
UNIT_SRC="$ROOT/deploy/systemd/kekkai-agent.service"
UNIT_DST="/etc/systemd/system/$UNIT_NAME"
SUDOERS_DIR=/etc/sudoers.d
SUDOERS_FILE_PREFIX=kekkai-cli-
LOCAL_AGENT_BIN="$ROOT/bin/kekkai-agent"
LOCAL_CLI_BIN="$ROOT/bin/kekkai"
BRANCH=main
REPO_OWNER=ExpTechTW
REPO_NAME=kekkai
RELEASES_API_BASE="https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/releases"
RAW_BASE="https://raw.githubusercontent.com/$REPO_OWNER/$REPO_NAME"
# ---------------------------------------------------------------------------
# CLI parsing
# ---------------------------------------------------------------------------
CMD=""
DO_INSTALL_DEPS=1
IFACE_OVERRIDE=""
DO_RUN=0
FORCE_UPDATE=0
while [[ $# -gt 0 ]]; do
case "$1" in
install|update|repair|doctor|uninstall)
CMD="$1"; shift ;;
--no-install) DO_INSTALL_DEPS=0; shift ;;
--iface) IFACE_OVERRIDE="$2"; shift 2 ;;
--run) DO_RUN=1; shift ;;
--force) FORCE_UPDATE=1; shift ;;
-h|--help)
sed -n '2,23p' "$0"; exit 0 ;;
*) die "unknown argument: $1" ;;
esac
done || true
# ---------------------------------------------------------------------------
# Pretty output (sandstone colours; works in 16-colour terminals)
# ---------------------------------------------------------------------------
if [[ -t 1 ]] && [[ "${NO_COLOR:-}" == "" ]]; then
C_RESET=$'\033[0m'
C_DIM=$'\033[2m'
C_BOLD=$'\033[1m'
C_OK=$'\033[1;32m' # green
C_WARN=$'\033[1;33m' # yellow
C_ERR=$'\033[1;31m' # red
C_INFO=$'\033[1;36m' # cyan
C_BLUE=$'\033[1;34m' # blue — "something changed" accent for update results
C_TITLE=$'\033[1;35m' # violet — kekkai barrier theme
else
C_RESET=""; C_DIM=""; C_BOLD=""; C_OK=""; C_WARN=""; C_ERR=""; C_INFO=""; C_BLUE=""; C_TITLE=""
fi
# Persistent log for kekkai.sh operations. Matches the agent's log
# directory so operators have one place to look when debugging an
# install / update / repair. We only append plain text (no ANSI) here —
# the terminal gets the colourised version, the file gets the scraped
# version.
KEKKAI_SH_LOG=/var/log/kekkai/kekkai.sh.log
# _kslog_append writes a single already-rendered line into the
# persistent log file. Best-effort: if the file isn't writable (non-root
# dev run, missing dir) we silently drop it rather than breaking the
# visible output. Timestamp format matches the agent's logx handler
# (UTC, 1-second resolution) so both log streams line up chronologically
# when they end up in the same terminal scrollback.
_kslog_append() {
local level="$1" msg="$2"
[[ -n "$KEKKAI_SH_LOG" ]] || return 0
local ts
ts="$(date -u '+%Y/%m/%d %H:%M:%S')"
# mkdir -p is idempotent and cheap; we do it every call in case the
# directory was removed between invocations. The :-"" guard means a
# failed mkdir just drops the line instead of erroring out.
mkdir -p "$(dirname "$KEKKAI_SH_LOG")" 2>/dev/null || return 0
printf '[%s(UTC)][%-5s][kekkai.sh] %s\n' "$ts" "$level" "$msg" \
>> "$KEKKAI_SH_LOG" 2>/dev/null || true
}
step() { printf '\n%s◈ %s%s\n' "$C_TITLE" "$*" "$C_RESET"; _kslog_append STEP "$*"; }
log() { printf '%s[+]%s %s\n' "$C_OK" "$C_RESET" "$*"; _kslog_append INFO "$*"; }
warn() { printf '%s[!]%s %s\n' "$C_WARN" "$C_RESET" "$*"; _kslog_append WARN "$*"; }
err() { printf '%s[x]%s %s\n' "$C_ERR" "$C_RESET" "$*" >&2; _kslog_append ERROR "$*"; }
info() { printf '%s[·]%s %s\n' "$C_INFO" "$C_RESET" "$*"; _kslog_append INFO "$*"; }
die() { err "$*"; exit 1; }
banner() {
printf '%s\n' "$C_TITLE"
cat <<'EOF'
██╗ ██╗███████╗██╗ ██╗██╗ ██╗ █████╗ ██╗
██║ ██╔╝██╔════╝██║ ██╔╝██║ ██╔╝██╔══██╗██║
█████╔╝ █████╗ █████╔╝ █████╔╝ ███████║██║
██╔═██╗ ██╔══╝ ██╔═██╗ ██╔═██╗ ██╔══██║██║
██║ ██╗███████╗██║ ██╗██║ ██╗██║ ██║██║
╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝
EOF
printf '%s 結界 · edge barrier installer%s\n\n' "$C_INFO" "$C_RESET"
}
# ---------------------------------------------------------------------------
# OS / arch detection
# ---------------------------------------------------------------------------
# Return values match what GitHub release assets will use once we publish
# prebuilt binaries (follows Go's GOOS/GOARCH conventions).
detect_os() {
case "$(uname -s)" in
Linux) echo linux ;;
Darwin) echo darwin ;;
*) echo "unsupported" ;;
esac
}
detect_arch() {
case "$(uname -m)" in
x86_64|amd64) echo amd64 ;;
aarch64|arm64) echo arm64 ;;
armv7l|armv6l) echo armv6 ;; # rpi 3 and older
*) echo unsupported ;;
esac
}
need_sudo() {
[[ $EUID -eq 0 ]] && echo "" || echo "sudo"
}
SUDO="$(need_sudo)"
OS="$(detect_os)"
ARCH="$(detect_arch)"
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# State detection — which subcommand should auto mode run?
# ---------------------------------------------------------------------------
detect_state() {
# Returns one of: install / repair / healthy.
#
# Update detection from the installed state is no longer automatic —
# operators run `kekkai update` explicitly when they want to check GitHub
# releases. The auto-mode path just ensures the local install is sane.
if [[ ! -x "$AGENT_BIN" ]] || [[ ! -x "$CLI_BIN" ]]; then
echo install
return
fi
if [[ ! -f "$UNIT_DST" ]]; then
echo repair
return
fi
if command -v systemctl >/dev/null 2>&1; then
if ! $SUDO systemctl is-enabled --quiet "$UNIT_NAME" 2>/dev/null; then
echo repair
return
fi
fi
if [[ ! -f "$CONFIG_FILE" ]]; then
echo repair
return
fi
echo healthy
}
# ---------------------------------------------------------------------------
# Dependency install
# ---------------------------------------------------------------------------
install_deps() {
[[ $DO_INSTALL_DEPS -eq 0 ]] && { info "skipping apt (--no-install)"; return; }
if ! command -v apt-get >/dev/null 2>&1; then
warn "no apt-get; install clang/libbpf-dev/linux-headers manually"
return
fi
log "installing apt dependencies"
$SUDO apt-get update -y
$SUDO apt-get install -y --no-install-recommends \
clang llvm libbpf-dev "linux-headers-$(uname -r)" \
make gcc pkg-config ca-certificates curl
}
check_kernel() {
log "kernel: $(uname -r)"
[[ "$OS" == "linux" ]] || die "kekkai requires Linux"
[[ "$ARCH" == "amd64" || "$ARCH" == "arm64" ]] || die "unsupported arch: $(uname -m)"
if [[ ! -r /sys/kernel/btf/vmlinux ]]; then
warn "/sys/kernel/btf/vmlinux not readable — OK, kekkai doesn't need BTF"
fi
if ! mount | grep -q 'type bpf '; then
log "mounting bpffs at /sys/fs/bpf"
$SUDO mount -t bpf bpf /sys/fs/bpf || warn "bpffs mount failed"
fi
$SUDO mkdir -p "$BPFFS_DIR"
}
detect_iface() {
if [[ -n "$IFACE_OVERRIDE" ]]; then
echo "$IFACE_OVERRIDE"
return
fi
local iface
iface="$(ip -o -4 route show default 2>/dev/null | awk '{print $5; exit}')"
[[ -z "$iface" ]] && iface="$(ip -br link 2>/dev/null | awk '$1!="lo" && $2=="UP" {print $1; exit}')"
echo "$iface"
}
iface_has_default_allowlist_ip() {
local iface="$1"
[[ -n "$iface" ]] || return 1
# default allowlist is 192.168.0.0/16
ip -o -4 addr show dev "$iface" scope global 2>/dev/null | \
awk '
{
split($4, parts, "/")
ip = parts[1]
split(ip, octets, ".")
if (octets[1] == 192 && octets[2] == 168) {
found = 1
}
}
END { exit(found ? 0 : 1) }
'
}
read_update_channel_from_config() {
local cfg="${1:-$CONFIG_FILE}"
[[ -f "$cfg" ]] || return 1
awk '
/^[[:space:]]*#/ { next }
/^update:[[:space:]]*$/ { in_update=1; next }
/^[^[:space:]]/ { in_update=0 }
in_update && /^[[:space:]]+channel:[[:space:]]*/ {
line=$0
sub(/^[[:space:]]+channel:[[:space:]]*/, "", line)
gsub(/["'\''[:space:]]/, "", line)
print line
exit 0
}
' "$cfg"
}
resolve_update_channel() {
local ch
ch="${KEKKAI_UPDATE_CHANNEL:-}"
if [[ -z "$ch" ]]; then
ch="$(read_update_channel_from_config "$CONFIG_FILE" 2>/dev/null || true)"
fi
[[ -n "$ch" ]] || ch="release"
case "$ch" in
release|pre-release) ;;
*)
warn "unknown update.channel '$ch' — fallback to release"
ch="release"
;;
esac
echo "$ch"
}
prepare_binaries() {
local channel
channel="$(resolve_update_channel)"
fetch_release_binaries_to_root_bin "$channel"
}
install_binaries_from() {
local src_agent="$1"
local src_cli="$2"
[[ -x "$src_agent" ]] || die "missing agent binary: $src_agent"
[[ -x "$src_cli" ]] || die "missing cli binary: $src_cli"
# Rollback snapshot of the current daemon (update only — install has
# nothing to roll back to).
if [[ -f "$AGENT_BIN" ]]; then
$SUDO cp -a "$AGENT_BIN" "$ROLLBACK_BIN" || true
fi
$SUDO install -D -m 0755 "$src_agent" "$AGENT_BIN"
log "installed: $AGENT_BIN"
$SUDO install -D -m 0755 "$src_cli" "$CLI_BIN"
log "installed: $CLI_BIN"
install_completions
install_motd
}
# persist_script_for_updates puts a copy of kekkai.sh at /usr/local/bin/kekkai.sh
# so future `sudo kekkai update` calls can find it via resolveUpdateScript().
#
# Three sources, in priority order:
# 1. $ROOT/kekkai.sh (repo clone or persist_self_script() already worked)
# 2. $0 itself, if it's a readable regular file (not /dev/fd/*)
# 3. curl from the main branch on GitHub (last resort for one-shot
# `curl | bash` installs where $0 is /dev/fd/* and $ROOT is empty)
persist_script_for_updates() {
[[ "$OS" == "linux" ]] || return 0
local src=""
if [[ -f "$ROOT/kekkai.sh" ]] && [[ -s "$ROOT/kekkai.sh" ]]; then
src="$ROOT/kekkai.sh"
elif [[ -r "$0" ]] && [[ -f "$0" ]]; then
src="$0"
fi
# Skip self-copy: if $0 is already the installed script (common during
# `sudo kekkai update`, where kekkai delegates to /usr/local/bin/kekkai.sh),
# `install` would error with "same file". Treat that case as already persisted.
if [[ -n "$src" ]]; then
local src_real dst_real
src_real="$(readlink -f "$src" 2>/dev/null || echo "$src")"
dst_real="$(readlink -f "$SCRIPT_INSTALL_PATH" 2>/dev/null || echo "$SCRIPT_INSTALL_PATH")"
if [[ "$src_real" == "$dst_real" ]]; then
return 0
fi
$SUDO install -D -m 0755 "$src" "$SCRIPT_INSTALL_PATH"
log "installed: $SCRIPT_INSTALL_PATH (for future 'sudo kekkai update')"
return 0
fi
# Fallback: fetch from GitHub. Acceptable here because we're already
# mid-install from curl|bash — the user has implicitly trusted main.
if command -v curl >/dev/null 2>&1; then
local tmp
tmp="$(mktemp)"
if curl -fsSL "$RAW_BASE/$BRANCH/kekkai.sh" -o "$tmp" 2>/dev/null && [[ -s "$tmp" ]]; then
$SUDO install -D -m 0755 "$tmp" "$SCRIPT_INSTALL_PATH"
rm -f "$tmp"
log "installed: $SCRIPT_INSTALL_PATH (fetched from $BRANCH — for future 'sudo kekkai update')"
return 0
fi
rm -f "$tmp"
fi
warn "could not persist kekkai.sh to $SCRIPT_INSTALL_PATH — 'sudo kekkai update' will need KEKKAI_SCRIPT set"
}
# fetch_or_copy_asset: stage a repo-tracked file at $1 (relative to $ROOT)
# into a temp path. Prefers the on-disk copy; falls back to curl from
# $RAW_BASE/$BRANCH/$1. Echoes the staged path on success, empty on failure.
fetch_or_copy_asset() {
local rel="$1"
local local_src="$ROOT/$rel"
if [[ -f "$local_src" ]] && [[ -s "$local_src" ]]; then
echo "$local_src"
return 0
fi
command -v curl >/dev/null 2>&1 || return 1
local tmp
tmp="$(mktemp)"
if curl -fsSL "$RAW_BASE/$BRANCH/$rel" -o "$tmp" 2>/dev/null && [[ -s "$tmp" ]]; then
echo "$tmp"
return 0
fi
rm -f "$tmp"
return 1
}
# install_completions drops the bash + zsh completion scripts into the
# distro's standard vendor paths. Silently skips targets whose parent
# dir doesn't exist (e.g. systems without zsh installed). Non-fatal.
install_completions() {
[[ "$OS" == "linux" ]] || return 0
local bash_src zsh_src
bash_src="$(fetch_or_copy_asset contrib/completions/kekkai.bash)" || bash_src=""
zsh_src="$(fetch_or_copy_asset contrib/completions/_kekkai)" || zsh_src=""
if [[ -n "$bash_src" ]] && [[ -d "$(dirname "$BASH_COMPLETION_DST")" ]]; then
$SUDO install -D -m 0644 "$bash_src" "$BASH_COMPLETION_DST"
log "installed: $BASH_COMPLETION_DST"
fi
if [[ -n "$zsh_src" ]] && [[ -d "$(dirname "$ZSH_COMPLETION_DST")" ]]; then
$SUDO install -D -m 0644 "$zsh_src" "$ZSH_COMPLETION_DST"
log "installed: $ZSH_COMPLETION_DST"
fi
# Clean up any temp files fetch_or_copy_asset may have created.
[[ -n "$bash_src" && "$bash_src" != "$ROOT"* ]] && rm -f "$bash_src"
[[ -n "$zsh_src" && "$zsh_src" != "$ROOT"* ]] && rm -f "$zsh_src"
if [[ -z "$bash_src" ]] && [[ -z "$zsh_src" ]]; then
warn "shell completions not installed (no local or remote source)"
fi
}
# install_motd drops the auto-update failure notice into
# /etc/update-motd.d/ and ensures the state directory exists for
# kekkai-agent's auto-update goroutine. Silently skips if the host
# doesn't use update-motd.d (mostly non-systemd distros).
install_motd() {
[[ "$OS" == "linux" ]] || return 0
# State dirs are created unconditionally — agent auto-update and the
# rotating logger both need them even on hosts without update-motd.d.
$SUDO install -d -m 0755 "$STATE_DIR"
$SUDO install -d -m 0755 "$STAGED_DIR"
$SUDO install -d -m 0755 /var/log/kekkai
if [[ ! -d "$(dirname "$MOTD_DST")" ]]; then
info "update-motd.d not present — skipping login-warning hook"
return 0
fi
local motd_src
motd_src="$(fetch_or_copy_asset contrib/motd/98-kekkai)" || motd_src=""
if [[ -z "$motd_src" ]]; then
warn "motd script not installed (no local or remote source)"
return 0
fi
$SUDO install -D -m 0755 "$motd_src" "$MOTD_DST"
log "installed: $MOTD_DST"
[[ "$motd_src" != "$ROOT"* ]] && rm -f "$motd_src"
}
install_binaries() {
install_binaries_from "$LOCAL_AGENT_BIN" "$LOCAL_CLI_BIN"
}
read_cli_version() {
local bin="$1"
[[ -x "$bin" ]] || { echo "(none)"; return 0; }
local v
v="$("$bin" version 2>/dev/null | awk 'NR==1{print $2}' || true)"
[[ -n "$v" ]] || v="unknown"
echo "$v"
}
# print_update_result renders the final coloured summary block that users
# should scan first after an update. Two states:
#
# state=updated → blue accent, headline "UPDATED"
# state=unchanged → green accent, headline "ALREADY UP-TO-DATE"
#
# Args: state old_ver new_ver tag channel changed
# `tag` / `channel` / `changed` may be empty. `changed` is a human-readable
# comma-separated list of components that were actually rewritten (e.g.
# "agent, cli, kekkai.sh") — only rendered for state=updated.
print_update_result() {
local state="$1" old_v="$2" new_v="$3" tag="$4" channel="$5" changed="$6"
local accent headline
case "$state" in
updated)
accent="$C_BLUE"
headline="UPDATED"
;;
unchanged)
accent="$C_OK"
headline="ALREADY UP-TO-DATE"
;;
*)
accent="$C_INFO"
headline="$state"
;;
esac
local bar="═══════════════════════════════════════════════"
echo
printf '%s%s%s\n' "$accent" "$bar" "$C_RESET"
printf '%s ◈ %s%s\n' "$accent" "$headline" "$C_RESET"
printf '%s%s%s\n' "$accent" "$bar" "$C_RESET"
if [[ "$state" == "unchanged" ]]; then
printf ' %sversion%s %s%s%s (no change)\n' \
"$C_DIM" "$C_RESET" "$C_BOLD" "$new_v" "$C_RESET"
else
printf ' %sversion%s %s%s%s → %s%s%s\n' \
"$C_DIM" "$C_RESET" \
"$C_DIM" "$old_v" "$C_RESET" \
"$C_BOLD" "$new_v" "$C_RESET"
fi
if [[ -n "$changed" ]]; then
printf ' %schanged%s %s\n' "$C_DIM" "$C_RESET" "$changed"
fi
if [[ -n "$tag" ]]; then
printf ' %stag%s %s\n' "$C_DIM" "$C_RESET" "$tag"
fi
if [[ -n "$channel" ]]; then
printf ' %schannel%s %s\n' "$C_DIM" "$C_RESET" "$channel"
fi
printf '%s%s%s\n' "$accent" "$bar" "$C_RESET"
echo
}
setup_passwordless_sudo() {
# Install a sudoers drop-in so `sudo kekkai ...` never prompts for a
# password. Intentionally NO shell alias — we want the literal `sudo`
# keystrokes so users build the right muscle memory across hosts where
# the alias may not exist.
[[ "$OS" == "linux" ]] || return 0
local target_user
target_user="${SUDO_USER:-$USER}"
if [[ -z "$target_user" ]] || [[ "$target_user" == "root" ]]; then
info "skip sudoers drop-in for root user"
return 0
fi
local sudoers_file="$SUDOERS_DIR/${SUDOERS_FILE_PREFIX}${target_user}"
local sudoers_line="$target_user ALL=(root) NOPASSWD: $CLI_BIN, $CLI_BIN *"
log "configuring passwordless sudo for $CLI_BIN (user=$target_user)"
$SUDO install -d -m 0755 "$SUDOERS_DIR"
printf '%s\n' "$sudoers_line" | $SUDO tee "$sudoers_file" >/dev/null
$SUDO chmod 0440 "$sudoers_file"
if ! $SUDO visudo -cf "$sudoers_file" >/dev/null; then
$SUDO rm -f "$sudoers_file"
warn "sudoers syntax check failed; removed $sudoers_file"
warn "you will be prompted for a password each time you run: sudo kekkai"
return 0
fi
info "sudo kekkai will no longer prompt for a password"
}
install_config() {
if [[ -f "$CONFIG_FILE" ]]; then
info "$CONFIG_FILE already exists — leaving untouched"
return
fi
local iface
iface="$(detect_iface)"
[[ -n "$iface" ]] || die "could not detect a default interface; pass --iface <name>"
log "writing default config to $CONFIG_FILE (iface=$iface)"
$SUDO install -d -m 0755 "$CONFIG_DIR"
# We delegate the template to `kekkai-agent -reset` so shell and Go stay
# in sync on one source of truth for the default config.
$SUDO "$AGENT_BIN" -reset -config "$CONFIG_FILE" -iface "$iface" >/dev/null
# Persist KEKKAI_UPDATE_CHANNEL into the fresh config so future
# `kekkai update` runs (without the env var) don't flip back to the
# default `release` channel. Only apply when the env var is explicitly
# set AND it's a supported value — otherwise leave whatever the
# template generated.
local desired_channel="${KEKKAI_UPDATE_CHANNEL:-}"
case "$desired_channel" in
release|pre-release)
if grep -qE '^[[:space:]]+channel:' "$CONFIG_FILE" 2>/dev/null; then
$SUDO sed -i -E "s|^([[:space:]]+channel:[[:space:]]*).*$|\1$desired_channel|" "$CONFIG_FILE"
log "update.channel set to $desired_channel (from KEKKAI_UPDATE_CHANNEL)"
fi
;;
esac
if ! iface_has_default_allowlist_ip "$iface"; then
warn "detected iface '$iface' is not in default ingress_allowlist 192.168.0.0/16"
warn "service may reject startup until you set filter.ingress_allowlist to your management subnet"
fi
warn "review $CONFIG_FILE and set filter.ingress_allowlist to your management network"
}
install_systemd_unit() {
command -v systemctl >/dev/null 2>&1 || { warn "systemctl not found — skipping unit install"; return; }
log "installing systemd unit to $UNIT_DST"
if [[ -f "$UNIT_SRC" ]]; then
$SUDO install -D -m 0644 "$UNIT_SRC" "$UNIT_DST"
else
warn "systemd unit template not found in $ROOT; using built-in fallback unit"
local tmp_unit
tmp_unit="$(mktemp)"
cat > "$tmp_unit" <<'EOF'
[Unit]
Description=kekkai edge XDP firewall agent
Documentation=https://github.com/ExpTechTW/kekkai
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/kekkai-agent -config /etc/kekkai/kekkai.yaml -managed-config /etc/kekkai/kekkai.agent.yaml
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=2s
User=root
AmbientCapabilities=CAP_BPF CAP_NET_ADMIN CAP_PERFMON CAP_SYS_ADMIN
CapabilityBoundingSet=CAP_BPF CAP_NET_ADMIN CAP_PERFMON CAP_SYS_ADMIN
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=false
ReadWritePaths=/sys/fs/bpf /var/run /run /etc/kekkai /var/log/kekkai /var/lib/kekkai
StandardOutput=journal
StandardError=journal
SyslogIdentifier=kekkai-agent
[Install]
WantedBy=multi-user.target
EOF
$SUDO install -D -m 0644 "$tmp_unit" "$UNIT_DST"
rm -f "$tmp_unit"
fi
$SUDO systemctl daemon-reload
}
enable_and_start() {
command -v systemctl >/dev/null 2>&1 || return
if $SUDO systemctl is-enabled --quiet "$UNIT_NAME" 2>/dev/null; then
log "unit already enabled"
else
log "enabling unit at boot"
$SUDO systemctl enable "$UNIT_NAME" || warn "enable failed"
fi
log "starting unit"
if ! $SUDO systemctl restart "$UNIT_NAME"; then
warn "restart failed; rolling back if possible"
if [[ -f "$ROLLBACK_BIN" ]]; then
$SUDO install -m 0755 "$ROLLBACK_BIN" "$AGENT_BIN"
$SUDO systemctl restart "$UNIT_NAME" || true
die "rolled back to previous binary. check: journalctl -u $UNIT_NAME -n 50"
fi
die "no rollback available. check: journalctl -u $UNIT_NAME -n 50"
fi
sleep 1
if ! $SUDO systemctl is-active --quiet "$UNIT_NAME"; then
if [[ -f "$ROLLBACK_BIN" ]]; then
warn "service did not stay active; rolling back"
$SUDO install -m 0755 "$ROLLBACK_BIN" "$AGENT_BIN"
$SUDO systemctl restart "$UNIT_NAME" || true
fi
$SUDO journalctl -u "$UNIT_NAME" -n 20 --no-pager >&2 || true
die "service failed to come up"
fi
}
fetch_release_metadata() {
local channel="$1"
local endpoint
case "$channel" in
release)
endpoint="$RELEASES_API_BASE/latest"
;;
pre-release)
endpoint="$RELEASES_API_BASE?per_page=30"
;;
*)
die "fetch_release_metadata: unsupported channel '$channel'"
;;
esac
curl -fsSL -H "Accept: application/vnd.github+json" "$endpoint"
}
select_release_assets() {
local channel="$1"
local os="$2"
local arch="$3"
python3 -c '
import json
import re
import sys
channel, os_name, arch = sys.argv[1:4]
data = json.load(sys.stdin)
# Tag format is fixed by draft-release.yml: vYYYY.MM.DD+build.N
# Anything that does not match sorts as (0,0,0,0) so it loses to any
# well-formed tag — we never want to accidentally pick a hand-pushed
# tag over the CI-generated ones.
TAG_RE = re.compile(r"^v(\d{4})\.(\d{2})\.(\d{2})\+build\.(\d+)$")
def parse_version(tag):
m = TAG_RE.match(tag or "")
if not m:
return (0, 0, 0, 0)
return tuple(int(m.group(i)) for i in range(1, 5))
def pick_release(obj):
# release channel: /releases/latest already returns the single
# newest non-prerelease release, nothing to sort.
if channel == "release":
return obj
# pre-release channel: the list endpoint is sorted by created_at
# (newest first), which is NOT the same as version order — a
# re-published older build would hop to the top and shadow the
# real latest. Sort by parsed tag version and take the max.
candidates = [r for r in obj if not r.get("draft") and r.get("prerelease")]
if not candidates:
return None
return max(candidates, key=lambda r: parse_version(r.get("tag_name", "")))
release = pick_release(data)
if not release:
raise SystemExit("no matching release found")
assets = release.get("assets", [])
def is_noise(name):
n = name.lower()
return n.endswith((".sha256", ".sha256sum", ".sig", ".txt", ".json", ".sbom"))
def score(kind, name):
n = name.lower()
if kind not in n:
return -1
if kind == "kekkai" and "agent" in n:
return -1
if is_noise(name):
return -1
s = 0
if os_name in n:
s += 5
if arch in n:
s += 5
if f"{os_name}-{arch}" in n or f"{os_name}_{arch}" in n:
s += 3
if n.endswith((".tar.gz", ".tgz", ".zip")):
s -= 1
return s
def best_asset(kind):
best = None
best_s = -1
for a in assets:
name = a.get("name", "")
s = score(kind, name)
if s > best_s:
best_s = s
best = a
return best if best_s >= 8 else None
agent = best_asset("kekkai-agent")
cli = best_asset("kekkai")
if agent is None or cli is None:
raise SystemExit("release assets for kekkai-agent/kekkai not found for target os/arch")
print(release.get("tag_name", "unknown"))
print(agent["browser_download_url"])
print(cli["browser_download_url"])
' "$channel" "$os" "$arch"
}
download_release_binary() {
local url="$1"
local want_name="$2"
local tmpdir="$3"
local archive="$tmpdir/$(basename "${url%%\?*}")"
[[ -n "$archive" ]] || die "invalid asset url: $url"
curl -fL --retry 4 --retry-delay 1 --retry-all-errors --connect-timeout 10 \
"$url" -o "$archive" || return 1
local out="$tmpdir/$want_name"
case "$archive" in
*.tar.gz|*.tgz)
local ex="$tmpdir/extract-$want_name"
mkdir -p "$ex"
tar -xzf "$archive" -C "$ex"
local found
found="$(find "$ex" -type f -name "$want_name" -print -quit)"
[[ -n "$found" ]] || die "archive $(basename "$archive") missing $want_name"
cp "$found" "$out"
;;
*.zip)
command -v unzip >/dev/null 2>&1 || die "unzip not found (required for zip release assets)"
local ex="$tmpdir/extract-$want_name"
mkdir -p "$ex"
unzip -q "$archive" -d "$ex"
local found
found="$(find "$ex" -type f -name "$want_name" -print -quit)"
[[ -n "$found" ]] || die "archive $(basename "$archive") missing $want_name"
cp "$found" "$out"
;;
*)
cp "$archive" "$out"
;;
esac
chmod +x "$out"
# Quick sanity check: broken/partial downloads often crash immediately.
# We treat signal exits as corrupted binary and abort update early.
"$out" -h >/dev/null 2>&1 || {
local rc=$?
if (( rc >= 128 )); then
err "downloaded $want_name looks corrupted (exit=$rc)"
return 1
fi
}
echo "$out"
}
require_release_tools() {
command -v curl >/dev/null 2>&1 || die "curl not found"
command -v python3 >/dev/null 2>&1 || die "python3 not found (required for release metadata parsing)"
}
# fetch_release_artifacts: shared release fetch/parse/download.
# Inputs: channel, tmpdir
# Outputs (via globals): REL_TAG, REL_NEW_AGENT, REL_NEW_CLI
#
# Using globals keeps the caller simple (vs. parsing stdout). A trailing
# `unset` in each caller is unnecessary — install is a one-shot script.
fetch_release_artifacts() {
local channel="$1"
local tmpdir="$2"
require_release_tools
local meta parsed
meta="$(fetch_release_metadata "$channel")" || die "failed to fetch GitHub release metadata"
parsed="$(printf '%s' "$meta" | select_release_assets "$channel" "$OS" "$ARCH")" \
|| die "failed to resolve release assets for $OS/$ARCH"
REL_TAG="$(printf '%s\n' "$parsed" | sed -n '1p')"
local agent_url cli_url
agent_url="$(printf '%s\n' "$parsed" | sed -n '2p')"
cli_url="$(printf '%s\n' "$parsed" | sed -n '3p')"
[[ -n "$agent_url" && -n "$cli_url" ]] || die "release metadata incomplete"
log "selected release: $REL_TAG ($channel)"
info "agent asset: $(basename "${agent_url%%\?*}")"
info "cli asset: $(basename "${cli_url%%\?*}")"
REL_NEW_AGENT="$(download_release_binary "$agent_url" "kekkai-agent" "$tmpdir")" \
|| die "failed to download/verify kekkai-agent binary"
REL_NEW_CLI="$(download_release_binary "$cli_url" "kekkai" "$tmpdir")" \
|| die "failed to download/verify kekkai binary"
}
# files_match: 0 (true) if both files exist and have identical sha256.
files_match() {
local a="$1" b="$2"
[[ -f "$a" && -f "$b" ]] || return 1
local a_sha b_sha
a_sha="$(sha256sum "$a" | awk '{print $1}')"
b_sha="$(sha256sum "$b" | awk '{print $1}')"
[[ "$a_sha" == "$b_sha" ]]
}
# agent_unchanged / cli_unchanged: 0 (true) if the candidate binary matches
# the currently installed one byte-for-byte. Used to decide whether a
# release actually needs a service restart (or any write at all).
agent_unchanged() { files_match "$AGENT_BIN" "$1"; }
cli_unchanged() { files_match "$CLI_BIN" "$1"; }
# version_is_newer: 0 (true) if $1 (candidate) is strictly newer than $2
# (installed), using natural version sort. Used to refuse downgrades —
# if somebody runs `kekkai update` while on pre-release build.9, the
# release channel's build.4 must NOT replace it.
#
# Special values:
# - "unknown" / "(none)" for the installed version → always accept
# (treat as "we don't know what's on disk, trust the candidate")
# - "unknown" / "(none)" for the candidate → always refuse
# (can't prove it's newer)
version_is_newer() {
local candidate="$1" installed="$2"
[[ "$candidate" == "unknown" || "$candidate" == "(none)" || -z "$candidate" ]] && return 1
[[ "$installed" == "unknown" || "$installed" == "(none)" || -z "$installed" ]] && return 0
[[ "$candidate" == "$installed" ]] && return 1
local top
top="$(printf '%s\n%s\n' "$candidate" "$installed" | sort -V | tail -n1)"
[[ "$top" == "$candidate" ]]
}
# sync_script_from_remote: fetch the latest kekkai.sh from $RAW_BASE and
# compare with the currently installed /usr/local/bin/kekkai.sh.
#
# Exit codes:
# 0 → remote content differs, installed copy was overwritten
# 10 → remote matches installed copy (no-op)
# 11 → fetch failed (network / curl missing) — caller should warn but not fail
#
# Kept separate from binary updates because the script can ship fixes that
# have no corresponding binary release (this very patch is one such case).
# use_staged_binaries reports whether /var/lib/kekkai/staged/ holds a
# complete, strictly-newer release that release_update should consume
# instead of fetching. Requirements:
#
# - both binaries present and non-empty
# - VERSION marker present and parseable
# - VERSION strictly newer than the currently installed CLI
#
# Conservative on failure (never trust half-staged state): any missing
# piece → return 1, and release_update falls through to the fetch path.
use_staged_binaries() {
[[ -d "$STAGED_DIR" ]] || return 1
[[ -s "$STAGED_DIR/kekkai-agent" && -s "$STAGED_DIR/kekkai" ]] || return 1
[[ -f "$STAGED_DIR/VERSION" ]] || return 1
local staged_ver installed_ver
staged_ver="$(cat "$STAGED_DIR/VERSION" 2>/dev/null | tr -d '[:space:]')"
[[ -n "$staged_ver" ]] || return 1
# Strip any leading `v` to line up with read_cli_version's format.
staged_ver="${staged_ver#v}"
installed_ver="$(read_cli_version "$CLI_BIN")"
# Must be strictly newer — identical tag would mean we're about to
# reinstall the same bytes, which is wasted work. Downgrade is
# impossible here because the agent's staging logic only writes when
# it has proven it's newer.
if ! version_is_newer "$staged_ver" "$installed_ver"; then
return 1
fi
# Also require the staged binaries to actually run — catches half-
# written files from an interrupted download.
"$STAGED_DIR/kekkai-agent" -check /dev/null >/dev/null 2>&1 || return 1
return 0
}
sync_script_from_remote() {
[[ "$OS" == "linux" ]] || return 10
command -v curl >/dev/null 2>&1 || return 11