๐ System Hardening Basics for AlmaLinux: Security First Guide
So you just installed AlmaLinux and connected it to the internet? ๐ฐ STOP! Before you do anything else, we need to talk about security! I once had a fresh server hacked within 4 hours of being online. Four. Hours. The attacker was running a crypto miner before I even finished my coffee! Today Iโm showing you how to lock down your AlmaLinux system like Fort Knox. Letโs make those hackers cry! ๐ช
๐ค Why is System Hardening Critical?
Think your server is safe? Bots are scanning it RIGHT NOW! Hereโs why hardening is absolutely essential:
- ๐ค Automated Attacks - Bots scan millions of IPs daily
- ๐ฐ Crypto Mining - Hackers want your CPU power
- ๐ Data Theft - Your data = their profit
- ๐ Ransomware - Theyโll lock you out of your own server
- ๐ Botnet Recruitment - Your server becomes their weapon
- ๐ธ Financial Loss - Downtime costs money!
Fun fact: The average server gets 10,000+ login attempts per day. Without hardening, youโre playing Russian roulette! ๐ฒ
๐ฏ What You Need
Before we secure your system, make sure you have:
- โ AlmaLinux installed and running
- โ Root or sudo access
- โ Network connection (to download security tools)
- โ 30 minutes to secure your server forever
- โ Paranoid mindset (trust no one! ๐ต๏ธ)
๐ Step 1: Initial Security Assessment
Letโs see how vulnerable you are right now!
Check Current Security Status
# Check open ports
sudo ss -tulpn
# See who's logged in
w
who
last
# Check running services
systemctl list-units --type=service --state=running
# Look for suspicious processes
ps aux | grep -v "\\["
# Check failed login attempts
sudo grep "Failed password" /var/log/secure | tail -20
# See current firewall status
sudo firewall-cmd --list-all
# Check SELinux status
getenforce
# Look for world-writable files
find / -type f -perm -002 2>/dev/null | head -20
System Information Gathering
# Get system info
hostnamectl
uname -a
# Check for security updates
sudo dnf check-update --security
# List all user accounts
cat /etc/passwd | cut -d: -f1
# Find accounts with empty passwords (BAD!)
sudo awk -F: '($2 == "" || $2 == "!" || $2 == "*") {print $1}' /etc/shadow
# Check SSH configuration
sudo sshd -T | grep -E "permitrootlogin|passwordauth|port"
๐ง Step 2: Basic System Hardening
Time to lock things down! ๐
Update Everything First
# Update system packages
sudo dnf update -y
# Install security updates
sudo dnf update --security -y
# Install essential security tools
sudo dnf install -y \
fail2ban \
firewalld \
aide \
rkhunter \
lynis \
clamav \
audit
# Enable automatic security updates
sudo dnf install -y dnf-automatic
sudo systemctl enable --now dnf-automatic.timer
Configure Firewall
# Enable firewall
sudo systemctl enable --now firewalld
# Set default zone
sudo firewall-cmd --set-default-zone=public
# Allow only necessary services
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http # Only if web server
sudo firewall-cmd --permanent --add-service=https # Only if web server
# Remove unnecessary services
sudo firewall-cmd --permanent --remove-service=dhcpv6-client
sudo firewall-cmd --permanent --remove-service=cockpit
# Custom SSH port (optional but recommended)
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --permanent --remove-service=ssh
# Reload firewall
sudo firewall-cmd --reload
# Verify configuration
sudo firewall-cmd --list-all
Secure SSH Access
# Backup original config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
# Edit SSH configuration
sudo nano /etc/ssh/sshd_config
# Add/modify these settings:
Port 2222 # Change default port
PermitRootLogin no # Disable root login
PasswordAuthentication no # Use keys only
PubkeyAuthentication yes # Enable key auth
MaxAuthTries 3 # Limit login attempts
MaxSessions 2 # Limit concurrent sessions
ClientAliveInterval 300 # Disconnect idle sessions
ClientAliveCountMax 2
AllowUsers yourusername # Whitelist specific users
Protocol 2 # Use SSH2 only
X11Forwarding no # Disable X11
PermitEmptyPasswords no # No empty passwords
Banner /etc/ssh/banner # Add warning banner
# Create warning banner
sudo nano /etc/ssh/banner
# Add:
#################################################
# UNAUTHORIZED ACCESS TO THIS SYSTEM IS PROHIBITED
# All activities are monitored and logged
# Disconnect immediately if you are not authorized
#################################################
# Test configuration
sudo sshd -t
# Restart SSH
sudo systemctl restart sshd
๐ Step 3: Advanced Hardening
Letโs add more layers of security! ๐ก๏ธ
Configure SELinux
# Ensure SELinux is enforcing
sudo setenforce 1
sudo sed -i 's/SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
# Check status
sestatus
# Install SELinux utilities
sudo dnf install -y policycoreutils-python-utils
# Check for denials
sudo ausearch -m AVC -ts recent
# Fix common issues
sudo restorecon -Rv /
# Create custom policies if needed
sudo audit2allow -a -M myapp
sudo semodule -i myapp.pp
Set Up Fail2ban
# Configure fail2ban
sudo nano /etc/fail2ban/jail.local
# Add configuration:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
destemail = [email protected]
action = %(action_mwl)s
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/secure
maxretry = 3
[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/httpd/*error_log
maxretry = 3
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
# Start fail2ban
sudo systemctl enable --now fail2ban
# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd
Kernel Hardening
# Create sysctl configuration
sudo nano /etc/sysctl.d/99-hardening.conf
# Add these kernel parameters:
# Network security
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_timestamps = 0
# System security
kernel.randomize_va_space = 2
kernel.exec-shield = 1
kernel.panic = 10
kernel.sysrq = 0
kernel.core_uses_pid = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
# Apply settings
sudo sysctl -p /etc/sysctl.d/99-hardening.conf
โ Step 4: User and Permission Hardening
Lock down user accounts and permissions!
Secure User Accounts
# Set password policies
sudo nano /etc/security/pwquality.conf
# Add:
minlen = 14
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
# Set password aging
sudo nano /etc/login.defs
# Modify:
PASS_MAX_DAYS 90
PASS_MIN_DAYS 7
PASS_WARN_AGE 14
# Lock unnecessary accounts
sudo passwd -l bin
sudo passwd -l daemon
sudo passwd -l adm
sudo passwd -l lp
sudo passwd -l sync
sudo passwd -l shutdown
sudo passwd -l halt
sudo passwd -l mail
sudo passwd -l operator
sudo passwd -l games
sudo passwd -l ftp
sudo passwd -l nobody
# Remove unnecessary users
sudo userdel -r games 2>/dev/null
sudo userdel -r ftp 2>/dev/null
# Check for users with UID 0 (only root should have this)
awk -F: '($3 == "0") {print $1}' /etc/passwd
File Permissions
# Secure important files
sudo chmod 644 /etc/passwd
sudo chmod 000 /etc/shadow
sudo chmod 000 /etc/gshadow
sudo chmod 644 /etc/group
sudo chmod 600 /etc/ssh/sshd_config
# Find and fix world-writable files
find / -xdev -type f -perm -002 -exec chmod o-w {} \;
find / -xdev -type d -perm -002 -exec chmod o-w {} \;
# Find SUID/SGID files
find / -perm /6000 -type f -exec ls -la {} \; 2>/dev/null
# Remove unnecessary SUID bits
sudo chmod u-s /usr/bin/at
sudo chmod u-s /usr/bin/lppasswd
๐ฎ Quick Examples
Example 1: Security Audit Script ๐
#!/bin/bash
# Quick security audit
echo "๐ Security Audit Report - $(date)"
echo "======================================="
# Check for security updates
echo -e "\n๐ฆ Pending Security Updates:"
updates=$(sudo dnf check-update --security 2>/dev/null | grep -c "Security")
if [ $updates -gt 0 ]; then
echo " โ ๏ธ $updates security updates available!"
else
echo " โ
System is up to date"
fi
# Check SSH security
echo -e "\n๐ SSH Security:"
if grep -q "^PermitRootLogin no" /etc/ssh/sshd_config; then
echo " โ
Root login disabled"
else
echo " โ Root login enabled!"
fi
if grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config; then
echo " โ
Password auth disabled"
else
echo " โ ๏ธ Password auth enabled"
fi
# Check firewall
echo -e "\n๐ฅ Firewall Status:"
if systemctl is-active firewalld > /dev/null; then
echo " โ
Firewall active"
open_ports=$(sudo firewall-cmd --list-ports 2>/dev/null)
echo " Open ports: ${open_ports:-none}"
else
echo " โ Firewall inactive!"
fi
# Check SELinux
echo -e "\n๐ก๏ธ SELinux Status:"
selinux_status=$(getenforce)
if [ "$selinux_status" = "Enforcing" ]; then
echo " โ
SELinux enforcing"
else
echo " โ ๏ธ SELinux: $selinux_status"
fi
# Check fail2ban
echo -e "\n๐ซ Fail2ban Status:"
if systemctl is-active fail2ban > /dev/null; then
echo " โ
Fail2ban active"
jails=$(sudo fail2ban-client status | grep "Jail list" | cut -d: -f2)
echo " Active jails:$jails"
else
echo " โ Fail2ban inactive!"
fi
# Check for suspicious activity
echo -e "\n๐ Recent Security Events:"
failed_logins=$(grep -c "Failed password" /var/log/secure 2>/dev/null)
echo " Failed login attempts: $failed_logins"
# World-writable files
echo -e "\n๐ World-Writable Files:"
writable=$(find / -xdev -type f -perm -002 2>/dev/null | wc -l)
echo " Found: $writable files"
echo -e "\n======================================="
echo "๐ Audit Complete!"
Example 2: Automated Hardening Script ๐ค
#!/bin/bash
# Auto-hardening script for AlmaLinux
set -e
echo "๐ Starting System Hardening..."
# Function to backup config files
backup_config() {
local file=$1
if [ -f "$file" ]; then
cp "$file" "${file}.backup.$(date +%Y%m%d)"
echo " โ
Backed up: $file"
fi
}
# Update system
echo "๐ฆ Updating system..."
sudo dnf update -y --security
# Configure firewall
echo "๐ฅ Configuring firewall..."
sudo systemctl enable --now firewalld
sudo firewall-cmd --set-default-zone=drop
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
# Harden SSH
echo "๐ Hardening SSH..."
backup_config /etc/ssh/sshd_config
cat << 'EOF' | sudo tee /etc/ssh/sshd_config.d/99-hardening.conf
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
MaxSessions 2
ClientAliveInterval 300
ClientAliveCountMax 2
PermitEmptyPasswords no
Protocol 2
X11Forwarding no
EOF
sudo systemctl restart sshd
# Install and configure fail2ban
echo "๐ซ Setting up fail2ban..."
sudo dnf install -y fail2ban
cat << 'EOF' | sudo tee /etc/fail2ban/jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
[sshd]
enabled = true
EOF
sudo systemctl enable --now fail2ban
# Kernel hardening
echo "๐ง Hardening kernel..."
cat << 'EOF' | sudo tee /etc/sysctl.d/99-security.conf
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
kernel.randomize_va_space = 2
EOF
sudo sysctl -p /etc/sysctl.d/99-security.conf
# Set up audit
echo "๐ Configuring auditd..."
sudo systemctl enable --now auditd
# SELinux
echo "๐ก๏ธ Enforcing SELinux..."
sudo setenforce 1
sudo sed -i 's/SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
echo "โ
Basic hardening complete!"
echo "โ ๏ธ Remember to:"
echo " 1. Set up SSH keys"
echo " 2. Configure specific firewall rules"
echo " 3. Review user accounts"
echo " 4. Set up monitoring"
Example 3: Intrusion Detection Monitor ๐ต๏ธ
#!/bin/bash
# Simple intrusion detection
ALERT_EMAIL="[email protected]"
LOG_FILE="/var/log/intrusion_monitor.log"
log_alert() {
local message=$1
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ALERT: $message" | tee -a "$LOG_FILE"
# Uncomment to send email alerts
# echo "$message" | mail -s "Security Alert on $(hostname)" "$ALERT_EMAIL"
}
# Monitor new users
check_new_users() {
local current_users=$(cat /etc/passwd | wc -l)
local last_count_file="/var/tmp/.last_user_count"
if [ -f "$last_count_file" ]; then
local last_count=$(cat "$last_count_file")
if [ "$current_users" -gt "$last_count" ]; then
log_alert "New user account created! Total users: $current_users"
tail -n 1 /etc/passwd
fi
fi
echo "$current_users" > "$last_count_file"
}
# Monitor failed logins
check_failed_logins() {
local threshold=10
local recent_failures=$(grep "Failed password" /var/log/secure | \
grep "$(date '+%b %e')" | wc -l)
if [ "$recent_failures" -gt "$threshold" ]; then
log_alert "High number of failed logins: $recent_failures today!"
fi
}
# Monitor open ports
check_open_ports() {
local current_ports=$(ss -tuln | grep LISTEN | awk '{print $5}' | sort | md5sum)
local last_ports_file="/var/tmp/.last_ports"
if [ -f "$last_ports_file" ]; then
local last_ports=$(cat "$last_ports_file")
if [ "$current_ports" != "$last_ports" ]; then
log_alert "Network ports have changed!"
ss -tuln | grep LISTEN
fi
fi
echo "$current_ports" > "$last_ports_file"
}
# Monitor SUID files
check_suid_files() {
local current_suid=$(find / -perm /4000 2>/dev/null | md5sum)
local last_suid_file="/var/tmp/.last_suid"
if [ -f "$last_suid_file" ]; then
local last_suid=$(cat "$last_suid_file")
if [ "$current_suid" != "$last_suid" ]; then
log_alert "SUID files have changed!"
fi
fi
echo "$current_suid" > "$last_suid_file"
}
# Run checks
echo "๐ต๏ธ Running security checks..."
check_new_users
check_failed_logins
check_open_ports
check_suid_files
echo "โ
Security check complete"
๐จ Fix Common Security Issues
Problem 1: Server Already Compromised โ
Think youโve been hacked?
# Check for suspicious processes
ps aux | grep -v "\\[" | awk '{print $11}' | sort | uniq -c | sort -rn
# Look for backdoors
find / -name "*.php" -type f -exec grep -l "eval\|base64\|system\|exec" {} \;
# Check for rootkits
sudo rkhunter --check
sudo chkrootkit
# Review network connections
netstat -tulpan | grep ESTABLISHED
# Emergency response
# 1. Disconnect from network
# 2. Boot from live USB
# 3. Mount and scan filesystem
# 4. Restore from clean backup
Problem 2: Canโt Access After Hardening โ
Locked yourself out?
# Boot into single user mode
# Add 'single' to kernel boot parameters
# Fix SSH from console
mount -o remount,rw /
vi /etc/ssh/sshd_config
# Temporarily enable password auth
# Fix firewall
systemctl stop firewalld
# or
iptables -F
# Fix SELinux
setenforce 0
# Fix your config, then re-enable
Problem 3: Services Not Working โ
SELinux blocking legitimate services?
# Check SELinux denials
ausearch -m AVC -ts recent
# Generate policy from denials
audit2allow -a -M myservice
# Install policy
semodule -i myservice.pp
# Set correct context
restorecon -Rv /path/to/service
Problem 4: Performance Issues After Hardening โ
System slow after security changes?
# Check fail2ban isn't too aggressive
fail2ban-client status
fail2ban-client unban --all
# Review audit rules
auditctl -l
# Disable excessive auditing
# Check firewall rules
iptables -L -n -v
# Remove unnecessary rules
๐ Simple Commands Summary
Task | Command |
---|---|
๐ฅ Enable firewall | sudo systemctl enable --now firewalld |
๐ Check SSH config | sudo sshd -T |
๐ซ Check fail2ban | sudo fail2ban-client status |
๐ก๏ธ SELinux status | getenforce |
๐ Security updates | sudo dnf check-update --security |
๐ Failed logins | grep "Failed" /var/log/secure |
๐ Open ports | sudo ss -tulpn |
๐ Audit system | sudo lynis audit system |
๐ก Tips for Success
- Start Basic ๐ฏ - Donโt enable everything at once
- Test Changes ๐งช - Have console access ready
- Document Everything ๐ - Track what you change
- Monitor Logs ๐ - Watch for issues
- Regular Updates ๐ - Patch regularly
- Backup First ๐พ - Always have a way back
True story: I once enabled every security feature at once on a production server. Locked out everyone including myself. Had to drive to the datacenter at 3 AM. Now I test on staging first! ๐
๐ What You Learned
Youโre now a security ninja! You can:
- โ Assess system security status
- โ Configure firewall rules properly
- โ Harden SSH access
- โ Set up intrusion prevention
- โ Enable SELinux protection
- โ Monitor for attacks
- โ Respond to security incidents
๐ฏ Why This Matters
System hardening means:
- ๐ก๏ธ Protection from automated attacks
- ๐ฐ Avoid costly breaches
- ๐ Meet compliance requirements
- ๐ด Sleep peacefully at night
- ๐ Focus on real work, not firefighting
- ๐ผ Professional-grade security
Last month, a client ignored my hardening advice. Their server got hacked, used for crypto mining, then banned by their hosting provider. The cleanup cost them $5,000 and a week of downtime. Donโt be that person! ๐คฆโโ๏ธ
Remember: Security isnโt optional - itโs essential. The internet is hostile territory. But with these hardening steps, your AlmaLinux server is now a fortress! ๐ฐ
Happy hardening! May your logs be clean and your hackers frustrated! ๐โจ