forked from CISOfy/lynis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlynis_hardening_2.sh
More file actions
executable file
·768 lines (627 loc) · 23.5 KB
/
lynis_hardening_2.sh
File metadata and controls
executable file
·768 lines (627 loc) · 23.5 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
#!/bin/bash
# ============================================
# Script Name: ultimate_lynis_hardening.sh
# Description: Ultimate Lynis fix + comprehensive hardening
# Author: Security Admin
# ============================================
# Set strict mode but with error handling
set -uo pipefail
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Banner
print_banner() {
clear
echo -e "${PURPLE}"
echo "╔══════════════════════════════════════════════════════════╗"
echo "║ ║"
echo "║ ULTIMATE LYNIS HARDENING & SECURITY SCRIPT ║"
echo "║ ║"
echo "║ Comprehensive System Hardening Based on Lynis ║"
echo "║ ║"
echo "╚══════════════════════════════════════════════════════════╝"
echo -e "${NC}"
}
print_success() {
echo -e "${GREEN}[✓]${NC} $1"
}
print_error() {
echo -e "${RED}[✗]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[!]${NC} $1"
}
print_info() {
echo -e "${BLUE}[i]${NC} $1"
}
print_step() {
echo -e "${CYAN}[→]${NC} $1"
}
# ==================== FIX LYNIS ====================
fix_lynis_completely() {
print_step "STEP 1: COMPLETE LYNIS FIX"
echo "========================================"
# Kill any running lynis processes
pkill -f lynis 2>/dev/null || true
# Find and fix lynis
local lynis_paths=(
"/home/anna/anna/lynis"
"/usr/local/lynis"
"/opt/lynis"
"/usr/bin/lynis"
"/usr/sbin/lynis"
"$(pwd)"
)
for path in "${lynis_paths[@]}"; do
if [[ -d "$path" ]] && [[ -f "$path/lynis" ]]; then
print_info "Found Lynis at: $path"
# Fix ownership
chown -R root:root "$path" 2>/dev/null || print_warning "Could not change ownership of $path"
# Fix permissions
find "$path" -type f -exec chmod 644 {} \; 2>/dev/null || true
find "$path" -type d -exec chmod 755 {} \; 2>/dev/null || true
# Make lynis executable for all
if [[ -f "$path/lynis" ]]; then
chmod 755 "$path/lynis"
chmod +x "$path/lynis"
print_success "Fixed permissions for $path/lynis"
# Create symlink in /usr/local/bin if not exists
if [[ ! -f "/usr/local/bin/lynis" ]]; then
ln -sf "$path/lynis" /usr/local/bin/lynis 2>/dev/null || true
fi
fi
fi
done
# Verify fix
if command -v lynis &>/dev/null; then
print_success "Lynis is now accessible system-wide"
else
# Try to run directly
if [[ -f "/home/anna/anna/lynis/lynis" ]]; then
chmod 755 "/home/anna/anna/lynis/lynis"
print_info "You can run: /home/anna/anna/lynis/lynis audit system"
fi
fi
return 0
}
# ==================== RUN LYNIS AUDIT ====================
run_comprehensive_audit() {
print_step "STEP 2: COMPREHENSIVE SECURITY AUDIT"
echo "=========================================="
local lynis_cmd=""
# Find lynis command
if command -v lynis &>/dev/null; then
lynis_cmd="lynis"
elif [[ -f "/home/anna/anna/lynis/lynis" ]]; then
lynis_cmd="/home/anna/anna/lynis/lynis"
else
print_error "Cannot find lynis"
return 1
fi
print_info "Running comprehensive audit with $lynis_cmd"
# Create audit directory
local audit_dir="/root/security_audits"
mkdir -p "$audit_dir"
local audit_file="$audit_dir/lynis_audit_$(date +%Y%m%d_%H%M%S).txt"
# Run audit
echo "Audit started at: $(date)" > "$audit_file"
echo "======================================" >> "$audit_file"
if $lynis_cmd audit system --quick --no-colors 2>&1 | tee -a "$audit_file"; then
print_success "Audit completed"
# Extract critical findings
local critical_file="$audit_dir/critical_findings_$(date +%Y%m%d).txt"
grep -i -E "(warning|suggestion|recommendation|vulnerability)" "$audit_file" | head -50 > "$critical_file"
if [[ -s "$critical_file" ]]; then
echo -e "\n${YELLOW}=== TOP SECURITY FINDINGS ===${NC}"
cat "$critical_file"
echo -e "\n${YELLOW}Full report: $audit_file${NC}"
else
print_info "No critical findings detected"
fi
else
print_error "Audit failed"
return 1
fi
return 0
}
# ==================== EXTREME HARDENING ====================
apply_extreme_hardening() {
print_step "STEP 3: EXTREME SYSTEM HARDENING"
echo "====================================="
local backup_dir="/root/system_backup_$(date +%Y%m%d)"
mkdir -p "$backup_dir"
# 1. KERNEL HARDENING
print_info "1. Kernel & Network Hardening"
cat > /etc/sysctl.d/99-extreme-security.conf << 'EOF'
# ========== KERNEL SECURITY ==========
# ASLR (Address Space Layout Randomization)
kernel.randomize_va_space = 2
# Restrict kernel pointers
kernel.kptr_restrict = 2
# Restrict dmesg
kernel.dmesg_restrict = 1
# Enable kernel stack protection
kernel.stack-protector = 1
# Restrict kernel module loading
kernel.modules_disabled = 0
# ========== NETWORK SECURITY ==========
# IP spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Disable ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# Disable source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# SYN flood protection
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
# Ignore ICMP broadcasts
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Ignore bogus ICMP errors
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
# ========== MEMORY PROTECTION ==========
# Disable core dumps
fs.suid_dumpable = 0
# Protect hardlinks/symlinks
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
# ========== ADDITIONAL HARDENING ==========
# Restrict ptrace
kernel.yama.ptrace_scope = 2
# Enable BPF hardening
kernel.unprivileged_bpf_disabled = 1
# Restrict perf events
kernel.perf_event_paranoid = 3
EOF
sysctl -p /etc/sysctl.d/99-extreme-security.conf 2>/dev/null
print_success "Kernel hardening applied"
# 2. SSH EXTREME HARDENING
print_info "2. SSH Extreme Hardening"
if [[ -f "/etc/ssh/sshd_config" ]]; then
cp /etc/ssh/sshd_config "$backup_dir/sshd_config.backup"
cat > /etc/ssh/sshd_config << 'EOF'
# ========== SSH EXTREME HARDENING ==========
Port 22
Protocol 2
LogLevel VERBOSE
MaxAuthTries 2
MaxSessions 2
TCPKeepAlive no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
PrintMotd yes
PrintLastLog yes
ClientAliveInterval 300
ClientAliveCountMax 2
Compression no
UsePAM yes
UseDNS no
PermitRootLogin no
PermitEmptyPasswords no
PasswordAuthentication no
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256
EOF
print_warning "SSH hardened with extreme settings"
print_info "You MUST use SSH keys to connect now!"
fi
# 3. USER & PASSWORD POLICIES
print_info "3. User & Password Policies"
# login.defs
cat > /etc/login.defs << 'EOF'
# ========== PASSWORD POLICIES ==========
ENCRYPT_METHOD SHA512
SHA_CRYPT_MIN_ROUNDS 1000000
SHA_CRYPT_MAX_ROUNDS 1000000
PASS_MAX_DAYS 60
PASS_MIN_DAYS 2
PASS_WARN_AGE 7
UMASK 027
USERGROUPS_ENAB yes
CREATE_HOME yes
LOGIN_RETRIES 3
LOGIN_TIMEOUT 60
FAIL_DELAY 4
TTYGROUP tty
TTYPERM 0600
EOF
# PAM hardening
if [[ -f "/etc/pam.d/common-password" ]]; then
cp /etc/pam.d/common-password "$backup_dir/common-password.backup"
sed -i 's/pam_unix.so.*/pam_unix.so obscure sha512 shadow nullok rounds=1000000 minlen=12 remember=5/' /etc/pam.d/common-password
print_success "PAM password policy hardened"
fi
# 4. FILE SYSTEM SECURITY
print_info "4. File System Security"
# Secure critical directories
chmod 700 /root
chmod 755 /usr/bin /usr/sbin /bin /sbin
chmod 644 /etc/passwd /etc/group
chmod 600 /etc/shadow /etc/gshadow
# Secure /tmp
echo "tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0" >> /etc/fstab
mount -o remount /tmp
# 5. DISABLE UNUSED SERVICES & PROTOCOLS
print_info "5. Disabling Unused Services"
local disable_services=(
"telnet" "rsh" "rlogin" "rexec" "nfs" "nfs-server"
"vsftpd" "tftp" "xinetd" "ypbind" "autofs"
"cups" "avahi-daemon" "snmpd" "squid"
)
for service in "${disable_services[@]}"; do
systemctl disable --now "$service" 2>/dev/null && print_info "Disabled $service" || true
done
# Disable protocols
cat > /etc/modprobe.d/disable-protocols.conf << 'EOF'
# Disable unused protocols
install dccp /bin/true
blacklist dccp
install sctp /bin/true
blacklist sctp
install rds /bin/true
blacklist rds
install tipc /bin/true
blacklist tipc
install bluetooth /bin/true
blacklist bluetooth
install firewire-core /bin/true
blacklist firewire-core
EOF
# 6. INSTALL SECURITY TOOLS
print_info "6. Installing Security Tools"
apt-get update > /dev/null 2>&1
local security_tools=(
# System audit
"lynis" "tiger" "chkrootkit" "rkhunter" "lynis" "aide" "tripwire"
# Network security
"fail2ban" "arpwatch" "nmap" "net-tools" "iptables-persistent"
# Monitoring
"auditd" "acct" "sysstat" "logwatch"
# Package security
"debsums" "apt-show-versions" "needrestart" "unattended-upgrades"
# Malware scanning
"clamav" "clamav-daemon" "clamtk"
# Firewall
"ufw" "firewalld"
)
for tool in "${security_tools[@]}"; do
if apt-get install -y "$tool" > /dev/null 2>&1; then
print_info "Installed $tool"
# Post-install configuration
case $tool in
"fail2ban")
systemctl enable fail2ban
systemctl start fail2ban
;;
"auditd")
systemctl enable auditd
systemctl start auditd
;;
"aide")
aideinit --yes
;;
"unattended-upgrades")
dpkg-reconfigure -plow unattended-upgrades
;;
esac
fi
done
# 7. CONFIGURE FIREWALL (EXTREME)
print_info "7. Configuring Extreme Firewall"
# Reset iptables
iptables -F
iptables -X
iptables -Z
# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allow established connections
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (change port if needed)
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
# Allow ICMP (ping) - limited
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/second -j ACCEPT
# Save rules
iptables-save > /etc/iptables/rules.v4
print_warning "Firewall configured: ONLY SSH allowed (port 22)"
# 8. AUDIT CONFIGURATION
print_info "8. Configuring Audit System"
if command -v auditctl &>/dev/null; then
cat > /etc/audit/rules.d/99-hardening.rules << 'EOF'
# Monitor system calls
-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change
-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time-change
-a always,exit -F arch=b64 -S clock_settime -k time-change
-a always,exit -F arch=b32 -S clock_settime -k time-change
# Monitor user/group changes
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/security/opasswd -p wa -k identity
# Monitor sudoers
-w /etc/sudoers -p wa -k scope
-w /etc/sudoers.d/ -p wa -k scope
# Monitor kernel module loading
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
# Monitor file deletions
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -k delete
-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -k delete
# Monitor network configuration
-w /etc/hosts -p wa -k hosts
-w /etc/network/ -p wa -k network
EOF
systemctl restart auditd
print_success "Audit system configured"
fi
# 9. LOGGING ENHANCEMENT
print_info "9. Enhancing Logging"
# Configure rsyslog
cat > /etc/rsyslog.d/99-security.conf << 'EOF'
# Enhanced logging
auth,authpriv.* /var/log/auth.log
*.*;auth,authpriv.none -/var/log/syslog
kern.* -/var/log/kern.log
mail.* -/var/log/mail.log
*.emerg :omusrmsg:*
EOF
systemctl restart rsyslog
# Configure logrotate
cat > /etc/logrotate.d/security << 'EOF'
/var/log/auth.log
/var/log/syslog
/var/log/kern.log
{
daily
missingok
rotate 365
compress
delaycompress
create 640 root adm
postrotate
systemctl reload rsyslog >/dev/null 2>&1 || true
endscript
}
EOF
# 10. ADDITIONAL HARDENING
print_info "10. Additional Hardening Measures"
# Disable USB storage
echo "install usb-storage /bin/true" > /etc/modprobe.d/disable-usb.conf
echo "blacklist usb-storage" >> /etc/modprobe.d/disable-usb.conf
# Disable IPv6 if not needed
cat >> /etc/sysctl.d/99-security.conf << 'EOF'
# Disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
EOF
# Harden compiler
chmod 750 /usr/bin/gcc /usr/bin/g++ /usr/bin/as 2>/dev/null || true
print_success "Extreme hardening completed!"
print_warning "BACKUP LOCATION: $backup_dir"
print_warning "SYSTEM MAY REQUIRE REBOOT"
}
# ==================== POST-HARDENING CHECKS ====================
post_hardening_checks() {
print_step "POST-HARDENING SECURITY CHECKS"
echo "===================================="
echo -e "\n${CYAN}=== SYSTEM SECURITY STATUS ===${NC}"
# 1. User accounts
echo -e "\n${YELLOW}1. User Accounts:${NC}"
echo "Root login disabled: $(grep -i "PermitRootLogin no" /etc/ssh/sshd_config 2>/dev/null && echo "YES" || echo "NO")"
echo "Users with UID 0: $(awk -F: '($3 == 0) {print $1}' /etc/passwd | tr '\n' ' ')"
# 2. Password policies
echo -e "\n${YELLOW}2. Password Policies:${NC}"
echo "Password max days: $(grep ^PASS_MAX_DAYS /etc/login.defs | awk '{print $2}')"
echo "Password min days: $(grep ^PASS_MIN_DAYS /etc/login.defs | awk '{print $2}')"
# 3. SSH status
echo -e "\n${YELLOW}3. SSH Status:${NC}"
systemctl is-active ssh >/dev/null 2>&1 && echo "SSH: ACTIVE" || echo "SSH: INACTIVE"
echo "SSH port: $(grep ^Port /etc/ssh/sshd_config 2>/dev/null | awk '{print $2}' || echo "22")"
# 4. Firewall status
echo -e "\n${YELLOW}4. Firewall Status:${NC}"
iptables -L -n | grep -q "INPUT.*DROP" && echo "Firewall: ACTIVE (Default DROP)" || echo "Firewall: WARNING"
# 5. Audit status
echo -e "\n${YELLOW}5. Audit System:${NC}"
systemctl is-active auditd >/dev/null 2>&1 && echo "Auditd: ACTIVE" || echo "Auditd: INACTIVE"
# 6. Update status
echo -e "\n${YELLOW}6. System Updates:${NC}"
apt-get update >/dev/null 2>&1
local updates=$(apt list --upgradable 2>/dev/null | grep -c upgradable || echo "0")
echo "Pending updates: $updates"
# 7. Critical file permissions
echo -e "\n${YELLOW}7. Critical File Permissions:${NC}"
local files=("/etc/shadow" "/etc/passwd" "/etc/group" "/etc/sudoers")
for file in "${files[@]}"; do
if [[ -f "$file" ]]; then
local perm=$(stat -c "%a" "$file" 2>/dev/null)
[[ "$perm" == "600" || "$perm" == "640" ]] && status="OK" || status="WARNING"
echo "$file: $perm ($status)"
fi
done
echo -e "\n${GREEN}=== RECOMMENDED ACTIONS ===${NC}"
echo "1. Test SSH connection before closing current session"
echo "2. Reboot system to apply all kernel changes"
echo "3. Run: lynis audit system --quick (to verify hardening)"
echo "4. Configure automatic updates: dpkg-reconfigure unattended-upgrades"
echo "5. Review logs in /var/log/auth.log and /var/log/audit/audit.log"
}
# ==================== MAIN MENU ====================
show_main_menu() {
print_banner
echo -e "${CYAN}Select an option:${NC}"
echo "══════════════════════════════════════════════════════════"
echo
echo " 1. Fix Lynis Ownership & Permissions (DO THIS FIRST)"
echo " 2. Run Comprehensive Security Audit"
echo " 3. Apply EXTREME System Hardening (VERY AGGRESSIVE)"
echo " 4. Post-Hardening Security Checks"
echo " 5. Run ALL Steps (Fix + Audit + Hardening)"
echo " 6. Quick Security Status Check"
echo " 7. Create Security Report"
echo " 0. Exit"
echo
echo "══════════════════════════════════════════════════════════"
echo -e "${YELLOW}Warning: Some options may break system functionality!${NC}"
echo
}
quick_status_check() {
print_step "QUICK SECURITY STATUS"
echo "========================"
echo -e "\n${YELLOW}Basic Checks:${NC}"
# Lynis status
if command -v lynis &>/dev/null || [[ -f "/home/anna/anna/lynis/lynis" ]]; then
echo "✓ Lynis: Available"
else
echo "✗ Lynis: Not found"
fi
# Root SSH
if grep -q "PermitRootLogin no" /etc/ssh/sshd_config 2>/dev/null; then
echo "✓ SSH root login: Disabled"
else
echo "✗ SSH root login: Enabled (RISKY)"
fi
# Firewall
if iptables -L -n 2>/dev/null | grep -q "DROP"; then
echo "✓ Firewall: Active"
else
echo "✗ Firewall: Not configured"
fi
# Updates
local updates=$(apt list --upgradable 2>/dev/null | grep -c upgradable 2>/dev/null || echo "0")
if [[ "$updates" -eq 0 ]]; then
echo "✓ System updates: Up to date"
else
echo "✗ System updates: $updates pending"
fi
# Critical permissions
if [[ "$(stat -c "%a" /etc/shadow 2>/dev/null)" == "640" || "$(stat -c "%a" /etc/shadow 2>/dev/null)" == "600" ]]; then
echo "✓ /etc/shadow permissions: OK"
else
echo "✗ /etc/shadow permissions: INSECURE"
fi
}
create_security_report() {
print_step "CREATING SECURITY REPORT"
echo "==========================="
local report_dir="/root/security_reports"
mkdir -p "$report_dir"
local report_file="$report_dir/security_report_$(date +%Y%m%d_%H%M%S).txt"
echo "SECURITY REPORT - $(date)" > "$report_file"
echo "=====================================" >> "$report_file"
# System info
echo -e "\n=== SYSTEM INFORMATION ===" >> "$report_file"
uname -a >> "$report_file"
echo "Hostname: $(hostname)" >> "$report_file"
# User info
echo -e "\n=== USER ACCOUNTS ===" >> "$report_file"
echo "Users with UID 0:" >> "$report_file"
awk -F: '($3 == 0) {print $1}' /etc/passwd >> "$report_file"
# SSH config
echo -e "\n=== SSH CONFIGURATION ===" >> "$report_file"
grep -E "^(PermitRootLogin|PasswordAuthentication|Port|Protocol)" /etc/ssh/sshd_config 2>/dev/null >> "$report_file" || echo "Not found" >> "$report_file"
# Firewall rules
echo -e "\n=== FIREWALL RULES ===" >> "$report_file"
iptables -L -n 2>/dev/null >> "$report_file" || echo "iptables not available" >> "$report_file"
# Listening ports
echo -e "\n=== LISTENING PORTS ===" >> "$report_file"
netstat -tulpn 2>/dev/null | grep LISTEN >> "$report_file" || ss -tulpn 2>/dev/null | grep LISTEN >> "$report_file"
# Package updates
echo -e "\n=== PACKAGE UPDATES ===" >> "$report_file"
apt list --upgradable 2>/dev/null | grep upgradable >> "$report_file" || echo "No updates available" >> "$report_file"
print_success "Report saved to: $report_file"
echo -e "\n${YELLOW}Report Contents:${NC}"
tail -50 "$report_file"
}
# ==================== MAIN EXECUTION ====================
main() {
# Check if root
if [[ $EUID -ne 0 ]]; then
print_error "This script must be run as root"
echo "Try: sudo $0"
exit 1
fi
while true; do
show_main_menu
read -p "Enter your choice (0-7): " choice
case $choice in
1)
fix_lynis_completely
;;
2)
run_comprehensive_audit
;;
3)
print_warning "EXTREME HARDENING WILL MAKE IRREVERSIBLE CHANGES!"
print_warning "You may lose remote access if not configured properly!"
read -p "Are you REALLY sure? (type YES to continue): " confirm
if [[ "$confirm" == "YES" ]]; then
apply_extreme_hardening
else
print_info "Extreme hardening cancelled"
fi
;;
4)
post_hardening_checks
;;
5)
print_warning "Running ALL steps (Fix + Audit + Extreme Hardening)"
read -p "Continue? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
fix_lynis_completely
echo
run_comprehensive_audit
echo
apply_extreme_hardening
echo
post_hardening_checks
fi
;;
6)
quick_status_check
;;
7)
create_security_report
;;
0)
print_success "Exiting Ultimate Hardening Script"
exit 0
;;
*)
print_error "Invalid choice. Please try again."
;;
esac
echo
echo "══════════════════════════════════════════════════════════"
read -p "Press Enter to return to menu..."
done
}
# Run main function
main