-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathdu_setup.sh
More file actions
6207 lines (5565 loc) · 255 KB
/
du_setup.sh
File metadata and controls
6207 lines (5565 loc) · 255 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
# Debian and Ubuntu Server Hardening Interactive Script
# Version: 0.80.5 | 2026-03-26
# Changelog:
# - v0.80.5: Fixed a crash in timezone validation by checking for files (-f) instead of directories.
# Resolved unexpected set -e terminations during 'pretty hostname' assignment and SSH port detection.
# - v0.80.4: Warn and finish the script if Docker, Tailscale and Netbird fail to install properly.
# - v0.80.3: Warn about password-less sudo and offer to generate password for the user if they choose to do so.
# Improve SSH service detection for Debian systems.
# - v0.80.2: Added an optional install of netbird (https://netbird.io/) as an alternative to tailscale.
# - v0.80.1: Added a safety check to trigger the SSH rollback function if user is disconnected during SSH port change, preventing lockout.
# Implement a check for a validated ssh key for the sudo user before revoking root access.
# Perform changes to sshd config in a low-lexical-order file (10-hardening.conf) to minimize risk of conflicts with existing provider configs.
# - v0.80.0: Added 2FA, optionally set 2FA for SSH Login.
# - v0.79.1: Added CrowdSec collections install to CrowdSec setup.
# - v0.79.0: Added CrowdSec, now you can choose between fail2ban and CrowdSec for system level firewall.
# - v0.78.5: Switched to using nano as the default editor in .bashrc.
# - v0.78.4: Improved configure_swap to detect swap partitions vs files.
# Prevents 'fallocate' crashes on physical partitions by offering to disable them or skip.
# - v0.78.3: Update the summary to try to show the right environment detection based on finding personal VMs and cloud VPS.
# Run update & upgrade in the final step to ensure system is fully updated after restart.
# - v0.78.2: In configure_system set chosen hostname from collect_config in the /etc/hosts
# - v0.78.1: Collect config failure fixed on IPv6 only VPS.
# - v0.78: Script tries to handles different environments: Direct Public IP, NAT/Router and Local VM only
# The configure_ssh function provides context-aware instructions based on different environments.
# In setup_user handle if group exists but user doesn't - attach user to existing group.
# - v0.77.2: Fixed an unbound variable for SSH when on a local virtual machine;
# check_dependencies should come before check_system to keep minimal servers from failing.
# - v0.77.1: Auto SSH connection whitelist feat & whitelist deduplication.
# - v0.77: User-configurable ignoreip functionality for configure_fail2ban function.
# Add a few more core packages in install_packages function.
# - v0.76: Improve the flexibility of the built-in Docker daemon.json file to prevent any potential Docker issues.
# - v0.75: Updated Docker daemon.json file to be more secure.
# - v0.74: Add optional dtop (https://github.com/amir20/dtop) after docker installation.
#. Update .bashrc
# - v0.73: Revised/improved logic in .bashrc for memory and system updates.
# - v0.72: Added configure_custom_bashrc() function that creates and installs a feature-rich .bashrc file during user creation.
# - v0.71: Simplify test backup function to work reliably with Hetzner storagebox
# - v0.70.1: Fix SSH port validation and improve firewall handling during SSH port transitions.
# - v0.70: Option to remove cloud VPS provider packages (like cloud-init).
# New operational modes: --cleanup-preview, --cleanup-only, --skip-cleanup.
# Add help and usage instructions with --help flag.
# Improve SSH port validation and rollback logic.
# - v0.69: Ensure .ssh directory ownership is set for new user.
# - v0.68: Enable UFW IPv6 support if available
# - v0.67: Do not log taiscale auth key in log file
# - v0.66: While configuring and in the summary, display both IPv6 and IPv4.
# - v0.65: If reconfigure locales - apply newly configured locale to the current environment.
# - v0.64: Tested at Debian 13 to confirm it works as expected
# - v0.63: Added ssh install in key packages
# - v0.62: Added fix for fail2ban by creating empty ufw log file
# - v0.61: Display Lynis suggestions in summary, hide tailscale auth key, cleanup temp files
# - v0.60: CI for shellcheck
# - v0.59: Add a new optional function that applies a set of recommended sysctl security settings to harden the kernel.
# Script can now check for update and can run self-update.
# - v0.58: improved fail2ban to parse ufw logs
# - v0.57: Fix for silent failure at test_backup()
# Option to choose which directories to back up.
# - v0.56: Make tailscale config optional
# - v0.55: Improving setup_user() - ssh-keygen replaced the option to skip ssh key
# - v0.54: Fix for rollback_ssh_changes() - more reliable on newer Ubuntu
# Better error message if script is executed by non-root or without sudo
# - v0.53: Fix for test_backup() - was failing if run as non root sudo user
# - v0.52: Roll-back SSH config on failure to configure SSH port, confirmed SSH config support for Ubuntu 24.10
# - v0.51: corrected repo links
# - v0.50: versioning format change and repo name change
# - v4.3: Add SHA256 integrity verification
# - v4.2: Added Security Audit Tools (Integrating Lynis and Optionally Debsecan) & option to do Backup Testing
# Fixed debsecan compatibility (Debian-only), added global BACKUP_LOG, added backup testing
# - v4.1: Added tailscale config to connect to tailscale or headscale server
# - v4.0: Added automated backup config. Mainly for Hetzner Storage Box but can be used for any rsync/SSH enabled remote solution.
# - v3.*: Improvements to script flow and fixed bugs which were found in tests at Oracle Cloud
#
# Description:
# This script provisions and hardens a fresh Debian 12 or Ubuntu server with essential security
# configurations, user management, SSH hardening, firewall setup, and optional features
# like Docker and Tailscale and automated backups to Hetzner storage box or any rsync location.
# It is designed to be idempotent, safe.
# README at GitHub: https://github.com/buildplan/du_setup/blob/main/README.md
#
# Prerequisites:
# - Run as root on a fresh Debian 12 or Ubuntu server (e.g., sudo ./du_setup.sh or run as root -E ./du_setup.sh).
# - Internet connectivity is required for package installation.
#
# Usage:
# Download: wget https://raw.githubusercontent.com/buildplan/du_setup/refs/heads/main/du_setup.sh
# Make it executable: chmod +x du_setup.sh
# Run it: sudo -E ./du_setup.sh [--quiet]
#
# Options:
# --quiet: Suppress non-critical output for automation. (Not recommended always best to review all the options)
#
# Notes:
# - The script creates a log file in /var/log/du_setup_*.log.
# - Critical configurations are backed up before modification. Backup files are at /root/setup_harden_backup_*.
# - A new admin user is created with a mandatory password or SSH key for authentication.
# - Root SSH login is disabled; all access is via the new user with sudo privileges.
# - The user will be prompted to select a timezone, swap size, and custom firewall ports.
# - A reboot is recommended at the end to apply all changes.
# - Test the script in a VM before production use.
#
# Troubleshooting:
# - Check the log file for errors if the script fails.
# - If SSH access is lost, use the server console to restore /etc/ssh/sshd_config.backup_*.
# - Ensure sufficient disk space (>2GB) for swap file creation.
set -euo pipefail
# --- Update Configuration ---
CURRENT_VERSION="0.80.5"
SCRIPT_URL="https://raw.githubusercontent.com/buildplan/du_setup/refs/heads/main/du_setup.sh"
CHECKSUM_URL="${SCRIPT_URL}.sha256"
# --- GLOBAL VARIABLES & CONFIGURATION ---
# --- Colors for output ---
if command -v tput >/dev/null 2>&1 && tput setaf 1 >/dev/null 2>&1; then
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW="$(tput bold)$(tput setaf 3)"
BLUE=$(tput setaf 4)
PURPLE=$(tput setaf 5)
CYAN=$(tput setaf 6)
BOLD=$(tput bold)
NC=$(tput sgr0)
else
RED=$'\e[0;31m'
GREEN=$'\e[0;32m'
YELLOW=$'\e[1;33m'
BLUE=$'\e[0;34m'
PURPLE=$'\e[0;35m'
CYAN=$'\e[0;36m'
NC=$'\e[0m'
BOLD=$'\e[1m'
fi
# Script variables
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="/var/log/du_setup_$(date +%Y%m%d_%H%M%S).log"
BACKUP_LOG="/var/log/backup_rsync.log"
REPORT_FILE="/var/log/du_setup_report_$(date +%Y%m%d_%H%M%S).txt"
VERBOSE=true
BACKUP_DIR="/root/setup_harden_backup_$(date +%Y%m%d_%H%M%S)"
ORIGINAL_ARGS="$*"
CLEANUP_PREVIEW=false # If true, show what would be cleaned up without making changes
CLEANUP_ONLY=false # If true, only perform cleanup tasks
SKIP_CLEANUP=false # If true, skip cleanup tasks
DETECTED_VIRT_TYPE=""
DETECTED_MANUFACTURER=""
DETECTED_PRODUCT=""
IS_CONTAINER=false
ENVIRONMENT_TYPE="unknown"
DETECTED_PROVIDER_NAME=""
SERVER_IP_V4="Unknown"
SERVER_IP_V6="Not available"
LOCAL_IP_V4=""
SSHD_BACKUP_FILE=""
LOCAL_KEY_ADDED=false
SSH_SERVICE=""
ID="" # This will be populated from /etc/os-release
FAILED_SERVICES=()
PREVIOUS_SSH_PORT=""
IDS_INSTALLED=""
TWO_FACTOR_ENABLED="false"
DOCKER_INSTALL_WARN=false
DOCKER_SANITY_WARN=false
TAILSCALE_INSTALL_WARN=false
NETBIRD_INSTALL_WARN=false
# --- --help ---
show_usage() {
printf "\n"
printf "%s%s%s\n" "$CYAN" "Debian/Ubuntu Server Setup & Hardening Script" "$NC"
printf "\n%sUsage:%s\n" "$BOLD" "$NC"
printf " sudo -E %s [OPTIONS]\n" "$(basename "$0")"
printf "\n%sDescription:%s\n" "$BOLD" "$NC"
printf " This script provisions a fresh Debian or Ubuntu server with secure base configurations.\n"
printf " It handles updates, firewall, SSH hardening, user creation, and optional tools.\n"
printf "\n%sOperational Modes:%s\n" "$BOLD" "$NC"
printf " %-22s %s\n" "--cleanup-preview" "Show which provider packages/users would be cleaned without making changes."
printf " %-22s %s\n" "--cleanup-only" "Run only the provider cleanup function (for existing servers)."
printf "\n%sModifiers:%s\n" "$BOLD" "$NC"
printf " %-22s %s\n" "--skip-cleanup" "Skip provider cleanup entirely during a full setup run."
printf " %-22s %s\n" "--quiet" "Suppress verbose output (intended for automation)."
printf " %-22s %s\n" "-h, --help" "Display this help message and exit."
printf "\n%sUsage Examples:%s\n" "$BOLD" "$NC"
printf " # Run the full interactive setup\n"
printf " %ssudo -E ./%s%s\n\n" "$YELLOW" "$(basename "$0")" "$NC"
printf " # Preview provider cleanup actions without applying them\n"
printf " %ssudo -E ./%s --cleanup-preview%s\n\n" "$YELLOW" "$(basename "$0")" "$NC"
printf " # Run a full setup but skip the provider cleanup step\n"
printf " %ssudo -E ./%s --skip-cleanup%s\n\n" "$YELLOW" "$(basename "$0")" "$NC"
printf " # Run in quiet mode for automation\n"
printf " %ssudo -E ./%s --quiet%s\n" "$YELLOW" "$(basename "$0")" "$NC"
printf "\n%sImportant Notes:%s\n" "$BOLD" "$NC"
printf " - The -E flag preserves your environment variables (recommended)\n"
printf " - Logs are saved to %s/var/log/du_setup_*.log%s\n" "$BOLD" "$NC"
printf " - Backups of modified configs are in %s/root/setup_harden_backup_*%s\n" "$BOLD" "$NC"
printf " - For full documentation, see the project repository:\n"
printf " %s%s%s\n" "$CYAN" "https://github.com/buildplan/du-setup" "$NC"
printf "\n"
exit 0
}
# --- PARSE ARGUMENTS ---
while [[ $# -gt 0 ]]; do
case $1 in
--quiet) VERBOSE=false; shift ;;
--cleanup-preview) CLEANUP_PREVIEW=true; shift ;;
--cleanup-only) CLEANUP_ONLY=true; shift ;;
--skip-cleanup) SKIP_CLEANUP=true; shift ;;
-h|--help) show_usage ;;
*) shift ;;
esac
done
# --- Root Check ---
if [[ $EUID -ne 0 ]]; then
printf "\n"
printf "%s✗ You are running as user '%s'. This script must be run as root.%s\n" "$RED" "$(whoami)" "$NC"
printf "\n"
printf "This script makes system-level changes including:\n"
printf " - Package installation/removal\n"
printf " - Firewall configuration\n"
printf " - SSH hardening\n"
printf " - User account management\n"
printf "\n"
printf "Choose one of the following methods to run this script:\n"
printf "\n"
printf "%s%sRun with sudo (-E preserves environment):%s\n" "$BOLD" "$GREEN" "$NC"
if [[ -n "$ORIGINAL_ARGS" ]]; then
printf " %ssudo -E %s %s%s\n" "$CYAN" "$0" "$ORIGINAL_ARGS" "$NC"
else
printf " %ssudo -E %s%s\n" "$CYAN" "$0" "$NC"
fi
printf "\n"
printf "%s%sAlternative methods:%s\n" "$BOLD" "$YELLOW" "$NC"
printf " %ssudo su %s # Switch to root\n" "$CYAN" "$NC"
if [[ -n "$ORIGINAL_ARGS" ]]; then
printf " And run: %s%s %s%s\n" "$CYAN" "$0" "$ORIGINAL_ARGS" "$NC"
else
printf " And run: %s%s%s\n" "$CYAN" "$0" "$NC"
fi
printf "\n"
exit 1
fi
# --- LOGGING & PRINT FUNCTIONS ---
log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}
print_header() {
[[ $VERBOSE == false ]] && return
printf '\n'
printf '%s\n' "${CYAN}╔═════════════════════════════════════════════════════════════════╗${NC}"
printf '%s\n' "${CYAN}║ ║${NC}"
printf '%s\n' "${CYAN}║ DEBIAN/UBUNTU SERVER SETUP AND HARDENING SCRIPT ║${NC}"
printf '%s\n' "${CYAN}║ v0.80.5 | 2026-03-26 ║${NC}"
printf '%s\n' "${CYAN}║ ║${NC}"
printf '%s\n' "${CYAN}╚═════════════════════════════════════════════════════════════════╝${NC}"
printf '\n'
}
print_section() {
[[ $VERBOSE == false ]] && return
printf '\n%s\n' "${BLUE}▓▓▓ $1 ▓▓▓${NC}" | tee -a "$LOG_FILE"
printf '%s\n' "${BLUE}$(printf '═%.0s' {1..65})${NC}"
}
print_success() {
[[ $VERBOSE == false ]] && return
printf '%s\n' "${GREEN}✓ $1${NC}" | tee -a "$LOG_FILE"
}
print_error() {
printf '%s\n' "${RED}✗ $1${NC}" | tee -a "$LOG_FILE"
}
print_warning() {
[[ $VERBOSE == false ]] && return
printf '%s\n' "${YELLOW}⚠ $1${NC}" | tee -a "$LOG_FILE"
}
print_info() {
[[ $VERBOSE == false ]] && return
printf '%s\n' "${PURPLE}ℹ $1${NC}" | tee -a "$LOG_FILE"
}
print_separator() {
local header_text="$1"
local color="${2:-$YELLOW}"
local separator_char="${3:-=}"
printf '%s\n' "${color}${header_text}${NC}"
printf "${separator_char}%.0s" $(seq 1 ${#header_text})
printf '\n'
}
# --- CLEANUP HELPER FUNCTIONS ---
execute_check() {
"$@"
}
execute_command() {
local cmd_string="$*"
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
printf '%s Would execute: %s\n' "${CYAN}[PREVIEW]${NC}" "${BOLD}$cmd_string${NC}" | tee -a "$LOG_FILE"
return 0
else
"$@"
return $?
fi
}
# --- ENVIRONMENT DETECTION (Cloud VPS or Trusted VM) ---
detect_environment() {
local VIRT_TYPE=""
local MANUFACTURER=""
local PRODUCT=""
local IS_CLOUD_VPS=false
# systemd-detect-virt
if command -v systemd-detect-virt &>/dev/null; then
VIRT_TYPE=$(systemd-detect-virt 2>/dev/null || echo "none")
fi
# dmidecode for hardware info
if command -v dmidecode &>/dev/null && [[ $(id -u) -eq 0 ]]; then
MANUFACTURER=$(dmidecode -s system-manufacturer 2>/dev/null | tr '[:upper:]' '[:lower:]' || echo "unknown")
PRODUCT=$(dmidecode -s system-product-name 2>/dev/null | tr '[:upper:]' '[:lower:]' || echo "unknown")
fi
# Check /sys/class/dmi/id/ (fallback, doesn't require dmidecode)
if [[ -z "$MANUFACTURER" || "$MANUFACTURER" == "unknown" ]]; then
if [[ -r /sys/class/dmi/id/sys_vendor ]]; then
MANUFACTURER=$(tr '[:upper:]' '[:lower:]' < /sys/class/dmi/id/sys_vendor 2>/dev/null || echo "unknown")
fi
fi
if [[ -z "$PRODUCT" || "$PRODUCT" == "unknown" ]]; then
if [[ -r /sys/class/dmi/id/product_name ]]; then
PRODUCT=$(tr '[:upper:]' '[:lower:]' < /sys/class/dmi/id/product_name 2>/dev/null || echo "unknown")
fi
fi
if command -v dmidecode &>/dev/null && [[ $(id -u) -eq 0 ]]; then
DETECTED_BIOS_VENDOR=$(dmidecode -s bios-vendor 2>/dev/null | tr '[:upper:]' '[:lower:]' || echo "unknown")
elif [[ -r /sys/class/dmi/id/bios_vendor ]]; then
DETECTED_BIOS_VENDOR=$(tr '[:upper:]' '[:lower:]' < /sys/class/dmi/id/bios_vendor 2>/dev/null || echo "unknown")
fi
# Cloud provider detection patterns
local CLOUD_PATTERNS=(
# VPS/Cloud Providers
"digitalocean"
"linode"
"vultr"
"hetzner"
"ovh"
"scaleway"
"contabo"
"netcup"
"ionos"
"hostinger"
"racknerd"
"upcloud"
"dreamhost"
"kimsufi"
"online.net"
"equinix metal"
"lightsail"
"scaleway"
# Major Cloud Platforms
"amazon"
"amazon ec2"
"aws"
"google"
"gce"
"google compute engine"
"microsoft"
"azure"
"oracle cloud"
"alibaba"
"tencent"
"rackspace"
# Virtualization indicating cloud VPS
"droplet"
"linodekvm"
"kvm"
"openstack"
)
# Check if manufacturer or product matches cloud patterns
for pattern in "${CLOUD_PATTERNS[@]}"; do
if [[ "$MANUFACTURER" == *"$pattern"* ]] || [[ "$PRODUCT" == *"$pattern"* ]]; then
IS_CLOUD_VPS=true
break
fi
done
# Additional checks based on virtualization type
case "$VIRT_TYPE" in
kvm|qemu)
if [[ -z "$IS_CLOUD_VPS" ]] || [[ "$IS_CLOUD_VPS" == "false" ]]; then
if [[ -d /etc/cloud/cloud.cfg.d ]] && grep -qE "(Hetzner|DigitalOcean|Vultr|OVH)" /etc/cloud/cloud.cfg.d/* 2>/dev/null; then
IS_CLOUD_VPS=true
fi
fi
;;
vmware)
IS_CLOUD_VPS=false
;;
oracle|virtualbox)
IS_CLOUD_VPS=false
;;
xen)
IS_CLOUD_VPS=true
;;
hyperv|microsoft)
if [[ "$MANUFACTURER" == *"microsoft"* ]] && [[ "$PRODUCT" == *"virtual machine"* ]]; then
IS_CLOUD_VPS=false
fi
;;
none)
IS_CLOUD_VPS=false
;;
esac
# Determine environment type based on detection
if [[ "$VIRT_TYPE" == "none" ]]; then
ENVIRONMENT_TYPE="bare-metal"
elif [[ "$IS_CLOUD_VPS" == "true" ]]; then
ENVIRONMENT_TYPE="commercial-cloud"
elif [[ "$VIRT_TYPE" =~ ^(kvm|qemu)$ ]]; then
if [[ "$MANUFACTURER" == "qemu" && "$PRODUCT" =~ ^(standard pc|pc-|pc ) ]]; then
ENVIRONMENT_TYPE="uncertain-kvm"
else
ENVIRONMENT_TYPE="commercial-cloud"
fi
elif [[ "$VIRT_TYPE" =~ ^(vmware|virtualbox|oracle)$ ]]; then
ENVIRONMENT_TYPE="personal-vm"
elif [[ "$VIRT_TYPE" == "xen" ]]; then
ENVIRONMENT_TYPE="uncertain-xen"
else
ENVIRONMENT_TYPE="unknown"
fi
DETECTED_PROVIDER_NAME=""
case "$ENVIRONMENT_TYPE" in
commercial-cloud)
if [[ "$MANUFACTURER" =~ digitalocean ]]; then
DETECTED_PROVIDER_NAME="DigitalOcean"
elif [[ "$MANUFACTURER" =~ hetzner ]]; then
DETECTED_PROVIDER_NAME="Hetzner Cloud"
elif [[ "$MANUFACTURER" =~ vultr ]]; then
DETECTED_PROVIDER_NAME="Vultr"
elif [[ "$MANUFACTURER" =~ linode || "$PRODUCT" =~ akamai ]]; then
DETECTED_PROVIDER_NAME="Linode/Akamai"
elif [[ "$MANUFACTURER" =~ ovh ]]; then
DETECTED_PROVIDER_NAME="OVH"
elif [[ "$MANUFACTURER" =~ amazon || "$PRODUCT" =~ "ec2" ]]; then
DETECTED_PROVIDER_NAME="Amazon Web Services (AWS)"
elif [[ "$MANUFACTURER" =~ google ]]; then
DETECTED_PROVIDER_NAME="Google Cloud Platform"
elif [[ "$MANUFACTURER" =~ microsoft ]]; then
DETECTED_PROVIDER_NAME="Microsoft Azure"
else
DETECTED_PROVIDER_NAME="Cloud VPS Provider"
fi
;;
personal-vm)
if [[ "$VIRT_TYPE" == "virtualbox" || "$MANUFACTURER" =~ innotek ]]; then
DETECTED_PROVIDER_NAME="VirtualBox"
elif [[ "$VIRT_TYPE" == "vmware" ]]; then
DETECTED_PROVIDER_NAME="VMware"
else
DETECTED_PROVIDER_NAME="Personal VM"
fi
;;
uncertain-kvm)
DETECTED_PROVIDER_NAME="KVM/QEMU Hypervisor"
;;
esac
# Export results as global variables
export ENVIRONMENT_TYPE
DETECTED_VIRT_TYPE="$VIRT_TYPE"
DETECTED_MANUFACTURER="$MANUFACTURER"
DETECTED_PRODUCT="$PRODUCT"
DETECTED_BIOS_VENDOR="${DETECTED_BIOS_VENDOR:-unknown}"
log "Environment detection: VIRT=$VIRT_TYPE, MANUFACTURER=$MANUFACTURER, PRODUCT=$PRODUCT, IS_CLOUD=$IS_CLOUD_VPS, TYPE=$ENVIRONMENT_TYPE"
}
cleanup_provider_packages() {
print_section "Provider Package Cleanup (Optional)"
# --quiet mode check
if [[ "$VERBOSE" == "false" ]]; then
print_warning "Provider cleanup cannot be run in --quiet mode due to its interactive nature. Skipping."
log "Provider cleanup skipped due to --quiet mode."
return 0
fi
# Validate required variables
if [[ -z "${LOG_FILE:-}" ]]; then
LOG_FILE="/var/log/du_setup_$(date +%Y%m%d_%H%M%S).log"
echo "Warning: LOG_FILE not set, using: $LOG_FILE"
fi
if [[ -z "${USERNAME:-}" ]]; then
USERNAME="${SUDO_USER:-root}"
log "USERNAME defaulted to '$USERNAME' for cleanup-only mode"
fi
if [[ -z "${BACKUP_DIR:-}" ]]; then
BACKUP_DIR="/root/setup_harden_backup_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"
log "Created backup directory: $BACKUP_DIR"
fi
# Ensure cleanup mode variables are set
CLEANUP_PREVIEW="${CLEANUP_PREVIEW:-false}"
CLEANUP_ONLY="${CLEANUP_ONLY:-false}"
VERBOSE="${VERBOSE:-true}"
# Detect environment first
detect_environment
# Display environment information
printf '%s\n' "${CYAN}=== Environment Detection ===${NC}"
printf 'Virtualization Type: %s\n' "${DETECTED_VIRT_TYPE:-unknown}"
printf 'System Manufacturer: %s\n' "${DETECTED_MANUFACTURER:-unknown}"
printf 'Product Name: %s\n' "${DETECTED_PRODUCT:-unknown}"
printf 'Environment Type: %s\n' "${ENVIRONMENT_TYPE:-unknown}"
if [[ -n "${DETECTED_BIOS_VENDOR}" && "${DETECTED_BIOS_VENDOR}" != "unknown" ]]; then
printf 'BIOS Vendor: %s\n' "${DETECTED_BIOS_VENDOR}"
fi
if [[ -n "${DETECTED_PROVIDER_NAME}" ]]; then
printf 'Detected Provider: %s\n' "${DETECTED_PROVIDER_NAME}"
fi
printf '\n'
# Determine recommendation based on three-way detection
local CLEANUP_RECOMMENDED=false
local DEFAULT_ANSWER="n"
local RECOMMENDATION_TEXT=""
local ENVIRONMENT_CONFIDENCE="${ENVIRONMENT_CONFIDENCE:-low}"
case "$ENVIRONMENT_TYPE" in
commercial-cloud)
CLEANUP_RECOMMENDED=true
DEFAULT_ANSWER="y"
printf '%s\n' "${YELLOW}☁ Commercial Cloud VPS Detected${NC}"
if [[ -n "${DETECTED_PROVIDER_NAME}" ]]; then
printf 'Provider: %s\n' "${CYAN}${DETECTED_PROVIDER_NAME}${NC}"
fi
printf 'This is a commercial VPS from an external provider.\n'
RECOMMENDATION_TEXT="Provider cleanup is ${BOLD}RECOMMENDED${NC} for security."
printf '%s\n' "$RECOMMENDATION_TEXT"
printf 'Providers may install monitoring agents, pre-configured users, and management tools.\n'
;;
uncertain-kvm)
CLEANUP_RECOMMENDED=false
DEFAULT_ANSWER="n"
printf '%s\n' "${YELLOW}⚠ KVM/QEMU Virtualization Detected (Uncertain)${NC}"
printf 'This environment could be:\n'
printf ' %s A commercial cloud provider VPS (Hetzner, Vultr, OVH, smaller providers)\n' "${CYAN}•${NC}"
printf ' %s A personal VM on Proxmox, KVM, or QEMU\n' "${CYAN}•${NC}"
printf ' %s A VPS from a regional/unlisted provider\n' "${CYAN}•${NC}"
printf '\n'
RECOMMENDATION_TEXT="Cleanup is ${BOLD}OPTIONAL${NC} - review packages carefully before proceeding."
printf '%s\n' "$RECOMMENDATION_TEXT"
printf 'If this is a commercial VPS, cleanup is recommended.\n'
printf 'If you control the hypervisor (Proxmox/KVM), cleanup is optional.\n'
;;
personal-vm)
CLEANUP_RECOMMENDED=false
DEFAULT_ANSWER="n"
printf '%s\n' "${CYAN}ℹ Personal/Private Virtualization Detected${NC}"
if [[ -n "${DETECTED_PROVIDER_NAME}" ]]; then
printf 'Platform: %s\n' "${CYAN}${DETECTED_PROVIDER_NAME}${NC}"
fi
printf 'This appears to be a personal VM (VirtualBox, VMware Workstation, etc.)\n'
RECOMMENDATION_TEXT="Provider cleanup is ${BOLD}NOT RECOMMENDED${NC} for trusted environments."
printf '%s\n' "$RECOMMENDATION_TEXT"
printf 'If you control the hypervisor/host, you likely don'\''t need cleanup.\n'
;;
bare-metal)
printf '%s\n' "${GREEN}✓ Bare Metal Server Detected${NC}"
printf 'This appears to be a physical (bare metal) server.\n'
RECOMMENDATION_TEXT="Provider cleanup is ${BOLD}NOT NEEDED${NC} for bare metal."
printf '%s\n' "$RECOMMENDATION_TEXT"
printf 'No virtualization layer detected - skipping cleanup.\n'
log "Provider package cleanup skipped: bare metal server detected."
return 0
;;
uncertain-xen|unknown|*)
CLEANUP_RECOMMENDED=false
DEFAULT_ANSWER="n"
printf '%s\n' "${YELLOW}⚠ Virtualization Environment: Uncertain${NC}"
printf 'Could not definitively identify the hosting provider or environment.\n'
RECOMMENDATION_TEXT="Cleanup is ${BOLD}OPTIONAL${NC} - proceed with caution."
printf '%s\n' "$RECOMMENDATION_TEXT"
printf 'Review packages carefully before removing anything.\n'
;;
esac
printf '\n'
# Decision point based on environment and flags
if [[ "$CLEANUP_PREVIEW" == "false" ]] && [[ "$CLEANUP_ONLY" == "false" ]]; then
local PROMPT_TEXT=""
if [[ "$ENVIRONMENT_TYPE" == "commercial-cloud" ]]; then
PROMPT_TEXT="Run provider package cleanup? (Recommended for cloud VPS)"
elif [[ "$ENVIRONMENT_TYPE" == "uncertain-kvm" ]]; then
PROMPT_TEXT="Run provider package cleanup? (Verify your environment first)"
else
PROMPT_TEXT="Run provider package cleanup? (Not recommended for trusted environments)"
fi
if ! confirm "$PROMPT_TEXT" "$DEFAULT_ANSWER"; then
print_info "Skipping provider package cleanup."
log "Provider package cleanup skipped by user (environment: $ENVIRONMENT_TYPE)."
return 0
fi
# Extra warning for non-cloud environments
if [[ "$CLEANUP_RECOMMENDED" == "false" ]] && [[ "$ENVIRONMENT_TYPE" != "uncertain-kvm" ]]; then
echo
print_warning "⚠ You chose to run cleanup on a trusted/personal environment."
print_warning "This may remove useful tools or break functionality."
echo
if ! confirm "Are you sure you want to continue?" "n"; then
print_info "Cleanup cancelled."
log "User cancelled cleanup after warning."
return 0
fi
fi
fi
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_warning "=== PREVIEW MODE ENABLED ==="
print_info "No changes will be made. This is a simulation only."
printf '\n'
fi
if [[ "$CLEANUP_PREVIEW" == "false" ]]; then
print_warning "RECOMMENDED: Create a snapshot/backup via provider dashboard before cleanup."
if ! confirm "Have you created a backup snapshot?" "n"; then
print_info "Please create a backup first. Exiting cleanup."
log "User declined to proceed without backup snapshot."
return 0
fi
fi
print_warning "This will identify packages and configurations installed by your VPS provider."
if [[ "$CLEANUP_PREVIEW" == "false" ]]; then
print_warning "Removing critical packages can break system functionality."
fi
local PROVIDER_PACKAGES=()
local PROVIDER_SERVICES=()
local PROVIDER_USERS=()
local ROOT_SSH_KEYS=()
# List of common provider and virtualization packages
local COMMON_PROVIDER_PKGS=(
"qemu-guest-agent"
"virtio-utils"
"virt-what"
"cloud-init"
"cloud-guest-utils"
"cloud-initramfs-growroot"
"cloud-utils"
"open-vm-tools"
"xe-guest-utilities"
"xen-tools"
"hyperv-daemons"
"oracle-cloud-agent"
"aws-systems-manager-agent"
"amazon-ssm-agent"
"google-compute-engine"
"google-osconfig-agent"
"walinuxagent"
"hetzner-needrestart"
"digitalocean-agent"
"do-agent"
"linode-agent"
"vultr-monitoring"
"scaleway-ecosystem"
"ovh-rtm"
"openstack-guest-utils"
"openstack-nova-agent"
)
# Common provider-created default users
local COMMON_PROVIDER_USERS=(
"ubuntu"
"debian"
"admin"
"cloud-user"
"ec2-user"
"linuxuser"
)
print_info "Scanning for provider-installed packages..."
for pkg in "${COMMON_PROVIDER_PKGS[@]}"; do
if execute_check dpkg -l "$pkg" 2>/dev/null | grep -q '^ii'; then
PROVIDER_PACKAGES+=("$pkg")
fi
done
# Detect associated services
print_info "Scanning for provider-related services..."
for pkg in "${PROVIDER_PACKAGES[@]}"; do
local service_name="${pkg}.service"
if execute_check systemctl list-unit-files "$service_name" 2>/dev/null | grep -q "$service_name"; then
if execute_check systemctl is-enabled "$service_name" 2>/dev/null | grep -qE 'enabled|static'; then
PROVIDER_SERVICES+=("$service_name")
fi
fi
done
# Check for provider-created users (excluding current admin user and script-managed user)
print_info "Scanning for default provisioning users..."
local MANAGED_USER=""
if [[ -f /root/.du_setup_managed_user ]]; then
MANAGED_USER=$(tr -d '[:space:]' < /root/.du_setup_managed_user 2>/dev/null)
log "Script-managed user detected: $MANAGED_USER (will be excluded from cleanup)"
fi
for user in "${COMMON_PROVIDER_USERS[@]}"; do
if execute_check id "$user" &>/dev/null && \
[[ "$user" != "$USERNAME" ]] && \
[[ "$user" != "$MANAGED_USER" ]]; then
PROVIDER_USERS+=("$user")
fi
done
# Audit root SSH keys
print_info "Auditing /root/.ssh/authorized_keys for unexpected keys..."
if [[ -f /root/.ssh/authorized_keys ]]; then
local key_count
key_count=$( (grep -cE '^ssh-(rsa|ed25519|ecdsa)' /root/.ssh/authorized_keys 2>/dev/null || echo 0) | tr -dc '0-9' )
if [ "$key_count" -gt 0 ]; then
print_warning "Found $key_count SSH key(s) in /root/.ssh/authorized_keys"
ROOT_SSH_KEYS=("present")
fi
fi
# Summary of findings
echo
print_info "=== Scan Results ==="
echo "Packages found: ${#PROVIDER_PACKAGES[@]}"
echo "Services found: ${#PROVIDER_SERVICES[@]}"
echo "Default users found: ${#PROVIDER_USERS[@]}"
echo "Root SSH keys: ${#ROOT_SSH_KEYS[@]}"
echo
if [[ ${#PROVIDER_PACKAGES[@]} -eq 0 && ${#PROVIDER_USERS[@]} -eq 0 && ${#ROOT_SSH_KEYS[@]} -eq 0 ]]; then
print_success "No common provider packages or users detected."
return 0
fi
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_info "=== PREVIEW: Showing what would be done ==="
printf '\n'
fi
# Audit and optionally clean up root SSH keys
if [[ ${#ROOT_SSH_KEYS[@]} -gt 0 ]]; then
print_section "Root SSH Key Audit"
print_warning "SSH keys in /root/.ssh/authorized_keys can allow provider or previous admins access."
printf '\n'
printf '%s\n' "${YELLOW}Current keys in /root/.ssh/authorized_keys:${NC}"
awk '{print NR". "$0}' /root/.ssh/authorized_keys 2>/dev/null | head -20
printf '\n'
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_info "[PREVIEW] Would offer to review and edit /root/.ssh/authorized_keys"
print_info "[PREVIEW] Would backup to $BACKUP_DIR/root_authorized_keys.backup.<timestamp>"
else
if confirm "Review and potentially remove root SSH keys?" "n"; then
local backup_file
backup_file="$BACKUP_DIR/root_authorized_keys.backup.$(date +%Y%m%d_%H%M%S)"
cp /root/.ssh/authorized_keys "$backup_file"
log "Backed up /root/.ssh/authorized_keys to $backup_file"
print_warning "IMPORTANT: Do NOT delete ALL keys or you'll be locked out!"
print_info "Opening /root/.ssh/authorized_keys for manual review..."
read -rp "Press Enter to continue..."
"${EDITOR:-nano}" /root/.ssh/authorized_keys
if [[ ! -s /root/.ssh/authorized_keys ]]; then
print_error "WARNING: authorized_keys is empty! This could lock you out."
if [[ -f "$backup_file" ]] && confirm "Restore from backup?" "y"; then
cp "$backup_file" /root/.ssh/authorized_keys
print_info "Restored backup."
log "Restored /root/.ssh/authorized_keys from backup due to empty file."
fi
fi
local new_key_count
new_key_count=$(grep -cE '^ssh-(rsa|ed25519|ecdsa)' /root/.ssh/authorized_keys 2>/dev/null || echo 0)
print_info "Keys remaining: $new_key_count"
log "Root SSH keys audit completed. Keys remaining: $new_key_count"
else
print_info "Skipping root SSH key audit."
fi
fi
printf '\n'
fi
# Special handling for cloud-init due to its complexity
if [[ " ${PROVIDER_PACKAGES[*]} " =~ " cloud-init " ]]; then
print_section "Cloud-Init Management"
printf '%s\n' "${CYAN}ℹ cloud-init${NC}"
printf ' Purpose: Initial VM provisioning (SSH keys, hostname, network)\n'
printf ' %s\n' "${YELLOW}Official recommendation: DISABLE rather than remove${NC}"
printf ' Benefits of disabling vs removing:\n'
printf ' - Can be re-enabled if needed for reprovisioning\n'
printf ' - Safer than package removal\n'
printf ' - No dependency issues\n'
printf '\n'
if [[ "$CLEANUP_PREVIEW" == "true" ]] || confirm "Disable cloud-init (recommended over removal)?" "y"; then
print_info "Disabling cloud-init..."
if ! [[ -f /etc/cloud/cloud-init.disabled ]]; then
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_info "[PREVIEW] Would create /etc/cloud/cloud-init.disabled"
else
execute_command touch /etc/cloud/cloud-init.disabled
print_success "Created /etc/cloud/cloud-init.disabled"
log "Created /etc/cloud/cloud-init.disabled"
fi
else
print_info "/etc/cloud/cloud-init.disabled already exists."
fi
local cloud_services=(
"cloud-init.service"
"cloud-init-local.service"
"cloud-config.service"
"cloud-final.service"
)
for service in "${cloud_services[@]}"; do
if execute_check systemctl is-enabled "$service" &>/dev/null; then
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_info "[PREVIEW] Would stop and disable $service"
else
execute_command systemctl stop "$service" 2>/dev/null || true
execute_command systemctl disable "$service" 2>/dev/null || true
print_success "Disabled $service"
log "Disabled $service"
fi
fi
done
if [[ "$CLEANUP_PREVIEW" == "false" ]]; then
print_success "cloud-init disabled successfully."
print_info "To re-enable: sudo rm /etc/cloud/cloud-init.disabled && systemctl enable cloud-init.service"
fi
local filtered_packages=()
for pkg in "${PROVIDER_PACKAGES[@]}"; do
if [[ "$pkg" != "cloud-init" && -n "$pkg" ]]; then
filtered_packages+=("$pkg")
fi
done
PROVIDER_PACKAGES=("${filtered_packages[@]}")
else
print_info "Keeping cloud-init enabled."
fi
printf '\n'
fi
# Remove identified provider packages
if [[ ${#PROVIDER_PACKAGES[@]} -gt 0 ]]; then
print_section "Provider Package Removal"
for pkg in "${PROVIDER_PACKAGES[@]}"; do
[[ -z "$pkg" ]] && continue
case "$pkg" in
qemu-guest-agent)
printf '%s\n' "${RED}⚠ $pkg${NC}"
printf ' Purpose: VM-host communication for snapshots and graceful shutdowns\n'
printf ' %s\n' "${RED}CRITICAL RISKS if removed:${NC}"
printf ' - Snapshot backups will FAIL or be inconsistent\n'
printf ' - Console access may break\n'
printf ' - Graceful shutdowns replaced with forced stops\n'
printf ' - Provider backup systems will malfunction\n'
printf ' %s\n' "${RED}STRONGLY RECOMMENDED to keep${NC}"
;;
*-agent|*-monitoring)
printf '%s\n' "${YELLOW}⚠ $pkg${NC}"
printf ' Purpose: Provider monitoring/management\n'
printf ' Risks if removed:\n'
printf ' - Provider dashboard metrics will disappear\n'
printf ' - May affect support troubleshooting\n'
printf ' %s\n' "${YELLOW}Remove only if you don't need provider monitoring${NC}"
;;
*)
printf '%s\n' "${CYAN}ℹ $pkg${NC}"
printf ' Purpose: Provider-specific tooling\n'
printf ' %s\n' "${YELLOW}Review before removing${NC}"
;;
esac
printf '\n'
if [[ "$CLEANUP_PREVIEW" == "true" ]] || confirm "Remove $pkg?" "n"; then
if [[ "$pkg" == "qemu-guest-agent" && "$CLEANUP_PREVIEW" == "false" ]]; then
print_error "FINAL WARNING: Removing qemu-guest-agent will break backups and console access!"
if ! confirm "Are you ABSOLUTELY SURE?" "n"; then
print_info "Keeping $pkg (wise choice)."
continue
fi
fi
local service_name="${pkg}.service"
if execute_check systemctl is-active "$service_name" &>/dev/null; then
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_info "[PREVIEW] Would stop and disable $service_name"
else
print_info "Stopping $service_name..."
execute_command systemctl stop "$service_name" 2>/dev/null || true
execute_command systemctl disable "$service_name" 2>/dev/null || true
log "Stopped and disabled $service_name"
fi
fi
if [[ "$CLEANUP_PREVIEW" == "true" ]]; then
print_info "[PREVIEW] Would remove package: $pkg (with --purge flag)"
log "[PREVIEW] Would remove provider package: $pkg"
else
print_info "Removing $pkg..."
if execute_command apt-get remove --purge -y "$pkg" 2>&1 | tee -a "$LOG_FILE"; then
print_success "$pkg removed."
log "Removed provider package: $pkg"
else
print_error "Failed to remove $pkg. Check logs."
log "Failed to remove: $pkg"
fi
fi
else
print_info "Keeping $pkg."
fi
done
printf '\n'
fi
# Check and remove default users
if [[ ${#PROVIDER_USERS[@]} -gt 0 ]]; then
print_section "Provider User Cleanup"
print_warning "Default users created during provisioning can be security risks."
printf '\n'
for user in "${PROVIDER_USERS[@]}"; do
printf '%s\n' "${YELLOW}Found user: $user${NC}"
local proc_count
proc_count=$( (ps -u "$user" --no-headers 2>/dev/null || true) | wc -l)
if [[ $proc_count -gt 0 ]]; then
print_warning "User $user has $proc_count running process(es)."
fi
if [[ -d "/home/$user" ]] && [[ -f "/home/$user/.ssh/authorized_keys" ]]; then
local key_count=0
key_count=$( (grep -cE '^ssh-(rsa|ed25519|ecdsa)' "/home/$user/.ssh/authorized_keys" 2>/dev/null || echo 0) | tr -dc '0-9' )
if [ "$key_count" -gt 0 ]; then
print_warning "User $user has $key_count SSH key(s) configured."