Security Hardening

Implement CIS benchmarks, harden Linux systems, configure firewalls, enable audit logging, and build defense-in-depth security architectures.

⏱️ 50 minutes 📊 Intermediate 📝 5 steps 🏷️ System Administration

Prerequisites

  • Linux system administration basics
  • Understanding of networking concepts
  • Root/sudo access to target systems
  • Backup of current system configuration

Learning Objectives

  • Apply CIS benchmark security configurations
  • Harden SSH and network services
  • Configure host-based firewalls
  • Implement audit logging and monitoring
  • Set up intrusion detection systems

Step-by-Step Guide

1System Audit and Baseline

Assess current security posture before making changes.

# Install security audit tools
sudo apt update
sudo apt install -y lynis auditd fail2ban rkhunter chkrootkit

# Run Lynis security audit
sudo lynis audit system

# Check for rootkits
sudo rkhunter --check
sudo chkrootkit

# Review current SSH configuration
sudo ssh-vuln-scanner 2>&1 || echo "Manual review needed"
cat /etc/ssh/sshd_config | grep -v "^#" | grep -v "^$"

# Check open ports
sudo ss -tulpn

# Review running services
systemctl list-units --type=service --state=running

# Check for outdated packages
sudo apt list --upgradable

2SSH Hardening

Secure SSH access - the most common attack vector.

# Backup current config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# Create hardened SSH configuration
sudo tee /etc/ssh/sshd_config << 'EOF'
# Basic Settings
Port 2222
Protocol 2
AddressFamily inet

# Authentication
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes

# Security Settings
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
PermitTunnel no
ClientAliveInterval 300
ClientAliveCountMax 2
MaxAuthTries 3
MaxSessions 10

# Logging
SyslogFacility AUTH
LogLevel VERBOSE

# Restrict users (optional)
AllowUsers admin deploy
# AllowGroups sshusers

# Banner
Banner /etc/issue.net

# Disable unused authentication methods
KerberosAuthentication no
GSSAPIAuthentication no
EOF

# Create legal banner
sudo tee /etc/issue.net << 'EOF'
**************************************************************************
AUTHORIZED ACCESS ONLY
This system is for authorized users only. All activities are monitored
and recorded. Unauthorized access will be prosecuted.
**************************************************************************
EOF

# Generate new host keys
sudo rm -f /etc/ssh/ssh_host_*
sudo ssh-keygen -A

# Restart SSH
sudo systemctl restart sshd

# Test new configuration before closing session
ssh -p 2222 your_username@your_server

3Firewall Configuration

Implement host-based firewall with UFW.

# Install and configure UFW
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH (on new port)
sudo ufw allow 2222/tcp comment 'SSH'

# Allow HTTP/HTTPS (if web server)
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'

# Allow specific application ports
sudo ufw allow 3306/tcp from 10.0.0.0/8 comment 'MySQL internal only'
sudo ufw allow 6379/tcp from 127.0.0.1 comment 'Redis local only'

# Enable rate limiting for SSH
sudo ufw limit 2222/tcp

# Enable firewall
sudo ufw enable

# View status
sudo ufw status verbose
sudo ufw status numbered

# For iptables (advanced)
sudo apt install -y iptables-persistent

# Save current rules
sudo iptables-save > /etc/iptables/rules.v4

# Example: Drop invalid packets
sudo iptables -A INPUT -m state --state INVALID -j DROP

# Example: Protect against SYN flood
sudo iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT

# Example: Block known bad countries (using geoip)
sudo apt install -y python3-geoip2
# Download and configure GeoIP blocks

4Audit Logging

Enable comprehensive audit logging for security monitoring.

# Configure auditd
sudo tee /etc/audit/auditd.conf << 'EOF'
# Log format
log_format ENRICHED

# Flush after each write
flush = SYNC

# Admin priority
admin_priority = 10

# Max log file size (MB)
max_log_file = 50

# Number of logs to keep
num_logs = 5

# Space left before action (MB)
space_left = 100

# Action when space is low
space_left_action = EMAIL
admin_space_left_action = SUSPEND
action_mail_acct = root

# Disk full action
disk_full_action = SUSPEND
disk_error_action = SUSPEND

# Delete old logs when rotating
max_log_file_action = ROTATE

# Enable privileged user tracking
admin_pid = 1
EOF

# Add audit rules
sudo tee -a /etc/audit/rules.d/audit.rules << 'EOF'
# Delete existing rules
-D

