๐ AlmaLinux Security: Complete SELinux & Hardening Guide
Welcome to the fortress of AlmaLinux security! ๐ก๏ธ Whether youโre protecting sensitive data, defending against cyber threats, or ensuring compliance, this comprehensive guide will transform you into a security expert who can lock down systems tighter than Fort Knox! ๐
Security isnโt just about installing firewalls โ itโs about creating multiple layers of defense that work together to protect your valuable data and services. Letโs build an impenetrable security fortress! ๐ช
๐ค Why is SELinux and Security Hardening Important?
Imagine having a bouncer at every door, window, and ventilation shaft of your system โ thatโs SELinux! ๐ช Hereโs why mastering security on AlmaLinux is absolutely critical:
- ๐ก๏ธ Multi-Layer Defense - Protection at kernel, application, and network levels
- ๐ Mandatory Access Control - Even root canโt bypass security policies
- ๐ฏ Targeted Protection - Confine services to minimum required permissions
- ๐จ Intrusion Prevention - Stop attacks before they cause damage
- ๐ Compliance Requirements - Meet industry security standards
- ๐ Audit Trail - Track every security-relevant event
- ๐ฐ Data Protection - Prevent costly data breaches
- ๐ Zero Trust Architecture - Never trust, always verify
๐ฏ What You Need
Letโs prepare your security toolkit for maximum protection! โ
System Requirements:
- โ AlmaLinux 8.x or 9.x installation
- โ Root or sudo access for configuration
- โ Basic understanding of Linux permissions
- โ Network connectivity for security updates
- โ At least 2GB free disk space for logs
Security Tools Weโll Configure:
- โ SELinux (Security-Enhanced Linux)
- โ Firewalld for network protection
- โ Fail2ban for intrusion prevention
- โ AIDE for file integrity monitoring
- โ Audit daemon for security logging
๐ Understanding and Configuring SELinux
Letโs master SELinux, your systemโs most powerful security feature! ๐ง
SELinux Basics and Modes
# Check current SELinux status
sestatus
# Check SELinux mode
getenforce
# SELinux modes:
# Enforcing - SELinux is active and blocking violations
# Permissive - SELinux logs violations but doesn't block
# Disabled - SELinux is completely off (NOT recommended!)
# Temporarily change SELinux mode
sudo setenforce 0 # Set to Permissive
sudo setenforce 1 # Set to Enforcing
# Permanently change SELinux mode
sudo vi /etc/selinux/config
# Change SELINUX=enforcing/permissive/disabled
# View SELinux contexts
ls -Z /var/www/html/
ps -eZ | grep httpd
# Check SELinux denials
sudo ausearch -m AVC -ts recent
sudo sealert -a /var/log/audit/audit.log
Managing SELinux Contexts
# View file contexts
ls -lZ /var/www/html/
# Change file context
sudo semanage fcontext -a -t httpd_sys_content_t '/webdata(/.*)?'
sudo restorecon -Rv /webdata
# Copy context from another file
sudo chcon --reference=/var/www/html /custom/web/directory
# Restore default contexts
sudo restorecon -Rv /var/www/
# View current context mappings
sudo semanage fcontext -l
# Add custom context permanently
sudo semanage fcontext -a -t samba_share_t '/shared(/.*)?'
sudo restorecon -Rv /shared
SELinux Booleans and Policies
# List all SELinux booleans
getsebool -a
# Check specific boolean
getsebool httpd_can_network_connect
# Enable boolean temporarily
sudo setsebool httpd_can_network_connect on
# Enable boolean permanently
sudo setsebool -P httpd_can_network_connect on
# Common useful booleans
sudo setsebool -P httpd_can_network_connect_db on # Allow web server to connect to database
sudo setsebool -P httpd_enable_cgi on # Enable CGI scripts
sudo setsebool -P ftpd_full_access on # Allow FTP full access
sudo setsebool -P samba_enable_home_dirs on # Allow Samba to share home directories
# Install SELinux policy tools
sudo dnf install -y setools-console policycoreutils-python-utils
๐ง System Hardening Best Practices
Letโs implement comprehensive system hardening! ๐ก๏ธ
Secure SSH Configuration
# Backup SSH configuration
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
# Secure SSH settings
sudo tee /etc/ssh/sshd_config.d/99-security.conf << 'EOF'
# Security hardening settings
Protocol 2
Port 2222 # Change default port
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowUsers yourusername # Restrict to specific users
# Or use AllowGroups sshusers
# Disable weak ciphers
Ciphers [email protected],[email protected],[email protected]
MACs [email protected],[email protected]
KexAlgorithms curve25519-sha256,[email protected]
EOF
# Restart SSH service
sudo systemctl restart sshd
# Configure SSH key authentication
ssh-keygen -t ed25519 -C "[email protected]"
ssh-copy-id -p 2222 user@server
Firewall Configuration
# Enable and start firewalld
sudo systemctl enable --now firewalld
# Check firewall status
sudo firewall-cmd --state
sudo firewall-cmd --get-active-zones
# Configure default zone
sudo firewall-cmd --set-default-zone=public
# Add services
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
# Add custom port
sudo firewall-cmd --permanent --add-port=2222/tcp
# Remove unnecessary services
sudo firewall-cmd --permanent --remove-service=dhcpv6-client
# Add rich rules for specific IPs
sudo firewall-cmd --permanent --add-rich-rule='
rule family="ipv4"
source address="192.168.1.100/32"
port protocol="tcp" port="22" accept'
# Enable logging
sudo firewall-cmd --set-log-denied=all
# Reload firewall
sudo firewall-cmd --reload
# List all rules
sudo firewall-cmd --list-all
๐ Intrusion Detection and Prevention
Set up comprehensive intrusion detection systems! ๐จ
Installing and Configuring Fail2ban
# Install fail2ban
sudo dnf install -y epel-release
sudo dnf install -y fail2ban fail2ban-systemd
# Create local configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# Configure fail2ban
sudo tee /etc/fail2ban/jail.d/sshd.local << 'EOF'
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/secure
maxretry = 3
findtime = 600
bantime = 3600
ignoreip = 127.0.0.1/8 192.168.1.0/24
EOF
# Apache/Nginx protection
sudo tee /etc/fail2ban/jail.d/apache.local << 'EOF'
[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/httpd/error_log
maxretry = 3
bantime = 3600
[apache-badbots]
enabled = true
port = http,https
filter = apache-badbots
logpath = /var/log/httpd/access_log
maxretry = 1
bantime = 86400
EOF
# Start and enable fail2ban
sudo systemctl enable --now fail2ban
# Check fail2ban status
sudo fail2ban-client status
sudo fail2ban-client status sshd
# Unban an IP
sudo fail2ban-client unban 192.168.1.100
File Integrity Monitoring with AIDE
# Install AIDE
sudo dnf install -y aide
# Initialize AIDE database
sudo aide --init
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Configure AIDE
sudo tee /etc/aide.conf.d/custom.conf << 'EOF'
# Custom AIDE rules
/etc/passwd p+u+g+s+m+c+md5+sha256
/etc/shadow p+u+g+s+m+c+md5+sha256
/etc/ssh/sshd_config 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
EOF
# Run AIDE check
sudo aide --check
# Update database after legitimate changes
sudo aide --update
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
# Create AIDE cron job
sudo tee /etc/cron.daily/aide-check << 'EOF'
#!/bin/bash
/usr/sbin/aide --check | mail -s "AIDE Report $(hostname)" [email protected]
EOF
sudo chmod +x /etc/cron.daily/aide-check
โ Security Auditing and Monitoring
Implement comprehensive security auditing! ๐
Configuring Audit Daemon
# Install audit tools
sudo dnf install -y audit audit-libs
# Enable and start auditd
sudo systemctl enable --now auditd
# Configure audit rules
sudo tee -a /etc/audit/rules.d/security.rules << 'EOF'
# Monitor authentication events
-w /var/log/lastlog -p wa -k authentication
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
# Monitor SSH configuration
-w /etc/ssh/sshd_config -p wa -k sshd_config
# Monitor kernel modules
-w /sbin/insmod -p x -k kernel_modules
-w /sbin/rmmod -p x -k kernel_modules
-w /sbin/modprobe -p x -k kernel_modules
# Monitor network configuration
-a always,exit -F arch=b64 -S sethostname -S setdomainname -k network_changes
# Monitor privilege escalation
-a always,exit -F arch=b64 -S setuid -S setgid -S setreuid -S setregid -k privilege_escalation
# Monitor file deletion
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -k file_deletion
EOF
# Load new rules
sudo augenrules --load
# Search audit logs
sudo ausearch -k authentication
sudo ausearch -m USER_LOGIN
sudo aureport --summary
Security Scanning and Vulnerability Assessment
# Install security scanning tools
sudo dnf install -y openscap openscap-scanner scap-security-guide
# Run security compliance scan
sudo oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \
/usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xml
# Generate HTML report
sudo oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis \
--results results.xml \
--report report.html \
/usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xml
# Install Lynis for security auditing
sudo dnf install -y lynis
# Run Lynis audit
sudo lynis audit system
# Check for rootkits
sudo dnf install -y rkhunter
sudo rkhunter --update
sudo rkhunter --check
๐ฎ Quick Examples
Example 1: Securing Web Server with SELinux
# Allow httpd to connect to database
sudo setsebool -P httpd_can_network_connect_db on
# Allow httpd to send mail
sudo setsebool -P httpd_can_sendmail on
# Set correct context for custom web directory
sudo semanage fcontext -a -t httpd_sys_content_t '/srv/website(/.*)?'
sudo restorecon -Rv /srv/website
# Allow httpd to bind to custom port
sudo semanage port -a -t http_port_t -p tcp 8080
# Check for SELinux denials related to httpd
sudo ausearch -m AVC -c httpd
Example 2: Automated Security Updates
# Install automatic updates
sudo dnf install -y dnf-automatic
# Configure automatic security updates
sudo tee /etc/dnf/automatic.conf << 'EOF'
[commands]
upgrade_type = security
download_updates = yes
apply_updates = yes
random_sleep = 360
[emitters]
emit_via = motd
system_name = AlmaLinux Security Updates
[email]
email_from = root@localhost
email_to = [email protected]
email_host = localhost
[command_email]
email_from = root@localhost
email_to = [email protected]
EOF
# Enable automatic updates
sudo systemctl enable --now dnf-automatic.timer
# Check timer status
sudo systemctl status dnf-automatic.timer
Example 3: Creating Security Monitoring Dashboard
# Create security monitoring script
sudo tee /usr/local/bin/security-monitor.sh << 'EOF'
#!/bin/bash
echo "=== Security Status Report ==="
echo "Date: $(date)"
echo ""
echo "=== SELinux Status ==="
sestatus | grep -E "SELinux status|Current mode"
echo -e "\n=== Failed Login Attempts (Last 24h) ==="
sudo grep "Failed password" /var/log/secure | grep "$(date '+%b %d')" | wc -l
echo -e "\n=== Fail2ban Status ==="
sudo fail2ban-client status | grep "Jail list"
echo -e "\n=== Active Network Connections ==="
sudo ss -tuln | grep LISTEN
echo -e "\n=== Recent Security Events ==="
sudo aureport --summary --start today
echo -e "\n=== System Updates Available ==="
sudo dnf check-update --security 2>/dev/null | grep -c "."
echo -e "\n=== Disk Usage ==="
df -h | grep -vE '^Filesystem|tmpfs|cdrom'
echo -e "\n=== Top CPU Processes ==="
ps aux --sort=-%cpu | head -5
EOF
sudo chmod +x /usr/local/bin/security-monitor.sh
# Create cron job for daily report
echo "0 6 * * * /usr/local/bin/security-monitor.sh | mail -s 'Security Report' [email protected]" | sudo crontab -
๐จ Fix Common Security Issues
Letโs solve frequent security problems! ๐ ๏ธ
Problem 1: SELinux Blocking Service
Symptoms: Service fails with permission denied, works when SELinux is disabled Solution:
# Check for SELinux denials
sudo ausearch -m AVC -ts recent
# Generate policy to allow the action
sudo ausearch -m AVC -ts recent | audit2allow -M myapp
sudo semodule -i myapp.pp
# Alternative: Set correct context
sudo semanage fcontext -a -t appropriate_type_t '/path/to/file'
sudo restorecon -v '/path/to/file'
Problem 2: Canโt Access Service After Firewall Setup
Symptoms: Service unreachable from network Solution:
# Check if port is open
sudo firewall-cmd --list-ports
# Add the service or port
sudo firewall-cmd --permanent --add-service=servicename
# OR
sudo firewall-cmd --permanent --add-port=8080/tcp
# Reload firewall
sudo firewall-cmd --reload
# Verify
sudo ss -tuln | grep :8080
Problem 3: Locked Out by Fail2ban
Symptoms: Canโt SSH to server, IP is banned Solution:
# From console or different IP:
sudo fail2ban-client status sshd
sudo fail2ban-client unban YOUR.IP.ADDRESS
# Whitelist IP to prevent future bans
sudo vi /etc/fail2ban/jail.local
# Add to ignoreip line: YOUR.IP.ADDRESS
sudo systemctl restart fail2ban
Problem 4: Audit Log Filling Disk
Symptoms: /var/log/audit/ consuming too much space Solution:
# Configure log rotation
sudo vi /etc/audit/auditd.conf
# Set:
# max_log_file = 50
# num_logs = 5
# max_log_file_action = ROTATE
# Clean old logs
sudo service auditd stop
sudo rm /var/log/audit/audit.log.*
sudo service auditd start
๐ Security Command Quick Reference
Essential security commands at your fingertips! โก
Command | Purpose |
---|---|
sestatus | Check SELinux status |
getenforce | Get SELinux mode |
setenforce 1 | Enable SELinux |
restorecon -Rv /path | Restore SELinux contexts |
getsebool -a | List SELinux booleans |
firewall-cmd --list-all | Show firewall rules |
fail2ban-client status | Check fail2ban |
ausearch -m AVC | Search SELinux denials |
aide --check | Run integrity check |
aureport --summary | Audit summary |
๐ก Security Best Practices
Become a security expert with these pro tips! ๐ฏ
- ๐ Defense in Depth - Layer multiple security controls
- ๐ Regular Updates - Apply security patches immediately
- ๐ Principle of Least Privilege - Grant minimum necessary permissions
- ๐จ Monitor Everything - Log and alert on suspicious activity
- ๐ก๏ธ Keep SELinux Enforcing - Never disable SELinux in production
- ๐ Strong Authentication - Use keys, not passwords
- ๐ Regular Audits - Schedule security scans weekly
- ๐พ Backup Security Configs - Version control security settings
- ๐ Network Segmentation - Isolate critical services
- ๐ Stay Informed - Subscribe to security advisories
๐ What Youโve Accomplished
Congratulations on mastering AlmaLinux security! ๐ Youโve achieved:
- โ Complete SELinux mastery with contexts and policies
- โ System hardening implementation completed
- โ Firewall configuration for network protection
- โ Intrusion prevention with fail2ban setup
- โ File integrity monitoring using AIDE
- โ Security auditing with auditd configured
- โ Vulnerability scanning tools deployed
- โ SSH hardening for secure access
- โ Automated security updates enabled
- โ Security monitoring and alerting established
๐ฏ Why These Skills Matter
Your security expertise protects what matters most! ๐ With these skills, you can:
Immediate Benefits:
- ๐ก๏ธ Prevent 99% of common attacks
- ๐ Detect intrusions within minutes
- ๐ Meet compliance requirements
- ๐ฐ Avoid costly data breaches
Long-term Value:
- ๐ Become the security expert everyone relies on
- ๐ผ Command higher salaries in cybersecurity
- ๐ Protect critical infrastructure
- ๐ Build zero-trust architectures
Youโre now equipped to defend against sophisticated threats and build security into every layer of your infrastructure! Remember, security isnโt a product โ itโs a process, and youโre now a master of that process! ๐
Stay vigilant, stay secure! ๐