+
nim
+
+
+
couchdb
symfony
+
mysql
+
+
+
+
react
elixir
+
::
+
+
dask
+
+
+
vb
+
pascal
+
+
[]
swift
+
php
emacs
rb
+
โ‰ˆ
cypress
+
+
+
junit
+
aurelia
+
โŠ‚
+
+
azure
+
+
+
+
yarn
pytest
+
zig
http
+
+
+
vscode
@
haskell
==
+
jax
+
+
โŠ‚
+
+
+
&
+
+
+
โ‰ˆ
neo4j
+
+
+
astro
+
+
docker
argocd
+
*
+
linux
Back to Blog
๐Ÿ”’ System Hardening Basics for AlmaLinux: Security First Guide
AlmaLinux Security Hardening

๐Ÿ”’ System Hardening Basics for AlmaLinux: Security First Guide

Published Aug 20, 2025

Learn essential system hardening techniques for AlmaLinux. Secure your server with firewall rules, SELinux, fail2ban, SSH hardening, and security best practices for beginners.

12 min read
0 views
Table of Contents

๐Ÿ”’ 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

TaskCommand
๐Ÿ”ฅ Enable firewallsudo systemctl enable --now firewalld
๐Ÿ”’ Check SSH configsudo sshd -T
๐Ÿšซ Check fail2bansudo fail2ban-client status
๐Ÿ›ก๏ธ SELinux statusgetenforce
๐Ÿ“Š Security updatessudo dnf check-update --security
๐Ÿ‘€ Failed loginsgrep "Failed" /var/log/secure
๐Ÿ” Open portssudo ss -tulpn
๐Ÿ“ Audit systemsudo lynis audit system

๐Ÿ’ก Tips for Success

  1. Start Basic ๐ŸŽฏ - Donโ€™t enable everything at once
  2. Test Changes ๐Ÿงช - Have console access ready
  3. Document Everything ๐Ÿ“ - Track what you change
  4. Monitor Logs ๐Ÿ“Š - Watch for issues
  5. Regular Updates ๐Ÿ”„ - Patch regularly
  6. 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! ๐Ÿ”’โœจ