forked from Varckin/amneziawg-install
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathamneziawg-install.sh
More file actions
7424 lines (6785 loc) · 280 KB
/
Copy pathamneziawg-install.sh
File metadata and controls
7424 lines (6785 loc) · 280 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
#!/bin/bash
# AmneziaWG server installer
# https://github.com/wiresock/amneziawg-install
RED='\033[0;31m'
ORANGE='\033[0;33m'
GREEN='\033[0;32m'
NC='\033[0m'
AMNEZIAWG_DIR="/etc/amnezia/amneziawg"
WEB_PANEL_CONFIG_DIR="${AMNEZIAWG_DIR}/clients"
WEB_PANEL_ENV_FILE="/etc/amneziawg-web/env.conf"
WEB_PANEL_SYSTEMD_UNIT="/etc/systemd/system/amneziawg-web.service"
WEB_PANEL_DATA_DIR="/var/lib/amneziawg-web"
# Protocol state is deliberately independent from package/tool versions. A
# missing value in an older params file always means AWG 2.0; AWG 3.0 is only
# entered through the explicit, capability-gated migration path.
AWG_PROTOCOL_VERSION_2="2"
AWG_PROTOCOL_VERSION_3="3"
AWG3_DEFAULT_CONTENT_PADDING_ADDITION="10-100"
AWG3_DEFAULT_REKEY_AFTER_TIME="100-120"
AWG3_DEFAULT_REKEY_TIMEOUT="3-7"
AWG3_DEFAULT_REJECT_AFTER_TIME="150-180"
AWG3_DEFAULT_KEEPALIVE_TIMEOUT="5-15"
# Ensure sbin directories are in PATH for depmod, modprobe, sysctl, etc.
# Some minimal or non-login root shells may not include these by default.
# Only adjust PATH when the script is executed directly, not when sourced.
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
if [ -n "${PATH:-}" ]; then
export PATH="/sbin:/usr/sbin:${PATH:-}"
else
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
fi
fi
# Work around broken IPv6 on cloud VPS providers. Some providers resolve
# Launchpad / Ubuntu keyserver / COPR hostnames to both A and AAAA records,
# but outbound IPv6 connectivity is broken, causing apt, dnf,
# add-apt-repository, and COPR API calls to hang.
#
# Two complementary mitigations are applied:
#
# 1. APT ForceIPv4 (Debian/Ubuntu only) — a config file in apt.conf.d/
# forces all apt-based tools (including add-apt-repository, which uses
# python-apt internally) to use IPv4. This file is only written when
# apt-get or apt is present to avoid creating /etc/apt on RPM distros.
#
# 2. gai.conf IPv4-preference rule (all distros) — an IPv4-preference rule
# is injected into /etc/gai.conf so that glibc's getaddrinfo (and thus
# Python's socket.getaddrinfo and libcurl used by dnf) *prefers* IPv4.
# On Ubuntu 24.04 this also fixes a Python traceback from httplib2
# used by add-apt-repository, which does NOT honour Acquire::ForceIPv4.
APT_FORCE_IPV4_CONF="/etc/apt/apt.conf.d/99amneziawg-force-ipv4"
APT_FORCE_IPV4_SENTINEL="# Managed by amneziawg-install - safe to remove"
GAI_CONF="/etc/gai.conf"
GAI_CONF_SENTINEL="# Added by amneziawg-install - safe to remove"
GAI_CONF_IPV4_RULE="precedence ::ffff:0:0/96 100"
GAI_CONF_IPV4_RULE_REGEX='^[[:space:]]*precedence[[:space:]]+::ffff:0:0/96[[:space:]]+100([[:space:]]*(#.*)?)?$'
AMNEZIA_PPA_URI="https://ppa.launchpadcontent.net/amnezia/ppa/ubuntu"
AMNEZIA_PPA_SOURCES_DIR="/etc/apt/sources.list.d"
AMNEZIA_PPA_SOURCE_CREATED=0
_APT_IPV4_PREV_TRAP_EXIT=""
_APT_IPV4_PREV_TRAP_INT=""
_APT_IPV4_PREV_TRAP_TERM=""
# Return success when gai.conf has an active (uncommented) IPv4 precedence
# rule for ::ffff:0:0/96 with value 100; commented defaults must not match.
gai_conf_has_active_ipv4_rule() {
grep -Eq "${GAI_CONF_IPV4_RULE_REGEX}" "${GAI_CONF}" 2>/dev/null
}
enable_apt_ipv4() {
# Only write the APT ForceIPv4 config on distros that actually use APT,
# to avoid creating /etc/apt on RPM-based systems.
if command -v apt-get >/dev/null 2>&1 || command -v apt >/dev/null 2>&1 || [[ -d /etc/apt ]]; then
mkdir -p /etc/apt/apt.conf.d
printf '%s\n%s\n' "${APT_FORCE_IPV4_SENTINEL}" 'Acquire::ForceIPv4 "true";' \
> "${APT_FORCE_IPV4_CONF}"
fi
# Prefer IPv4 in the system resolver so all glibc consumers (Python,
# libcurl/dnf, etc.) connect over IPv4.
if ! gai_conf_has_active_ipv4_rule; then
local _gai_existed=0
[[ -f "${GAI_CONF}" ]] && _gai_existed=1
printf '\n%s\n%s\n' "${GAI_CONF_SENTINEL}" "${GAI_CONF_IPV4_RULE}" \
>> "${GAI_CONF}"
# Only set permissions when we created the file; leave existing
# ownership/mode untouched so the cleanup path can preserve them.
if [[ "${_gai_existed}" -eq 0 ]]; then
chmod 0644 "${GAI_CONF}"
fi
fi
# Save existing trap commands so we can chain them (not just restore).
# trap -p output is eval-safe by design (bash always emits: trap -- 'body' SIG).
_APT_IPV4_PREV_TRAP_EXIT="$(trap -p EXIT || true)"
_APT_IPV4_PREV_TRAP_INT="$(trap -p INT || true)"
_APT_IPV4_PREV_TRAP_TERM="$(trap -p TERM || true)"
# Install traps that clean up *and* invoke any prior handler, so
# pre-existing cleanup logic still runs even if the script exits
# while IPv4 forcing is active.
trap '_cleanup_apt_ipv4_and_chain EXIT' EXIT
trap '_cleanup_apt_ipv4_and_chain INT' INT
trap '_cleanup_apt_ipv4_and_chain TERM' TERM
}
# Internal: remove the APT ForceIPv4 config and revert gai.conf changes.
_remove_ipv4_overrides() {
# Only remove the file if it carries our sentinel.
if [[ -f "${APT_FORCE_IPV4_CONF}" ]] && grep -qFm1 "${APT_FORCE_IPV4_SENTINEL}" "${APT_FORCE_IPV4_CONF}"; then
rm -f "${APT_FORCE_IPV4_CONF}"
fi
# Remove gai.conf lines we added (if any). Only act when our sentinel
# is present so pre-existing admin rules are never touched. This must
# be idempotent so interrupted previous runs are also cleaned up.
if [[ -f "${GAI_CONF}" ]] && grep -qF "${GAI_CONF_SENTINEL}" "${GAI_CONF}"; then
awk -v sent="${GAI_CONF_SENTINEL}" -v regex="${GAI_CONF_IPV4_RULE_REGEX}" '
# State machine:
# 1) skip our sentinel line
# 2) skip the immediately following active IPv4 rule if present
# 3) print all other lines unchanged
$0 == sent { prev_sent=1; next }
prev_sent == 1 && $0 ~ regex { prev_sent=0; next }
{ prev_sent=0; print }
' "${GAI_CONF}" > "${GAI_CONF}.tmp"
if ! chmod --reference="${GAI_CONF}" "${GAI_CONF}.tmp" || ! chown --reference="${GAI_CONF}" "${GAI_CONF}.tmp"; then
rm -f "${GAI_CONF}.tmp"
return 1
fi
mv "${GAI_CONF}.tmp" "${GAI_CONF}"
fi
}
# Internal: remove the config file, restore the previous trap for the
# given signal, then immediately invoke the restored handler so it runs
# during the same exit / signal delivery.
_cleanup_apt_ipv4_and_chain() {
# Preserve the original exit status so chained handlers see the real value.
local _saved_status=$?
local sig="$1"
_remove_ipv4_overrides
# Restore + chain: re-install the previous trap (if any), then
# re-deliver the signal / exit so bash invokes the restored handler.
# This avoids parsing trap -p output entirely (no sed/eval of bodies).
local prev_var="_APT_IPV4_PREV_TRAP_${sig}"
local prev_trap="${!prev_var}"
if [[ -n "${prev_trap}" ]]; then
# Re-install the previous trap (e.g. trap -- 'handler' EXIT).
eval "${prev_trap}"
# Re-deliver the signal so bash invokes the just-restored handler.
if [[ "${sig}" == "EXIT" ]]; then
# For EXIT: exiting re-fires the EXIT trap with the original status.
exit "${_saved_status}"
else
# For INT/TERM: re-raise the signal to invoke the restored handler.
kill -s "${sig}" "$$" 2>/dev/null || {
case "${sig}" in
INT) exit 130 ;; # 128 + SIGINT(2)
TERM) exit 143 ;; # 128 + SIGTERM(15)
esac
}
fi
else
trap - "${sig}"
if [[ "${sig}" == "EXIT" ]]; then
# Preserve the original exit status when no prior handler exists.
exit "${_saved_status}"
elif [[ "${sig}" == INT || "${sig}" == TERM ]]; then
# Re-raise the signal so default termination semantics are preserved.
kill -s "${sig}" "$$" 2>/dev/null || {
case "${sig}" in
INT) exit 130 ;; # 128 + SIGINT(2)
TERM) exit 143 ;; # 128 + SIGTERM(15)
esac
}
fi
fi
}
disable_apt_ipv4() {
_remove_ipv4_overrides
# Restore any previously installed traps.
if [[ -n "${_APT_IPV4_PREV_TRAP_EXIT}" ]]; then
eval "${_APT_IPV4_PREV_TRAP_EXIT}"
else
trap - EXIT
fi
if [[ -n "${_APT_IPV4_PREV_TRAP_INT}" ]]; then
eval "${_APT_IPV4_PREV_TRAP_INT}"
else
trap - INT
fi
if [[ -n "${_APT_IPV4_PREV_TRAP_TERM}" ]]; then
eval "${_APT_IPV4_PREV_TRAP_TERM}"
else
trap - TERM
fi
}
# Return the Ubuntu archive codename that add-apt-repository should use.
# Linux Mint exposes its Ubuntu base in UBUNTU_CODENAME.
function getUbuntuPpaCodename() {
local CODENAME
if [[ "${ID:-}" == "linuxmint" ]]; then
CODENAME="${UBUNTU_CODENAME:-}"
else
CODENAME="${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}"
fi
if [[ -z "${CODENAME}" ]] || ! [[ "${CODENAME}" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then
echo -e "${RED}ERROR: Unable to determine a valid Ubuntu codename for the Amnezia PPA.${NC}" >&2
return 1
fi
printf '%s\n' "${CODENAME}"
}
# Reviewed cross-release mappings. Unknown releases must never be mapped
# automatically; every mapping requires package and DKMS compatibility testing.
function getAmneziaPpaFallbackSuite() {
case "$1" in
resolute) printf '%s\n' "noble" ;;
*) return 1 ;;
esac
}
# Noble currently publishes amneziawg-tools for these architectures. Although
# the Release file advertises i386, the required tools package is absent there.
function isAmneziaPpaFallbackArchitectureSupported() {
case "$1" in
amd64 | arm64 | armhf | ppc64el | riscv64 | s390x) return 0 ;;
*) return 1 ;;
esac
}
# Print the direct HTTP status for a PPA metadata URL without following
# redirects. A redirect is ambiguous and must remain a 3xx so the caller fails
# closed. Network, TLS, timeout, and tool failures return 2 without inventing a
# status. curl is installed by the normal Ubuntu flow; wget/python3 allow
# recovery from an older partial install before the first apt-get update.
function getAmneziaPpaHttpStatus() {
local URL="$1"
local STATUS=""
local OUTPUT=""
if command -v curl &>/dev/null; then
STATUS=$(curl --disable -4 --silent --show-error \
--connect-timeout 10 --max-time 30 \
--output /dev/null --write-out '%{http_code}' "${URL}") || return 2
elif command -v wget &>/dev/null; then
OUTPUT=$(wget -4 --server-response --spider --max-redirect=0 \
--timeout=30 --tries=1 "${URL}" 2>&1) || true
STATUS=$(printf '%s\n' "${OUTPUT}" | awk '
/^[[:space:]]*HTTP\/[0-9.]+[[:space:]]+[0-9][0-9][0-9]/ { status=$2 }
END { print status }
')
elif command -v python3 &>/dev/null; then
STATUS=$(python3 - "${URL}" <<'PY'
import sys
import urllib.error
import urllib.request
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, request, file_pointer, code, message, headers, new_url):
return None
request = urllib.request.Request(sys.argv[1], method="GET")
opener = urllib.request.build_opener(NoRedirect())
try:
with opener.open(request, timeout=30) as response:
print(response.status)
except urllib.error.HTTPError as error:
print(error.code)
except (OSError, urllib.error.URLError):
raise SystemExit(2)
PY
) || return 2
else
return 2
fi
if ! [[ "${STATUS}" =~ ^[0-9]{3}$ ]]; then
return 2
fi
printf '%s\n' "${STATUS}"
}
# Tri-state PPA metadata probe:
# 0: suite is available (signed metadata resource exists)
# 1: suite is definitely unavailable (both resources are 404/410)
# 2: status is unknown (network/server/auth/other failure)
function probeAmneziaPpaSuite() {
local SUITE="$1"
local RESOURCE
local STATUS
for RESOURCE in InRelease Release; do
STATUS=$(getAmneziaPpaHttpStatus \
"${AMNEZIA_PPA_URI}/dists/${SUITE}/${RESOURCE}") || return 2
case "${STATUS}" in
200) return 0 ;;
404 | 410) ;;
*) return 2 ;;
esac
done
return 1
}
# Select the native suite whenever it exists. A fallback is considered only
# after definite native absence, never after a transient or ambiguous failure.
function selectAmneziaPpaSuite() {
local NATIVE_SUITE="$1"
local ARCHITECTURE="$2"
local FALLBACK_SUITE
local PROBE_RC
if probeAmneziaPpaSuite "${NATIVE_SUITE}"; then
PROBE_RC=0
else
PROBE_RC=$?
fi
case "${PROBE_RC}" in
0)
printf '%s\n' "${NATIVE_SUITE}"
return 0
;;
2)
echo -e "${RED}ERROR: Could not determine whether the Amnezia PPA supports Ubuntu '${NATIVE_SUITE}'.${NC}" >&2
echo -e "${ORANGE}A network, TLS, rate-limit, or server error occurred. No cross-release fallback was applied.${NC}" >&2
return 1
;;
esac
FALLBACK_SUITE=$(getAmneziaPpaFallbackSuite "${NATIVE_SUITE}") || {
echo -e "${RED}ERROR: The Amnezia PPA does not publish packages for Ubuntu '${NATIVE_SUITE}', and no verified fallback is configured.${NC}" >&2
return 1
}
if ! isAmneziaPpaFallbackArchitectureSupported "${ARCHITECTURE}"; then
echo -e "${RED}ERROR: The verified ${NATIVE_SUITE} -> ${FALLBACK_SUITE} Amnezia PPA fallback is not available for architecture '${ARCHITECTURE}'.${NC}" >&2
return 1
fi
if probeAmneziaPpaSuite "${FALLBACK_SUITE}"; then
PROBE_RC=0
else
PROBE_RC=$?
fi
case "${PROBE_RC}" in
0)
echo -e "${ORANGE}WARNING: The Amnezia PPA has no native '${NATIVE_SUITE}' repository. Using signed '${FALLBACK_SUITE}' PPA packages from Ubuntu 24.04 for this reviewed compatibility fallback.${NC}" >&2
printf '%s\n' "${FALLBACK_SUITE}"
return 0
;;
1)
echo -e "${RED}ERROR: Neither the native '${NATIVE_SUITE}' suite nor its reviewed '${FALLBACK_SUITE}' fallback is available in the Amnezia PPA.${NC}" >&2
;;
2)
echo -e "${RED}ERROR: The native '${NATIVE_SUITE}' suite is unavailable, but the '${FALLBACK_SUITE}' fallback could not be verified because of a network or server error.${NC}" >&2
echo -e "${ORANGE}No cross-release fallback was applied.${NC}" >&2
;;
esac
return 1
}
# Transform one legacy .list file. Only active deb/deb-src lines whose URI
# token is exactly the Amnezia PPA are considered. Exit codes: 0 matched,
# 3 no match, 4 malformed matching entry.
function _transformAmneziaPpaLegacyFile() {
local FILE="$1"
local MODE="$2"
local SUITE="${3:-}"
local ARCHITECTURE="${4:-}"
awk -v mode="${MODE}" -v replacement="${SUITE}" \
-v target="${AMNEZIA_PPA_URI}" -v host_arch="${ARCHITECTURE}" '
function is_target_uri(uri, normalized, http_target) {
normalized=uri
sub(/\/+$/, "", normalized)
http_target=target
sub(/^https:/, "http:", http_target)
return normalized == target || normalized == http_target
}
function contains_target_literal(value, http_target) {
http_target=target
sub(/^https:/, "http:", http_target)
return index(value, target) > 0 || index(value, http_target) > 0
}
function dequote_token(value, first, last) {
first=substr(value, 1, 1)
last=substr(value, length(value), 1)
if (length(value) >= 2 && first == "\"" && last == "\"") {
return substr(value, 2, length(value) - 2)
}
return value
}
function has_unsupported_quote(value, first, last) {
first=substr(value, 1, 1)
last=substr(value, length(value), 1)
return (first == "\"" && last != "\"") ||
first == "\047" || last == "\047"
}
function hex_value(character) {
return index("0123456789abcdef", tolower(character)) - 1
}
function percent_decode(value, result, i, character, high, low) {
result=""
for (i=1; i<=length(value); i++) {
character=substr(value, i, 1)
if (character == "%" && i + 2 <= length(value)) {
high=hex_value(substr(value, i + 1, 1))
low=hex_value(substr(value, i + 2, 1))
if (high >= 0 && low >= 0) {
result=result sprintf("%c", high * 16 + low)
i += 2
continue
}
}
result=result character
}
return result
}
function apt_comment_position(value, i, character, in_options) {
in_options=0
for (i=1; i<=length(value); i++) {
character=substr(value, i, 1)
if (character == "[") {
in_options=1
} else if (character == "]") {
in_options=0
} else if (character == "#" && !in_options) {
return i
}
}
return 0
}
function emit_line(value) {
if (mode != "count") {
print value
}
}
function csv_contains(value, wanted, count, values, i) {
count=split(value, values, ",")
for (i=1; i<=count; i++) {
if (values[i] == wanted) {
for (i=1; i<=count; i++) delete values[i]
return 1
}
}
for (i=1; i<=count; i++) delete values[i]
return 0
}
function options_are_safe(value, count, options, i, option, option_value, arch_value) {
# APT applies a quote-word lexer to option tokens. Reject quoted option
# text instead of attempting a partial reimplementation that could miss
# a quoted signature-bypass key.
if (index(value, "\"") > 0 || index(value, "\047") > 0 ||
index(value, "\\") > 0 || index(value, "%") > 0) {
return 0
}
count=split(value, options, /[[:space:]]+/)
for (i=1; i<=count; i++) {
option=tolower(options[i])
if (option ~ /^(trusted|allow-insecure|allow-weak|allow-downgrade-to-insecure)$/) {
for (i=1; i<=count; i++) delete options[i]
return 0
}
if (option ~ /^(trusted|allow-insecure|allow-weak|allow-downgrade-to-insecure)=/) {
option_value=substr(option, index(option, "=") + 1)
if (option_value !~ /^(0|no|false|off|disable|without)$/) {
for (i=1; i<=count; i++) delete options[i]
return 0
}
}
if (option ~ /^arch=/) {
arch_value=substr(option, 6)
if (host_arch == "" || !csv_contains(arch_value, host_arch)) {
for (i=1; i<=count; i++) delete options[i]
return 0
}
}
if (option ~ /^arch[-+]=/) {
# Avoid guessing how additive/subtractive filters interact with
# the host architecture in an administrator-authored entry.
for (i=1; i<=count; i++) delete options[i]
return 0
}
}
for (i=1; i<=count; i++) delete options[i]
return 1
}
BEGIN {
found=0
binary_found=0
source_found=0
malformed=0
}
{
line=$0
comment_position=apt_comment_position(line)
if (comment_position > 0) {
length_line=comment_position - 1
} else {
length_line=length(line)
}
position=1
while (position <= length_line && substr(line, position, 1) ~ /[[:space:]]/) {
position++
}
type_start=position
while (position <= length_line && substr(line, position, 1) !~ /[[:space:]]/) {
position++
}
entry_type=substr(line, type_start, position - type_start)
if (entry_type != "deb" && entry_type != "deb-src") {
emit_line(line)
next
}
while (position <= length_line && substr(line, position, 1) ~ /[[:space:]]/) {
position++
}
options=""
if (substr(line, position, 1) == "[") {
close_offset=index(substr(line, position), "]")
if (close_offset == 0) {
if (contains_target_literal(substr(line, 1, length_line))) {
malformed=1
}
emit_line(line)
next
}
options=substr(line, position + 1, close_offset - 2)
position += close_offset
while (position <= length_line && substr(line, position, 1) ~ /[[:space:]]/) {
position++
}
}
uri_start=position
while (position <= length_line && substr(line, position, 1) !~ /[[:space:]]/) {
position++
}
raw_uri=substr(line, uri_start, position - uri_start)
decoded_uri_token=percent_decode(raw_uri)
uri=dequote_token(decoded_uri_token)
if (!is_target_uri(uri)) {
if (has_unsupported_quote(raw_uri) && contains_target_literal(decoded_uri_token)) {
malformed=1
}
emit_line(line)
next
}
found++
if (mode == "remove") {
next
}
if (!options_are_safe(options)) {
malformed=1
emit_line(line)
next
}
while (position <= length_line && substr(line, position, 1) ~ /[[:space:]]/) {
position++
}
suite_start=position
while (position <= length_line && substr(line, position, 1) !~ /[[:space:]]/) {
position++
}
if (suite_start > length_line) {
malformed=1
emit_line(line)
next
}
suite_end=position - 1
suite_value=substr(line, suite_start, suite_end - suite_start + 1)
if (suite_value !~ /^[a-z0-9][a-z0-9-]*$/) {
malformed=1
emit_line(line)
next
}
while (position <= length_line && substr(line, position, 1) ~ /[[:space:]]/) {
position++
}
component_start=position
while (position <= length_line && substr(line, position, 1) !~ /[[:space:]]/) {
position++
}
component=substr(line, component_start, position - component_start)
if (component != "main") {
malformed=1
emit_line(line)
next
}
while (position <= length_line && substr(line, position, 1) ~ /[[:space:]]/) {
position++
}
if (position <= length_line && substr(line, position, 1) != "#") {
malformed=1
emit_line(line)
next
}
if (entry_type == "deb") {
binary_found++
} else {
source_found++
}
if (mode == "set" && suite_value != replacement) {
line=substr(line, 1, suite_start - 1) replacement substr(line, suite_end + 1)
}
emit_line(line)
}
END {
if (mode == "count") {
print found, binary_found, source_found
}
if (malformed) {
exit 4
}
if (!found) {
exit 3
}
if (mode != "remove" && !binary_found) {
exit 5
}
}
' "${FILE}"
}
# Transform one DEB822 .sources file stanza-by-stanza. A matching stanza must
# contain the Amnezia PPA as its sole URI; mixed-URI stanzas are rejected so an
# unrelated repository can never inherit the fallback suite.
function _transformAmneziaPpaDeb822File() {
local FILE="$1"
local MODE="$2"
local SUITE="${3:-}"
local ARCHITECTURE="${4:-}"
awk -v mode="${MODE}" -v replacement="${SUITE}" \
-v target="${AMNEZIA_PPA_URI}" -v host_arch="${ARCHITECTURE}" '
function trim(value) {
gsub(/^[[:space:]]+/, "", value)
gsub(/[[:space:]]+$/, "", value)
return value
}
function is_target_uri(uri, normalized, http_target) {
normalized=uri
sub(/\/+$/, "", normalized)
http_target=target
sub(/^https:/, "http:", http_target)
return normalized == target || normalized == http_target
}
function token_list_contains(value, wanted, count, tokens, i, result) {
result=0
count=split(trim(value), tokens, /[[:space:]]+/)
for (i=1; i<=count; i++) {
if (tokens[i] == wanted) {
result=1
}
delete tokens[i]
}
return result
}
function is_explicit_false(value, normalized) {
normalized=tolower(trim(value))
return normalized ~ /^(0|no|false|off|disable|without)$/
}
function is_explicit_true(value, normalized) {
normalized=tolower(trim(value))
return normalized ~ /^(1|yes|true|on|enable|with)$/
}
function clear_stanza( i) {
for (i=1; i<=line_count; i++) {
delete lines[i]
delete suite_continuation_lines[i]
delete skip_lines[i]
}
line_count=0
}
function emit_stanza( i) {
if (mode != "count") {
for (i=1; i<=line_count; i++) {
if (!skip_lines[i]) {
print lines[i]
}
}
}
}
function process_stanza( i, line, colon, field, value, current_field,
uri_value, type_value, suite_value, component_value, enabled_value,
trusted_value, allow_insecure_value, allow_weak_value,
allow_downgrade_value, architecture_value,
uri_fields, type_fields, suite_fields, component_fields,
enabled_fields, trusted_fields, allow_insecure_fields,
allow_weak_fields, allow_downgrade_fields, architecture_fields,
architecture_remove_fields, suite_line, syntax_error,
uri_count, target_count, type_count, type_has_deb,
type_has_deb_src, type_valid,
suite_count, suite_valid, component_count, component_valid,
start, finish) {
if (line_count == 0) {
return
}
current_field=""
uri_value=""
type_value=""
suite_value=""
component_value=""
enabled_value=""
trusted_value=""
allow_insecure_value=""
allow_weak_value=""
allow_downgrade_value=""
architecture_value=""
uri_fields=0
type_fields=0
suite_fields=0
component_fields=0
enabled_fields=0
trusted_fields=0
allow_insecure_fields=0
allow_weak_fields=0
allow_downgrade_fields=0
architecture_fields=0
architecture_remove_fields=0
suite_line=0
syntax_error=0
for (i=1; i<=line_count; i++) {
line=lines[i]
if (line ~ /^#/) {
continue
}
if (line ~ /^[A-Za-z0-9-]+:/) {
colon=index(line, ":")
field=tolower(substr(line, 1, colon - 1))
value=trim(substr(line, colon + 1))
current_field=field
if (field == "uris") {
uri_fields++
uri_value=(uri_value == "" ? value : uri_value " " value)
} else if (field == "types") {
type_fields++
type_value=(type_value == "" ? value : type_value " " value)
} else if (field == "suites") {
suite_fields++
suite_line=i
suite_value=(suite_value == "" ? value : suite_value " " value)
} else if (field == "components") {
component_fields++
component_value=(component_value == "" ? value : component_value " " value)
} else if (field == "enabled") {
enabled_fields++
enabled_value=(enabled_value == "" ? value : enabled_value " " value)
} else if (field == "trusted") {
trusted_fields++
trusted_value=(trusted_value == "" ? value : trusted_value " " value)
} else if (field == "allow-insecure") {
allow_insecure_fields++
allow_insecure_value=(allow_insecure_value == "" ? value : allow_insecure_value " " value)
} else if (field == "allow-weak") {
allow_weak_fields++
allow_weak_value=(allow_weak_value == "" ? value : allow_weak_value " " value)
} else if (field == "allow-downgrade-to-insecure") {
allow_downgrade_fields++
allow_downgrade_value=(allow_downgrade_value == "" ? value : allow_downgrade_value " " value)
} else if (field == "architectures") {
architecture_fields++
architecture_value=(architecture_value == "" ? value : architecture_value " " value)
} else if (field == "architectures-remove") {
architecture_remove_fields++
}
continue
}
if (line ~ /^[[:space:]]+/) {
value=trim(line)
if (current_field == "") {
syntax_error=1
} else if (current_field == "uris") {
uri_value=uri_value " " value
} else if (current_field == "types") {
type_value=type_value " " value
} else if (current_field == "suites") {
suite_value=suite_value " " value
suite_continuation_lines[i]=1
} else if (current_field == "components") {
component_value=component_value " " value
} else if (current_field == "enabled") {
enabled_value=enabled_value " " value
} else if (current_field == "trusted") {
trusted_value=trusted_value " " value
} else if (current_field == "allow-insecure") {
allow_insecure_value=allow_insecure_value " " value
} else if (current_field == "allow-weak") {
allow_weak_value=allow_weak_value " " value
} else if (current_field == "allow-downgrade-to-insecure") {
allow_downgrade_value=allow_downgrade_value " " value
} else if (current_field == "architectures") {
architecture_value=architecture_value " " value
}
} else {
syntax_error=1
current_field=""
}
}
uri_count=split(trim(uri_value), uri_tokens, /[[:space:]]+/)
target_count=0
for (i=1; i<=uri_count; i++) {
if (is_target_uri(uri_tokens[i])) {
target_count++
}
delete uri_tokens[i]
}
if (target_count == 0) {
emit_stanza()
clear_stanza()
return
}
found++
if (uri_fields != 1 || uri_count != 1 || target_count != 1) {
malformed=1
emit_stanza()
clear_stanza()
return
}
if (mode == "remove") {
# Preserve comments even when removing the repository stanza.
if (mode != "count") {
for (i=1; i<=line_count; i++) {
if (lines[i] ~ /^#/) {
print lines[i]
}
}
}
clear_stanza()
return
}
type_count=split(trim(type_value), type_tokens, /[[:space:]]+/)
type_has_deb=0
type_has_deb_src=0
type_valid=(type_count > 0)
for (i=1; i<=type_count; i++) {
if (type_tokens[i] == "deb") {
type_has_deb=1
} else if (type_tokens[i] == "deb-src") {
type_has_deb_src=1
} else {
type_valid=0
}
delete type_tokens[i]
}
suite_count=split(trim(suite_value), suite_tokens, /[[:space:]]+/)
suite_valid=(suite_count > 0)
for (i=1; i<=suite_count; i++) {
if (suite_tokens[i] !~ /^[a-z0-9][a-z0-9-]*$/) {
suite_valid=0
}
delete suite_tokens[i]
}
component_count=split(trim(component_value), component_tokens, /[[:space:]]+/)
component_valid=(component_count == 1 && component_tokens[1] == "main")
for (i=1; i<=component_count; i++) {
delete component_tokens[i]
}
if (syntax_error || type_fields != 1 || !type_valid ||
suite_fields != 1 || !suite_valid || component_fields != 1 ||
!component_valid || enabled_fields > 1 ||
(enabled_fields == 1 && !is_explicit_true(enabled_value)) ||
trusted_fields > 1 ||
(trusted_fields == 1 && !is_explicit_false(trusted_value)) ||
allow_insecure_fields > 1 ||
(allow_insecure_fields == 1 && !is_explicit_false(allow_insecure_value)) ||
allow_weak_fields > 1 ||
(allow_weak_fields == 1 && !is_explicit_false(allow_weak_value)) ||
allow_downgrade_fields > 1 ||
(allow_downgrade_fields == 1 && !is_explicit_false(allow_downgrade_value)) ||
architecture_fields > 1 ||
(architecture_fields == 1 &&
(host_arch == "" || !token_list_contains(architecture_value, host_arch))) ||
architecture_remove_fields > 0) {
malformed=1
emit_stanza()
clear_stanza()
return
}
if (type_has_deb) {
binary_found++
}
if (type_has_deb_src) {
source_found++
}
if (mode == "set" && trim(suite_value) != replacement) {
line=lines[suite_line]
start=index(line, ":") + 1
while (start <= length(line) && substr(line, start, 1) ~ /[[:space:]]/) {
start++
}
finish=length(line) + 1
while (finish > start && substr(line, finish - 1, 1) ~ /[[:space:]]/) {
finish--
}
lines[suite_line]=substr(line, 1, start - 1) replacement substr(line, finish)
for (i=1; i<=line_count; i++) {
if (suite_continuation_lines[i]) {
skip_lines[i]=1
}
}
}
emit_stanza()
clear_stanza()
}
BEGIN {
line_count=0
found=0
binary_found=0
source_found=0
malformed=0
}
{
if ($0 ~ /^[[:space:]]*$/) {
process_stanza()
if (mode != "count") {
print $0
}
} else {
lines[++line_count]=$0
}
}
END {
process_stanza()
if (mode == "count") {
print found, binary_found, source_found
}
if (malformed) {
exit 4
}
if (!found) {
exit 3
}
if (mode != "remove" && !binary_found) {
exit 5
}
}
' "${FILE}"
}
function _transformAmneziaPpaSourceFile() {
local FILE="$1"
local MODE="$2"
local SUITE="${3:-}"
local ARCHITECTURE="${4:-}"
case "${FILE}" in
*.sources) _transformAmneziaPpaDeb822File "${FILE}" "${MODE}" "${SUITE}" "${ARCHITECTURE}" ;;
*.list) _transformAmneziaPpaLegacyFile "${FILE}" "${MODE}" "${SUITE}" "${ARCHITECTURE}" ;;
*) return 3 ;;
esac
}
function isValidAptSourceFilename() {
local BASENAME="${1##*/}"
[[ "${BASENAME}" =~ ^[A-Za-z0-9_.-]+\.(list|sources)$ ]]
}
function _preserveAptSourceFinalNewline() {
local SOURCE_FILE="$1"
local TRANSFORMED_FILE="$2"
local FINAL_BYTE_LINE_COUNT
[[ -s "${SOURCE_FILE}" && -s "${TRANSFORMED_FILE}" ]] || return 0
FINAL_BYTE_LINE_COUNT=$(tail -c 1 -- "${SOURCE_FILE}" | wc -l) || return 1
if [[ "${FINAL_BYTE_LINE_COUNT}" -eq 0 ]]; then
truncate -s -1 -- "${TRANSFORMED_FILE}"
fi
}
# Return 0 when exactly one usable binary entry exists, 1 when absent, and 2
# when target content is duplicated, unusable, malformed, or unsafe to rewrite.
function amneziaPpaSourceEntriesExist() {
local SOURCES_DIR="${1:-${AMNEZIA_PPA_SOURCES_DIR}}"
local ARCHITECTURE="${2:-}"
local FILE
local RC
local ENTRY_COUNTS
local FILE_TARGET_COUNT