forked from ZoeyVid/NPMplus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-npmplus.sh
More file actions
4966 lines (4676 loc) · 204 KB
/
Copy pathsetup-npmplus.sh
File metadata and controls
4966 lines (4676 loc) · 204 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
# Interactive NPMplus deployment and maintenance script (Debian 12/13 and Ubuntu 22.04+)
# Generates a compose.yaml with only the extras you pick (crowdsec, appsec, firewall
# bouncer, anubis, caddy), wires them together, optionally configures UFW, and starts
# everything. Run as root on the Linux docker host.
#
# deliberately only covers the common path; anything fancier -> edit the
# generated compose.yaml yourself afterwards, every option is commented in there.
set -euo pipefail
# bump this on every meaningful change - the script compares it against the
# copy on github at startup and tells the operator when theirs is stale
SCRIPT_VERSION="1.69"
DATA_DIR="/opt/npmplus"
CROWDSEC_DIR="/opt/crowdsec"
COMPOSE_FILE="$DATA_DIR/compose.yaml"
ADMIN_SECRET_FILE="/run/npmplus-initial-admin-password"
SELF_URL="https://raw.githubusercontent.com/mangyan1/NPMplus/develop/setup-npmplus.sh"
NPMPLUS_IMAGE_CHANNEL="ghcr.io/mangyan1/npmplus:develop"
CADDY_IMAGE_CHANNEL="ghcr.io/mangyan1/npmplus:caddy"
CROWDSEC_IMAGE_CHANNEL="ghcr.io/mangyan1/npmplus:crowdsec"
ANUBIS_IMAGE_CHANNEL="ghcr.io/mangyan1/npmplus:anubis"
DOCKER_INSTALL_URL="https://get.docker.com"
DOCKER_INSTALL_SHA256="36bab4d12295a539f7493d52ed8296244895d2febceff5e725dedc0b0708f77b"
PACKAGECLOUD_INSTALL_URL="https://packagecloud.io/install/repositories/crowdsec/crowdsec/script.deb.sh"
PACKAGECLOUD_INSTALL_SHA256="3a098063d364ab1e69516d6835d69945d0e4061c003f86a98e7cf307bb79a91e"
say() { printf '\n\033[1;32m== %s\033[0m\n' "$*"; }
ask() { # ask "question" "default" -> answer on stdout, default on empty enter
local q="$1" def="$2" answer
read -r -p "$(printf '\033[1m%s\033[0m [%s]: ' "$q" "$def")" answer || true
echo "${answer:-$def}"
}
askpw() { # askpw "question" "default" -> answer, no default echoed for passwords
local q="$1" def="$2" answer
read -rs -p "$(printf '\033[1m%s\033[0m%s: ' "$q" "${def:+ [$def]}")" answer || true
echo >&2
echo "${answer:-$def}"
}
confirm() { # confirm "question" "y|n" -> 0 if yes
local answer
answer=$(ask "$1" "$2")
[[ "$answer" == "y" || "$answer" == "Y" || "$answer" == "yes" ]]
}
package_is_installed() { # package_is_installed PACKAGE
# `dpkg -s` also succeeds for packages that were removed but left their
# configuration files behind. Only this exact state means a daemon/package
# is still installed and capable of conflicting with the container stack.
[[ "$(dpkg-query -W -f='${Status}' "$1" 2>/dev/null || true)" == "install ok installed" ]]
}
default_ipv4_interface() {
ip -o -4 route show to default 2>/dev/null |
awk '{ for (i = 1; i <= NF; i++) if ($i == "dev") { print $(i + 1); exit } }'
}
detect_private_lan_ipv4() {
local interface
interface=$(default_ipv4_interface)
[[ -n "$interface" ]] || return 1
ip -o -4 addr show dev "$interface" scope global 2>/dev/null |
awk '{ split($4, address, "/"); ip = address[1]
if (ip ~ /^10\./ || ip ~ /^192\.168\./ || ip ~ /^172\.(1[6-9]|2[0-9]|3[01])\./) { print ip; exit } }'
}
detect_private_lan_cidr() {
local interface
interface=$(default_ipv4_interface)
[[ -n "$interface" ]] || return 1
ip -o -4 route show dev "$interface" scope link 2>/dev/null |
awk '{ network = $1
if (network ~ /^10\./ || network ~ /^192\.168\./ || network ~ /^172\.(1[6-9]|2[0-9]|3[01])\./) { print network; exit } }'
}
valid_ipv4() {
local address="$1" octet
local -a octets
[[ "$address" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
IFS=. read -r -a octets <<<"$address"
for octet in "${octets[@]}"; do
[[ "$octet" =~ ^[0-9]+$ ]] && ((10#$octet <= 255)) || return 1
done
}
private_ipv4() {
local address="$1" first second _rest
valid_ipv4 "$address" || return 1
IFS=. read -r first second _rest <<<"$address"
((10#$first == 10 || (10#$first == 172 && 10#$second >= 16 && 10#$second <= 31) || (10#$first == 192 && 10#$second == 168)))
}
valid_private_ipv4_cidr() {
local value="$1" address prefix
[[ "$value" == */* ]] || return 1
address=${value%/*}
prefix=${value##*/}
private_ipv4 "$address" && [[ "$prefix" =~ ^[0-9]+$ ]] && ((10#$prefix >= 8 && 10#$prefix <= 32))
}
[[ $EUID -eq 0 ]] || { echo "run as root (sudo)" >&2; exit 1; }
# Generated host helpers may be refreshed by an update while an older copy is
# still executing. Replacing the directory entry atomically keeps that running
# process on its original inode instead of truncating its script underneath it.
write_root_file() { # write_root_file target mode < content
local target="$1" mode="$2" tmp
tmp=$(mktemp "${target}.tmp.XXXXXX")
if ! cat >"$tmp"; then
rm -f -- "$tmp"
return 1
fi
chown root:root "$tmp"
chmod "$mode" "$tmp"
mv -f -- "$tmp" "$target"
}
remove_crs_control() {
systemctl disable --now npmplus-crs-control.socket npmplus-crs-control.service >/dev/null 2>&1 || true
rm -f /etc/systemd/system/npmplus-crs-control.socket /etc/systemd/system/npmplus-crs-control.service
rm -f /usr/local/lib/npmplus-crs-control.py /usr/local/lib/npmplus-crs-enable
# state.json, the pre-change snapshot, and the 0700 directory are all ours
rm -rf /var/lib/npmplus/crs-control
rmdir /run/npmplus-crs-control >/dev/null 2>&1 || true
systemctl daemon-reload >/dev/null 2>&1 || true
}
remove_admin_lan_proxy() {
command -v systemctl >/dev/null || return 0
systemctl disable --now npmplus-admin-lan.socket npmplus-admin-lan.service >/dev/null 2>&1 || true
rm -f /etc/systemd/system/npmplus-admin-lan.socket /etc/systemd/system/npmplus-admin-lan.service
systemctl daemon-reload >/dev/null 2>&1 || true
}
configure_admin_lan_proxy() { # configure_admin_lan_proxy PRIVATE_IP
local listen_ip="$1" proxy_binary candidate
proxy_binary=$(command -v systemd-socket-proxyd || true)
if [[ -z "$proxy_binary" ]]; then
for candidate in /usr/lib/systemd/systemd-socket-proxyd /lib/systemd/systemd-socket-proxyd; do
if [[ -x "$candidate" ]]; then
proxy_binary="$candidate"
break
fi
done
fi
[[ -n "$proxy_binary" ]] || {
echo "systemd-socket-proxyd is unavailable; refusing to expose the admin UI" >&2
return 1
}
remove_admin_lan_proxy
write_root_file /etc/systemd/system/npmplus-admin-lan.socket 0644 <<EOF
[Unit]
Description=NPMplus private-LAN admin listener
Wants=network-online.target
After=network-online.target
[Socket]
ListenStream=$listen_ip:81
NoDelay=true
FreeBind=true
[Install]
WantedBy=sockets.target
EOF
write_root_file /etc/systemd/system/npmplus-admin-lan.service 0644 <<EOF
[Unit]
Description=NPMplus private-LAN admin relay
Requires=docker.service npmplus-admin-lan.socket
After=docker.service npmplus-admin-lan.socket
[Service]
Type=notify
ExecStart=$proxy_binary 127.0.0.1:81
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
NoNewPrivileges=true
EOF
systemctl daemon-reload
systemctl enable --now npmplus-admin-lan.socket >/dev/null
}
repair_admin_lan_proxy() {
local socket_file=/etc/systemd/system/npmplus-admin-lan.socket listen_ip
[[ -s "$socket_file" ]] || return 0
listen_ip=$(sed -n 's/^ListenStream=\([0-9][0-9.]*\):81$/\1/p' "$socket_file" | head -1)
if ! private_ipv4 "$listen_ip"; then
echo "existing private-LAN admin listener has an invalid address; leaving it unchanged" >&2
return 1
fi
configure_admin_lan_proxy "$listen_ip"
}
install_firewall_bouncer_boot_gate() {
command -v systemctl >/dev/null || return 0
write_root_file /usr/local/sbin/npmplus-wait-for-crowdsec-lapi 0755 <<'EOF'
#!/bin/sh
# The host firewall bouncer depends on the containerized CrowdSec LAPI. Docker
# being active does not mean that the LAPI is ready yet, so use a bounded gate.
if [ -s /opt/npmplus/compose.yaml ] && \
docker compose -f /opt/npmplus/compose.yaml config --services 2>/dev/null | grep -qx crowdsec; then
docker compose -f /opt/npmplus/compose.yaml up -d crowdsec
fi
for attempt in $(seq 1 180); do
code=$(curl -sS --connect-timeout 1 --max-time 2 -o /dev/null -w '%{http_code}' \
http://127.0.0.1:8080/v1/decisions?limit=1 2>/dev/null || true)
case "$code" in
200|401|403) exit 0 ;;
esac
[ "$attempt" -eq 180 ] || sleep 1
done
echo "npmplus: CrowdSec LAPI did not become ready within 180 seconds" >&2
exit 1
EOF
mkdir -p /etc/systemd/system/crowdsec-firewall-bouncer.service.d
write_root_file /etc/systemd/system/crowdsec-firewall-bouncer.service.d/10-npmplus-container-lapi.conf 0644 <<'EOF'
[Unit]
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target
PartOf=docker.service
Before=npmplus-public.service
[Service]
ExecStartPre=/usr/local/sbin/npmplus-wait-for-crowdsec-lapi
Restart=on-failure
RestartSec=5s
EOF
systemctl daemon-reload
}
firewall_bouncer_covers_public_paths() {
local rules
rules=$(iptables-save 2>/dev/null || true)
grep -Eq '^-A INPUT .*--match-set crowdsec-blacklists src.* -j (DROP|REJECT)$' <<<"$rules" &&
grep -Eq '^-A FORWARD .*--match-set crowdsec-blacklists src.* -j (DROP|REJECT)$' <<<"$rules"
}
normalize_firewall_bouncer_config() {
local config=/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml tmp disable_ipv6=true
[[ -s "$config" ]] || return 1
# Ubuntu's package writes a .yaml.local overlay that forces nftables even
# after the installer replaces the main file. This config is installer-owned
# whenever the marker exists, so remove the stale package overlay explicitly.
rm -f -- "${config}.local"
if command -v ip >/dev/null && ip -6 address show scope global | grep -q 'inet6 '; then
disable_ipv6=false
fi
tmp=$(mktemp "${config}.tmp.XXXXXX")
if ! awk -v disable_ipv6="$disable_ipv6" '
/^mode:/ { print "mode: iptables"; mode=1; next }
/^disable_ipv6:/ { print "disable_ipv6: " disable_ipv6; disable_ipv6_seen=1; next }
/^iptables_chains:/ {
in_chains_seen=1
print "iptables_chains:"
print " - INPUT"
print " - FORWARD"
in_chains=1
next
}
in_chains && /^ - / { next }
in_chains { in_chains=0 }
/^pid_dir:/ { pid_dir=1 }
/^daemonize:/ { daemonize=1 }
/^log_mode:/ { log_mode=1 }
/^log_dir:/ { log_dir=1 }
/^log_level:/ { log_level=1 }
/^log_compression:/ { log_compression=1 }
/^log_max_size:/ { log_max_size=1 }
/^log_max_backups:/ { log_max_backups=1 }
/^log_max_age:/ { log_max_age=1 }
{ print }
END {
if (!mode) print "mode: iptables"
if (!disable_ipv6_seen) print "disable_ipv6: " disable_ipv6
if (!in_chains_seen) {
print "iptables_chains:"
print " - INPUT"
print " - FORWARD"
}
if (!pid_dir) print "pid_dir: /var/run/"
if (!daemonize) print "daemonize: true"
if (!log_mode) print "log_mode: file"
if (!log_dir) print "log_dir: /var/log/"
if (!log_level) print "log_level: info"
if (!log_compression) print "log_compression: true"
if (!log_max_size) print "log_max_size: 100"
if (!log_max_backups) print "log_max_backups: 3"
if (!log_max_age) print "log_max_age: 30"
}
' "$config" >"$tmp"; then
rm -f -- "$tmp"
return 1
fi
chown root:root "$tmp"
chmod 0600 "$tmp"
mv -f -- "$tmp" "$config"
}
repair_installer_firewall_bouncer() {
[[ -f /var/lib/npmplus/installed-firewall-bouncer ]] || return 0
command -v crowdsec-firewall-bouncer >/dev/null || return 0
# the sources entry may point at an unpublished suite (trixie), which
# breaks apt update for every later host operation - repair it first
local suite
suite=$(crowdsec_repo_suite) || true
[[ -z "$suite" ]] || repair_crowdsec_sources_suite "$suite"
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ipset iptables
normalize_firewall_bouncer_config
install_firewall_bouncer_boot_gate
if ! crowdsec-firewall-bouncer -c /etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml -t; then
echo "the installer-managed CrowdSec firewall bouncer config is invalid" >&2
return 1
fi
systemctl enable crowdsec-firewall-bouncer >/dev/null
# Do not spend three minutes waiting during preflight when CrowdSec itself is
# down. The post-deployment call will start the bouncer once its LAPI answers.
if curl -sS --connect-timeout 1 --max-time 2 -o /dev/null \
http://127.0.0.1:8080/v1/decisions?limit=1 2>/dev/null; then
systemctl restart crowdsec-firewall-bouncer
# rule insertion is asynchronous: the bouncer must reach LAPI and
# create its ipset before the iptables rules appear, and systemctl
# returns before any of that. poll briefly instead of judging the
# rule set in the same instant the restart returns.
local waited=0
until firewall_bouncer_covers_public_paths || ((waited >= 10)); do
sleep 1
waited=$((waited + 1))
done
firewall_bouncer_covers_public_paths || {
echo "CrowdSec firewall bouncer is not protecting both INPUT and FORWARD" >&2
return 1
}
fi
}
adopt_legacy_installer_firewall_bouncer() {
local config=/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml
[[ ! -f /var/lib/npmplus/installed-firewall-bouncer ]] || return 0
package_is_installed crowdsec-firewall-bouncer || package_is_installed crowdsec-firewall-bouncer-iptables || return 0
command -v crowdsec-firewall-bouncer >/dev/null || return 0
[[ -s "$COMPOSE_FILE" && -s "$config" ]] || return 0
grep -q 'container_name: crowdsec' "$COMPOSE_FILE" || return 0
grep -Fq '# generated by setup-npmplus.sh' "$config" || return 0
grep -Eq '^api_url:[[:space:]]*http://127\.0\.0\.1:8080/?[[:space:]]*$' "$config" || return 0
say "adopting legacy installer-managed firewall bouncer"
mkdir -p /var/lib/npmplus
touch /var/lib/npmplus/installed-firewall-bouncer
}
activate_installer_firewall_bouncer() {
[[ -f /var/lib/npmplus/installed-firewall-bouncer ]] || return 0
repair_installer_firewall_bouncer
systemctl restart crowdsec-firewall-bouncer
systemctl is-active --quiet crowdsec-firewall-bouncer || {
systemctl status crowdsec-firewall-bouncer --no-pager -l >&2 || true
return 1
}
firewall_bouncer_covers_public_paths || {
echo "CrowdSec firewall bouncer started without INPUT + FORWARD enforcement" >&2
return 1
}
}
set_public_restart_policy() { # set_public_restart_policy POLICY
local policy="$1" tmp
[[ -s "$COMPOSE_FILE" ]] || return 1
tmp=$(mktemp "${COMPOSE_FILE}.tmp.XXXXXX")
awk -v policy="$policy" '
/^ [A-Za-z0-9_-]+:$/ {
service=$1
sub(/:$/, "", service)
managed=(service == "npmplus" || service == "anubis" || service == "npmplus-caddy")
}
managed && /^ restart:/ { print " restart: " policy; next }
{ print }
' "$COMPOSE_FILE" >"$tmp"
chown root:root "$tmp"
chmod 0600 "$tmp"
mv -f -- "$tmp" "$COMPOSE_FILE"
}
remove_strict_boot_protection() {
command -v systemctl >/dev/null || return 0
systemctl disable --now npmplus-public.service >/dev/null 2>&1 || true
systemctl disable --now npmplus-boot-guard.service >/dev/null 2>&1 || true
[[ ! -x /usr/local/sbin/npmplus-boot-guard ]] || \
/usr/local/sbin/npmplus-boot-guard remove >/dev/null 2>&1 || true
rm -f /etc/systemd/system/npmplus-public.service /usr/local/sbin/npmplus-start-protected \
/etc/systemd/system/npmplus-boot-guard.service /usr/local/sbin/npmplus-boot-guard \
/var/lib/npmplus/strict-boot-protection
systemctl daemon-reload >/dev/null 2>&1 || true
}
configure_boot_guard() {
write_root_file /usr/local/sbin/npmplus-boot-guard 0755 <<'EOF'
#!/bin/bash
# A pre-Docker raw-table guard. Local/private maintenance stays reachable, but
# public web traffic cannot reach an early container until protected startup
# verifies CrowdSec and application health, then removes these owned rules.
set -euo pipefail
remove_jump() { # remove_jump BINARY PROTOCOL PORTS
local binary="$1" protocol="$2" ports="$3"
while "$binary" -t raw -C PREROUTING -p "$protocol" -m multiport --dports "$ports" -j NPMPLUS-BOOT >/dev/null 2>&1; do
"$binary" -t raw -D PREROUTING -p "$protocol" -m multiport --dports "$ports" -j NPMPLUS-BOOT
done
}
apply_family() { # apply_family BINARY PRIVATE_CIDRS...
local binary="$1"; shift
local cidr
"$binary" -t raw -N NPMPLUS-BOOT >/dev/null 2>&1 || true
"$binary" -t raw -F NPMPLUS-BOOT
for cidr in "$@"; do
"$binary" -t raw -A NPMPLUS-BOOT -s "$cidr" -j RETURN
done
"$binary" -t raw -A NPMPLUS-BOOT -j DROP
remove_jump "$binary" tcp 80,443
remove_jump "$binary" udp 443
"$binary" -t raw -I PREROUTING 1 -p udp -m multiport --dports 443 -j NPMPLUS-BOOT
"$binary" -t raw -I PREROUTING 1 -p tcp -m multiport --dports 80,443 -j NPMPLUS-BOOT
}
remove_rules() {
local binary
for binary in iptables ip6tables; do
command -v "$binary" >/dev/null || continue
remove_jump "$binary" tcp 80,443
remove_jump "$binary" udp 443
"$binary" -t raw -F NPMPLUS-BOOT >/dev/null 2>&1 || true
"$binary" -t raw -X NPMPLUS-BOOT >/dev/null 2>&1 || true
done
}
ipv6_enabled() {
[[ ! -r /proc/sys/net/ipv6/conf/all/disable_ipv6 ]] ||
[[ "$(< /proc/sys/net/ipv6/conf/all/disable_ipv6)" == 0 ]]
}
case "${1:-apply}" in
apply)
apply_family iptables 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
if ipv6_enabled; then
apply_family ip6tables ::1/128 fc00::/7 fe80::/10
fi
;;
remove) remove_rules ;;
status)
iptables -t raw -C PREROUTING -p tcp -m multiport --dports 80,443 -j NPMPLUS-BOOT
if ipv6_enabled; then
ip6tables -t raw -C PREROUTING -p tcp -m multiport --dports 80,443 -j NPMPLUS-BOOT
fi
;;
*) echo "usage: $0 {apply|remove|status}" >&2; exit 2 ;;
esac
EOF
write_root_file /etc/systemd/system/npmplus-boot-guard.service 0644 <<'EOF'
[Unit]
Description=Keep NPMplus public ports blocked until protected startup succeeds
Before=docker.service
PartOf=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/npmplus-boot-guard apply
ExecStop=/usr/local/sbin/npmplus-boot-guard apply
[Install]
RequiredBy=docker.service
EOF
systemctl daemon-reload
systemctl enable npmplus-boot-guard.service >/dev/null
}
configure_strict_boot_protection() {
[[ -f /var/lib/npmplus/installed-firewall-bouncer ]] || {
echo "strict boot protection requires the installer-managed firewall bouncer" >&2
return 1
}
set_public_restart_policy "on-failure"
mkdir -p /var/lib/npmplus
touch /var/lib/npmplus/strict-boot-protection
configure_boot_guard
write_root_file /usr/local/sbin/npmplus-start-protected 0755 <<'EOF'
#!/bin/bash
# Starts public listeners only after the containerized LAPI and host packet
# bouncer are ready. Public services use on-failure, so Docker cannot race this
# gate when the daemon starts after a reboot.
set -euo pipefail
COMPOSE=/opt/npmplus/compose.yaml
/usr/local/sbin/npmplus-boot-guard apply
docker compose -f "$COMPOSE" up -d crowdsec
/usr/local/sbin/npmplus-wait-for-crowdsec-lapi
systemctl is-active --quiet crowdsec-firewall-bouncer.service
rules=$(iptables-save)
grep -Eq '^-A INPUT .*--match-set crowdsec-blacklists src.* -j (DROP|REJECT)$' <<<"$rules"
grep -Eq '^-A FORWARD .*--match-set crowdsec-blacklists src.* -j (DROP|REJECT)$' <<<"$rules"
# The v0.0.25 bouncer reports READY after starting its decision-stream goroutine.
# Keep listeners closed for a short initial-stream grace period, then prove the
# rules remain installed.
sleep 2
rules=$(iptables-save)
grep -Eq '^-A INPUT .*--match-set crowdsec-blacklists src.* -j (DROP|REJECT)$' <<<"$rules"
grep -Eq '^-A FORWARD .*--match-set crowdsec-blacklists src.* -j (DROP|REJECT)$' <<<"$rules"
if [[ -f /var/lib/npmplus/cloudflare-origin-lock ]]; then
systemctl start npmplus-cloudflare-origin-lock.service
systemctl is-active --quiet npmplus-cloudflare-origin-lock.service
fi
mapfile -t configured_services < <(docker compose -f "$COMPOSE" config --services)
services=()
for service in "${configured_services[@]}"; do
[[ "$service" == crowdsec ]] || services+=("$service")
done
(( ${#services[@]} > 0 )) || { echo "npmplus: Compose has no public services" >&2; exit 1; }
docker compose -f "$COMPOSE" up -d --no-deps "${services[@]}"
for _ in $(seq 1 300); do
ready=true
for service in "${services[@]}"; do
cid=$(docker compose -f "$COMPOSE" ps -a -q "$service" 2>/dev/null || true)
[[ -n "$cid" && "$(docker inspect --format '{{.State.Status}}' "$cid")" == running ]] || { ready=false; break; }
health=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$cid")
[[ "$health" == none || "$health" == healthy ]] || { ready=false; break; }
done
if [[ "$ready" == true ]] && \
timeout 3 bash -c 'exec 3<>/dev/tcp/127.0.0.1/443' && \
curl -fkSs --connect-timeout 2 --max-time 5 https://127.0.0.1:81/api | \
grep -qE '"status"[[:space:]]*:[[:space:]]*"OK"'; then
/usr/local/sbin/npmplus-boot-guard remove
exit 0
fi
sleep 1
done
echo "npmplus: public services did not become healthy; boot guard remains active" >&2
exit 1
EOF
write_root_file /etc/systemd/system/npmplus-public.service 0644 <<'EOF'
[Unit]
Description=Start NPMplus public listeners after CrowdSec enforcement
Requires=docker.service crowdsec-firewall-bouncer.service npmplus-boot-guard.service
After=docker.service crowdsec-firewall-bouncer.service npmplus-boot-guard.service npmplus-cloudflare-origin-lock.service network-online.target
Wants=network-online.target
PartOf=docker.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/npmplus-start-protected
[Install]
WantedBy=docker.service
EOF
systemctl daemon-reload
systemctl enable npmplus-public.service >/dev/null
}
remove_cloudflare_origin_lock() {
command -v systemctl >/dev/null || return 0
systemctl disable --now npmplus-cloudflare-origin-lock.service >/dev/null 2>&1 || true
[[ ! -x /usr/local/sbin/npmplus-cloudflare-origin-lock ]] || \
/usr/local/sbin/npmplus-cloudflare-origin-lock stop >/dev/null 2>&1 || true
rm -f /etc/systemd/system/npmplus-cloudflare-origin-lock.service \
/etc/cron.d/npmplus-cloudflare-origin-lock \
/usr/local/sbin/npmplus-cloudflare-origin-lock \
/var/lib/npmplus/cloudflare-origin-lock
rm -f /var/lib/npmplus/cloudflare-ips-v4 /var/lib/npmplus/cloudflare-ips-v6
systemctl daemon-reload >/dev/null 2>&1 || true
}
configure_cloudflare_origin_lock() {
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ipset iptables
mkdir -p /var/lib/npmplus
touch /var/lib/npmplus/cloudflare-origin-lock
write_root_file /usr/local/sbin/npmplus-cloudflare-origin-lock 0755 <<'EOF'
#!/bin/bash
# Allows public web traffic from Cloudflare and private/local networks only.
# The owned raw-table pre-routing chain runs before host INPUT, Docker FORWARD,
# UFW, and destination NAT. CrowdSec rules still run after an allowed source.
set -euo pipefail
STATE=/var/lib/npmplus
exec 9>/run/lock/npmplus-cloudflare-origin-lock.lock
flock 9
valid_list() { # valid_list 4|6 FILE
local family="$1" file="$2" validation="npcf-check-${1}-$$" network rc=0
[[ -s "$file" ]] || return 1
if [[ "$family" == 4 ]]; then
awk -F'[./]' '
NF != 5 { bad=1 }
$1 > 255 || $2 > 255 || $3 > 255 || $4 > 255 || $5 > 32 { bad=1 }
END { exit bad || NR < 10 || NR > 100 }
' "$file" || return 1
grep -qx '0.0.0.0/0' "$file" && return 1
else
awk -F/ '
NF != 2 || $1 !~ /^[0-9A-Fa-f:]+$/ || $2 !~ /^[0-9]+$/ || $2 > 128 { bad=1 }
END { exit bad || NR < 5 || NR > 100 }
' "$file" || return 1
grep -qx '::/0' "$file" && return 1
fi
ipset destroy "$validation" >/dev/null 2>&1 || true
ipset create "$validation" hash:net family "$([[ "$family" == 4 ]] && echo inet || echo inet6)" maxelem 100
while IFS= read -r network; do
ipset add "$validation" "$network" || { rc=1; break; }
done <"$file"
ipset destroy "$validation" >/dev/null 2>&1 || true
return "$rc"
}
refresh() {
local v4tmp v6tmp
v4tmp=$(mktemp "$STATE/cloudflare-ips-v4.tmp.XXXXXX")
v6tmp=$(mktemp "$STATE/cloudflare-ips-v6.tmp.XXXXXX")
trap 'rm -f -- "$v4tmp" "$v6tmp"' RETURN
curl -fsSL --retry 4 --connect-timeout 10 --max-time 60 https://www.cloudflare.com/ips-v4 -o "$v4tmp"
curl -fsSL --retry 4 --connect-timeout 10 --max-time 60 https://www.cloudflare.com/ips-v6 -o "$v6tmp"
valid_list 4 "$v4tmp"
valid_list 6 "$v6tmp"
chmod 0644 "$v4tmp" "$v6tmp"
mv -f -- "$v4tmp" "$STATE/cloudflare-ips-v4"
mv -f -- "$v6tmp" "$STATE/cloudflare-ips-v6"
trap - RETURN
}
load_set() { # load_set NAME FAMILY FILE
local name="$1" family="$2" file="$3" tmp
tmp="${name}-new"
ipset destroy "$tmp" >/dev/null 2>&1 || true
ipset create "$tmp" hash:net family "$family" maxelem 100000
while IFS= read -r network; do
[[ -n "$network" ]] && ipset add "$tmp" "$network"
done <"$file"
if ipset list "$name" >/dev/null 2>&1; then
ipset swap "$tmp" "$name"
ipset destroy "$tmp"
else
ipset rename "$tmp" "$name"
fi
}
remove_jump() { # remove_jump BINARY PROTOCOL PORTS
local binary="$1" protocol="$2" ports="$3"
while "$binary" -t raw -C PREROUTING -p "$protocol" -m multiport --dports "$ports" -j NPMPLUS-CF >/dev/null 2>&1; do
"$binary" -t raw -D PREROUTING -p "$protocol" -m multiport --dports "$ports" -j NPMPLUS-CF
done
}
apply_family() { # apply_family BINARY SET PRIVATE_CIDRS...
local binary="$1" set_name="$2"; shift 2
local cidr
"$binary" -t raw -N NPMPLUS-CF >/dev/null 2>&1 || true
"$binary" -t raw -F NPMPLUS-CF
"$binary" -t raw -A NPMPLUS-CF -m set --match-set "$set_name" src -j RETURN
for cidr in "$@"; do
"$binary" -t raw -A NPMPLUS-CF -s "$cidr" -j RETURN
done
"$binary" -t raw -A NPMPLUS-CF -j DROP
remove_jump "$binary" tcp 80,443
remove_jump "$binary" udp 443
"$binary" -t raw -I PREROUTING 1 -p udp -m multiport --dports 443 -j NPMPLUS-CF
"$binary" -t raw -I PREROUTING 1 -p tcp -m multiport --dports 80,443 -j NPMPLUS-CF
}
stop_rules() {
local binary
for binary in iptables ip6tables; do
command -v "$binary" >/dev/null || continue
remove_jump "$binary" tcp 80,443
remove_jump "$binary" udp 443
"$binary" -t raw -F NPMPLUS-CF >/dev/null 2>&1 || true
"$binary" -t raw -X NPMPLUS-CF >/dev/null 2>&1 || true
done
ipset destroy npcf4 >/dev/null 2>&1 || true
ipset destroy npcf6 >/dev/null 2>&1 || true
}
start_rules() {
if ! refresh; then
echo "Cloudflare list refresh failed; using the last validated copy" >&2
fi
valid_list 4 "$STATE/cloudflare-ips-v4"
valid_list 6 "$STATE/cloudflare-ips-v6"
load_set npcf4 inet "$STATE/cloudflare-ips-v4"
load_set npcf6 inet6 "$STATE/cloudflare-ips-v6"
apply_family iptables npcf4 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
apply_family ip6tables npcf6 ::1/128 fc00::/7 fe80::/10
}
case "${1:-start}" in
start) start_rules ;;
refresh) start_rules ;;
stop) stop_rules ;;
status)
iptables -t raw -C PREROUTING -p tcp -m multiport --dports 80,443 -j NPMPLUS-CF
ip6tables -t raw -C PREROUTING -p tcp -m multiport --dports 80,443 -j NPMPLUS-CF
;;
*) echo "usage: $0 {start|refresh|stop|status}" >&2; exit 2 ;;
esac
EOF
write_root_file /etc/systemd/system/npmplus-cloudflare-origin-lock.service 0644 <<'EOF'
[Unit]
Description=Restrict NPMplus public web ports to Cloudflare and private LANs
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target
PartOf=docker.service
Before=npmplus-public.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/local/sbin/npmplus-cloudflare-origin-lock start
ExecStop=/usr/local/sbin/npmplus-cloudflare-origin-lock stop
[Install]
WantedBy=docker.service
EOF
printf '19 3 * * * root /usr/local/sbin/npmplus-cloudflare-origin-lock refresh >>/var/log/npmplus-cloudflare-origin-lock.log 2>&1\n' \
>/etc/cron.d/npmplus-cloudflare-origin-lock
chmod 0644 /etc/cron.d/npmplus-cloudflare-origin-lock
systemctl daemon-reload
systemctl enable npmplus-cloudflare-origin-lock.service >/dev/null
}
run_crowdsec_doctor() (
# Keep diagnostics best-effort. A failed individual probe should be reported,
# not terminate the entire doctor before the remaining checks have run.
set +e
set -uo pipefail
local key="$DATA_DIR/crowdsec/lapi-ui.key"
local machine_key="$DATA_DIR/crowdsec/lapi-ui-machine.key"
local lapi="http://127.0.0.1:8080"
local fail=0 code kcode mcode auth_errors db_files answer container state state_error state_exit npmplus_state="missing"
doctor_header() { printf '\n\033[1m== %s\033[0m\n' "$*"; }
doctor_ok() { printf ' \033[32m[ok]\033[0m %s\n' "$*"; }
doctor_bad() { printf ' \033[31m[FAIL]\033[0m %s\n' "$*"; }
doctor_note() { printf ' %s\n' "$*"; }
doctor_bouncer_http_code() {
local value
value=$(cat "$1" 2>/dev/null || true)
[[ -n $value ]] || { echo 000; return; }
local code
code=$(printf 'header = "X-Api-Key: %s"\n' "$value" | \
curl -sS -m 5 -o /dev/null -w '%{http_code}' --config - \
"$lapi/v1/decisions?limit=1" 2>/dev/null || true)
[[ -n $code ]] || code=000
echo "$code"
}
doctor_machine_http_code() {
[[ -n $1 ]] || { echo 000; return; }
local code
code=$(printf '{"machine_id":"npmplus-ui","password":"%s"}' "$1" | \
curl -sS -m 5 -o /dev/null -w '%{http_code}' -H "Content-Type: application/json" \
--data-binary @- "$lapi/v1/watchers/login" 2>/dev/null || true)
[[ -n $code ]] || code=000
echo "$code"
}
doctor_header "1. containers"
for container in crowdsec npmplus; do
if docker inspect "$container" >/dev/null 2>&1; then
state=$(docker inspect --format '{{.State.Status}}' "$container" 2>/dev/null || echo unknown)
state_exit=$(docker inspect --format '{{.State.ExitCode}}' "$container" 2>/dev/null || echo unknown)
[[ "$container" != "npmplus" ]] || npmplus_state="$state"
if [[ "$state" == "running" ]]; then
doctor_ok "$container running"
else
doctor_bad "$container state is $state (exit $state_exit)"
state_error=$(docker inspect --format '{{.State.Error}}' "$container" 2>/dev/null || true)
[[ -z "$state_error" ]] || doctor_note "Docker error: $state_error"
if [[ "$container" == "npmplus" ]] && npmplus_uses_bootstrap_secret_mount && [[ ! -e "$ADMIN_SECRET_FILE" ]]; then
doctor_note "cause: the container retains a deleted one-time administrator secret mount"
doctor_note "repair: rerun this current setup script with --update"
fi
fail=1
fi
else
doctor_bad "$container does not exist"
fail=1
fi
done
doctor_header "2. LAPI answers on $lapi (no key - 401/403 expected)"
code=$(curl -sS -m 5 -o /dev/null -w '%{http_code}' "$lapi/v1/decisions?limit=1" 2>/dev/null || true)
[[ -n $code ]] || code=000
case $code in
401 | 403) doctor_ok "LAPI up (no-key answer: $code)" ;;
000) doctor_bad "LAPI unreachable - is the 127.0.0.1:8080 port publish up?"; fail=1 ;;
*) doctor_bad "unexpected no-key answer: $code"; fail=1 ;;
esac
doctor_header "2b. is the port the container's? (native crowdsec steals it)"
if package_is_installed crowdsec; then
doctor_bad "native crowdsec package is installed on the host"
doctor_note "its daemon binds 127.0.0.1:8080 before the container can, and"
doctor_note "then rejects every key the container's cscli ever registered"
doctor_note "fix: sudo apt remove crowdsec; docker compose -f $COMPOSE_FILE up -d crowdsec"
fail=1
elif command -v ss >/dev/null && ss -ltnp 2>/dev/null | grep ':8080' | grep -qv docker-proxy; then
doctor_bad "port 8080 is owned by something other than docker:"
ss -ltnp 2>/dev/null | grep ':8080' | sed 's/^/ /'
fail=1
else
doctor_ok "no native crowdsec, docker owns the port"
fi
doctor_header "3. bouncer key file ($key)"
if [[ ! -s "$key" ]]; then
doctor_bad "missing or empty"
fail=1
else
doctor_ok "present ($(wc -c <"$key") bytes, mode $(stat -c %a "$key"))"
if grep -q $'\r' "$key"; then
doctor_bad "contains CR (crlf) - the LAPI will never accept it"
fail=1
else
doctor_ok "no line-ending junk"
fi
fi
doctor_header "4. the key the UI backend uses"
kcode=$(doctor_bouncer_http_code "$key")
if [[ $kcode == 200 ]]; then
doctor_ok "LAPI accepts the key (200)"
else
doctor_bad "LAPI rejects the key: HTTP $kcode"
fail=1
fi
doctor_header "5. registration known to crowdsec"
if docker exec crowdsec cscli bouncers list 2>/dev/null | grep -qi "npmplus-ui"; then
doctor_ok "npmplus-ui bouncer exists"
docker exec crowdsec cscli bouncers list 2>/dev/null | grep -iE "name|npmplus" | head -3 | sed 's/^/ /'
else
doctor_bad "npmplus-ui is NOT in the bouncer list"
doctor_note "the registration was lost - classic cause: crowdsec's sqlite rolled"
doctor_note "back on an unclean shutdown"
fail=1
fi
doctor_header "6. what the npmplus container sees (/data/crowdsec/lapi-ui.key)"
if [[ "$npmplus_state" != "running" ]]; then
doctor_bad "cannot inspect the key because npmplus is $npmplus_state"
doctor_note "fix the container startup failure reported in step 1 first"
elif docker exec npmplus sh -c '[ -s /data/crowdsec/lapi-ui.key ]' 2>/dev/null; then
local host_hash container_hash
host_hash=$(sha256sum "$key" | cut -d' ' -f1)
container_hash=$(docker exec npmplus sha256sum /data/crowdsec/lapi-ui.key 2>/dev/null | cut -d' ' -f1)
if [[ $host_hash == "$container_hash" ]]; then
doctor_ok "container sees the same key"
else
doctor_bad "container sees a DIFFERENT key"
fail=1
fi
else
doctor_bad "missing inside the npmplus container - check the $DATA_DIR:/data mount"
fail=1
fi
doctor_header "7. machine key (unban + alert context only)"
mcode=$(doctor_machine_http_code "$(cat "$machine_key" 2>/dev/null || true)")
if [[ $mcode == 200 ]]; then
doctor_ok "machine login works"
else
doctor_bad "machine login: HTTP $mcode (unban/alerts will fail; the ban list itself still works)"
fail=1
fi
doctor_header "8. self-heal"
if [[ -f /etc/cron.d/npmplus-crowdsec-heal ]]; then
doctor_ok "heal cron installed"
else
doctor_bad "heal cron NOT installed - choose Safe update from the main menu"
doctor_note "it installs /usr/local/bin/npmplus-crowdsec-heal and the daily cron"
fi
if [[ -s /var/log/npmplus-crowdsec-heal.log ]]; then
doctor_note "last heal log lines:"
tail -5 /var/log/npmplus-crowdsec-heal.log | sed 's/^/ /'
fi
doctor_header "8b. host firewall bouncer"
if [[ -f /var/lib/npmplus/installed-firewall-bouncer ]]; then
if ! command -v crowdsec-firewall-bouncer >/dev/null; then
doctor_bad "installer marker exists, but the firewall bouncer binary is missing"
fail=1
elif ! crowdsec-firewall-bouncer -c /etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml -t >/dev/null 2>&1; then
doctor_bad "configuration is invalid - run Safe update to repair it"
fail=1
elif systemctl is-active --quiet crowdsec-firewall-bouncer; then
if firewall_bouncer_covers_public_paths; then
doctor_ok "firewall bouncer protects host INPUT and Docker FORWARD traffic"
else
doctor_bad "firewall bouncer is active but Docker FORWARD protection is missing"
doctor_note "run Safe update to migrate the installer-managed rules"
fail=1
fi
else
doctor_bad "firewall bouncer service is not active"
doctor_note "run Safe update to repair its boot ordering and restart it"
fail=1
fi
else
doctor_note "not installed by setup-npmplus.sh"
fi
doctor_header "8c. protected startup"
if [[ -f /var/lib/npmplus/strict-boot-protection ]]; then
if systemctl is-enabled --quiet npmplus-public.service && systemctl is-active --quiet npmplus-public.service && \
systemctl is-enabled --quiet npmplus-boot-guard.service && \
systemctl is-active --quiet npmplus-boot-guard.service && \
[[ -x /usr/local/sbin/npmplus-boot-guard ]]; then
doctor_ok "public listeners are gated behind CrowdSec at boot"
else
doctor_bad "strict boot marker exists but its public/guard services are incomplete"
if /usr/local/sbin/npmplus-boot-guard status >/dev/null 2>&1; then
doctor_note "the boot guard is active, so external ports 80/443 remain blocked"
fi
fail=1
fi
for container in npmplus npmplus-anubis npmplus-caddy; do
docker inspect "$container" >/dev/null 2>&1 || continue
if [[ "$(docker inspect --format '{{.HostConfig.RestartPolicy.Name}}' "$container")" == "on-failure" ]]; then
doctor_ok "$container cannot bypass the boot gate after Docker restarts"
else
doctor_bad "$container has a restart policy that can bypass the boot gate"
fail=1
fi
done
else
doctor_note "not enabled; public containers may start before the host bouncer after reboot"
fi
if [[ -f /var/lib/npmplus/cloudflare-origin-lock ]]; then
if systemctl is-active --quiet npmplus-cloudflare-origin-lock.service && \
/usr/local/sbin/npmplus-cloudflare-origin-lock status >/dev/null 2>&1; then
doctor_ok "Cloudflare origin lock filters host and Docker traffic before routing"
else
doctor_bad "Cloudflare origin lock is configured but its packet rules are missing"
fail=1
fi
else
doctor_note "Cloudflare origin lock is not enabled"
fi
doctor_header "9. recent crowdsec auth errors (2h)"
auth_errors=$(docker logs crowdsec --since 2h 2>&1 | grep -iE "api key|bouncer|403" | tail -8)
if [[ -n $auth_errors ]]; then
printf ' %s\n' "${auth_errors//$'\n'/$'\n '}"
else
doctor_note "none found"
fi
doctor_header "10. CrowdSec SQLite files (WAL/SHM are normal while running)"
db_files=$(find "$CROWDSEC_DIR/data" -maxdepth 1 -type f -name '*.db*' -print 2>/dev/null)
if [[ -n $db_files ]]; then
printf ' %s\n' "${db_files//$'\n'/$'\n '}"
else
doctor_note "no db files found at $CROWDSEC_DIR/data"
fi
doctor_header "11. prometheus metrics (the community blocklist count source)"
# the backend fetches these from inside the npmplus container (the compose
# service hostname is only resolvable there), so probe the same way
metrics_env=$(docker exec npmplus printenv CROWDSEC_METRICS_URL 2>/dev/null || true)
metrics_body=$(docker exec npmplus sh -c 'curl -sS -m 5 "$CROWDSEC_METRICS_URL"' 2>/dev/null || true)
if [[ -n $metrics_env ]]; then
doctor_ok "CROWDSEC_METRICS_URL is set: $metrics_env"
else
doctor_note "CROWDSEC_METRICS_URL is not set in the npmplus container;"
doctor_note "the backend falls back to the LAPI host with port 6060"
fi
if [[ -z $metrics_body ]]; then
doctor_bad "metrics fetch failed from inside the npmplus container"
doctor_note "if crowdsec was just restarted, its metrics listener may still be starting"
doctor_note "is the 127.0.0.1:6060:6060 port publish up on the crowdsec service?"
doctor_note "updates from setup v1.18 add it automatically via --update"
fail=1
elif grep -q '^cs_active_decisions{.*origin=' <<<"$metrics_body"; then
doctor_ok "cs_active_decisions carries origin labels (community count works)"
elif grep -q '^cs_active_decisions' <<<"$metrics_body"; then
doctor_bad "cs_active_decisions has no origin labels: set prometheus level to full"
doctor_note "edit $CROWDSEC_DIR/conf/config.yaml -> prometheus: { enabled: true, level: full }"
doctor_note "then restart: docker restart crowdsec"
fail=1
else
doctor_bad "cs_active_decisions is missing from the metrics output"
doctor_note "current prometheus settings:"
if [[ -f "$CROWDSEC_DIR/conf/config.yaml.local" ]]; then
doctor_note "WARNING: $CROWDSEC_DIR/conf/config.yaml.local overrides the main config"
grep -A4 '^prometheus' "$CROWDSEC_DIR/conf/config.yaml.local" 2>/dev/null | sed 's/^/ /'
fi