-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalighieri.sh
More file actions
executable file
·8326 lines (7862 loc) · 375 KB
/
Copy pathalighieri.sh
File metadata and controls
executable file
·8326 lines (7862 loc) · 375 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
# alighieri.sh — install, upgrade, and uninstall Alighieri as a systemd service.
#
# A single entry point for managing an Alighieri SOCKS5 proxy deployment:
#
# sudo ./scripts/alighieri.sh Install, or open a menu if installed
# sudo ./scripts/alighieri.sh install Install / reconfigure (unit + config)
# sudo ./scripts/alighieri.sh upgrade Replace the binary and restart
# sudo ./scripts/alighieri.sh uninstall Remove the service and binary
# sudo ./scripts/alighieri.sh status Show deployment status
# sudo ./scripts/alighieri.sh help Detailed help
#
# Run it from a repository checkout, or from a Linux release archive, which
# bundles this helper, the matching prebuilt binary, and the default config.
# In a complete release archive the helper automatically selects the bundled
# ./alighieri binary. A checkout without a prebuilt binary builds with Cargo and
# may fetch its locked dependencies, but the helper never clones a mutable
# repository branch or downloads a replacement lifecycle script.
#
# Configuration constants are intentionally NOT read from the environment:
# this script runs as root, and honouring env overrides would widen the attack
# surface for privilege escalation via environment injection. Use the
# documented flags instead.
#
# https://github.com/wiresock/alighieri
set -euo pipefail
SERVICE_NAME="alighieri"
INSTALLER_FS_HELPER_NAME="alighieri-installer-fs"
INSTALLER_FS_HELPER_PROTOCOL="alighieri-installer-fs-v2"
SERVICE_USER="alighieri"
CONFIG_DIR="/etc/alighieri"
LOG_DIR="/var/log/alighieri"
# systemd StateDirectory: created on start, owned by the service user, and kept
# writable under ProtectSystem=strict. Holds the ACME certificate cache.
STATE_DIR="/var/lib/${SERVICE_NAME}"
UNIT_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
CONFIG_FILE="${CONFIG_DIR}/${SERVICE_NAME}.conf"
# Defaults overridable by flags.
PREFIX="/usr/local"
PREFIX_EXPLICIT=0
BINARY=""
BINARY_EXPLICIT=0
INSTALLER_FS_HELPER_SOURCE=""
INSTALL_CONFIG=""
CONFIG_EXPLICIT=0
RESTART_ON_UPGRADE=1
START_ON_INSTALL=1
PURGE_CONFIG=0
PURGE_LOGS=0
PURGE_STATE=0
PURGE_USER=0
ACTION="auto"
COMMAND_SEEN=0
STAGED_BIN=""
STAGED_FS_HELPER=""
STAGED_UNIT=""
UNIT_CANDIDATE_GUARD=""
UNIT_CANDIDATE_SNAPSHOT=""
UNIT_CANDIDATE_WITNESS=""
UNIT_BACKUP=""
UNIT_TRANSACTION_DIR=""
UNIT_RETAINED_BACKUP=""
UNIT_TRANSACTION_ACTIVE=0
UNIT_HAD_ORIGINAL=0
UNIT_TRANSACTION_USES_STAGED_LINK=0
UNIT_TRANSACTION_EXCHANGE_V1=0
UNIT_CANDIDATE_PUBLISHED=0
UNIT_REJECTED=""
UNIT_ROLLBACK_CONFLICT_COPY=""
UNIT_ROLLBACK_RELOAD_FAILED=0
BINARY_COMMIT_IN_PROGRESS=0
BINARY_COMMIT_FD_OPEN=0
BINARY_COMMIT_SOURCE=""
BINARY_COMMIT_DESTINATION=""
BINARY_COMMIT_WITNESS=""
UPGRADE_LEGACY_UNIT_KIND=""
LIFECYCLE_LOCK_FILE="/run/alighieri-management.lock"
SCRIPT_DIR="$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
REPO_ROOT="$(CDPATH='' cd -- "${SCRIPT_DIR}/.." && pwd -P)"
# ── Output helpers ────────────────────────────────────────────────────────────
# Colour only when writing to a terminal so journald/pipes stay clean.
if [ -t 2 ]; then
C_RED=$'\033[0;31m'
C_YELLOW=$'\033[0;33m'
C_GREEN=$'\033[0;32m'
C_RESET=$'\033[0m'
else
C_RED='' C_YELLOW='' C_GREEN='' C_RESET=''
fi
info() { printf '%s\n' "$*" >&2; }
warn() { printf '%s[WARN]%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
ok() { printf '%s%s%s\n' "$C_GREEN" "$*" "$C_RESET" >&2; }
die() { printf '%s[ERROR]%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; exit 1; }
# systemd parses ExecStart itself rather than passing it through a shell. These
# characters introduce specifier/environment expansion or quoting/escaping, so
# the simple whitespace-delimited unit format below cannot represent them as
# literal path bytes. Reject them instead of validating one path and launching
# another.
validate_exec_start_path() {
local option="$1" value="$2"
case "$value" in
*%*|*'$'*|*'"'*|*"'"*|*\\*)
die "$option must not contain systemd ExecStart metacharacters (%, $, quotes, or backslash): $value"
;;
esac
}
# Lexically normalise a path — collapse `.`, `..`, and redundant `/` — using only
# shell parameter expansion, with no external command. Symlinks are deliberately
# NOT resolved: callers compare declared paths and need identical behaviour on
# GNU and BusyBox systems (which may lack `realpath -m`). A leading `/` is
# preserved; the result has no trailing slash except for the root itself.
normalize_path() {
local path="$1" abs='' out='' rest comp
case "$path" in
/*) abs=1 ;;
esac
rest="$path"
while [ -n "$rest" ]; do
case "$rest" in
/*) rest="${rest#/}"; continue ;; # collapse leading / and // runs
esac
comp="${rest%%/*}" # next component, up to the slash
case "$rest" in
*/*) rest="${rest#*/}" ;;
*) rest='' ;;
esac
case "$comp" in
'' | '.') ;; # drop empty and `.` segments
'..')
case "$out" in
'') [ -n "$abs" ] || out='..' ;; # absolute: `..` at root is a no-op
'..' | *'/..') out="$out/.." ;; # relative escape: cannot pop a `..`
*/*) out="${out%/*}" ;; # pop the last segment
*) out='' ;; # pop the only segment
esac
;;
*) if [ -z "$out" ]; then out="$comp"; else out="$out/$comp"; fi ;;
esac
done
if [ -n "$abs" ]; then
printf '%s\n' "/$out"
elif [ -n "$out" ]; then
printf '%s\n' "$out"
else
printf '%s\n' "."
fi
}
install_bin_dir_for_prefix() {
local prefix="$1"
[ "$(normalize_path "$prefix")" = "$prefix" ] || return 1
join_path_child "$prefix" bin
}
join_path_child() {
local directory="$1" child="$2"
# `${directory%/}` is empty only for `/`, yielding `/child` instead of
# `//child`. Every other accepted managed directory is already canonical.
printf '%s/%s' "${directory%/}" "$child"
}
validate_existing_install_directory() {
local directory="$1"
case "$directory" in
/*) ;;
*) die "the existing unit's install directory is not absolute ($directory); fix ExecStart or pass --prefix with an absolute path" ;;
esac
case "$directory" in
*[[:space:]]*)
die "the existing unit's install directory contains whitespace ($directory); pass --prefix with a whitespace-free path" ;;
esac
validate_exec_start_path "the existing unit's install directory" "$directory"
[ "$(normalize_path "$directory")" = "$directory" ] ||
die "the existing unit's install directory is not canonical ($directory); fix ExecStart or pass --prefix with a canonical path"
}
existing_install_directory_for_binary() {
local binary="$1" directory
case "$binary" in
/*) ;;
*) die "the existing unit's executable path is not absolute ($binary); fix ExecStart or pass --prefix with an absolute path" ;;
esac
[ "$(normalize_path "$binary")" = "$binary" ] ||
die "the existing unit's executable path is not canonical ($binary); fix ExecStart or pass --prefix with a canonical path"
directory="$(dirname -- "$binary")" ||
die "could not derive the existing unit's install directory from $binary"
validate_existing_install_directory "$directory"
printf '%s' "$directory"
}
usage() {
cat <<EOF
alighieri.sh — install, upgrade, and uninstall Alighieri as a systemd service.
Usage:
sudo $0 [COMMAND] [OPTIONS]
Commands:
install Build (or use) the binary, create a dedicated system user,
install a default config under ${CONFIG_DIR} (kept if
present), write a hardened systemd unit, then enable and
(re)start the service. Re-run to reconfigure.
upgrade Replace the installed binary with a newer build and restart
the service. Preserves the config; exact unmodified legacy
units are migrated transactionally when required.
uninstall Stop and disable the service and remove the unit and binary.
status Show the installed version, binary, service, and config state.
help Show this help.
With no command: open a management menu if Alighieri is already installed,
otherwise run install.
Options:
--binary PATH Use this prebuilt service binary. Checkout install/reconfigure
and legacy-unit upgrades still build the companion; release
archives need no toolchain.
--prefix DIR Install prefix for the binary (default: ${PREFIX}).
--config PATH (install) Use this config in the systemd unit. Without it,
reconfiguration preserves the unit's current config path.
A custom path must already be root:${SERVICE_USER} mode 640
beneath a physical, root-controlled directory chain.
--no-restart (upgrade) Replace the binary but do not restart the service.
--no-start (install) Prepare files and the unit without enabling or
starting it. Re-run install after creating credentials.
--purge-config (uninstall) Also remove ${CONFIG_DIR} (userlist, TLS keys!).
--purge-logs (uninstall) Also remove ${LOG_DIR}.
--purge-state (uninstall) Also remove ${STATE_DIR} (ACME certs/account!).
--purge-user (uninstall) Also remove the ${SERVICE_USER} system user.
--purge-all (uninstall) --purge-config --purge-logs --purge-state --purge-user.
-h, --help Show this help.
Examples:
sudo $0 # install, or manage if installed
sudo $0 install # use the bundled release binary, or build
sudo $0 install --binary ./alighieri # explicitly select a prebuilt binary
sudo $0 install --config /etc/alighieri/alighieri.conf
# explicitly select the unit config
sudo $0 upgrade # use bundled binary, or rebuild, and restart
sudo $0 upgrade --binary ./alighieri # swap in a prebuilt binary
sudo $0 uninstall --purge-all # remove everything
EOF
}
# ── Argument parsing ──────────────────────────────────────────────────────────
while [ $# -gt 0 ]; do
case "$1" in
install | upgrade | uninstall | status | __selftest)
# __selftest is hidden (CI self-tests, no root); it is still a command,
# so it obeys the same one-command mutual-exclusivity rule as the rest.
[ "$COMMAND_SEEN" -eq 0 ] || die "only one command may be given (already '$ACTION'): $1"
ACTION="$1"; COMMAND_SEEN=1 ;;
help | -h | --help) usage; exit 0 ;; # help always wins, immediately
--binary) shift; [ $# -gt 0 ] || die "--binary requires a path"; BINARY="$1"; BINARY_EXPLICIT=1 ;;
--prefix) shift; [ $# -gt 0 ] || die "--prefix requires a path"; PREFIX="$1"; PREFIX_EXPLICIT=1 ;;
--config) shift; [ $# -gt 0 ] || die "--config requires a path"; INSTALL_CONFIG="$1"; CONFIG_EXPLICIT=1 ;;
--config=*) INSTALL_CONFIG="${1#--config=}"; [ -n "$INSTALL_CONFIG" ] || die "--config requires a path"; CONFIG_EXPLICIT=1 ;;
--no-restart) RESTART_ON_UPGRADE=0 ;;
--no-start) START_ON_INSTALL=0 ;;
--purge-config) PURGE_CONFIG=1 ;;
--purge-logs) PURGE_LOGS=1 ;;
--purge-state) PURGE_STATE=1 ;;
--purge-user) PURGE_USER=1 ;;
--purge-all) PURGE_CONFIG=1; PURGE_LOGS=1; PURGE_STATE=1; PURGE_USER=1 ;;
*) usage >&2; die "unknown argument: $1" ;;
esac
shift
done
# systemd requires an absolute, whitespace-free ExecStart, and the install
# prefix forms that path, so reject anything that would produce an invalid one.
case "$PREFIX" in
/*) ;;
*) die "--prefix must be an absolute path: $PREFIX" ;;
esac
case "$PREFIX" in
*[[:space:]]*) die "--prefix must not contain whitespace: $PREFIX" ;;
esac
validate_exec_start_path "--prefix" "$PREFIX"
# Do not silently normalize: `/opt/link/..` is not necessarily `/opt` when
# `link` is a symlink. Requiring the canonical lexical spelling keeps both the
# kernel target and systemd's loaded path/argv comparison unambiguous.
[ "$(normalize_path "$PREFIX")" = "$PREFIX" ] ||
die "--prefix must use a canonical path without trailing/repeated slashes, . or .. components: $PREFIX"
if [ "$CONFIG_EXPLICIT" -eq 1 ]; then
[ "$ACTION" = "install" ] || die "--config is valid only with the install command"
case "$INSTALL_CONFIG" in
/*) ;;
*) die "--config must be an absolute path: $INSTALL_CONFIG" ;;
esac
case "$INSTALL_CONFIG" in
*[[:space:]]*) die "--config must not contain whitespace: $INSTALL_CONFIG" ;;
esac
validate_exec_start_path "--config" "$INSTALL_CONFIG"
fi
BIN_DIR="$(install_bin_dir_for_prefix "$PREFIX")" ||
die "could not derive an install directory from --prefix: $PREFIX"
# ── Helpers ───────────────────────────────────────────────────────────────────
require_root() {
[ "$(id -u)" -eq 0 ] && return
local hint="sudo $0"
[ "$ACTION" = "auto" ] || hint="$hint $ACTION"
die "must run as root (try: $hint)"
}
require_systemd() {
command -v systemctl >/dev/null 2>&1 ||
die "systemctl not found; this installer requires systemd"
}
flock_command() { command flock "$@"; }
# Serialize recovery and every mutating lifecycle command. Without one lock, a
# second invocation could mistake the first invocation's live migration journal
# for an interrupted transaction and roll it back underneath the binary commit.
acquire_lifecycle_lock() {
local previous_umask
command -v flock >/dev/null 2>&1 ||
die "flock not found (required to serialize privileged lifecycle commands)"
if [ -e "$LIFECYCLE_LOCK_FILE" ] || [ -L "$LIFECYCLE_LOCK_FILE" ]; then
if [ ! -f "$LIFECYCLE_LOCK_FILE" ] || [ -L "$LIFECYCLE_LOCK_FILE" ]; then
die "lifecycle lock path is not a physical regular file: $LIFECYCLE_LOCK_FILE"
fi
fi
previous_umask="$(umask)"
umask 077
if ! { exec 9>"$LIFECYCLE_LOCK_FILE"; }; then
umask "$previous_umask"
die "could not open lifecycle lock $LIFECYCLE_LOCK_FILE"
fi
umask "$previous_umask"
flock_command -n 9 ||
die "another Alighieri lifecycle command is already running (lock: $LIFECYCLE_LOCK_FILE)"
}
release_lifecycle_lock() {
flock_command -u 9 2>/dev/null || true
exec 9>&-
}
prepare_mutating_lifecycle_command() {
acquire_lifecycle_lock
if [ -e "${UNIT_FILE}.migration" ] || [ -L "${UNIT_FILE}.migration" ]; then
resolve_installer_fs_helper_source
stage_installer_fs_helper "/run/${SERVICE_NAME}" ||
die "could not stage the privileged installer companion for transaction recovery"
fi
recover_interrupted_legacy_unit_transaction
}
require_service_sandbox() {
command -v systemd-run >/dev/null 2>&1 ||
die "systemd-run not found; this installer requires it for service-sandbox preflight"
command -v busctl >/dev/null 2>&1 ||
die "busctl not found; this installer requires it for effective service-sandbox checks"
command -v readlink >/dev/null 2>&1 ||
die "readlink not found; this installer requires it for canonical service-path preflight"
}
nologin_shell() {
for candidate in /usr/sbin/nologin /sbin/nologin /bin/false; do
if [ -x "$candidate" ]; then
printf '%s' "$candidate"
return
fi
done
printf '%s' /bin/false
}
# ExecStart payload from the base unit file only. Empty when absent.
unit_file_exec_start_payload() {
local line=""
if [ -f "$UNIT_FILE" ]; then
line="$(grep '^[[:space:]]*ExecStart=' "$UNIT_FILE" 2>/dev/null | tail -n1 || true)"
fi
[ -n "$line" ] && printf '%s' "${line#*=}"
return 0
}
# Resolve the D-Bus object for the service unit, loading a freshly written unit
# when it is not already referenced or active. Manager.GetUnit only works for an
# already-loaded unit, which breaks a first install (especially --no-start).
service_unit_object_path() {
local response type object extra
response="$(busctl call \
org.freedesktop.systemd1 \
/org/freedesktop/systemd1 \
org.freedesktop.systemd1.Manager \
LoadUnit s "${SERVICE_NAME}.service" 2>/dev/null)" || return 1
read -r type object extra <<<"$response"
[ "$type" = "o" ] && [ -z "$extra" ] || return 1
object="${object#\"}"
object="${object%\"}"
case "$object" in
/org/freedesktop/systemd1/unit/*) printf '%s' "$object" ;;
*) return 1 ;;
esac
}
systemd_manager_version() {
local version
version="$(systemctl show --property=Version --value 2>/dev/null)" || return 1
version="${version%%[!0-9]*}"
case "$version" in
'' | *[!0-9]*) return 1 ;;
esac
printf '%s' "$version"
}
decode_busctl_simple_string() {
local value="$1"
case "$value" in
\"*\")
value="${value#\"}"
value="${value%\"}"
;;
*) return 1 ;;
esac
# Supported unit paths/arguments contain neither whitespace nor quoting
# escapes. Refuse a busctl-escaped value rather than decoding it differently
# from systemd. Dollar and percent markers are also unsafe here: systemd can
# expand them only when the service starts, after this manager-loaded value
# has been inspected, so preflighting the literal would validate a different
# path from the one used on restart.
case "$value" in
*\\* | *\"* | *'$'* | *%*) return 1 ;;
esac
printf '%s' "$value"
}
legacy_effective_exec_start_is_unmodified() {
# ExecStartEx (v243+) exposes every command prefix. The legacy D-Bus
# property exposes only `-`, so on older managers conservatively require
# each physical ExecStart assignment to be empty (a reset) or start with the
# managed unquoted absolute executable form. Reject includes, BOMs, and line
# continuations that could hide a privileged `+`/`!`/`:` prefix.
systemctl cat --no-pager -- "${SERVICE_NAME}.service" 2>/dev/null |
LC_ALL=C awk '
BEGIN { bom = "\357\273\277" }
/^[[:space:]]*[#;]/ { next }
index($0, bom) == 1 { exit 1 }
{
line = $0
sub(/^[[:space:]]*/, "", line)
if (line ~ /^\.include([[:space:]]|$)/) exit 1
if (line ~ /\\[[:space:]]*$/) exit 1
if (line !~ /^ExecStart[[:space:]]*=/) next
sub(/^ExecStart[[:space:]]*=[[:space:]]*/, "", line)
if (line != "" && substr(line, 1, 1) != "/") exit 1
}
'
}
# Canonical whitespace-delimited argv for the single manager-loaded ExecStart.
# Reading D-Bus rather than `systemctl cat` includes legacy `.include` files,
# continuations, and the exact post-daemon-reload command. The managed service
# uses simple, whitespace-free arguments, so reject shapes that cannot be
# represented by the installer's deliberately narrow parser.
loaded_exec_start_payload() {
local object output command_count executable argc flags token value payload="" \
i version property
local -a fields=() argv=()
object="$(service_unit_object_path)" || return 1
version="$(systemd_manager_version)" || return 1
if [ "$version" -ge 243 ]; then
property="ExecStartEx"
else
property="ExecStart"
legacy_effective_exec_start_is_unmodified || return 1
fi
output="$(busctl get-property \
org.freedesktop.systemd1 "$object" \
org.freedesktop.systemd1.Service "$property" 2>/dev/null)" || return 1
read -ra fields <<<"$output"
[ "${#fields[@]}" -ge 6 ] || return 1
command_count="${fields[1]}"
executable="$(decode_busctl_simple_string "${fields[2]}")" || return 1
argc="${fields[3]}"
case "$argc" in
'' | *[!0-9]*) return 1 ;;
esac
[ "$command_count" = "1" ] && [ "$argc" -ge 1 ] &&
[ "${#fields[@]}" -ge $((argc + 5)) ] || return 1
flags="${fields[$((argc + 4))]}"
if [ "$version" -ge 243 ]; then
[ "$flags" = "0" ] || return 1
else
[ "$flags" = "false" ] || return 1
fi
for ((i = 0; i < argc; i++)); do
token="${fields[$((i + 4))]}"
value="$(decode_busctl_simple_string "$token")" || return 1
argv+=("$value")
payload="${payload}${payload:+ }$value"
done
[ "${argv[0]}" = "$executable" ] || return 1
printf '%s' "$payload"
}
# Effective ExecStart payload (everything after its first '=') for the service.
# Prefer the manager-loaded D-Bus argv so includes/continuations and drop-ins are
# honoured; fall back to merged/on-disk text for non-mutating status/uninstall
# lookups when the manager or busctl is unavailable. Empty when none is found.
exec_start_payload() {
local line="" loaded=""
if command -v busctl >/dev/null 2>&1 &&
loaded="$(loaded_exec_start_payload 2>/dev/null)"; then
printf '%s' "$loaded"
return 0
fi
if command -v systemctl >/dev/null 2>&1; then
line="$(systemctl cat -- "${SERVICE_NAME}.service" 2>/dev/null |
grep '^[[:space:]]*ExecStart=' | tail -n1 || true)"
fi
if [ -z "$line" ]; then
unit_file_exec_start_payload
else
printf '%s' "${line#*=}"
fi
return 0
}
# True when systemd's merged ExecStart differs from the base unit we manage,
# which means a drop-in will survive rewriting that base file.
effective_exec_start_overrides_base() {
local base effective
base="$(unit_file_exec_start_payload)"
effective="$(exec_start_payload)"
[ "$effective" != "$base" ]
}
# Resolve where the binary actually lives, from the effective ExecStart (so a
# custom --prefix install — or a drop-in override — is found on upgrade and
# uninstall); fall back to the default prefix when it can't be parsed/validated.
installed_binary_path() {
local payload bin_path
payload="$(exec_start_payload)"
# Split on any whitespace (space or tab); the first field is the binary.
read -r bin_path _ <<<"$payload"
# Only trust an absolute path whose name matches the service; a malformed or
# hand-edited unit with a relative path must not make upgrade/uninstall mv or
# rm a path relative to the caller's CWD as root.
case "$bin_path" in
/*)
if [ "$(basename -- "$bin_path")" = "$SERVICE_NAME" ]; then
printf '%s' "$bin_path"
return
fi
;;
esac
join_path_child "$BIN_DIR" "$SERVICE_NAME"
}
# Resolve the config path the installed unit actually launches with. An explicit
# --config / --config=PATH flag (also supported by the binary) wins; otherwise
# the positional second token of ExecStart (the first is the binary). Only an
# absolute path is trusted, so a malformed or hand-edited unit with a relative
# token falls back to the default rather than pointing upgrade/status at a path
# relative to the caller's CWD.
installed_config_path() {
local payload cfg=""
payload="$(exec_start_payload)"
# read -ra splits on shell whitespace (space, tab) without glob-expanding;
# unit paths are whitespace-free.
local -a tokens=()
read -ra tokens <<<"$payload"
local i=0 n=${#tokens[@]}
while [ "$i" -lt "$n" ]; do
case "${tokens[$i]}" in
--config=*) cfg="${tokens[$i]#--config=}" ;;
--config)
if [ $((i + 1)) -lt "$n" ]; then cfg="${tokens[$((i + 1))]}"; fi
;;
esac
i=$((i + 1))
done
if [ -z "$cfg" ] && [ "$n" -ge 2 ]; then
cfg="${tokens[1]}" # positional config (binary is tokens[0])
fi
case "$cfg" in
/*) printf '%s' "$cfg"; return ;;
esac
printf '%s' "$CONFIG_FILE"
}
effective_install_matches() {
local expected_binary="$1" expected_config="$2" effective
# This is a post-daemon-reload safety check, not a status-path lookup. Match
# the exact payload we just wrote instead of using installed_*_path, whose
# deliberately conservative fallbacks would turn an empty/malformed
# surviving drop-in into the expected defaults and allow a stale service to
# start. Paths accepted by the installer contain neither whitespace nor
# systemd expansion/quoting characters, so this canonical form is exact.
effective="$(loaded_exec_start_payload)" || return 1
[ "$effective" = "$expected_binary $expected_config" ]
}
# Historical generated units are accepted for automatic migration only when
# their complete base-unit bytes still match a released template. This narrow
# fingerprint distinguishes an untouched old Alighieri install from a hand-
# edited unit whose operational intent the helper must not overwrite.
render_legacy_unit_v0_1() {
local install_bin="$1" config_file="$2"
cat <<UNIT
[Unit]
Description=Alighieri SOCKS5 proxy server
Documentation=https://github.com/wiresock/alighieri
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_USER
ExecStart=$install_bin $config_file
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5
# Hardening. The default config listens on an unprivileged port; to bind a
# port below 1024, add CAP_NET_BIND_SERVICE to AmbientCapabilities and
# CapabilityBoundingSet.
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictNamespaces=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
CapabilityBoundingSet=
AmbientCapabilities=
ReadWritePaths=$LOG_DIR
[Install]
WantedBy=multi-user.target
UNIT
}
render_legacy_unit_v0_2_to_v0_4() {
local install_bin="$1" config_file="$2" caps="$3"
case "$caps" in '' | CAP_NET_BIND_SERVICE) ;; *) return 1 ;; esac
cat <<UNIT
[Unit]
Description=Alighieri SOCKS5 proxy server
Documentation=https://github.com/wiresock/alighieri
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=$SERVICE_USER
Group=$SERVICE_USER
ExecStart=$install_bin $config_file
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5
# Hardening. CAP_NET_BIND_SERVICE is granted (below) only when the config needs
# a privileged port — an internal: port under 1024, or ACME, whose TLS-ALPN-01
# challenge is answered on :443; otherwise all capabilities are dropped.
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictNamespaces=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallFilter=@system-service
SystemCallErrorNumber=EPERM
CapabilityBoundingSet=$caps
AmbientCapabilities=$caps
ReadWritePaths=$LOG_DIR
# StateDirectory keeps /var/lib/${SERVICE_NAME} writable under
# ProtectSystem=strict (created on start, owned by the service user); it holds
# the ACME certificate cache (tls.acme.cache).
StateDirectory=${SERVICE_NAME}
StateDirectoryMode=0750
[Install]
WantedBy=multi-user.target
UNIT
}
unit_file_is_safe_for_legacy_migration() {
local path="${1:-$UNIT_FILE}"
[ -f "$path" ] && [ ! -L "$path" ] || return 1
local metadata owner mode extra permissions
metadata="$(stat -Lc '%u %a' -- "$path" 2>/dev/null)" || return 1
read -r owner mode extra <<<"$metadata"
[ "$owner" = 0 ] && [ -n "$mode" ] && [ -z "${extra:-}" ] || return 1
case "$mode" in *[!0-7]* | '') return 1 ;; esac
permissions=$((8#$mode))
[ $((permissions & 0022)) -eq 0 ]
}
loaded_unit_source_is_unoverridden() {
local properties
properties="$(systemctl show --no-pager \
--property=FragmentPath --property=DropInPaths \
-- "${SERVICE_NAME}.service" 2>/dev/null)" || return 1
printf '%s\n' "$properties" | grep -Fqx -- "FragmentPath=$UNIT_FILE" &&
printf '%s\n' "$properties" | grep -Fqx -- 'DropInPaths='
}
legacy_unit_file_matches_kind() {
local path="$1" kind="$2" install_bin="$3" config_file="$4" caps
case "$kind" in
v0.1.x)
cmp -s -- "$path" \
<(render_legacy_unit_v0_1 "$install_bin" "$config_file")
;;
v0.2.0-v0.4.0)
for caps in '' CAP_NET_BIND_SERVICE; do
if cmp -s -- "$path" \
<(render_legacy_unit_v0_2_to_v0_4 \
"$install_bin" "$config_file" "$caps"); then
return 0
fi
done
return 1
;;
*) return 1 ;;
esac
}
# Print the recognized legacy family. Failure means the loaded service is not
# backed by an exact, unmodified released template and must remain fail-closed.
legacy_generated_unit_kind() {
command -v cmp >/dev/null 2>&1 || return 2
unit_file_is_safe_for_legacy_migration || return 1
loaded_unit_source_is_unoverridden || return 1
local payload value
local -a argv=()
payload="$(loaded_exec_start_payload 2>/dev/null)" || return 1
read -ra argv <<<"$payload"
[ "${#argv[@]}" -eq 2 ] || return 1
for value in "${argv[@]}"; do
case "$value" in
/*) ;;
*) return 1 ;;
esac
case "$value" in *[[:space:]%\$\"\'\\]*) return 1 ;; esac
[ "$(normalize_path "$value")" = "$value" ] || return 1
done
[ "$(basename -- "${argv[0]}")" = "$SERVICE_NAME" ] || return 1
if legacy_unit_file_matches_kind \
"$UNIT_FILE" v0.1.x "${argv[0]}" "${argv[1]}"; then
printf '%s' 'v0.1.x'
return 0
fi
if legacy_unit_file_matches_kind \
"$UNIT_FILE" v0.2.0-v0.4.0 "${argv[0]}" "${argv[1]}"; then
printf '%s' 'v0.2.0-v0.4.0'
return 0
fi
return 1
}
# Decide whether upgrade can keep the current unit or should migrate a released
# legacy template. Exact legacy recognition comes first so semantically compatible
# v0.2-v0.4 units are refreshed too; every edited unit and every drop-in remains
# subject to the normal effective-sandbox guard.
prepare_upgrade_unit_migration() {
local install_bin="$1" config_file="$2" expected_exec_start="$3" \
kind status description
UPGRADE_LEGACY_UNIT_KIND=""
if kind="$(legacy_generated_unit_kind 2>/dev/null)"; then
[ "$expected_exec_start" = "$install_bin $config_file" ] ||
die "effective systemd ExecStart changed while identifying the legacy unit; review the unit/drop-ins, then retry"
UPGRADE_LEGACY_UNIT_KIND="$kind"
case "$kind" in
v0.1.x) description="v0.1-era" ;;
v0.2.0-v0.4.0) description="v0.2-v0.4-era" ;;
*) description="legacy" ;;
esac
info "recognized an untouched Alighieri $description systemd unit template; upgrade will migrate it to the current hardened unit"
return 0
else
status=$?
[ "$status" -ne 2 ] ||
die "cmp not found; install a coreutils-compatible cmp command before checking or migrating a legacy systemd unit"
fi
effective_service_sandbox_matches && return 0
die "effective systemd service settings differ from the managed unit, and the base unit is not an exact unmodified Alighieri legacy template. Inspect it with: systemctl show ${SERVICE_NAME}.service --no-pager -p FragmentPath -p DropInPaths; systemctl cat ${SERVICE_NAME}.service. After reviewing any deliberate customization, use 'sudo $0 install' to regenerate the managed unit."
}
# Effective identity and filesystem-view properties after systemd merges the
# managed unit with all surviving drop-ins. These must match the transient
# preflight exactly: an overridden WorkingDirectory would resolve relative
# userlists differently, while identity or namespace overrides could make paths
# readable during validation but unavailable after restart (or vice versa).
effective_service_sandbox_properties() {
systemctl show --no-pager \
--property=User \
--property=Group \
--property=WorkingDirectory \
--property=ProtectSystem \
--property=ProtectHome \
--property=PrivateTmp \
--property=PrivateDevices \
--property=ProtectKernelTunables \
--property=ProtectKernelModules \
--property=ProtectControlGroups \
--property=DynamicUser \
--property=PrivateUsers \
--property=SupplementaryGroups \
--property=RootDirectory \
--property=RootImage \
-- "${SERVICE_NAME}.service"
}
# True when the manager-loaded unit has no additive path-namespace directives.
# systemctl before v247 renders some of these complex arrays as `[unprintable]`
# even when empty. Read their stable raw D-Bus representation instead: its first
# value after the type signature is the top-level element count. This also sees
# legacy `.include` files, continuations, BOM-prefixed fragments, and the exact
# state the next restart will use without reimplementing systemd's unit parser.
effective_service_path_namespace_matches() {
local object version property output signature count value extra
local -a properties=(ReadOnlyPaths InaccessiblePaths BindPaths BindReadOnlyPaths)
object="$(service_unit_object_path)" || return 1
version="$(systemd_manager_version)" || return 1
if [ "$version" -ge 238 ]; then
properties+=(TemporaryFileSystem)
fi
if [ "$version" -ge 247 ]; then
properties+=(MountImages)
fi
if [ "$version" -ge 248 ]; then
properties+=(ExtensionImages NoExecPaths ExecPaths)
fi
if [ "$version" -ge 251 ]; then
properties+=(ExtensionDirectories)
fi
for property in "${properties[@]}"; do
output="$(busctl get-property \
org.freedesktop.systemd1 "$object" \
org.freedesktop.systemd1.Service "$property" 2>/dev/null)" || return 1
read -r signature count _ <<<"$output"
[ -n "$signature" ] && [ "$count" = "0" ] || return 1
done
# v260's RootMStack is another complete alternate root (overlay-backed),
# analogous to RootDirectory/RootImage, but is not present on older managers.
if [ "$version" -ge 260 ]; then
output="$(busctl get-property \
org.freedesktop.systemd1 "$object" \
org.freedesktop.systemd1.Service RootMStack 2>/dev/null)" || return 1
read -r signature value extra <<<"$output"
[ "$signature" = "s" ] && [ "$value" = '""' ] &&
[ -z "$extra" ] || return 1
fi
}
loaded_service_property() {
local object="$1" property="$2"
busctl get-property \
org.freedesktop.systemd1 "$object" \
org.freedesktop.systemd1.Service "$property" 2>/dev/null
}
loaded_single_string_array_equals() {
local raw="$1" expected="$2" signature count encoded extra decoded
read -r signature count encoded extra <<<"$raw"
[ "$signature" = as ] && [ "$count" = 1 ] && [ -n "$encoded" ] &&
[ -z "${extra:-}" ] || return 1
decoded="$(decode_busctl_simple_string "$encoded")" || return 1
[ "$decoded" = "$expected" ]
}
loaded_empty_string_array() {
local raw="$1" signature count extra
read -r signature count extra <<<"$raw"
[ "$signature" = as ] && [ "$count" = 0 ] && [ -z "${extra:-}" ]
}
loaded_unsigned_equals() {
local raw="$1" expected_signature="$2" expected="$3" signature value extra
read -r signature value extra <<<"$raw"
[ "$signature" = "$expected_signature" ] && [ -z "${extra:-}" ] || return 1
case "$value" in
'' | *[!0-9]*) return 1 ;;
esac
[ "$value" = "$expected" ]
}
# StateDirectorySymlink was added in systemd 250. Older implementations expose
# only actual destination mappings, while newer ones expose the ordinary
# `StateDirectory=alighieri` entry with an empty destination as well. Either
# exact representation is safe; every non-empty destination or flag is not.
loaded_state_directory_mapping_matches() {
local raw="$1" signature count source destination flags extra
read -r signature count source destination flags extra <<<"$raw"
[ "$signature" = 'a(sst)' ] || return 1
if [ "$count" = 0 ]; then
[ -z "${source:-}" ]
return
fi
[ "$count" = 1 ] && [ -n "${source:-}" ] &&
[ -n "${destination:-}" ] && [ -n "${flags:-}" ] &&
[ -z "${extra:-}" ] || return 1
source="$(decode_busctl_simple_string "$source")" || return 1
destination="$(decode_busctl_simple_string "$destination")" || return 1
[ "$source" = "$SERVICE_NAME" ] && [ -z "$destination" ] && [ "$flags" = 0 ]
}
# Verify the manager-loaded writable locations, not just the base unit text.
# List-valued drop-ins can reset StateDirectory/ReadWritePaths or add broader
# paths while leaving the scalar namespace properties above unchanged.
effective_service_managed_storage_matches() {
local object version property raw
object="$(service_unit_object_path)" || return 1
raw="$(loaded_service_property "$object" StateDirectory)" || return 1
loaded_single_string_array_equals "$raw" "$SERVICE_NAME" || return 1
raw="$(loaded_service_property "$object" StateDirectoryMode)" || return 1
# 0750 expressed as the unsigned decimal D-Bus value.
loaded_unsigned_equals "$raw" u 488 || return 1
raw="$(loaded_service_property "$object" ReadWritePaths)" || return 1
loaded_single_string_array_equals "$raw" "$LOG_DIR" || return 1
# These managed-directory directives create additional service-writable
# roots despite ProtectSystem=strict. The generated unit uses none of them,
# so a surviving drop-in must not be allowed to add one.
for property in RuntimeDirectory CacheDirectory LogsDirectory ConfigurationDirectory; do
raw="$(loaded_service_property "$object" "$property")" || return 1
loaded_empty_string_array "$raw" || return 1
done
version="$(systemd_manager_version)" || return 1
if [ "$version" -ge 250 ]; then
raw="$(loaded_service_property "$object" StateDirectorySymlink)" || return 1
loaded_state_directory_mapping_matches "$raw" || return 1
fi
}
effective_service_capability_sets_match() {
local expected="$1" object raw
case "$expected" in 0 | 1024) ;; *) return 1 ;; esac
object="$(service_unit_object_path)" || return 1
raw="$(loaded_service_property "$object" CapabilityBoundingSet)" || return 1
loaded_unsigned_equals "$raw" t "$expected" || return 1
raw="$(loaded_service_property "$object" AmbientCapabilities)" || return 1
loaded_unsigned_equals "$raw" t "$expected"
}
effective_service_sandbox_matches() {
local properties expected
properties="$(effective_service_sandbox_properties 2>/dev/null)" || return 1
for expected in \
"User=$SERVICE_USER" \
"Group=$SERVICE_USER" \
'ProtectSystem=strict' \
'ProtectHome=yes' \
'PrivateTmp=yes' \
'PrivateDevices=yes' \
'ProtectKernelTunables=yes' \
'ProtectKernelModules=yes' \
'ProtectControlGroups=yes' \
'DynamicUser=no' \
'PrivateUsers=no' \
'SupplementaryGroups=' \
'RootDirectory=' \
'RootImage='; do
printf '%s\n' "$properties" | grep -Fqx -- "$expected" || return 1
done
# An unset WorkingDirectory is systemd's system-service default `/`, so an
# older generated unit without the explicit directive is semantically equal.
printf '%s\n' "$properties" |
grep -Eq '^WorkingDirectory=(/)?$' || return 1