-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththe-too-complicated-hardening2.0.sh
More file actions
2034 lines (1696 loc) · 57.4 KB
/
the-too-complicated-hardening2.0.sh
File metadata and controls
2034 lines (1696 loc) · 57.4 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
set -euo pipefail
# Script Variables
SCRIPT_PATH=$(mktemp)
trap 'rm -f "$SCRIPT_PATH"' EXIT
SCRIPT_VERSION="1.1"
LOCK_FILE="/var/run/system_hardening.lock"
LOG_FILE="/var/log/system_hardening.log"
BACKUP_DIR="/root/system_hardening_backups/$(date +%Y%m%d_%H%M%S)"
validate_user() {
local username=$1
# Check if username is empty
if [[ -z "$username" ]]; then
return 1
fi
# Check if user exists
if ! id "$username" >/dev/null 2>&1; then
return 1
fi
# Check if home directory exists
local user_home
user_home=$(getent passwd "$username" | cut -d: -f6)
if [[ ! -d "$user_home" ]]; then
return 1
fi
return 0
}
get_user_shell() {
local username=$1
getent passwd "$username" | cut -d: -f7
}
is_system_user() {
local username=$1
local uid
uid=$(id -u "$username")
[[ "$uid" -lt 1000 ]]
}
install_prerequisites() {
log "INFO" "Installing prerequisites..."
apt-get update || {
log "ERROR" "Failed to update package lists"
return 1
}
if ! apt-get install -y wget curl systemd; then
log "ERROR" "Failed to install prerequisites"
return 1
fi
# Verify systemd is running
if ! command -v systemd-detect-virt >/dev/null 2>&1 || ! systemd-detect-virt --container | grep -q "lxc"; then
if ! pidof systemd >/dev/null 2>&1; then
log "WARNING" "systemd installed but not running. A system reboot is required."
echo "System needs to be rebooted to complete systemd installation."
read -r -p "Would you like to reboot now? (y/n): " response
if [[ "$response" =~ ^[Yy]$ ]]; then
log "INFO" "Rebooting system..."
reboot
else
log "ERROR" "Cannot continue without systemd running"
return 1
fi
fi
fi
log "INFO" "All prerequisites are installed"
return 0
}
# System Requirements
MIN_RAM_MB=400
MIN_DISK_MB=400
MIN_SWAP_MB=400
if systemd-detect-virt --container | grep -q "lxc"; then
REQUIRED_COMMANDS=(wget curl ping)
else
REQUIRED_COMMANDS=(systemctl wget curl ping)
fi
# Trap handlers
trap 'handle_error $LINENO' ERR
trap 'cleanup' EXIT
# Core Functions
handle_error() {
local exit_code=$?
local line_no=$1
log "ERROR" "Script failed at line ${line_no} with exit code ${exit_code}"
log "ERROR" "Command: $(sed -n ${line_no}p "$SCRIPT_PATH")"
log "ERROR" "Starting cleanup and rollback procedures..."
cleanup
exit "$exit_code"
}
cleanup() {
log "INFO" "Performing cleanup..."
rm -f "$LOCK_FILE"
[[ -d /tmp/system_hardening ]] && rm -rf /tmp/system_hardening
log "INFO" "Cleanup completed"
}
log() {
local level=$1; shift
local msg="[$(date +'%Y-%m-%d %H:%M:%S')] [$level] $*"
echo "$msg" | tee -a "$LOG_FILE"
# Send critical errors to syslog
if [[ "$level" == "ERROR" ]]; then
logger -p user.err "System Hardening: $*"
fi
}
create_backup() {
local file=$1
if [[ ! -f "$file" ]]; then
log "WARNING" "Cannot backup $file - file does not exist"
return 0
fi
mkdir -p "$BACKUP_DIR" || {
log "ERROR" "Failed to create backup directory"
return 1
}
local backup_file="$BACKUP_DIR/$(basename "$file")"
if ! cp -p "$file" "$backup_file"; then
log "ERROR" "Failed to create backup of $file"
return 1
fi
if ! cmp -s "$file" "$backup_file"; then
log "ERROR" "Backup verification failed for $file"
return 1
fi
log "INFO" "Successfully backed up $file to $backup_file"
return 0
}
check_requirements() {
log "INFO" "Checking system requirements..."
# Check for required commands
for cmd in "${REQUIRED_COMMANDS[@]}"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
log "ERROR" "Required command '$cmd' not found"
exit 1
fi
done
# Check if running as root
if [[ "$EUID" -ne 0 ]]; then
log "ERROR" "This script must be run as root"
exit 1
fi
# Modify systemd check to handle LXC
if systemd-detect-virt --container | grep -q "lxc"; then
log "INFO" "Running in LXC container - skipping systemd check"
else
if ! pidof systemd >/dev/null 2>&1; then
log "ERROR" "systemd is required but not running"
exit 1
fi
fi
}
check_system() {
log "INFO" "Performing system checks..."
check_interactive
# Memory check
local available_mem=$(free -m | awk '/^Mem:/{print $7}')
if (( available_mem < MIN_RAM_MB )); then
log "WARNING" "Less than ${MIN_RAM_MB}MB RAM available (Current: ${available_mem}MB)"
read -r -p "Continue despite low memory? (y/n): " response
[[ ! "$response" =~ ^[Yy]$ ]] && exit 1
fi
# Disk space check
local free_space=$(df -m / | awk 'NR==2 {print $4}')
if (( free_space < MIN_DISK_MB )); then
log "WARNING" "Less than ${MIN_DISK_MB}MB disk space available (Current: ${free_space}MB)"
read -r -p "Continue despite low disk space? (y/n): " response
[[ ! "$response" =~ ^[Yy]$ ]] && exit 1
fi
# CPU check
local cpu_cores=$(nproc)
if (( cpu_cores < 2 )); then
log "WARNING" "System has limited CPU resources (Cores: ${cpu_cores})"
read -r -p "Continue with limited CPU resources? (y/n): " response
[[ ! "$response" =~ ^[Yy]$ ]] && exit 1
fi
# Swap check
local swap_available=$(free -m | awk '/^Swap:/{print $2}')
if (( swap_available < MIN_SWAP_MB )); then
log "WARNING" "Limited swap space available (Current: ${swap_available}MB)"
read -r -p "Continue with limited swap? (y/n): " response
[[ ! "$response" =~ ^[Yy]$ ]] && exit 1
fi
# Network connectivity check (multiple DNS servers)
local dns_servers=("8.8.8.8" "1.1.1.1" "8.8.4.4")
local connected=false
for dns in "${dns_servers[@]}"; do
if ping -c 1 -W 5 "$dns" >/dev/null 2>&1; then
connected=true
break
fi
done
if ! $connected; then
log "ERROR" "No internet connectivity detected"
exit 1
fi
}
detect_os() {
if [[ -f /etc/os-release ]]; then
. /etc/os-release
OS=$ID
OS_VERSION=$VERSION_ID
log "INFO" "Detected OS: $OS $OS_VERSION"
else
log "ERROR" "Cannot detect OS version"
exit 1
fi
# Verify supported OS
case "$OS" in
ubuntu|debian)
;;
*)
log "ERROR" "Unsupported OS: $OS"
exit 1
;;
esac
}
check_interactive() {
if [[ ! -t 0 ]]; then
log "ERROR" "This script must be run interactively. Please run: bash -i /tmp/hardening.sh"
exit 1
fi
}
fix_locale() {
log "INFO" "Fixing locale settings..."
# Check if locales are properly generated
if ! locale -a | grep -q "en_US.utf8"; then
log "INFO" "Generating en_US.UTF-8 locale..."
echo "en_US.UTF-8 UTF-8" > /etc/locale.gen
locale-gen
fi
# Set correct environment variables
cat > /etc/default/locale <<EOF
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
LANGUAGE=en_US:en
EOF
# Export for current session
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
export LANGUAGE=en_US:en
# Source the new settings
. /etc/default/locale
log "INFO" "Locale settings updated"
}
verify_changes() {
local file=$1
local expected_content=$2
if [[ ! -f "$file" ]]; then
log "ERROR" "Configuration file $file does not exist"
return 1
fi
if ! grep -q "$expected_content" "$file"; then
log "ERROR" "Configuration verification failed for $file"
return 1
fi
log "INFO" "Configuration verified for $file"
return 0
}
# Script initialization
log "INFO" "Starting system hardening script v${SCRIPT_VERSION}"
# Check for existing lock file
if [[ -f "$LOCK_FILE" ]]; then
log "ERROR" "Another instance of the script is running"
exit 1
fi
# Create lock file with error handling
if ! touch "$LOCK_FILE" 2>/dev/null; then
log "ERROR" "Cannot create lock file at $LOCK_FILE. Check permissions."
exit 1
fi
# Create log directory with error handling
if ! mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null; then
log "ERROR" "Cannot create log directory at $(dirname "$LOG_FILE"). Check permissions."
rm -f "$LOCK_FILE"
exit 1
fi
install_prerequisites || exit 1
# Initial checks
check_requirements
check_system
detect_os
check_interactive
fix_locale
# Package Management Functions
install_package() {
local package=$1
local max_attempts=3
local attempt=1
while (( attempt <= max_attempts )); do
log "INFO" "Installing package $package (Attempt $attempt/$max_attempts)"
if ! dpkg -l | grep -q "^ii.*$package"; then
if apt-get install -y "$package" 2>/dev/null; then
log "INFO" "Successfully installed $package"
return 0
else
log "WARNING" "Failed to install $package on attempt $attempt"
(( attempt++ ))
sleep 5
fi
else
log "INFO" "Package $package is already installed"
return 0
fi
done
log "ERROR" "Failed to install package $package after $max_attempts attempts"
return 1
}
update_system() {
log "INFO" "Updating package lists..."
if ! apt-get update; then
log "ERROR" "Failed to update package lists"
return 1
fi
log "INFO" "Upgrading installed packages..."
if ! apt-get upgrade -y; then
log "ERROR" "Failed to upgrade packages"
return 1
fi
log "INFO" "Performing distribution upgrade..."
if ! apt-get dist-upgrade -y; then
log "ERROR" "Failed to perform distribution upgrade"
return 1
fi
log "INFO" "Removing unused packages..."
apt-get autoremove -y
apt-get clean
return 0
}
# Add SSH keys for users
configure_ssh_keys() {
local user_home=$1
local username=$(basename "$user_home")
local auth_keys_file="$user_home/.ssh/authorized_keys"
# Initialize temp_key_file at the beginning
local temp_key_file=""
# Skip root user
[[ "$username" == "root" ]] && return 0
# Skip if not a valid home directory
[[ ! -d "$user_home" ]] && return 0
log "INFO" "Checking SSH keys for user: $username"
# Create .ssh directory if it doesn't exist
if [[ ! -d "$user_home/.ssh" ]]; then
mkdir -p "$user_home/.ssh"
chmod 700 "$user_home/.ssh"
chown "$username:$username" "$user_home/.ssh"
fi
# Check for existing authorized_keys
if [[ ! -f "$auth_keys_file" ]]; then
log "INFO" "No authorized_keys file found for user: $username"
read -r -p "Do you want to add an SSH key for user $username? (y/n): " add_key
if [[ "$add_key" =~ ^[Yy]$ ]]; then
# Create temporary file for key input
local temp_key_file
temp_key_file=$(mktemp) || {
log "ERROR" "Failed to create temporary file for key input"
return 1
}
# Cleanup handler for temporary file
trap 'rm -f "$temp_key_file"' RETURN
echo "Please paste the SSH public key for user $username (press Ctrl+D when done):"
cat > "$temp_key_file"
# Validate SSH key format
if ! ssh-keygen -l -f "$temp_key_file" >/dev/null 2>&1; then
log "ERROR" "Invalid SSH key format provided for user $username"
return 1
fi
# Create authorized_keys with proper permissions
cat "$temp_key_file" > "$auth_keys_file"
chmod 600 "$auth_keys_file"
chown "$username:$username" "$auth_keys_file"
log "INFO" "SSH key added successfully for user $username"
# Display key fingerprint for verification
local key_fingerprint
key_fingerprint=$(ssh-keygen -l -f "$auth_keys_file")
log "INFO" "Key fingerprint: $key_fingerprint"
# Ask for verification
read -r -p "Does this key fingerprint look correct? (y/n): " verify_key
if [[ ! "$verify_key" =~ ^[Yy]$ ]]; then
log "WARNING" "Removing added key based on user verification"
rm -f "$auth_keys_file"
return 1
fi
else
log "INFO" "Skipping SSH key configuration for user $username"
fi
else
log "INFO" "Existing authorized_keys file found for user $username"
# Display existing key fingerprints
log "INFO" "Existing key fingerprints:"
while read -r key; do
[[ -n "$key" && "$key" != \#* ]] && {
echo "$key" | ssh-keygen -l -f - 2>/dev/null || \
log "WARNING" "Invalid key found in authorized_keys"
}
done < "$auth_keys_file"
# Option to add additional key
read -r -p "Do you want to add an additional SSH key for user $username? (y/n): " add_key
if [[ "$add_key" =~ ^[Yy]$ ]]; then
echo "Please paste the additional SSH public key (press Ctrl+D when done):"
local temp_key_file
temp_key_file=$(mktemp) || {
log "ERROR" "Failed to create temporary file for key input"
return 1
}
trap 'rm -f "$temp_key_file"' RETURN
cat > "$temp_key_file"
# Validate new key
if ! ssh-keygen -l -f "$temp_key_file" >/dev/null 2>&1; then
log "ERROR" "Invalid SSH key format provided"
return 1
fi
# Check for duplicate keys
if grep -qf "$temp_key_file" "$auth_keys_file"; then
log "WARNING" "This key is already present in authorized_keys"
return 1
fi
# Append new key
cat "$temp_key_file" >> "$auth_keys_file"
chmod 600 "$auth_keys_file"
chown "$username:$username" "$auth_keys_file"
log "INFO" "Additional SSH key added successfully"
fi
fi
return 0
}
configure_user_environment() {
local user_home=$1
local username=$(basename "$user_home")
log "INFO" "Configuring environment for user: $username"
# Skip if not a valid home directory
[[ ! -d "$user_home" ]] && {
log "WARNING" "Invalid home directory for user: $username"
return 0
}
# Backup existing configuration files
local config_files=(
"$user_home/.bashrc"
"$user_home/.bash_profile"
"$user_home/.profile"
)
for file in "${config_files[@]}"; do
if [[ -f "$file" ]]; then
create_backup "$file" || {
log "WARNING" "Failed to backup $file"
continue
}
fi
done
# Configure bash environment
if [[ -f "$user_home/.bashrc" ]]; then
# Configure color prompt
if grep -q "^#force_color_prompt=yes" "$user_home/.bashrc"; then
sed -i 's/^#force_color_prompt=yes/force_color_prompt=yes/' "$user_home/.bashrc"
elif ! grep -q "^force_color_prompt=yes" "$user_home/.bashrc"; then
echo "force_color_prompt=yes" >> "$user_home/.bashrc"
fi
# Configure PS1 prompt based on user and OS
local PS1_CONFIG
if [[ "$username" == "root" ]]; then
PS1_CONFIG='\[\033[01;31m\]\u\[\033[01;32m\]@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1_CONFIG='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
fi
# Update PS1 in .bashrc
sed -i '/^if \[ "\$color_prompt" = yes \]/,/^fi/c\
if [ "$color_prompt" = yes ]; then\
PS1="'"${PS1_CONFIG}"'"\
else\
PS1="${debian_chroot:+($debian_chroot)}\\u@\\h:\\w\\$ "\
fi' "$user_home/.bashrc"
# Add additional bash configurations
cat >> "$user_home/.bashrc" <<'EOF'
# Security aliases
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias ls='ls --color=auto'
alias ll='ls -lah'
alias grep='grep --color=auto'
alias sudo='sudo '
# History settings
HISTCONTROL=ignoreboth:erasedups
HISTSIZE=1000
HISTFILESIZE=2000
HISTTIMEFORMAT="%F %T "
PROMPT_COMMAND="history -a"
shopt -s histappend
# Security measures
umask 027
export TMOUT=900 # 15 minutes timeout
# Enable bash completion
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
# Path configuration
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# Set default editor
export EDITOR=vim
export VISUAL=vim
# Locale settings
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
# Default less options
export LESS='-R -i -g -c -W'
# Colored GCC warnings and errors
export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
EOF
fi
# Configure vim settings
cat > "$user_home/.vimrc" <<'EOF'
" Basic Settings
set nocompatible
syntax on
filetype plugin indent on
" Security Settings
set modelines=0
set nomodeline
" Editor Settings
set encoding=utf-8
set backspace=indent,eol,start
set hidden
set nobackup
set noswapfile
set noundofile
set directory=/tmp
set history=1000
" UI Settings
set ruler
set showcmd
set showmode
set showmatch
set laststatus=2
set wildmenu
set visualbell
set t_vb=
" Search Settings
set hlsearch
set incsearch
set ignorecase
set smartcase
" Indentation Settings
set autoindent
set smartindent
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set wrap
set textwidth=79
set formatoptions=qrn1
set colorcolumn=80
" Performance Settings
set lazyredraw
set ttyfast
" Security Settings
set secure
EOF
# Configure SSH directory and permissions
local ssh_dir="$user_home/.ssh"
if [[ ! -d "$ssh_dir" ]]; then
mkdir -p "$ssh_dir" || {
log "ERROR" "Failed to create SSH directory for user $username"
return 1
}
fi
chmod 700 "$ssh_dir"
chown "$username:$username" "$ssh_dir"
# Configure authorized_keys file if it doesn't exist
local auth_keys="$ssh_dir/authorized_keys"
if [[ ! -f "$auth_keys" ]]; then
touch "$auth_keys" || {
log "ERROR" "Failed to create authorized_keys file for user $username"
return 1
}
chmod 600 "$auth_keys"
chown "$username:$username" "$auth_keys"
fi
# Configure bash_logout
cat > "$user_home/.bash_logout" <<'EOF'
# Clear screen on logout
clear
# Clean history
cat /dev/null > "$HOME/.bash_history"
history -c
# Secure SSH agent
if [ -n "$SSH_AGENT_PID" ]; then
eval "$(ssh-agent -k)" >/dev/null 2>&1
fi
# Clear SSH keys from memory
ssh-add -D >/dev/null 2>&1
# Clear clipboard if available
if command -v xsel >/dev/null 2>&1; then
xsel -c
elif command -v xclip >/dev/null 2>&1; then
xclip -i /dev/null
fi
# Clear temporary files
rm -rf "$HOME/.local/share/Trash"/*
rm -rf "$HOME/tmp"/*
EOF
# Set proper ownership and permissions for all configuration files
local config_files=(
"$user_home/.vimrc"
"$user_home/.bash_logout"
"$user_home/.bashrc"
)
for file in "${config_files[@]}"; do
if [[ -f "$file" ]]; then
chown "$username:$username" "$file"
chmod 644 "$file"
fi
done
# Add SSH keys for users if running interactively
if [[ -t 0 && -t 1 ]]; then
configure_ssh_keys "$user_home" || {
log "WARNING" "Failed to configure SSH keys for user $username"
}
fi
log "INFO" "Completed environment configuration for user: $username"
return 0
}
setup_sudo_user() {
log "INFO" "Configuring sudo access..."
# Check if running in non-interactive mode
if [[ ! -t 0 ]]; then
log "ERROR" "This script must be run interactively for sudo configuration"
log "INFO" "Please run: bash -i /tmp/hardening.sh"
return 1
fi
if ! command -v sudo >/dev/null 2>&1; then
log "INFO" "Installing sudo package..."
install_package sudo || return 1
fi
# Show available users and configure sudo access
local users=()
while IFS= read -r -d '' dir; do
local username=$(basename "$dir")
if [[ "$username" != "root" && -d "/home/$username" ]]; then
users+=("$username")
fi
done < <(find /home -maxdepth 1 -mindepth 1 -type d -print0)
if (( ${#users[@]} == 0 )); then
log "WARNING" "No regular users found to grant sudo access"
return 0
fi
echo "Available users:"
PS3="Select user to grant sudo access (enter number): "
select username in "${users[@]}"; do
if [[ -n "$username" ]]; then
log "INFO" "Adding user $username to sudo group"
usermod -aG sudo "$username"
# Configure sudo settings
echo "$username ALL=(ALL:ALL) ALL" > "/etc/sudoers.d/$username"
chmod 440 "/etc/sudoers.d/$username"
log "INFO" "Successfully configured sudo access for $username"
break
else
echo "Invalid selection. Please try again."
continue
fi
done
return 0
}
# Main package installation
install_base_packages() {
log "INFO" "Installing base packages..."
local BASE_PACKAGES=(
curl
rsyslog
wget
socat
bash-completion
wireguard
vim
net-tools
htop
iftop
iotop
nmap
tcpdump
fail2ban
unattended-upgrades
)
# Add OS-specific packages
[[ "$OS" == "debian" ]] && BASE_PACKAGES+=(dnsmasq)
for package in "${BASE_PACKAGES[@]}"; do
if ! install_package "$package"; then
log "ERROR" "Failed to install package: $package"
return 1
fi
done
log "INFO" "Base package installation completed"
return 0
}
# Config dnsmasq
configure_dnsmasq() {
if [[ "$OS" == "debian" ]]; then
log "INFO" "Configuring dnsmasq for Debian..."
# Check if dnsmasq is installed
if ! command -v dnsmasq >/dev/null 2>&1; then
log "INFO" "Installing dnsmasq..."
if ! install_package dnsmasq; then
log "ERROR" "Failed to install dnsmasq"
return 1
fi
fi
# Backup existing configuration
create_backup /etc/dnsmasq.conf
# Create new configuration
cat > /etc/dnsmasq.conf <<EOF
no-resolv
server=8.8.8.8
server=8.8.4.4
EOF
# Set proper permissions
chmod 644 /etc/dnsmasq.conf
# Restart dnsmasq service
systemctl restart dnsmasq
# Verify service status
if ! systemctl is-active --quiet dnsmasq; then
log "ERROR" "dnsmasq service failed to start"
return 1
fi
log "INFO" "dnsmasq configuration completed successfully"
else
log "INFO" "Skipping dnsmasq configuration (not Debian)"
fi
}
# Execute system updates and package installation
if ! update_system; then
log "ERROR" "System update failed"
exit 1
fi
if ! install_base_packages; then
log "ERROR" "Base package installation failed"
exit 1
fi
configure_dnsmasq
# Configure sudo access
setup_sudo_user
# Configure user environments
configure_users() {
log "INFO" "Starting user environment configuration..."
# Create temporary file for error handling
local temp_file
temp_file=$(mktemp) || {
log "ERROR" "Failed to create temporary file"
return 1
}
# Add cleanup trap
trap 'rm -f "$temp_file"' RETURN
# Configure regular users
log "INFO" "Configuring regular user environments..."
while IFS= read -r -d '' user_dir; do
# Skip if not a directory
[[ ! -d "$user_dir" ]] && continue
# Get username and validate
username=$(basename "$user_dir")
if ! id "$username" >/dev/null 2>&1; then
log "WARNING" "User $username does not exist in system"
continue
fi
# Get user shell
shell=$(getent passwd "$username" | cut -d: -f7)
# Skip system users (UID < 1000)
uid=$(id -u "$username")
if [[ "$uid" -lt 1000 ]]; then
log "INFO" "Skipping system user $username (UID: $uid)"
continue
fi
# Only configure for users with valid shells
case "$shell" in
*/bash|*/sh)
log "INFO" "Configuring environment for user: $username (Shell: $shell)"
if ! configure_user_environment "$user_dir"; then
log "WARNING" "Failed to configure environment for user: $username"
echo "$username" >> "$temp_file"
fi
;;
*)
log "INFO" "Skipping user $username (non-standard shell: $shell)"
;;
esac
done < <(find /home -mindepth 1 -maxdepth 1 -type d -print0)
# Configure root separately
if [[ -d "/root" ]]; then
log "INFO" "Configuring root environment..."
if ! configure_user_environment "/root"; then
log "WARNING" "Failed to configure root environment"
echo "root" >> "$temp_file"
fi
else
log "WARNING" "Root directory not found"
fi
# Check for any failures
if [[ -s "$temp_file" ]]; then
log "WARNING" "Failed to configure some user environments:"
while IFS= read -r failed_user; do
log "WARNING" "- $failed_user"
done < "$temp_file"
return 1
fi
log "INFO" "User environment configuration completed successfully"
return 0
}
# Execute user configuration
if ! configure_users; then
log "ERROR" "User environment configuration had some failures"
# Continue script execution despite failures
fi
# Disable ssh.socket in LXC
check_ssh_socket() {
log "INFO" "Checking SSH service configuration..."
# Check if running in LXC container
if systemd-detect-virt --container | grep -q "lxc"; then
log "INFO" "LXC container detected, checking ssh.socket status"
local socket_active=false
local socket_enabled=false
# Check if ssh.socket is active
if systemctl is-active ssh.socket >/dev/null 2>&1; then
socket_active=true
log "INFO" "ssh.socket is currently active"
fi
# Check if ssh.socket is enabled
if systemctl is-enabled ssh.socket >/dev/null 2>&1; then
socket_enabled=true
log "INFO" "ssh.socket is currently enabled"
fi
# If socket is active or enabled, switch to service
if $socket_active || $socket_enabled; then