Lesson 10 of 10
Practice & Quiz - Linux Security & Hardening
Test your Linux security skills: file permissions, SSH hardening, auditd log analysis, and system hardening scripts with a practical bash hardening exercise and 5 quiz questions.
Practical Exercise - Linux System Hardening Script
#!/usr/bin/env bash
# Linux Security Hardening Script (CIS Benchmark aligned)
# Run as root. Review each section before applying to production.
set -euo pipefail
LOG="/var/log/hardening_$(date +%Y%m%d_%H%M%S).log"
exec > >(tee -a "$LOG") 2>&1
echo "=== Linux Hardening Script - $(date) ==="
echo "Hostname: $(hostname) | Kernel: $(uname -r)"
# ─── 1. SSH Hardening ─────────────────────────────────────────
echo -e "\n[1] Hardening SSH..."
SSHD_CONF="/etc/ssh/sshd_config"
cp "$SSHD_CONF" "${SSHD_CONF}.bak.$(date +%s)"
# Apply CIS-recommended SSH settings
declare -A SSH_SETTINGS=(
["PermitRootLogin"]="no" # never SSH as root
["PasswordAuthentication"]="no" # keys only
["PubkeyAuthentication"]="yes"
["AuthorizedKeysFile"]=".ssh/authorized_keys"
["PermitEmptyPasswords"]="no"
["X11Forwarding"]="no" # disable X11 forwarding
["MaxAuthTries"]="3" # lock after 3 failed attempts
["ClientAliveInterval"]="300" # disconnect idle sessions after 5 min
["ClientAliveCountMax"]="2"
["LoginGraceTime"]="60" # 60s to authenticate
["Protocol"]="2" # SSHv1 is deprecated and vulnerable
["AllowGroups"]="sshusers" # only members of sshusers group
["UsePAM"]="yes"
["Ciphers"]="chacha20-poly1305@openssh.com,aes256-gcm@openssh.com"
["MACs"]="hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com"
["KexAlgorithms"]="curve25519-sha256,diffie-hellman-group16-sha512"
)
for key in "${!SSH_SETTINGS[@]}"; do
value="${SSH_SETTINGS[$key]}"
if grep -qE "^#?\s*$key" "$SSHD_CONF"; then
sed -i "s|^#\?\s*$key.*|$key $value|" "$SSHD_CONF"
else
echo "$key $value" >> "$SSHD_CONF"
fi
echo " SET: $key = $value"
done
sshd -t && echo "SSH config syntax OK" || { echo "SSH config ERROR - check $SSHD_CONF"; exit 1; }
systemctl reload sshd && echo "SSH reloaded"
# ─── 2. Filesystem Permissions Audit ─────────────────────────
echo -e "\n[2] Filesystem Permission Audit..."
# Find world-writable files (anyone can modify - dangerous)
echo "World-writable files (excluding /proc /sys /dev):"
find / -xdev -type f -perm -0002 \
! -path "/proc/*" ! -path "/sys/*" ! -path "/dev/*" \
-ls 2>/dev/null | head -20
# Find SUID/SGID binaries (execute with owner's privileges)
echo "\nSUID binaries (execute as root - audit carefully):"
find / -xdev -type f \( -perm -4000 -o -perm -2000 \) -ls 2>/dev/null
# Find files with no owner (orphaned files - potential backdoor)
echo "\nFiles with no owner:"
find / -xdev \( -nouser -o -nogroup \) -ls 2>/dev/null | head -10
# ─── 3. auditd Rules for Key Security Events ─────────────────
echo -e "\n[3] Configuring auditd rules..."
if command -v auditctl &>/dev/null; then
cat > /etc/audit/rules.d/security.rules << 'RULES'
# Monitor sudo usage
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/sudo -k sudo_usage
# Monitor /etc/passwd and shadow changes (user modification)
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers_change
# Monitor SSH key directory changes
-w /root/.ssh -p rwxa -k ssh_keys
# Monitor login/logout events
-w /var/log/lastlog -p wa -k login
# Monitor privilege escalation
-a always,exit -F arch=b64 -S setuid -S setgid -k privilege_escalation
# Capture all failed system calls
-a always,exit -F arch=b64 -S all -F success=0 -k failed_syscalls
RULES
service auditd restart && echo "auditd rules applied"
fi
# ─── 4. Parse audit logs for suspicious events ───────────────
python3 << 'PYEOF'
import subprocess, re
from collections import Counter
# Parse sudo usage from audit log
result = subprocess.run(['ausearch', '-k', 'sudo_usage', '--interpret'],
capture_output=True, text=True)
sudo_users = Counter(re.findall(r'auid=(S+)', result.stdout))
print("\nSudo usage by user (last 24h):")
for user, count in sudo_users.most_common(10):
flag = " ← INVESTIGATE" if count > 50 else ""
print(f" {user}: {count} executions{flag}")
PYEOF
echo "\nHardening complete. Review log: $LOG"Module Quiz
What does a file permission of `chmod 4755` (SUID bit) on a binary do and why is it a security risk?
Tip
Tip
Practice Practice Quiz Linux Security Hardening in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Linux Security Hardening from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Linux Security Hardening is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Finished this lesson?