Introduction
Security hardening is a critical process for any Rocky Linux deployment, whether it’s a single server or an enterprise infrastructure. This comprehensive security checklist provides a systematic approach to securing Rocky Linux systems, covering everything from initial installation to ongoing maintenance. By following this guide, you’ll implement defense-in-depth strategies that protect against common threats while maintaining system functionality.
Pre-Installation Security Considerations
Secure Installation Media
# Download Rocky Linux ISO
wget https://download.rockylinux.org/pub/rocky/9/isos/x86_64/Rocky-9-latest-x86_64-dvd.iso
# Download checksum and signature
wget https://download.rockylinux.org/pub/rocky/9/isos/x86_64/CHECKSUM
wget https://download.rockylinux.org/pub/rocky/9/isos/x86_64/CHECKSUM.sig
# Verify checksum
sha256sum -c CHECKSUM 2>&1 | grep OK
# Import Rocky Linux GPG key
curl -o RPM-GPG-KEY-Rocky-9 https://download.rockylinux.org/pub/rocky/RPM-GPG-KEY-Rocky-9
gpg --import RPM-GPG-KEY-Rocky-9
# Verify signature
gpg --verify CHECKSUM.sig CHECKSUM
Secure Boot Configuration
Enable UEFI Secure Boot when possible:
- Verify hardware supports Secure Boot
- Enable Secure Boot in UEFI/BIOS
- Use GPT partitioning scheme
- Configure encrypted boot partition
Initial System Hardening
1. Update System Immediately
# Update all packages
sudo dnf update -y
# Enable automatic security updates
sudo dnf install -y dnf-automatic
sudo systemctl enable --now dnf-automatic.timer
# Configure automatic updates
sudo vim /etc/dnf/automatic.conf
# Set:
# apply_updates = yes
# upgrade_type = security
2. Configure Secure Kernel Parameters
# Edit GRUB configuration
sudo vim /etc/default/grub
# Add security parameters to GRUB_CMDLINE_LINUX
GRUB_CMDLINE_LINUX="... audit=1 kernel.kptr_restrict=2 kernel.dmesg_restrict=1 kernel.kexec_load_disabled=1 kernel.yama.ptrace_scope=3 kernel.unprivileged_bpf_disabled=1 net.core.bpf_jit_harden=2"
# Rebuild GRUB configuration
sudo grub2-mkconfig -o /boot/grub2/grub.cfg
# For UEFI systems
sudo grub2-mkconfig -o /boot/efi/EFI/rocky/grub.cfg
3. Set System Security Limits
# Configure system limits
cat >> /etc/security/limits.conf << 'EOF'
# Prevent fork bombs
* hard nproc 1000
# Limit core dumps
* hard core 0
# Maximum locked memory
* hard memlock 64
# Maximum file size
* hard fsize 1000000
EOF
# Configure sysctl security parameters
cat > /etc/sysctl.d/99-security.conf << 'EOF'
# IP Spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
# Ignore source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# Log Martians
net.ipv4.conf.all.log_martians = 1
# Ignore ICMP ping requests
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Ignore Directed pings
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Enable TCP/IP SYN cookies
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 5
# Disable packet forwarding
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
# Disable IPv6 if not needed
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
# Protect against SYN flood attacks
net.ipv4.tcp_max_syn_backlog = 1280
# Increase system file descriptor limit
fs.file-max = 65535
# Allow for more PIDs
kernel.pid_max = 65535
# Restrict access to kernel logs
kernel.dmesg_restrict = 1
# Restrict ptrace usage
kernel.yama.ptrace_scope = 3
# Disable kexec
kernel.kexec_load_disabled = 1
# Restrict kernel pointer exposure
kernel.kptr_restrict = 2
# Restrict performance events
kernel.perf_event_paranoid = 3
# Restrict unprivileged BPF
kernel.unprivileged_bpf_disabled = 1
EOF
# Apply sysctl settings
sudo sysctl -p /etc/sysctl.d/99-security.conf
User and Access Management
1. Secure User Account Policies
# Set password policy
sudo vim /etc/security/pwquality.conf
# Add/modify:
minlen = 14
minclass = 4
maxrepeat = 2
maxclassrepeat = 2
lcredit = -1
ucredit = -1
dcredit = -1
ocredit = -1
# Configure password aging
sudo vim /etc/login.defs
# Set:
PASS_MAX_DAYS 90
PASS_MIN_DAYS 7
PASS_WARN_AGE 14
ENCRYPT_METHOD SHA512
SHA_CRYPT_MIN_ROUNDS 10000
UMASK 077
2. Configure PAM Security
# Prevent reuse of passwords
cat >> /etc/pam.d/system-auth << 'EOF'
password requisite pam_pwhistory.so remember=24 enforce_for_root
EOF
# Account lockout policy
cat >> /etc/pam.d/system-auth << 'EOF'
auth required pam_faillock.so preauth audit silent deny=5 unlock_time=900
auth [default=die] pam_faillock.so authfail audit deny=5 unlock_time=900
account required pam_faillock.so
EOF
# Configure su access
cat >> /etc/pam.d/su << 'EOF'
auth required pam_wheel.so use_uid
EOF
# Add users to wheel group for su access
usermod -aG wheel adminuser
3. Disable Unnecessary Users
# Lock system accounts
for user in bin daemon adm lp sync shutdown halt mail operator games ftp nobody; do
sudo usermod -L $user
sudo usermod -s /sbin/nologin $user
done
# Remove unnecessary users
sudo userdel -r games 2>/dev/null
sudo userdel -r news 2>/dev/null
# Set secure shell for system accounts
sudo usermod -s /sbin/nologin root
4. Implement sudo Best Practices
# Configure sudoers
sudo visudo
# Add secure sudo configuration
Defaults requiretty
Defaults use_pty
Defaults logfile="/var/log/sudo.log"
Defaults timestamp_timeout=15
Defaults passwd_timeout=1
Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
# Example user configuration
adminuser ALL=(ALL) NOPASSWD: /usr/bin/systemctl status *, /usr/bin/journalctl *
adminuser ALL=(ALL) ALL
SSH Hardening
1. Secure SSH Configuration
# Backup original config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
# Create secure SSH configuration
cat > /etc/ssh/sshd_config.d/99-security.conf << 'EOF'
# Network and Protocol
Port 22
Protocol 2
AddressFamily inet
ListenAddress 0.0.0.0
# Host Keys
HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
# Logging
SyslogFacility AUTH
LogLevel INFO
# Authentication
LoginGraceTime 60
PermitRootLogin no
StrictModes yes
MaxAuthTries 3
MaxSessions 10
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
UsePAM yes
# User Access
AllowUsers adminuser
DenyUsers root
AllowGroups sshusers
# Security Features
X11Forwarding no
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
PermitUserEnvironment no
Compression delayed
ClientAliveInterval 300
ClientAliveCountMax 2
UseDNS no
PidFile /var/run/sshd.pid
MaxStartups 10:30:100
PermitTunnel no
# Crypto Settings
Ciphers [email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected],hmac-sha2-512,hmac-sha2-256
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group16-sha512,diffie-hellman-group18-sha512
# SFTP Configuration
Subsystem sftp /usr/libexec/openssh/sftp-server -f AUTHPRIV -l INFO
# Banner
Banner /etc/issue.net
EOF
# Create login banner
cat > /etc/issue.net << 'EOF'
******************************************************************
* WARNING *
* This system is for authorized use only. All activities are *
* monitored and logged. Unauthorized access is prohibited and *
* will be prosecuted to the fullest extent of the law. *
******************************************************************
EOF
# Set correct permissions
chmod 600 /etc/ssh/sshd_config.d/99-security.conf
chmod 644 /etc/issue.net
# Restart SSH service
sudo systemctl restart sshd
2. SSH Key Management
# Generate secure SSH keys for users
ssh-keygen -t ed25519 -C "user@rockylinux" -f ~/.ssh/id_ed25519
# Set proper permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
chmod 600 ~/.ssh/authorized_keys
# Configure SSH client
cat > ~/.ssh/config << 'EOF'
Host *
Protocol 2
ServerAliveInterval 300
ServerAliveCountMax 2
StrictHostKeyChecking ask
VerifyHostKeyDNS yes
ForwardAgent no
ForwardX11 no
PasswordAuthentication no
HashKnownHosts yes
Ciphers [email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
MACs [email protected],[email protected]
KexAlgorithms curve25519-sha256,[email protected]
EOF
chmod 600 ~/.ssh/config
Firewall Configuration
1. Configure firewalld
# Ensure firewalld is installed and running
sudo dnf install -y firewalld
sudo systemctl enable --now firewalld
# Set default zone
sudo firewall-cmd --set-default-zone=drop
# Create custom zone for services
sudo firewall-cmd --permanent --new-zone=services
sudo firewall-cmd --permanent --zone=services --set-target=default
# Add allowed services
sudo firewall-cmd --permanent --zone=services --add-service=ssh
sudo firewall-cmd --permanent --zone=services --add-service=https
sudo firewall-cmd --permanent --zone=services --add-service=http
# Add source IP restrictions
sudo firewall-cmd --permanent --zone=services --add-source=10.0.0.0/8
sudo firewall-cmd --permanent --zone=services --add-source=192.168.0.0/16
# Enable logging
sudo firewall-cmd --permanent --zone=services --set-target=LOG --set-log-level=info
# Rate limiting for SSH
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" service name="ssh" limit value="3/m" accept'
# Block common attack ports
for port in 23 135 137 138 139 445 1433 3389; do
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' port port='$port' protocol='tcp' reject"
done
# Reload firewall
sudo firewall-cmd --reload
# Verify configuration
sudo firewall-cmd --list-all-zones
2. Configure nftables (Alternative)
# Install nftables
sudo dnf install -y nftables
# Create base configuration
cat > /etc/nftables/main.nft << 'EOF'
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
# Allow loopback
iif lo accept
# Allow established connections
ct state established,related accept
# Drop invalid connections
ct state invalid drop
# Allow ICMP
ip protocol icmp icmp type { echo-request, echo-reply } limit rate 10/second accept
ip6 nexthdr icmpv6 icmpv6 type { echo-request, echo-reply } limit rate 10/second accept
# Allow SSH with rate limiting
tcp dport 22 ct state new limit rate 3/minute accept
# Allow HTTP/HTTPS
tcp dport { 80, 443 } accept
# Log dropped packets
log prefix "[nftables] Dropped: " level info
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
EOF
# Enable and start nftables
sudo systemctl enable --now nftables
SELinux Configuration
1. Enable and Configure SELinux
# Ensure SELinux is enforcing
sudo setenforce 1
sudo sed -i 's/SELINUX=permissive/SELINUX=enforcing/' /etc/selinux/config
# Install SELinux tools
sudo dnf install -y setools-console policycoreutils-python-utils setroubleshoot-server
# Check SELinux status
sestatus
# Set SELinux booleans for security
sudo setsebool -P deny_execmem on
sudo setsebool -P secure_mode_insmod on
sudo setsebool -P ssh_sysadm_login off
# Configure SELinux for services
sudo setsebool -P httpd_can_network_connect off
sudo setsebool -P httpd_can_sendmail off
sudo setsebool -P httpd_enable_cgi off
2. Create Custom SELinux Policies
# Monitor SELinux denials
sudo ausearch -m avc -ts recent
# Create policy for custom application
cat > myapp.te << 'EOF'
module myapp 1.0;
require {
type httpd_t;
type myapp_data_t;
class file { read getattr };
}
# Allow httpd to read myapp data
allow httpd_t myapp_data_t:file { read getattr };
EOF
# Compile and install policy
checkmodule -M -m -o myapp.mod myapp.te
semodule_package -o myapp.pp -m myapp.mod
sudo semodule -i myapp.pp
System Auditing
1. Configure auditd
# Install audit daemon
sudo dnf install -y audit
# Configure audit rules
cat > /etc/audit/rules.d/security.rules << 'EOF'
# Delete all existing rules
-D
# Buffer Size
-b 8192
# Failure Mode
-f 1
# Monitor authentication
-w /etc/passwd -p wa -k passwd_changes
-w /etc/group -p wa -k group_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/gshadow -p wa -k gshadow_changes
# Monitor sudo usage
-w /etc/sudoers -p wa -k sudoers_changes
-w /etc/sudoers.d/ -p wa -k sudoers_changes
# Monitor SSH configuration
-w /etc/ssh/sshd_config -p wa -k sshd_config
-w /etc/ssh/sshd_config.d/ -p wa -k sshd_config
# 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 network changes
-a always,exit -F arch=b64 -S sethostname -S setdomainname -k system-locale
-a always,exit -F arch=b32 -S sethostname -S setdomainname -k system-locale
-w /etc/issue -p wa -k system-locale
-w /etc/issue.net -p wa -k system-locale
-w /etc/hosts -p wa -k system-locale
# Monitor login/logout events
-w /var/log/faillog -p wa -k logins
-w /var/log/lastlog -p wa -k logins
-w /var/log/tallylog -p wa -k logins
# Monitor file deletion
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
# Monitor kernel modules
-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
-e 2
EOF
# Restart auditd
sudo service auditd restart
# Verify audit rules
sudo auditctl -l
2. Configure Log Management
# Configure rsyslog
cat > /etc/rsyslog.d/security.conf << 'EOF'
# Log authentication messages
auth,authpriv.* /var/log/secure
# Log all kernel messages
kern.* /var/log/kern.log
# Log cron jobs
cron.* /var/log/cron
# Forward logs to central server (optional)
*.* @@logserver.example.com:514
EOF
# Configure log rotation
cat > /etc/logrotate.d/security << 'EOF'
/var/log/secure
/var/log/kern.log
/var/log/cron
{
daily
rotate 90
compress
delaycompress
missingok
notifempty
create 0600 root root
sharedscripts
postrotate
/usr/bin/systemctl kill -s HUP rsyslog.service >/dev/null 2>&1 || true
endscript
}
EOF
# Set proper permissions on log files
chmod 0600 /var/log/secure*
chmod 0600 /var/log/kern.log*
chmod 0600 /var/log/cron*
File System Security
1. Partition Security
# Add secure mount options to /etc/fstab
# Example entries:
UUID=xxx /tmp ext4 defaults,nodev,nosuid,noexec 1 2
UUID=xxx /var ext4 defaults,nodev 1 2
UUID=xxx /var/log ext4 defaults,nodev,nosuid,noexec 1 2
UUID=xxx /var/tmp ext4 defaults,nodev,nosuid,noexec 1 2
UUID=xxx /home ext4 defaults,nodev,nosuid 1 2
# Remount with secure options
mount -o remount,nodev,nosuid,noexec /tmp
mount -o remount,nodev,nosuid,noexec /var/tmp
mount -o remount,nodev,nosuid /home
2. File Permissions
# Find and fix world-writable files
find / -xdev -type f -perm -0002 -print | while read file; do
chmod o-w "$file"
done
# Find and fix world-writable directories
find / -xdev -type d -perm -0002 -print | while read dir; do
chmod o-w "$dir"
done
# Find SUID/SGID files
find / -perm /6000 -type f -exec ls -ld {} \; > /root/suid_files.txt
# Remove unnecessary SUID bits
chmod u-s /usr/bin/at
chmod u-s /usr/bin/lppasswd
chmod u-s /usr/bin/newgrp
chmod u-s /usr/bin/staprun
chmod g-s /usr/bin/wall
3. Secure Temporary Directories
# Create secure temporary directory
cat > /etc/systemd/system/secure-tmp.service << 'EOF'
[Unit]
Description=Create secure temporary directories
DefaultDependencies=no
After=local-fs.target
Before=sysinit.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/secure-tmp.sh
RemainAfterExit=yes
[Install]
WantedBy=sysinit.target
EOF
# Create secure temp script
cat > /usr/local/bin/secure-tmp.sh << 'EOF'
#!/bin/bash
# Create secure temporary directories
# Set secure permissions on /tmp
mount -t tmpfs -o mode=1777,strictatime,noexec,nodev,nosuid tmpfs /tmp
# Set secure permissions on /var/tmp
mount -t tmpfs -o mode=1777,strictatime,noexec,nodev,nosuid tmpfs /var/tmp
# Create user-specific temp directories
for user in $(awk -F: '$3 >= 1000 {print $1}' /etc/passwd); do
USER_TMP="/tmp/user_${user}"
mkdir -p "${USER_TMP}"
chown ${user}:${user} "${USER_TMP}"
chmod 700 "${USER_TMP}"
done
EOF
chmod +x /usr/local/bin/secure-tmp.sh
systemctl enable secure-tmp.service
Network Security
1. Disable Unnecessary Services
# Disable unnecessary services
for service in avahi-daemon cups bluetooth kdump; do
systemctl disable --now $service 2>/dev/null
done
# Disable unnecessary network protocols
cat > /etc/modprobe.d/disable-protocols.conf << 'EOF'
# Disable rare network protocols
install dccp /bin/true
install sctp /bin/true
install rds /bin/true
install tipc /bin/true
EOF
# Disable IPv6 if not needed
cat > /etc/modprobe.d/disable-ipv6.conf << 'EOF'
options ipv6 disable=1
EOF
2. Network Time Protocol Security
# Configure chrony for secure NTP
cat > /etc/chrony.conf << 'EOF'
# Use Rocky Linux NTP servers
server 0.rocky.pool.ntp.org iburst
server 1.rocky.pool.ntp.org iburst
server 2.rocky.pool.ntp.org iburst
server 3.rocky.pool.ntp.org iburst
# Record the rate at which the system clock gains/losses time
driftfile /var/lib/chrony/drift
# Allow the system clock to be stepped in the first three updates
makestep 1.0 3
# Enable kernel synchronization
rtcsync
# Specify directory for log files
logdir /var/log/chrony
# Select which information is logged
log measurements statistics tracking
# Deny all clients
deny all
# Allow only localhost
allow 127.0.0.1
allow ::1
EOF
systemctl restart chronyd
Application Security
1. Web Server Hardening (Apache)
# Secure Apache configuration
cat > /etc/httpd/conf.d/security.conf << 'EOF'
# Hide Apache version
ServerTokens Prod
ServerSignature Off
# Disable directory browsing
Options -Indexes
# Disable server-side includes
Options -Includes
# Disable CGI execution
Options -ExecCGI
# Enable XSS protection
Header set X-XSS-Protection "1; mode=block"
# Prevent clickjacking
Header always append X-Frame-Options SAMEORIGIN
# Prevent MIME sniffing
Header set X-Content-Type-Options nosniff
# Enable HSTS
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
# Disable TRACE method
TraceEnable off
# Set secure cookies
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
# Limit request size
LimitRequestBody 10485760
# Timeout settings
Timeout 60
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
EOF
2. Database Security (MariaDB)
# Secure MariaDB installation
mysql_secure_installation
# Additional security configuration
mysql -u root -p << 'EOF'
-- Remove anonymous users
DELETE FROM mysql.user WHERE User='';
-- Remove remote root access
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- Remove test database
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%';
-- Create secure user
CREATE USER 'dbadmin'@'localhost' IDENTIFIED BY 'StrongPassword123!';
GRANT ALL PRIVILEGES ON *.* TO 'dbadmin'@'localhost' WITH GRANT OPTION;
-- Flush privileges
FLUSH PRIVILEGES;
EOF
# Configure MariaDB security
cat >> /etc/my.cnf.d/security.cnf << 'EOF'
[mysqld]
# Disable LOCAL INFILE
local_infile = 0
# Bind to localhost only
bind-address = 127.0.0.1
# Disable symbolic links
symbolic-links = 0
# Set secure file permissions
secure_file_priv = /var/lib/mysql-files/
# Enable binary logging
log_bin = /var/log/mariadb/mariadb-bin
# Enable error logging
log_error = /var/log/mariadb/mariadb.err
# Enable slow query log
slow_query_log = 1
slow_query_log_file = /var/log/mariadb/mariadb-slow.log
long_query_time = 2
EOF
System Monitoring
1. Install Security Monitoring Tools
# Install monitoring tools
sudo dnf install -y aide tripwire rkhunter chkrootkit fail2ban
# Initialize AIDE
sudo aide --init
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Configure AIDE
cat > /etc/aide.conf.d/custom.conf << 'EOF'
# Custom AIDE rules
/etc p+u+g+s+m+c+md5+sha256
/bin p+u+g+s+m+c+md5+sha256
/sbin p+u+g+s+m+c+md5+sha256
/usr/bin p+u+g+s+m+c+md5+sha256
/usr/sbin p+u+g+s+m+c+md5+sha256
/boot p+u+g+s+m+c+md5+sha256
/lib p+u+g+s+m+c+md5+sha256
/lib64 p+u+g+s+m+c+md5+sha256
/usr/lib p+u+g+s+m+c+md5+sha256
/usr/lib64 p+u+g+s+m+c+md5+sha256
EOF
# Create AIDE check script
cat > /usr/local/bin/aide-check.sh << 'EOF'
#!/bin/bash
/usr/sbin/aide --check | mail -s "AIDE Report for $(hostname)" [email protected]
EOF
chmod +x /usr/local/bin/aide-check.sh
# Add to crontab
echo "0 5 * * * /usr/local/bin/aide-check.sh" | crontab -
2. Configure fail2ban
# Configure fail2ban
cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = systemd
banaction = firewallcmd-ipset
banaction_allports = firewallcmd-ipset
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
maxretry = 3
[httpd-auth]
enabled = true
port = http,https
logpath = %(apache_error_log)s
[httpd-badbots]
enabled = true
port = http,https
logpath = %(apache_access_log)s
maxretry = 2
[httpd-noscript]
enabled = true
port = http,https
logpath = %(apache_error_log)s
[httpd-overflows]
enabled = true
port = http,https
logpath = %(apache_error_log)s
maxretry = 2
[mariadb]
enabled = true
port = 3306
logpath = /var/log/mariadb/mariadb.err
maxretry = 3
EOF
# Start fail2ban
systemctl enable --now fail2ban
Compliance and Reporting
1. Security Compliance Script
# Create compliance check script
cat > /usr/local/bin/security-compliance-check.sh << 'EOF'
#!/bin/bash
# Rocky Linux Security Compliance Check
REPORT_FILE="/var/log/security-compliance-$(date +%Y%m%d).log"
echo "Rocky Linux Security Compliance Report" > $REPORT_FILE
echo "Generated: $(date)" >> $REPORT_FILE
echo "========================================" >> $REPORT_FILE
# Check SELinux status
echo -e "\n[SELinux Status]" >> $REPORT_FILE
getenforce >> $REPORT_FILE
# Check firewall status
echo -e "\n[Firewall Status]" >> $REPORT_FILE
firewall-cmd --state >> $REPORT_FILE
# Check for system updates
echo -e "\n[Available Updates]" >> $REPORT_FILE
dnf check-update | grep -E "^[a-zA-Z0-9]" | wc -l >> $REPORT_FILE
# Check SSH configuration
echo -e "\n[SSH Configuration]" >> $REPORT_FILE
grep -E "^PermitRootLogin|^PasswordAuthentication|^PubkeyAuthentication" /etc/ssh/sshd_config >> $REPORT_FILE
# Check for failed login attempts
echo -e "\n[Failed Login Attempts]" >> $REPORT_FILE
grep "Failed password" /var/log/secure | tail -20 >> $REPORT_FILE
# Check listening services
echo -e "\n[Listening Services]" >> $REPORT_FILE
ss -tlnp | grep LISTEN >> $REPORT_FILE
# Check for world-writable files
echo -e "\n[World-Writable Files]" >> $REPORT_FILE
find / -xdev -type f -perm -0002 2>/dev/null | head -20 >> $REPORT_FILE
# Check SUID files
echo -e "\n[SUID Files]" >> $REPORT_FILE
find / -perm /4000 2>/dev/null | head -20 >> $REPORT_FILE
# Email report
mail -s "Security Compliance Report - $(hostname)" [email protected] < $REPORT_FILE
EOF
chmod +x /usr/local/bin/security-compliance-check.sh
# Add to crontab for weekly reports
echo "0 6 * * 1 /usr/local/bin/security-compliance-check.sh" | crontab -
2. Automated Security Updates
# Configure automatic security updates
cat > /etc/dnf/automatic.conf << 'EOF'
[commands]
upgrade_type = security
random_sleep = 300
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
output_width = 80
[email]
email_from = root@localhost
email_to = [email protected]
email_host = localhost
[base]
debuglevel = 1
EOF
# Enable automatic updates
systemctl enable --now dnf-automatic.timer
Backup and Recovery Security
1. Secure Backup Configuration
# Create secure backup script
cat > /usr/local/bin/secure-backup.sh << 'EOF'
#!/bin/bash
# Secure backup script with encryption
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/system_backup_${DATE}.tar.gz"
ENCRYPTED_FILE="${BACKUP_FILE}.enc"
BACKUP_KEY="/root/.backup_key"
# Create backup directory
mkdir -p ${BACKUP_DIR}
# Generate backup encryption key if not exists
if [ ! -f ${BACKUP_KEY} ]; then
openssl rand -base64 32 > ${BACKUP_KEY}
chmod 600 ${BACKUP_KEY}
fi
# Create backup
tar -czf ${BACKUP_FILE} \
--exclude=/proc \
--exclude=/sys \
--exclude=/dev \
--exclude=/tmp \
--exclude=/var/tmp \
--exclude=/backup \
--exclude=/mnt \
--exclude=/media \
/etc /var /home /root
# Encrypt backup
openssl enc -aes-256-cbc -salt -in ${BACKUP_FILE} -out ${ENCRYPTED_FILE} -pass file:${BACKUP_KEY}
# Remove unencrypted backup
rm -f ${BACKUP_FILE}
# Set secure permissions
chmod 600 ${ENCRYPTED_FILE}
# Remove old backups (keep 30 days)
find ${BACKUP_DIR} -name "*.enc" -mtime +30 -delete
echo "Backup completed: ${ENCRYPTED_FILE}"
EOF
chmod +x /usr/local/bin/secure-backup.sh
# Add to crontab
echo "0 2 * * * /usr/local/bin/secure-backup.sh" | crontab -
Security Maintenance
1. Regular Security Tasks
# Create security maintenance script
cat > /usr/local/bin/security-maintenance.sh << 'EOF'
#!/bin/bash
# Weekly security maintenance tasks
echo "Starting security maintenance - $(date)"
# Update virus definitions
freshclam
# Update rkhunter database
rkhunter --update
# Run rkhunter check
rkhunter --check --skip-keypress
# Check for rootkits with chkrootkit
chkrootkit
# Update AIDE database
aide --update
mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Check system integrity
rpm -Va > /var/log/rpm-verify-$(date +%Y%m%d).log
# Review user accounts
echo "User accounts with UID 0:"
awk -F: '($3 == "0") {print}' /etc/passwd
echo "Security maintenance completed - $(date)"
EOF
chmod +x /usr/local/bin/security-maintenance.sh
2. Incident Response Preparation
# Create incident response toolkit
mkdir -p /root/incident-response
# Create system information collection script
cat > /root/incident-response/collect-evidence.sh << 'EOF'
#!/bin/bash
# Incident Response Evidence Collection
EVIDENCE_DIR="/root/incident-response/evidence-$(date +%Y%m%d_%H%M%S)"
mkdir -p ${EVIDENCE_DIR}
# System information
date > ${EVIDENCE_DIR}/collection_time.txt
hostname > ${EVIDENCE_DIR}/hostname.txt
uname -a > ${EVIDENCE_DIR}/kernel.txt
uptime > ${EVIDENCE_DIR}/uptime.txt
# Running processes
ps auxww > ${EVIDENCE_DIR}/processes.txt
pstree -p > ${EVIDENCE_DIR}/process_tree.txt
# Network connections
ss -antup > ${EVIDENCE_DIR}/network_connections.txt
netstat -rn > ${EVIDENCE_DIR}/routing_table.txt
iptables -L -n -v > ${EVIDENCE_DIR}/iptables.txt
# User information
w > ${EVIDENCE_DIR}/logged_in_users.txt
last -50 > ${EVIDENCE_DIR}/last_logins.txt
lastb -50 > ${EVIDENCE_DIR}/failed_logins.txt
# File system
mount > ${EVIDENCE_DIR}/mounted_filesystems.txt
df -h > ${EVIDENCE_DIR}/disk_usage.txt
lsof > ${EVIDENCE_DIR}/open_files.txt
# Recent logs
tail -1000 /var/log/secure > ${EVIDENCE_DIR}/secure_log.txt
tail -1000 /var/log/messages > ${EVIDENCE_DIR}/messages_log.txt
journalctl -n 1000 > ${EVIDENCE_DIR}/journal_log.txt
# Create archive
tar -czf ${EVIDENCE_DIR}.tar.gz ${EVIDENCE_DIR}/
echo "Evidence collected: ${EVIDENCE_DIR}.tar.gz"
EOF
chmod +x /root/incident-response/collect-evidence.sh
Security Checklist Summary
Daily Tasks
- Review authentication logs
- Check fail2ban status
- Monitor disk usage
- Verify backup completion
Weekly Tasks
- Run security compliance check
- Review SELinux denials
- Check for available updates
- Run vulnerability scanner
Monthly Tasks
- Review user accounts and permissions
- Audit sudo usage
- Check SSL certificate expiration
- Review firewall rules
- Run full system integrity check
Quarterly Tasks
- Perform penetration testing
- Review and update security policies
- Conduct security training
- Update incident response procedures
Conclusion
This comprehensive security checklist provides a solid foundation for hardening Rocky Linux systems. Security is an ongoing process that requires constant vigilance, regular updates, and continuous improvement. By implementing these measures and maintaining them through regular reviews and updates, you can significantly reduce the attack surface and improve the overall security posture of your Rocky Linux infrastructure.
Remember that security requirements vary by organization and use case. This checklist should be adapted to meet your specific needs while maintaining compliance with relevant regulations and industry standards. Regular security assessments and staying informed about new threats and vulnerabilities are essential for maintaining a secure environment.