-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurebsd.sh
More file actions
executable file
·3633 lines (3141 loc) · 117 KB
/
securebsd.sh
File metadata and controls
executable file
·3633 lines (3141 loc) · 117 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/sh
# Exit on errors and undefined variables
set -eu
###############################################################################
# Global Constants And State
###############################################################################
# Repository and managed-state paths
script_dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd)
template_root="$script_dir/templates"
cutover_state_dir="/var/db/securebsd"
cutover_state_file="$cutover_state_dir/admin_cutover.state"
# Managed system config paths
sshd_config_file="/etc/ssh/sshd_config"
pam_sshd_config_file="/etc/pam.d/sshd"
loader_conf_file="/boot/loader.conf"
rc_conf_file="/etc/rc.conf"
managed_ipfw_rules_file="/etc/ipfw.rules"
source_ipfw_rules_file="$script_dir/ipfw.rules"
suricata_conf_file="/usr/local/etc/suricata/suricata.yaml"
suricata_custom_conf_file="/usr/local/etc/suricata/suricata-custom.yaml"
suricata_rules_file="/var/lib/suricata/rules/custom.rules"
# Immutable file sets
service_scheduler_files="/var/cron/allow /var/at/at.allow"
full_lockdown_files="$service_scheduler_files /etc/rc.firewall /etc/ipfw.rules /etc/crontab \
/usr/local/etc/sudoers /usr/local/etc/sudoers.d/sudo /etc/sysctl.conf /boot/loader.conf \
/boot/loader.rc /etc/fstab /etc/login.conf /etc/login.access /etc/newsyslog.conf \
/etc/ssh/sshd_config /etc/pam.d/sshd /etc/hosts /etc/hosts.allow /etc/ttys"
password_related_files="/etc/master.passwd"
service_related_files="/etc/rc.conf /usr/local/etc/anacrontab"
audit_log_files="/var/audit"
sensitive_files="$service_scheduler_files $password_related_files $service_related_files $audit_log_files"
# FreeBSD config literals
freebsd_true="YES"
freebsd_false="NO"
# Default input values
default_ssh_port="2222"
default_suricata_port="8000"
default_password_expiration_days="120"
# Shared policy strings and regex
sudo_policy_line='%sudo ALL=(ALL:ALL) ALL'
ssh_pam_ga_line='auth requisite pam_google_authenticator.so'
strict_ssh_effective_policy_lines='
passwordauthentication no
kbdinteractiveauthentication yes
pubkeyauthentication yes
usepam yes
authenticationmethods publickey,keyboard-interactive
'
# Firewall policy surfaces
firewall_full_scope_set="load,reapply,validate,render"
firewall_transition_scope_set="validate,render"
firewall_policy_var_defs="
internal_if=$firewall_full_scope_set
nat_if=$firewall_full_scope_set
tun_if=$firewall_full_scope_set
ssh_ipv4=$firewall_full_scope_set
ssh_ipv6=$firewall_full_scope_set
log_ssh_hits=$firewall_full_scope_set
log_wan_tcp_hits=$firewall_full_scope_set
allow_multicast=$firewall_full_scope_set
allow_multicast_legacy=$firewall_full_scope_set
suricata_port=$firewall_full_scope_set
install_suricata=reapply
ssh_port=render
port_transition_old_port=$firewall_transition_scope_set
"
# Managed FreeBSD config blocks
managed_firewall_rc_conf_settings='
firewall_enable=YES
firewall_script=/etc/ipfw.rules
firewall_logging=YES
'
suricata_rc_conf_settings='
suricata_enable=YES
'
fail2ban_rc_conf_settings='
fail2ban_enable=YES
'
securelevel_rc_conf_settings='
kern_securelevel_enable=YES
kern_securelevel=1
'
syslog_tmp_rc_conf_settings='
syslogd_flags=-ss
clear_tmp_enable=YES
'
# Operator-facing status and guidance messages
managed_cutover_cli_omit_message="Rerun without --user, --ssh-port, --disable-wheel, or --remove-wheel-members for a normal managed baseline reapply."
managed_cutover_cli_preserve_state_message="Do not clear the managed cutover state just to continue an existing managed cutover, especially during SSH port migration."
managed_cutover_cli_restart_message="Only clear the managed cutover state if you are intentionally abandoning the current managed cutover context and starting a brand-new staged cutover from scratch."
managed_ssh_port_transition_resolution_message="A new --ssh-port on a committed managed host uses the staged SSH port migration flow. Keep the managed cutover state in place and let the script perform the staged port transition; do not clear the managed cutover state just to change the SSH port."
committed_ssh_port_transition_mode_message="Committed managed state detected. This run is switching from fast-path baseline reapply to staged SSH port migration because --ssh-port changed."
pending_cutover_cli_resolution_message="An in-progress managed cutover already owns --user, --ssh-port, --disable-wheel, and --remove-wheel-members. Rerun without cutover-defining flags and use only --confirm-stage-advance yes to continue the current cutover."
stale_cutover_cli_resolution_message="The saved managed cutover state is stale or incomplete. Rerun without cutover-defining flags for ordinary managed maintenance. Only clear the managed cutover state if you are intentionally abandoning the current cutover context and starting a brand-new staged cutover from scratch; do not clear it to continue an SSH port migration."
pending_port_reboot_next_step="Reboot the host, verify a fresh login on the new SSH port, then rerun this script with --confirm-stage-advance yes to remove the old SSH port from the managed boot policy."
pending_port_commit_reboot_next_step="Reboot the host, verify a fresh login on the new SSH port again, then rerun this script with --confirm-stage-advance yes to finalize the port migration."
# Public operator inputs
public_cli_config_defaults="
user=
ssh_port=
ssh_ipv4=
ssh_ipv6=
log_ssh_hits=
log_wan_tcp_hits=
allow_multicast=
allow_multicast_legacy=
internal_if=
nat_if=
tun_if=
install_auditing=
install_microcode=
install_suricata=
suricata_port=
password_exp=
disable_wheel=
remove_wheel_members=
confirm_stage_advance=
cpu_type=unknown
"
runtime_default_values="
allow_multicast=no
allow_multicast_legacy=no
confirm_stage_advance=no
"
package_option_default_values="
install_auditing=yes
install_microcode=yes
"
# Persisted cutover schema
cutover_state_var_defs='
cutover_stage=stage
cutover_boot_marker=direct
user=direct
cutover_user_uid=direct
ssh_port=direct
transitional_ssh_port=stage
disable_wheel=direct
remove_wheel_members=direct
wheel_sudo_finalized=direct
wheel_membership_finalized=direct
port_transition_old_port=stage
'
# Persisted internal cutover defaults
internal_cutover_state_defaults="
transitional_ssh_port=
wheel_sudo_finalized=
wheel_membership_finalized=
cutover_boot_marker=
port_transition_old_port=
"
# Derived mutable runtime state
public_cutover_fields="user ssh_port disable_wheel remove_wheel_members"
desired_mutable_baseline_settings=""
saved_public_cutover_settings=""
###############################################################################
# Generic Utility Helpers
###############################################################################
set_kv_defaults() {
kv_list=$1
old_ifs=$IFS
IFS='
'
for entry in $kv_list; do
[ -n "$entry" ] || continue
var=${entry%%=*}
value=${entry#*=}
eval "$var=\${$var-$value}"
done
IFS=$old_ifs
}
set_kv_defaults_if_empty() {
kv_list=$1
old_ifs=$IFS
IFS='
'
for entry in $kv_list; do
[ -n "$entry" ] || continue
set_var_if_empty "${entry%%=*}" "${entry#*=}"
done
IFS=$old_ifs
}
get_var_value() {
target_var="$1"
eval "printf '%s\n' \"\${$target_var-}\""
}
set_var_value() {
target_var="$1"
target_value="${2-}"
eval "$target_var=\$target_value"
}
clear_vars() {
var_list="$1"
old_ifs=$IFS
IFS=' '
for target_var in $var_list; do
[ -n "$target_var" ] || continue
set_var_value "$target_var" ""
done
IFS=$old_ifs
}
set_var_if_empty() {
target_var="$1"
default_value="$2"
current_value=$(get_var_value "$target_var")
[ -n "$current_value" ] || set_var_value "$target_var" "$default_value"
}
set_default_if_empty() {
var_name=$1
default_value=$2
set_var_if_empty "$var_name" "$default_value"
}
say() {
printf '%s\n' "$*"
}
say_err() {
printf '%s\n' "$*" >&2
}
warn_msg() {
say "Warning: $*"
}
error_msg() {
say_err "Error: $*"
}
defined_kv_vars() {
kv_list="$1"
old_ifs=$IFS
IFS='
'
for entry in $kv_list; do
[ -n "$entry" ] || continue
printf '%s ' "${entry%%=*}"
done
IFS=$old_ifs
}
policy_vars_for_scope() {
target_scope="$1"
old_ifs=$IFS
IFS='
'
for policy_entry in $firewall_policy_var_defs; do
[ -n "$policy_entry" ] || continue
policy_var=${policy_entry%%=*}
policy_scopes=${policy_entry#*=}
case ",$policy_scopes," in
*",$target_scope,"*)
printf '%s ' "$policy_var"
;;
esac
done
IFS=$old_ifs
}
cutover_state_value() {
state_field="$1"
case "$(settings_block_value "$cutover_state_var_defs" "$state_field" 2>/dev/null || printf 'direct')" in
stage)
stage_owned_cutover_state_value "$state_field"
;;
*)
get_var_value "$state_field"
;;
esac
}
resolved_wheel_policy_finalized_state() {
requested_value="$1"
finalized_value="$2"
if ! value_is_yes "$requested_value" || value_is_yes "$finalized_value"; then
printf '%s\n' "yes"
else
printf '%s\n' "no"
fi
}
value_is_yes() {
[ "${1:-no}" = "yes" ]
}
value_is_none() {
[ "${1:-}" = "none" ]
}
value_is_configured() {
[ -n "${1:-}" ] && ! value_is_none "$1"
}
resolve_install_suricata_default() {
if [ -z "${install_suricata-}" ]; then
if value_is_configured "${suricata_port-}"; then
install_suricata="yes"
else
install_suricata="no"
fi
fi
}
resolve_suricata_port_default() {
if suricata_requested; then
set_var_if_empty "suricata_port" "$default_suricata_port"
fi
}
resolve_runtime_defaults() {
set_kv_defaults_if_empty "$runtime_default_values"
resolve_install_suricata_default
resolve_suricata_port_default
}
resolve_package_option_defaults() {
set_kv_defaults_if_empty "$package_option_default_values"
resolve_install_suricata_default
}
detect_cpu_type() {
cpu_info=$(sysctl -n hw.model | tr '[:upper:]' '[:lower:]')
if printf '%s\n' "$cpu_info" | grep -qF "intel"; then
printf '%s\n' "intel"
elif printf '%s\n' "$cpu_info" | grep -qF "amd"; then
printf '%s\n' "amd"
else
printf '%s\n' "unknown"
fi
}
validate_cpu_type() {
case "$1" in
intel | amd | unknown)
;;
*)
error_msg "Invalid cpu_type '$1'. Use intel, amd, or unknown."
return 1
;;
esac
}
resolve_password_expiration_value() {
set_var_if_empty "password_exp" "$default_password_expiration_days"
case "$password_exp" in
none)
printf '%s\n' "none"
;;
*d)
printf '%s\n' "$password_exp"
;;
*)
printf '%sd\n' "$password_exp"
;;
esac
}
validate_password_expiration_value() {
value="$1"
case "$value" in
none)
return 0
;;
*d)
validate_password_expiration "${value%d}"
;;
*)
validate_password_expiration "$value"
;;
esac
}
validate_suricata_cli_consistency() {
if value_is_configured "${suricata_port-}" && ! suricata_requested; then
error_msg "--suricata-port requires --install-suricata yes."
return 1
fi
if suricata_requested && value_is_none "${suricata_port:-}"; then
error_msg "--install-suricata yes requires a real --suricata-port, not 'none'."
return 1
fi
if suricata_requested && suricata_ports_defined && ! value_is_configured "${nat_if:-none}"; then
error_msg "Suricata firewall integration requires --nat-if to be set to a real interface."
return 1
fi
}
set_kv_defaults "$public_cli_config_defaults"
set_kv_defaults "$internal_cutover_state_defaults"
reapplied_firewall_vars=$(policy_vars_for_scope reapply)
loaded_firewall_vars=$(policy_vars_for_scope load)
validated_firewall_vars=$(policy_vars_for_scope validate)
rendered_firewall_vars=$(policy_vars_for_scope render)
supported_cli_options=$(defined_kv_vars "$public_cli_config_defaults")
persisted_cutover_state_vars=$(defined_kv_vars "$cutover_state_var_defs")
# Captured CLI identity/policy values
cli_user="${user-}"
cli_ssh_port="${ssh_port-}"
cli_disable_wheel="${disable_wheel-}"
cli_remove_wheel_members="${remove_wheel_members-}"
capture_desired_mutable_baseline_settings() {
desired_mutable_baseline_settings=$(settings_block_for_vars "$reapplied_firewall_vars")
}
restore_desired_mutable_baseline_settings() {
restore_vars_from_settings_block "$reapplied_firewall_vars" "$desired_mutable_baseline_settings"
}
# Ensure the script is run as root
if [ "$(id -u)" -ne 0 ]; then
say_err "This script must be run as root. Please use sudo or run as root user."
exit 1
fi
###############################################################################
# Validation Helpers
###############################################################################
# Validate the existence of a user
validate_user() {
if ! id "$1" >/dev/null 2>&1; then
say_err "User '$1' does not exist."
return 1
fi
}
# Validate SSH port input
validate_port() {
if ! [ "$1" -eq "$1" ] 2>/dev/null || [ "$1" -lt 1 ] || [ "$1" -gt 65535 ]; then
error_msg "Invalid port number '$1'. Port must be an integer between 1 and 65535."
return 1
fi
}
# Validate network interface
validate_interface() {
if ! ifconfig "$1" >/dev/null 2>&1; then
error_msg "Invalid interface '$1'. Please enter a valid network interface."
return 1
fi
}
# Validate password expiration input
validate_password_expiration() {
if ! [ "$1" -eq "$1" ] 2>/dev/null || [ "$1" -le 0 ]; then
error_msg "Invalid password expiration '$1'. Days must be a positive integer."
return 1
fi
}
validate_yes_no() {
value="$1"
option_name="$2"
if [ "$value" != "yes" ] && [ "$value" != "no" ]; then
say_err "Invalid value for $option_name: $value (use yes or no)."
return 1
fi
}
validate_optional_yes_no() {
value="$1"
option_name="$2"
[ -z "$value" ] || validate_yes_no "$value" "$option_name"
}
validate_optional_interface() {
value="$1"
[ -z "$value" ] || value_is_none "$value" || validate_interface "$value"
}
user_in_group() {
target_user="$1"
target_group="$2"
id -Gn "$target_user" | tr ' ' '\n' | grep -qx "$target_group"
}
set_user_auth_paths() {
auth_user="$1"
ssh_dir="/home/$auth_user/.ssh"
ssh_key="$ssh_dir/id_ed25519"
ssh_pub_key="${ssh_key}.pub"
authorized_keys="$ssh_dir/authorized_keys"
ga_config="/home/$auth_user/.google_authenticator"
}
read_simple_assignment_value() {
target_file="$1"
target_key="$2"
[ -f "$target_file" ] || return 1
awk -v target_key="$target_key" '
index($0, "=") {
key = substr($0, 1, index($0, "=") - 1)
if (key != target_key) {
next
}
value = substr($0, index($0, "=") + 1)
sub(/^"/, "", value)
sub(/"$/, "", value)
print value
found = 1
exit
}
END { exit(found ? 0 : 1) }
' "$target_file"
}
assignment_settings_block_from_file() {
target_file="$1"
[ -f "$target_file" ] || return 1
awk '
index($0, "=") {
key = substr($0, 1, index($0, "=") - 1)
value = substr($0, index($0, "=") + 1)
sub(/^"/, "", value)
sub(/"$/, "", value)
print key "=" value
}
' "$target_file"
}
text_has_all_exact_lines() {
text_block="$1"
expected_lines="$2"
printf '%s\n' "$text_block" |
awk -v expected_lines="$expected_lines" '
BEGIN {
expected_count = split(expected_lines, expected, "\n")
for (i = 1; i <= expected_count; i++) {
if (expected[i] != "") {
required[expected[i]] = 1
}
}
}
{
seen[$0] = 1
}
END {
for (line in required) {
if (!(line in seen)) {
exit 1
}
}
}
'
}
file_has_all_exact_lines() {
target_file="$1"
expected_lines="$2"
[ -f "$target_file" ] || return 1
text_has_all_exact_lines "$(cat "$target_file")" "$expected_lines"
}
settings_block_value() {
settings_block="$1"
target_key="$2"
printf '%s\n' "$settings_block" |
awk -F '=' -v target_key="$target_key" '
$1 == target_key {
value = substr($0, index($0, "=") + 1)
print value
found = 1
exit
}
END { exit(found ? 0 : 1) }
'
}
settings_block_for_vars() {
var_list="$1"
settings_block_for_vars_with_value_fn "$var_list" "get_var_value"
}
settings_block_for_vars_with_value_fn() {
var_list="$1"
value_fn="$2"
old_ifs=$IFS
IFS=' '
for var_name in $var_list; do
[ -n "$var_name" ] || continue
var_value=$("$value_fn" "$var_name")
printf '%s=%s\n' "$var_name" "${var_value-}"
done
IFS=$old_ifs
}
each_settings_block_entry() {
settings_block="$1"
callback_fn="$2"
old_ifs=$IFS
IFS='
'
for setting in $settings_block; do
[ -n "$setting" ] || continue
"$callback_fn" "${setting%%=*}" "${setting#*=}"
done
IFS=$old_ifs
}
quoted_setting_line() {
key="$1"
value="$2"
escaped_value=$(printf '%s' "$value" | sed 's/["\\]/\\&/g')
printf '%s="%s"\n' "$key" "$escaped_value"
}
emit_overridden_settings_entry() {
setting_key="$1"
setting_value="$2"
override_value=$(settings_block_value "$current_settings_overrides" "$setting_key" 2>/dev/null || printf '%s' "$setting_value")
printf '%s=%s\n' "$setting_key" "$override_value"
}
emit_quoted_settings_entry() {
setting_key="$1"
setting_value="$2"
quoted_setting_line "$setting_key" "$setting_value"
}
apply_sysrc_settings_entry() {
setting_key="$1"
setting_value="$2"
sysrc "$(quoted_setting_line "$setting_key" "$setting_value")"
}
settings_block_with_overrides() {
base_block="$1"
current_settings_overrides="$2"
each_settings_block_entry "$base_block" "emit_overridden_settings_entry"
}
render_quoted_settings_block() {
settings_block="$1"
each_settings_block_entry "$settings_block" "emit_quoted_settings_entry"
}
settings_blocks_match() {
expected_block="$1"
actual_block="$2"
awk -v expected_block="$expected_block" -v actual_block="$actual_block" '
BEGIN {
expected_count = split(expected_block, expected_lines, "\n")
for (i = 1; i <= expected_count; i++) {
if (expected_lines[i] == "") {
continue
}
split(expected_lines[i], expected_parts, "=")
expected_key = expected_parts[1]
expected_value = substr(expected_lines[i], index(expected_lines[i], "=") + 1)
expected_map[expected_key] = expected_value
}
actual_count = split(actual_block, actual_lines, "\n")
for (i = 1; i <= actual_count; i++) {
if (actual_lines[i] == "") {
continue
}
split(actual_lines[i], actual_parts, "=")
actual_key = actual_parts[1]
actual_value = substr(actual_lines[i], index(actual_lines[i], "=") + 1)
actual_map[actual_key] = actual_value
}
for (key in expected_map) {
if (!(key in actual_map) || actual_map[key] != expected_map[key]) {
exit 1
}
}
}
' </dev/null
}
restore_vars_from_settings_block() {
var_list="$1"
settings_block="$2"
only_if_missing="${3:-no}"
wanted_vars=" $var_list "
each_settings_block_entry "$settings_block" "restore_settings_block_entry"
}
restore_settings_block_entry() {
target_var="$1"
target_value="$2"
case "$wanted_vars" in
*" $target_var "*) ;;
*)
return 0
;;
esac
if [ "$only_if_missing" = "yes" ] && [ -n "$(get_var_value "$target_var")" ]; then
return 0
fi
set_var_value "$target_var" "$target_value"
}
sudo_policy_is_valid() {
[ -f /usr/local/etc/sudoers.d/sudo ] &&
grep -qxF "$sudo_policy_line" /usr/local/etc/sudoers.d/sudo &&
visudo -c >/dev/null
}
wheel_sudo_is_active() {
awk '
/^%wheel[[:blank:]]+ALL=\(ALL(:ALL)?\)[[:blank:]]+(NOPASSWD:[[:blank:]]+)?ALL$/ {
found = 1
exit
}
END { exit(found ? 0 : 1) }
' /usr/local/etc/sudoers ||
{ [ -f /usr/local/etc/sudoers.d/wheel ] && [ ! -f /usr/local/etc/sudoers.d/wheel.disabled ]; }
}
non_root_wheel_members_present() {
getent group wheel | cut -d ':' -f 4 | tr ',' '\n' | grep -qEv '^(|root)$'
}
load_live_managed_firewall_context() {
[ -f "$managed_ipfw_rules_file" ] || return 0
managed_firewall_settings=$(assignment_settings_block_from_file "$managed_ipfw_rules_file" 2>/dev/null || printf '')
restore_vars_from_settings_block "$loaded_firewall_vars" "$managed_firewall_settings" "yes"
resolve_install_suricata_default
}
###############################################################################
# SSH, Firewall, And Live-State Validation
###############################################################################
effective_sshd_has_line() {
sshd_effective="$1"
expected_line="$2"
printf '%s\n' "$sshd_effective" | grep -qxF "$expected_line"
}
effective_sshd_lacks_line() {
sshd_effective="$1"
blocked_line="$2"
if effective_sshd_has_line "$sshd_effective" "$blocked_line"; then
return 1
fi
}
effective_sshd_matches_lines() {
sshd_effective="$1"
expected_lines="$2"
text_has_all_exact_lines "$sshd_effective" "$expected_lines"
}
normalize_csv_set() {
csv_value="$1"
if [ -z "$csv_value" ]; then
printf '\n'
return 0
fi
printf '%s\n' "$csv_value" |
tr ',' '\n' |
sed '/^$/d' |
sort -u |
paste -sd, -
}
compose_normalized_port_set() {
primary_port="$1"
extra_port="${2:-}"
ports_csv="$primary_port"
if value_is_configured "$extra_port" && [ "$extra_port" != "$primary_port" ]; then
ports_csv="$extra_port,$primary_port"
fi
normalize_csv_set "$ports_csv"
}
csv_items_lines() {
csv_value="$1"
[ -n "$csv_value" ] || return 0
printf '%s\n' "$csv_value" |
tr ',' '\n' |
sed 's/^[[:space:]]*//; s/[[:space:]]*$//; /^$/d'
}
group_member_lines() {
group_name="$1"
getent group "$group_name" | cut -d ':' -f 4 | tr ',' '\n' | sed '/^$/d'
}
append_line_block() {
line_block="$1"
new_line="$2"
if [ -n "$line_block" ]; then
printf '%s\n%s\n' "$line_block" "$new_line"
else
printf '%s\n' "$new_line"
fi
}
normalize_line_block_csv() {
line_block="$1"
printf '%s\n' "$line_block" | sed '/^$/d' | awk '!seen[$0]++' | paste -sd, -
}
update_group_membership() {
group_name="$1"
action="$2"
user_list="$3"
success_message="$4"
empty_message="$5"
changed_users=""
for member_user in $user_list; do
[ -n "$member_user" ] || continue
case "$action" in
add)
pw groupmod "$group_name" -m "$member_user"
;;
remove)
pw groupmod "$group_name" -d "$member_user"
;;
*)
error_msg "Unknown group membership action '$action'."
return 1
;;
esac
changed_users=$(append_line_block "$changed_users" "$member_user")
done
if [ -n "$changed_users" ]; then
say "$success_message $(normalize_line_block_csv "$changed_users")"
else
say "$empty_message"
fi
}
load_effective_sshd() {
if ! sshd -t -f "$sshd_config_file" >/dev/null 2>&1; then
return 1
fi
sshd -T -f "$sshd_config_file" 2>/dev/null
}
effective_sshd_ports_csv() {
sshd_effective="$1"
actual_ports_csv=$(printf '%s\n' "$sshd_effective" |
awk '$1 == "port" { print $2 }' |
sort -u |
paste -sd, -)
normalize_csv_set "$actual_ports_csv"
}
effective_sshd_ports_match() {
sshd_effective="$1"
expected_ports_csv="$2"
[ "$(effective_sshd_ports_csv "$sshd_effective")" = "$(normalize_csv_set "$expected_ports_csv")" ]
}
effective_sshd_has_single_port() {
sshd_effective="$1"
port_count=$(printf '%s\n' "$sshd_effective" | awk '$1 == "port" { count++ } END { print count + 0 }')
[ "$port_count" -eq 1 ]
}
effective_sshd_allowusers_includes() {
sshd_effective="$1"
allow_user="$2"
printf '%s\n' "$sshd_effective" |
awk -v allow_user="$allow_user" '
$1 == "allowusers" {
for (i = 2; i <= NF; i++) {
if ($i == allow_user) {
found = 1
}
}
}
END { exit(found ? 0 : 1) }
'
}
admin_access_error() {
error_msg "$1. Deferred admin fallback policy has not been changed."
}
strict_ssh_config_ready() {
[ -n "${user-}" ] || return 1
[ -n "${ssh_port-}" ] || return 1
sshd_effective=$(load_effective_sshd) || return 1
effective_sshd_matches_lines "$sshd_effective" "$strict_ssh_effective_policy_lines" &&
effective_sshd_ports_match "$sshd_effective" "$ssh_port" &&
effective_sshd_allowusers_includes "$sshd_effective" "$user"
}
transitional_ssh_config_ready() {
[ -n "${user-}" ] || return 1
sshd_effective=$(load_effective_sshd) || return 1
effective_sshd_has_line "$sshd_effective" "passwordauthentication yes" &&
effective_sshd_has_line "$sshd_effective" "kbdinteractiveauthentication yes" &&
effective_sshd_has_line "$sshd_effective" "pubkeyauthentication yes" &&
effective_sshd_has_line "$sshd_effective" "usepam yes" &&
effective_sshd_allowusers_includes "$sshd_effective" "$user" &&
effective_sshd_has_single_port "$sshd_effective" &&
[ -n "${transitional_ssh_port:-}" ] &&
effective_sshd_ports_match "$sshd_effective" "$transitional_ssh_port" &&
effective_sshd_lacks_line "$sshd_effective" "authenticationmethods publickey,keyboard-interactive"
}
pending_port_transition_sshd_matches_state() {
[ -n "${user-}" ] || return 1
[ -n "${ssh_port-}" ] || return 1
sshd_effective=$(load_effective_sshd) || return 1
case "${cutover_stage:-}" in
pending_port_transition_reboot)
effective_sshd_matches_lines "$sshd_effective" "$strict_ssh_effective_policy_lines" &&
effective_sshd_allowusers_includes "$sshd_effective" "$user" &&
effective_sshd_ports_match "$sshd_effective" "$port_transition_old_port,$ssh_port"
;;
pending_port_commit_reboot)
effective_sshd_matches_lines "$sshd_effective" "$strict_ssh_effective_policy_lines" &&
effective_sshd_allowusers_includes "$sshd_effective" "$user" &&
effective_sshd_ports_match "$sshd_effective" "$ssh_port"
;;
*)
return 1
;;
esac
}
ssh_admin_path_matches_state() {
[ -n "${user-}" ] || return 1
validate_user "$user" >/dev/null 2>&1 || return 1
strict_ssh_config_ready || return 1
set_user_auth_paths "$user"
[ -f "$authorized_keys" ] &&
[ -s "$authorized_keys" ] &&
[ -f "$ga_config" ] &&
[ -s "$ga_config" ]
}
cutover_state_matches_live_identity() {
[ -n "${user-}" ] || return 1
[ -n "${cutover_user_uid-}" ] || return 1
validate_user "$user" >/dev/null 2>&1 || return 1
[ "$(id -u "$user")" = "$cutover_user_uid" ]
}
sudo_admin_path_matches_state() {
[ -n "${user-}" ] || return 1
validate_user "$user" >/dev/null 2>&1 || return 1
sudo_policy_is_valid &&
user_in_group "$user" "sudo"
}