-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPVE9-Harden-FinalVersion-v1.sh
More file actions
executable file
·2062 lines (1725 loc) · 68 KB
/
PVE9-Harden-FinalVersion-v1.sh
File metadata and controls
executable file
·2062 lines (1725 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# PVE9-Harden-FinalVersion-v1.sh (Final Version)
# Modern interactive PVE hardening toolkit
# Features: Menu box modern, progress bar horizontal, modular framework
# Author: black_platoon23 | Ismail Djamhur
set -e
set -o pipefail
IFS=$'\n\t'
#########################################
# Global Configuration
#########################################
VERSION="1.0-FINAL"
LOG="/var/log/haqqsec_interactive.log"
BACKUP_DIR="/root/haqqsec_backups_$(date +%Y%m%d_%H%M%S)"
REPORT="/root/haqqsec_report_$(date +%Y%m%d_%H%M%S).html"
SEC_LEVEL="2"
DRY_RUN=false
VERBOSE=false
#########################################
# Color Palette (Bold & Modern)
#########################################
C_RESET='\033[0m'
C_BOLD='\033[1m'
C_RED='\033[1;31m'
C_GREEN='\033[1;32m'
C_YELLOW='\033[1;33m'
C_BLUE='\033[1;34m'
C_CYAN='\033[1;36m'
C_WHITE='\033[1;37m'
#########################################
# Logging
#########################################
log() {
echo -e "[$(date +'%H:%M:%S')] $*" | tee -a "$LOG"
}
execute_command() {
local description="$1"
shift
local command="$@"
if [[ "${DRY_RUN}" == "true" ]]; then
log INFO "[DRY RUN] ${description}: ${command}"
return 0
fi
log INFO "${description}"
eval "${command}"
}
backup_file() {
local file="$1"
if [[ -f "$file" ]]; then
mkdir -p "${BACKUP_DIR}/$(dirname "$file")"
cp "$file" "${BACKUP_DIR}/$file.$(date +%s)"
log "INFO" "Backed up $file"
fi
}
wait_for_apt() {
local max_wait=300
local waited=0
while sudo fuser /var/lib/dpkg/lock-frontend >/dev/null 2>&1 || \
sudo fuser /var/lib/apt/lists/lock >/dev/null 2>&1 || \
sudo fuser /var/cache/apt/archives/lock >/dev/null 2>&1; do
if [[ ${waited} -eq 0 ]]; then
log WARNING "Waiting for other package managers to finish..."
fi
sleep 2
waited=$((waited + 2))
if [[ ${waited} -ge ${max_wait} ]]; then
log ERROR "Timed out waiting for package manager"
return 1
fi
done
return 0
}
#########################################
# PROGRESS BAR HORIZONTAL
#########################################
progress_bar() {
local progress=$1
local total=$2
# Hitung persentase
local percent=$(( 100 * progress / total ))
[[ $percent -gt 100 ]] && percent=100
# Hitung panjang bar (50 karakter total)
local filled=$(( percent / 2 ))
local empty=$(( 50 - filled ))
# Clear line dan draw bar
tput el # Clear sampai akhir baris
echo -ne "${C_GREEN}["
# Bagian terisi
for ((i=0; i<filled; i++)); do
echo -ne "█"
done
# Bagian kosong
for ((i=0; i<empty; i++)); do
echo -ne "░"
done
# Tampilkan persentase
echo -ne "] ${percent}%${C_RESET}"
}
#########################################
# UI — BOX MENU MODERN WITH ASCII ART & DISCLAIMER
#########################################
draw_menu_box() {
clear
# ASCII Art untuk "Hardening" (bagian bawah)
echo " ██╗ ██╗ █████╗ ██████╗ ██████╗ ███████╗███╗ ██╗██╗███╗ ██╗ ██████╗ "
echo " ██║ ██║██╔══██╗██╔══██╗██╔══██╗██╔════╝████╗ ██║██║████╗ ██║██╔════╝ "
echo " ███████║███████║██████╔╝██║ ██║█████╗ ██╔██╗ ██║██║██╔██╗ ██║██║ ███╗"
echo " ██╔══██║██╔══██║██╔══██╗██║ ██║██╔══╝ ██║╚██╗██║██║██║╚██╗██║██║ ██║"
echo " ██║ ██║██║ ██║██║ ██║██████╔╝███████╗██║ ╚████║██║██║ ╚████║╚██████╔╝"
echo " ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═══╝ ╚═════╝ "
echo " PROMOX VE 9.1"
echo -e "${C_RESET}"
# Menu Box
echo -e "${C_BLUE}${C_BOLD}"
echo "┌───────────────────────────────────────┐"
echo "│ Proxmox VE 9.1 Hardening │"
echo "├───────────────────────────────────────┤"
echo "│ 1. Select Security Level │"
echo "│ 2. Select Modules Manually │"
echo "│ 3. Start Hardening │"
echo "│ 4. List of Modules │"
echo "│ 5. Exit │"
echo "└───────────────────────────────────────┘"
echo -e "${C_RESET}"
# Disclaimer dengan format yang diminta
echo ""
echo -e "${C_RED}${C_BOLD}╔══════════════════════════════════════════════════════════════════════════════════════════╗${C_RESET}"
echo -e "${C_RED}${C_BOLD}║ DISCLAIMER AND USER ACKNOWLEDGMENT ║${C_RESET}"
echo -e "${C_RED}${C_BOLD}╠══════════════════════════════════════════════════════════════════════════════════════════╣${C_RESET}"
echo -e "${C_RED}║ By using this hardening script, you acknowledge and accept that the implementation of ║${C_RESET}"
echo -e "${C_RED}║ these security modules is undertaken voluntarily and at your own risk. You understand ║${C_RESET}"
echo -e "${C_RED}║ that applying security configurations carries inherent potential risks, including but ║${C_RESET}"
echo -e "${C_RED}║ not limited to system lockout, service disruption, performance degradation, data loss, ║${C_RESET}"
echo -e "${C_RED}║ or cluster failure. All consequences arising from the execution of this script, whether ║${C_RESET}"
echo -e "${C_RED}║ direct or indirect, are solely your responsibility as the user. The script author and ║${C_RESET}"
echo -e "${C_RED}║ contributors explicitly disclaim any liability for damages, downtime, operational issues,║${C_RESET}"
echo -e "${C_RED}║ or compliance violations that may occur, given the unpredictable nature of individual ║${C_RESET}"
echo -e "${C_RED}║ system environments, custom configurations, and external factors beyond the developer's ║${C_RESET}"
echo -e "${C_RED}║ control. ║${C_RESET}"
echo -e "${C_RED}${C_BOLD}╚══════════════════════════════════════════════════════════════════════════════════════════╝${C_RESET}"
echo ""
}
#########################################
# READ INPUT SAFE (ANTI EXIT)
#########################################
safe_read() {
set +e
read -r "$1"
set -e
}
#########################################
# MODULE STRUCTURE
#########################################
declare -A MODULE_LABELS
declare -A MODULE_LIST
MODULE_ORDER=(
system_update
audit
secure_shared_memory
ssh_hardening
automatic_updates
firewall
sysctl
password_policy
ntp
apparmor
filesystems
package_verification
)
#########################################
# DEFAULT SECURITY LEVEL
#########################################
# Jika user tidak memilih apa pun → Level 2
#SEC_LEVEL=2
#########################################
# MAPPING MODUL PER LEVEL SECURITY
#########################################
LEVEL1_MODULES=(
system_update
firewall
)
LEVEL2_MODULES=(
system_update
firewall
ssh_hardening
password_policy
ntp
audit
)
LEVEL3_MODULES=(
system_update
firewall
ssh_hardening
password_policy
ntp
audit
sysctl
filesystems
)
LEVEL4_MODULES=(
system_update
firewall
ssh_hardening
password_policy
ntp
audit
sysctl
filesystems
automatic_updates
)
LEVEL5_MODULES=(
system_update
firewall
ssh_hardening
password_policy
ntp
audit
sysctl
filesystems
automatic_updates
secure_shared_memory
package_verification
)
#########################################
# Define module names & descriptions
#########################################
MODULES=(
system_update
audit
secure_shared_memory
ssh_hardening
automatic_updates
firewall
sysctl
password_policy
ntp
apparmor
filesystems
package_verification
)
declare -A MODULE_LABELS=(
[system_update]="System update & upgrade"
[audit]="Auditd rules"
[secure_shared_memory]="/dev/shm Hardening"
[ssh_hardening]="SSH hardening"
[automatic_updates]="Unattended upgrades"
[firewall]="Firewall PVE/NFT"
[sysctl]="Kernel hardening"
[password_policy]="Password policy"
[ntp]="Time sync (Chrony)"
[apparmor]="AppArmor enable"
[filesystems]="Disable unused FS"
[package_verification]="Package verification"
)
#########################################
# Show Module
#########################################
show_modules() {
echo -e "\nList of Hardening Modules PVE 9.1"
echo "=================================\n"
local index=1
for mod in "${MODULES[@]}"; do
printf "%2d) %-22s - %s\n" \
"$index" "$mod" "${MODULE_LABELS[$mod]}"
index=$((index+1))
done
echo -e "\n 0) Back"
read -r input
[[ "$input" == "0" ]] && return
}
#########################################
# Define Maturity Security Level
#########################################
choose_security_level() {
clear
echo -e "${C_CYAN}${C_BOLD}Choose Security Level:${C_RESET}"
echo "1. Level 1 (Very minimum compliance security)"
echo "2. Level 2 (Minimum compliance security)"
echo "3. Level 3 (Security compliance enough)"
echo "4. Level 4 (Security compliance near fully)"
echo "5. Level 5 (Security compliance fully)"
echo "0. Back to main menu"
echo -n "Choose: "
safe_read lvl
case "$lvl" in
1)
SEC_LEVEL=1
MODULE_ORDER=("${LEVEL1_MODULES[@]}")
;;
2)
SEC_LEVEL=2
MODULE_ORDER=("${LEVEL2_MODULES[@]}")
;;
3)
SEC_LEVEL=3
MODULE_ORDER=("${LEVEL3_MODULES[@]}")
;;
4)
SEC_LEVEL=4
MODULE_ORDER=("${LEVEL4_MODULES[@]}")
;;
5)
SEC_LEVEL=5
MODULE_ORDER=("${LEVEL5_MODULES[@]}")
;;
0)
# Kembali ke menu tanpa mengubah apapun
return 0
;;
*)
echo -e "${C_YELLOW}Invalid choice, using default Level 2${C_RESET}"
SEC_LEVEL=2
MODULE_ORDER=("${LEVEL2_MODULES[@]}")
sleep 1
;;
esac
# clear
# echo -e "${C_GREEN}${C_BOLD}Set Security level to: Level $SEC_LEVEL${C_RESET}"
# echo -e "\nModules to be executed:"
# for m in "${MODULE_ORDER[@]}"; do
# echo " - $m (${MODULE_LABELS[$m]})"
# done
# echo ""
# echo "Press Enter to return to the menu..."
# read
if [[ "$lvl" != "0" ]]; then
clear
echo -e "${C_GREEN}${C_BOLD}Security level set to: Level $SEC_LEVEL${C_RESET}"
echo -e "\nModules to be executed:"
for m in "${MODULE_ORDER[@]}"; do
echo " - $m (${MODULE_LABELS[$m]})"
done
echo ""
#echo "Press Enter to return to the menu..."
#read
run_hardening
fi
}
#########################################
# MODULE IMPLEMENTATIONS
#########################################
mod_system_update() {
log "Running system update"
wait_for_apt
execute_command "Refreshing package lists" \
"sudo apt-get update"
if [[ "${SECURITY_LEVEL}" == "5" ]]; then
execute_command "Upgrading all packages (full upgrade)" \
"sudo DEBIAN_FRONTEND=noninteractive apt-get full-upgrade -y"
else
execute_command "Upgrading packages (safe upgrade)" \
"sudo DEBIAN_FRONTEND=noninteractive apt-get upgrade -y"
fi
log SUCCESS "System packages updated"
return 0
}
mod_audit() {
log "Configuring auditd"
execute_command "Installing auditd" \
"sudo apt-get install -y auditd audispd-plugins"
local audit_rules="/etc/audit/rules.d/haqqsec.rules"
if [[ "${DRY_RUN}" == "false" ]]; then
sudo tee "${audit_rules}" > /dev/null << 'EOF'
# HaqqSecTools-PVE9-Harden.sh - Audit Rules
# Delete all existing rules
-D
# Buffer size
-b 8192
# Failure mode (1 = print, 2 = panic)
-f 1
# Authentication and authorization
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/sudoers -p wa -k actions
-w /etc/sudoers.d/ -p wa -k actions
# Login and logout
-w /var/log/faillog -p wa -k logins
-w /var/log/lastlog -p wa -k logins
-w /var/run/utmp -p wa -k session
-w /var/log/wtmp -p wa -k logins
-w /var/log/btmp -p wa -k logins
# Network configuration
-w /etc/hosts -p wa -k network
-w /etc/network/ -p wa -k network
-a always,exit -F arch=b64 -S sethostname -S setdomainname -k network
-a always,exit -F arch=b32 -S sethostname -S setdomainname -k network
# Discretionary access control
-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b32 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod
-a always,exit -F arch=b32 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod
# Unauthorized access attempts
-a always,exit -F arch=b64 -S open -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k access
-a always,exit -F arch=b32 -S open -S openat -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k access
-a always,exit -F arch=b64 -S open -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -k access
-a always,exit -F arch=b32 -S open -S openat -F exit=-EPERM -F auid>=1000 -F auid!=4294967295 -k access
# System administration
-w /var/log/sudo.log -p wa -k actions
# Kernel module loading
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
-a always,exit -F arch=b64 -S init_module -S delete_module -k modules
# Make configuration immutable (requires reboot to change)
-e 2
EOF
execute_command "Loading audit rules" \
"sudo augenrules --load"
execute_command "Enabling auditd" \
"sudo systemctl enable auditd && sudo systemctl restart auditd"
log SUCCESS "Audit logging configured"
else
log INFO "[DRY RUN] Would configure audit logging"
fi
return 0
}
mod_secure_shared_memory() {
local fstab="/etc/fstab"
local is_ceph_node="false"
local is_pve_node="false"
local ceph_version=""
# Detect Proxmox VE (case-insensitive)
if grep -qi "pve" /etc/os-release 2>/dev/null || command -v pveversion >/dev/null 2>&1; then
is_pve_node="true"
log INFO "Proxmox VE detected"
fi
# Detect Ceph installation (binary present + services active)
if command -v ceph >/dev/null 2>&1; then
# Try to get a version string (tolerant)
ceph_version=$(ceph --version 2>/dev/null | awk '{print $3}' || true)
# If ceph binary exists, check that Ceph services are active
if systemctl is-active --quiet ceph.target 2>/dev/null || systemctl is-active --quiet ceph-mon@* 2>/dev/null; then
is_ceph_node="true"
log INFO "Ceph detected: version ${ceph_version:-unknown}"
log INFO "Ceph services appear active"
else
log WARNING "Ceph binary present but Ceph services not active; treating as non-Ceph node for safety"
is_ceph_node="false"
fi
fi
# Check if /dev/shm contains Ceph-specific entries (safe check)
local shm_ceph_usage="false"
if [[ "${is_ceph_node}" == "true" ]]; then
# Use shell globbing check safely (avoid ls failures)
shopt -s nullglob 2>/dev/null || true
local ceph_shm_items=(/dev/shm/ceph-*)
if [[ ${#ceph_shm_items[@]} -gt 0 ]]; then
shm_ceph_usage="true"
log INFO "Ceph appears to be using /dev/shm (found ${#ceph_shm_items[@]} entries)"
# Show sizes but ignore errors
du -sh /dev/shm/ceph-* 2>/dev/null || true
else
log INFO "No Ceph-specific files found under /dev/shm"
fi
shopt -u nullglob 2>/dev/null || true
fi
# Backup fstab before changes
backup_file "${fstab}"
if [[ "${DRY_RUN}" == "false" ]]; then
# Remove any existing /dev/shm and /run/shm lines to avoid duplicates
sudo sed -i.bak -E '/[[:space:]]+\/dev\/shm[[:space:]]/d' "${fstab}" 2>/dev/null || true
sudo sed -i -E '/[[:space:]]+\/run\/shm[[:space:]]/d' "${fstab}" 2>/dev/null || true
# Add explanatory header
{
echo ""
echo "# HaqqSecTools-PVE9-Harden.sh - Shared Memory Hardening"
echo "# Applied: $(date '+%Y-%m-%d %H:%M:%S')"
} | sudo tee -a "${fstab}" >/dev/null
if [[ "${is_ceph_node}" == "true" ]]; then
# Ceph detected - Progressive Hardening Approach
{
echo "# Proxmox VE with Ceph detected - using progressive hardening"
echo "# Phase 1: nosuid + nodev (ACTIVE - safe)"
echo "# Phase 2: Add noexec after verification (see instructions below)"
echo ""
echo "tmpfs /dev/shm tmpfs defaults,nodev,nosuid 0 0"
echo "# After Ceph verification (24-48h), uncomment the line below and comment the line above:"
echo "# tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0"
} | sudo tee -a "${fstab}" >/dev/null
log WARNING "Ceph-aware hardening applied (Phase 1)"
log INFO " /dev/shm: nosuid,nodev (Phase 1 - Conservative)"
elif [[ "${is_pve_node}" == "true" ]]; then
# PVE without Ceph - still use conservative approach
{
echo "# Proxmox VE detected (no Ceph) - using conservative hardening"
echo "tmpfs /dev/shm tmpfs defaults,nodev,nosuid 0 0"
echo "# Optional: Add noexec after testing VM/CT operations:"
echo "# tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0"
} | sudo tee -a "${fstab}" >/dev/null
log INFO "PVE hardening applied (conservative)"
log INFO " /dev/shm: nosuid,nodev"
else
# Non-PVE system - full hardening
{
echo "# Standard system - full hardening"
echo "tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0"
} | sudo tee -a "${fstab}" >/dev/null
log INFO "Full hardening applied"
log INFO " /dev/shm: nosuid,nodev,noexec"
fi
# Always harden /run/shm fully (not used by Ceph or PVE)
{
echo ""
echo "# /run/shm - Full hardening (not used by Ceph/PVE)"
echo "tmpfs /run/shm tmpfs defaults,nodev,nosuid,noexec 0 0"
} | sudo tee -a "${fstab}" >/dev/null
# Apply Phase 1 settings immediately (remount appropriately)
if [[ "${is_ceph_node}" == "true" ]] || [[ "${is_pve_node}" == "true" ]]; then
execute_command "Remounting /dev/shm (Phase 1: nosuid,nodev)" \
"sudo mount -o remount,nodev,nosuid /dev/shm 2>/dev/null || true"
else
execute_command "Remounting /dev/shm with full security" \
"sudo mount -o remount,nodev,nosuid,noexec /dev/shm 2>/dev/null || true"
fi
execute_command "Remounting /run/shm with full security" \
"sudo mount -o remount,nodev,nosuid,noexec /run/shm 2>/dev/null || true"
# Verify mount options and display to user
echo ""
log SUCCESS "Shared memory hardening applied"
echo ""
log INFO "Current mount options:"
mount | grep -E "/dev/shm|/run/shm" | sed 's/^/ /'
echo ""
else
log INFO "[DRY RUN] Would apply shared memory hardening (no changes made)"
fi
return 0
}
mod_ssh_hardening() {
log "Hardening SSH"
local ssh_config="/etc/ssh/sshd_config"
# Check if SSH is installed
if ! command -v sshd &>/dev/null; then
log "WARNING" "SSH server not installed - skipping SSH hardening"
return 0
fi
# Safety check: Ensure key-based auth exists before disabling password auth
# Check if there are any authorized_keys files
local has_keys=false
if [[ -f ~/.ssh/authorized_keys ]] && [[ -s ~/.ssh/authorized_keys ]]; then
has_keys=true
fi
# Check for any root authorized_keys
if [[ -f /root/.ssh/authorized_keys ]] && [[ -s /root/.ssh/authorized_keys ]]; then
has_keys=true
fi
if [[ "$has_keys" == "false" ]]; then
log "WARNING" "No SSH keys detected. Skipping SSH hardening to prevent lockout."
log "INFO" "To setup SSH keys:"
log "INFO" " 1. On client: ssh-keygen -t ed25519"
log "INFO" " 2. Copy to server: ssh-copy-id user@hostname"
log "INFO" " 3. Test connection, then run this module again"
return 0
fi
# Backup current SSH config
if [[ -f "$ssh_config" ]]; then
local backup_file="${BACKUP_DIR}/etc/ssh/sshd_config"
mkdir -p "$(dirname "$backup_file")"
cp "$ssh_config" "$backup_file"
log "INFO" "Backed up SSH config to: $backup_file"
fi
if [[ "$DRY_RUN" == "false" ]]; then
# Write hardened SSH config
sudo tee "$ssh_config" > /dev/null << 'EOF'
# HaqqSecTools-PVE9-Harden.sh SSH Configuration
# Strong security, key-based authentication only
# Authentication
PermitRootLogin prohibit-password
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
# Strong cryptography (compatible with OpenSSH 8/9)
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
# Connection settings
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 30
MaxAuthTries 3
MaxSessions 10
# Logging
SyslogFacility AUTH
LogLevel VERBOSE
# Security settings
X11Forwarding no
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
EOF
# Validate SSH configuration
if sudo sshd -t 2>/dev/null; then
execute_command "Restarting SSH service" \
"sudo systemctl restart sshd"
log "SUCCESS" "SSH hardened - password authentication disabled"
else
log "ERROR" "SSH configuration validation failed - restoring backup"
# Restore backup
if [[ -f "${BACKUP_DIR}/etc/ssh/sshd_config" ]]; then
sudo cp "${BACKUP_DIR}/etc/ssh/sshd_config" "$ssh_config"
sudo systemctl restart sshd
log "INFO" "SSH configuration restored from backup"
fi
return 1
fi
else
log "INFO" "[DRY RUN] Would configure SSH hardening"
fi
return 0
}
mod_automatic_updates() {
execute_command "Installing unattended-upgrades" \
"sudo apt-get install -y unattended-upgrades apt-listchanges"
local auto_upgrades="/etc/apt/apt.conf.d/20auto-upgrades"
local unattended_conf="/etc/apt/apt.conf.d/50unattended-upgrades"
if [[ "${DRY_RUN}" == "false" ]]; then
sudo tee "${auto_upgrades}" > /dev/null << 'EOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
EOF
# Configure unattended upgrades
sudo tee "${unattended_conf}" > /dev/null << 'EOF'
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
"${distro_id}ESMApps:${distro_codename}-apps-security";
"${distro_id}ESM:${distro_codename}-infra-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "03:00";
EOF
execute_command "Enabling automatic updates" \
"sudo systemctl enable unattended-upgrades && sudo systemctl start unattended-upgrades"
log SUCCESS "Automatic security updates enabled"
else
log INFO "[DRY RUN] Would enable automatic security updates"
fi
return 0
}
mod_firewall() {
log "[APPLY firewall-pve] SAFE MODE for PVE 9.1"
NODE=$(hostname)
log "1. Enable PVE Firewall (cluster + node)"
pvesh set /cluster/firewall/options --enable 1
pvesh set /nodes/$NODE/firewall/options --enable 1
log "2. Add mandatory allow rules (SSH, GUI, SPICE)"
# Add node-level rules
add_rule() {
local COMMENT="$1"
shift
if ! pvesh get /nodes/$NODE/firewall/rules | grep -q "$COMMENT"; then
pvesh create /nodes/$NODE/firewall/rules "$@" --enable 1 --comment "$COMMENT"
log "Added NODE rule: $COMMENT"
else
log "Node rule already exists: $COMMENT"
fi
}
# Add datacenter-level rules
add_dc_rule() {
local COMMENT="$1"
shift
if ! pvesh get /cluster/firewall/rules | grep -q "$COMMENT"; then
pvesh create /cluster/firewall/rules "$@" --enable 1 --comment "$COMMENT"
log "Added DC rule: $COMMENT"
else
log "DC rule already exists: $COMMENT"
fi
}
# List of essential ports (node + datacenter)
RULES=(
"Allow SSH|tcp|22"
"Allow PVE Web GUI|tcp|8006"
"Allow SPICE console|tcp|3128"
"Allow VNC Console|tcp|5900:5999"
"Allow ICMP ping|icmp|"
)
for R in "${RULES[@]}"; do
COMMENT="${R%%|*}"
PROTO_PORT="${R#*|}"
PROTO="${PROTO_PORT%%|*}"
PORT="${PROTO_PORT#*|}"
# Node-level
if [ "$PROTO" = "icmp" ]; then
add_rule "$COMMENT" --type in --action ACCEPT --proto icmp
add_dc_rule "$COMMENT" --type in --action ACCEPT --proto icmp
else
add_rule "$COMMENT" --type in --action ACCEPT --proto "$PROTO" --dport "$PORT"
add_dc_rule "$COMMENT" --type in --action ACCEPT --proto "$PROTO" --dport "$PORT"
fi
done
log "3. Detecting Cluster (Corosync) & Ceph"
if systemctl is-active --quiet corosync || [ -f /etc/pve/corosync.conf ]; then
for PORT in 5404 5405 5406 5407; do
add_rule "Corosync $PORT" --type in --action ACCEPT --proto udp --dport "$PORT"
add_dc_rule "Corosync $PORT" --type in --action ACCEPT --proto udp --dport "$PORT"
done
fi
if command -v ceph >/dev/null 2>&1; then
add_rule "Ceph MON 3300" --type in --action ACCEPT --proto tcp --dport 3300
add_dc_rule "Ceph MON 3300" --type in --action ACCEPT --proto tcp --dport 3300
add_rule "Ceph MON 6789" --type in --action ACCEPT --proto tcp --dport 6789
add_dc_rule "Ceph MON 6789" --type in --action ACCEPT --proto tcp --dport 6789
add_rule "Ceph OSD/MGR 6800-7300" --type in --action ACCEPT --proto tcp --dport 6800:7300
add_dc_rule "Ceph OSD/MGR 6800-7300" --type in --action ACCEPT --proto tcp --dport 6800:7300
fi
log "4. Apply default cluster firewall policy"
CFG="/etc/pve/firewall/cluster.fw"
if [ ! -f "$CFG" ]; then
cat <<EOF > "$CFG"
[OPTIONS]
enable: 1
policy_in: DROP
policy_out: ACCEPT
policy_forward: DROP
EOF
else
grep -q "enable:" "$CFG" || echo "enable: 1" >> "$CFG"
grep -q "policy_in:" "$CFG" || echo "policy_in: DROP" >> "$CFG"
grep -q "policy_out:" "$CFG" || echo "policy_out: ACCEPT" >> "$CFG"
grep -q "policy_forward:" "$CFG" || echo "policy_forward: DROP" >> "$CFG"
fi
log "5. Compile firewall"
pve-firewall compile
log "SAFE FIREWALL APPLIED for PVE 9.1"
}
mod_sysctl() {
log "Configuring kernel security parameters"
local final_conf="/etc/sysctl.d/99-haqqsec.conf"
local tmp_conf="/tmp/99-haqqsec.conf.tmp.$$"
# Check if running in dry run mode
if [[ "${DRY_RUN}" == "true" ]]; then
log "INFO" "[DRY RUN] Would configure kernel security parameters"
return 0
fi
# Backup existing config if it exists
if [[ -f "$final_conf" ]]; then
local backup_file="${BACKUP_DIR}/etc/sysctl.d/99-haqqsec.conf.backup"
mkdir -p "$(dirname "$backup_file")"
cp "$final_conf" "$backup_file"
log "INFO" "Backed up existing sysctl config to: $backup_file"
fi
# Write new config to temp file
cat > "${tmp_conf}" << 'EOF'
#########################################################################
# HaqqSecTools-PVE9-Harden.sh - Hardened sysctl (CIS Debian 13 compatible)
# Safe for Proxmox VE 9.1
#########################################################################
# Network security
net.ipv4.tcp_syncookies = 1
# Reverse path filtering - mode 2 (loose mode) safer for Proxmox cluster
net.ipv4.conf.all.rp_filter = 2
net.ipv4.conf.default.rp_filter = 2
# Disable source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0
# Disable ICMP redirects (ALL) - safe for Proxmox
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
# Disable secure redirects
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
# Disable send_redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# ICMP protections
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Logging packets with suspicious source addresses
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# IP forwarding (enabled for Proxmox VM/CT networking)
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 1
# Memory protection
kernel.randomize_va_space = 2
kernel.kptr_restrict = 1
# Core dump restrictions
kernel.core_uses_pid = 1
fs.suid_dumpable = 0
# Process restrictions
kernel.dmesg_restrict = 1
kernel.perf_event_paranoid = 3
EOF
# Verify temp file was created and is not empty
if [[ ! -f "${tmp_conf}" ]] || [[ ! -s "${tmp_conf}" ]]; then
log "ERROR" "Temporary sysctl file is empty or not created"
rm -f "${tmp_conf}"
return 1
fi
# Validate syntax (all lines should contain '=' or be comments/empty)
if ! grep -qE '^[a-z].*=.*$' "${tmp_conf}"; then
log "ERROR" "Syntax error in sysctl temp file - no valid entries found"
rm -f "${tmp_conf}"
return 1
fi
# Test the configuration before applying
local test_output
test_output=$(sudo sysctl -p "${tmp_conf}" 2>&1)
local test_exit=$?
if [[ $test_exit -ne 0 ]]; then
log "ERROR" "Sysctl validation failed:"
echo "$test_output" | head -10
rm -f "${tmp_conf}"
# Restore backup if exists
if [[ -f "${BACKUP_DIR}/etc/sysctl.d/99-haqqsec.conf.backup" ]]; then
sudo cp "${BACKUP_DIR}/etc/sysctl.d/99-haqqsec.conf.backup" "$final_conf"
sudo sysctl --system > /dev/null 2>&1
log "INFO" "Restored previous sysctl configuration"
fi
return 1
fi
# Move temp file to final location (atomic)
sudo mkdir -p "$(dirname "$final_conf")"
sudo mv "${tmp_conf}" "${final_conf}"
if [[ $? -ne 0 ]]; then
log "ERROR" "Failed to move sysctl config to final location"
rm -f "${tmp_conf}"
return 1
fi
log "INFO" "Sysctl config applied to ${final_conf}"
# Apply all sysctl settings
if sudo sysctl --system > /dev/null 2>&1; then
log "SUCCESS" "Kernel security parameters configured successfully"
else
log "ERROR" "Failed to apply sysctl settings - restoring backup"
# Restore backup
if [[ -f "${BACKUP_DIR}/etc/sysctl.d/99-haqqsec.conf.backup" ]]; then