# Don't load kernel module rules
-B 8

# Set buffer size
-b 8192

# Failure mode (panic on disk full)
-f 1

# Monitor authentication files
-w /etc/passwd -p wa -g identity
-w /etc/group -p wa -g identity
-w /etc/shadow -p wa -g identity
-w /etc/gshadow -p wa -g identity

# Monitor sudo usage
-w /etc/sudoers -p wa -g sudo
-w /etc/sudoers.d/ -p wa -g sudo
-w /var/log/sudo.log -p wa -g sudo

# Monitor SSH
-w /etc/ssh/sshd_config -p wa -g ssh
-w /var/log/auth.log -p wa -g logins

# Monitor kernel modules
-w /sbin/insmod -p x -g modules
-w /sbin/rmmod -p x -g modules
-w /sbin/modprobe -p x -g modules

# Monitor system calls for privilege escalation
-a always,exit -F arch=b64 -S setuid -S setgid -S setreuid -S setregid -F auid>=1000 -F auid!=4294967295 -k priv_esc
-a always,exit -F arch=b32 -S setuid -S setgid -S setreuid -S setregid -F auid>=1000 -F auid!=4294967295 -k priv_esc

# 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 login/logout
-w /var/log/wtmp -p wa -g logins
-w /var/log/btmp -p wa -g logins
-w /var/log/faillog -p wa -g logins

# Monitor cron
-w /etc/crontab -p wa -g cron
-w /var/spool/cron/ -p wa -g cron
-w /etc/cron.d/ -p wa -g cron
-w /etc/cron.daily/ -p wa -g cron
-w /etc/cron.hourly/ -p wa -g cron
-w /etc/cron.monthly/ -p wa -g cron
-w /etc/cron.weekly/ -p wa -g cron
EOF

# Restart auditd
sudo systemctl restart auditd

# Verify rules are loaded
sudo auditctl -l

# Test audit logging
sudo touch /etc/passwd
sudo ausearch -f /etc/passwd

5Intrusion Detection

Deploy fail2ban and OSSEC for intrusion prevention and detection.

# Install and configure fail2ban
sudo apt install -y fail2ban

# Create custom jail configuration
sudo tee /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
# Ban duration (10 minutes)
bantime = 600

# Find time window
findtime = 600

# Max retries before ban
maxretry = 3

# Ban all IPs or exclude ranges
ignoreip = 127.0.0.1/8 10.0.0.0/8 192.168.0.0/16

# Backend
backend = auto

[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600

[apache-auth]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log
maxretry = 5

[nginx-http-auth]
enabled = true
port = http,https
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 5

[nginx-badbots]
enabled = true
port = http,https
filter = nginx-badbots
logpath = /var/log/nginx/access.log
maxretry = 2

[sshd-ddos]
enabled = true
port = 2222
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 6
EOF

# Restart fail2ban
sudo systemctl restart fail2ban
sudo systemctl enable fail2ban

# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd

# View banned IPs
sudo fail2ban-client get sshd bannedhost

# Install OSSEC (HIDS)
sudo apt install -y ossec-hids

# Configure OSSEC
sudo tee -a /var/ossec/etc/ossec.conf << 'EOF'
  
    yes
  

  
    
      yes
    

    
      43200
      /etc,/usr/bin,/usr/sbin
      /etc/mtab
      /etc/hosts.deny
      /etc/mail/statistics
      /etc/random-seed
      /etc/random.seed
      /etc/adjtime
      /etc/httpd/logs
      /etc/utmpx
      /etc/wtmpx
      /etc/cups/certs
      /etc/dumpdates
      /etc/sudoers
    
  
EOF

sudo systemctl restart ossec
sudo systemctl enable ossec

# View OSSEC alerts
tail -f /var/ossec/logs/alerts/alerts.log

Best Practices

Defense in Depth Layers:
  • Physical: Datacenter security, access control
  • Network: Firewalls, segmentation, IDS/IPS
  • Host: OS hardening, patches, HIDS
  • Application: WAF, input validation, secure coding
  • Data: Encryption, DLP, access controls
  • Identity: MFA, PAM, least privilege

Assessment

1. What is the recommended SSH setting for PermitRootLogin?

2. Which tool is used for Linux security auditing?

3. What does CIS stand for?

Answer Key: 1-C, 2-B, 3-A

Resources