SECURE YOUR
SERVER

// Defense is the best offense.

YOUR SERVER IS UNDER CONSTANT ATTACK.

Every minute, automated bots scan the internet for vulnerable servers. They hunt for weak passwords, open ports, and misconfigured services. Without proper hardening, your server is a sitting duck.

HARDENING IS YOUR SHIELD.

Server hardening is the process of securing a system by reducing its attack surface. Close unnecessary ports, disable unused services, enforce strong authentication, and monitor for intrusions. Make your server a fortress.

BECOME A SECURITY GUARDIAN.

Learn SSH key authentication, firewall rules, user privileges, automatic updates, intrusion detection, log monitoring, and security scanning. Protect your data and your users from threats.

START HARDENING →

// The Path to Security

12 lessons. Complete server protection.

LESSON 01

Introduction to Hardening

What server hardening is, why it matters, and understanding attack surfaces.

Beginner
LESSON 02

SSH Security

Disable root login, enable key authentication, change default port, and configure fail2ban.

Beginner
LESSON 03

Firewall with UFW

Install UFW, configure rules, set default deny policy, and allow necessary services.

Beginner
LESSON 04

User Management

Create users, configure sudo privileges, disable root, and enforce password policies.

Beginner
LESSON 05

Automatic Updates

Configure unattended-upgrades for automatic security updates and patches.

Intermediate
LESSON 06

Fail2ban Setup

Install fail2ban, configure jails, and set up automatic IP banning for brute force attacks.

Intermediate
LESSON 07

File Permissions

Master chmod, chown, umask, and understand special permissions and access control.

Intermediate
LESSON 08

Services & Ports

Audit running services with ss, disable unnecessary services, and practice minimal installation.

Intermediate
LESSON 09

Log Monitoring

Monitor system logs with journalctl, configure logwatch, and manage rsyslog.

Intermediate
LESSON 10

Security Scanning

Run security audits with Lynis, detect rootkits with rkhunter and chkrootkit.

Advanced
LESSON 11

Backup Strategies

Implement backup solutions with rsync, schedule with cron, and manage offsite backups.

Advanced
LESSON 12

Security Checklist

Complete server hardening checklist and ongoing security maintenance practices.

Advanced

// Why Server Hardening

Server hardening is not optional—it's essential. Every day, thousands of servers are compromised due to basic security misconfigurations. A single open port, weak password, or outdated package can be the entry point for attackers.

The attack surface of a server is the sum of all possible entry points. Every installed package, running service, and open port expands this surface. Hardening systematically reduces this surface by removing unnecessary components and securing essential ones.

Security is a process, not a product. Threats evolve, new vulnerabilities are discovered, and attackers develop new techniques. Regular audits, updates, and monitoring are required to maintain security over time.

Secure your server before attackers secure it for you.

// Security Tools

🔥 UFW

Uncomplicated Firewall

wiki.ubuntu.com/UFW

🚫 Fail2ban

Intrusion Prevention

fail2ban.org

🔍 Lynis

Security Auditing Tool

cisofy.com

🛡️ rkhunter

Rootkit Detector

rkhunter.sf.net

📝 Logwatch

Log Analyzer

logwatch.sf.net

⚡ OpenSCAP

Security Compliance

open-scap.org

// Introduction to Hardening

×

What is Server Hardening?

Server hardening is the process of securing a server by reducing its vulnerability surface. It involves removing unnecessary software, closing unused ports, configuring security policies, and implementing monitoring systems.

Why Harden Your Server?

  • Prevent unauthorized access: Block attackers before they breach your system
  • Protect sensitive data: Secure customer information and business secrets
  • Ensure uptime: Avoid service disruptions from attacks
  • Compliance: Meet regulatory requirements for data protection
  • Reputation: Maintain trust with users and customers
SECURITY PRINCIPLE: Defense in depth. Multiple layers of security ensure that if one layer fails, others remain to protect your system.

The Attack Surface

The attack surface is the sum of all possible entry points an attacker could exploit:

  • Open network ports
  • Running services and daemons
  • Installed software packages
  • User accounts and privileges
  • File permissions
  • Configuration files

Common Attack Vectors

# Most common server attack vectors: 1. Brute force SSH attacks 2. Unpatched software vulnerabilities 3. Weak or default passwords 4. Open database ports (3306, 5432) 5. Misconfigured web servers 6. Unnecessary services running

Hardening Methodology

  1. Inventory: Document what's running on your server
  2. Assess: Identify vulnerabilities and unnecessary components
  3. Secure: Apply configuration changes and updates
  4. Monitor: Set up logging and intrusion detection
  5. Maintain: Regular updates and security audits

Before You Begin

$ whoami root # cat /etc/os-release PRETTY_NAME="Ubuntu 22.04.3 LTS"
WARNING: Always test hardening changes in a staging environment first. Document all changes and have a rollback plan.

Quiz

1. Server hardening reduces the _____ surface.

Hint: Vulnerability

2. Defense in _____ means multiple security layers.

Hint: Opposite of shallow

3. SSH uses port _____ by default.

Hint: Twenty-two

4. Always test changes in a _____ environment first.

Hint: Test environment

Show All Answers

Answers

  1. attack
  2. depth
  3. 22
  4. staging

// SSH Security

×

Why SSH Security Matters

SSH (Secure Shell) is the primary way to remotely administer Linux servers. It's also the #1 attack vector for brute force attacks. Proper SSH hardening is critical for server security.

THREAT: Automated bots constantly scan for SSH servers and attempt brute force attacks using common passwords. Default configurations make you an easy target.

Generate SSH Key Pair

$ ssh-keygen -t ed25519 -C "your-email@example.com" Generating public/private ed25519 key pair. Enter file in which to save the key (~/.ssh/id_ed25519): Enter passphrase (empty for no passphrase): Your identification has been saved in ~/.ssh/id_ed25519 Your public key has been saved in ~/.ssh/id_ed25519.pub

Copy Public Key to Server

$ ssh-copy-id user@server-ip /usr/bin/ssh-copy-id: INFO: attempting to log in... user@server-ip's password: Number of key(s) added: 1

Edit SSH Configuration

# nano /etc/ssh/sshd_config
# SSH Hardening Configuration PermitRootLogin no PasswordAuthentication no PubkeyAuthentication yes Port 2222 MaxAuthTries 3 ClientAliveInterval 300 ClientAliveCountMax 2 AllowUsers yourusername

Restart SSH Service

# systemctl restart sshd # Test new configuration before closing current session! $ ssh -p 2222 user@server-ip
CRITICAL: Never close your current SSH session until you've tested the new configuration in a separate terminal. A misconfiguration could lock you out permanently.

SSH Key Best Practices

  • Use Ed25519 keys (modern, secure, compact)
  • Set a passphrase on your private key
  • Store keys in ~/.ssh with proper permissions (600)
  • Use ssh-agent for key management
  • Never share your private key

Quiz

1. Set PermitRootLogin to _____ to disable root SSH.

Hint: Opposite of yes

2. ssh-keygen creates a key _____.

Hint: Two keys

3. Use ssh-copy-id to copy your _____ key.

Hint: Not private

4. Test in a separate _____ before closing current session.

Hint: Command window

Show All Answers

Answers

  1. no
  2. pair
  3. public
  4. terminal

// Firewall with UFW

×

What is UFW?

UFW (Uncomplicated Firewall) is a user-friendly frontend for iptables. It provides a simple command-line interface for managing firewall rules on Ubuntu and Debian systems.

Install UFW

$ sudo apt update && sudo apt install ufw -y Reading package lists... Done Building dependency tree... Done Setting up ufw (0.36.1-4) ...

Default Policy

Set default to deny incoming and allow outgoing:

$ sudo ufw default deny incoming Default incoming policy changed to 'deny' $ sudo ufw default allow outgoing Default outgoing policy changed to 'allow'
SECURITY PRINCIPLE: Default deny is the foundation of firewall security. Block everything by default, then explicitly allow only what you need.

Allow Essential Services

# Allow SSH (use your custom port if changed) $ sudo ufw allow 2222/tcp Rules updated # Allow HTTP $ sudo ufw allow 80/tcp # Allow HTTPS $ sudo ufw allow 443/tcp # Allow specific IP $ sudo ufw allow from 192.168.1.100 to any port 22

Enable and Check Status

$ sudo ufw enable Command may disrupt existing ssh connections. Proceed? (y|n): y Firewall is active and enabled on system startup $ sudo ufw status verbose Status: active To Action From -- ------ ---- 2222/tcp ALLOW IN Anywhere 80/tcp ALLOW IN Anywhere 443/tcp ALLOW IN Anywhere

Common UFW Commands

# Disable firewall $ sudo ufw disable # Delete a rule $ sudo ufw delete allow 80/tcp # Show numbered rules $ sudo ufw status numbered # Delete by number $ sudo ufw delete 2 # Rate limit (prevents brute force) $ sudo ufw limit 2222/tcp

Quiz

1. UFW stands for Uncomplicated _____.

Hint: Network security

2. Default policy should be deny _____.

Hint: Entering

3. HTTP uses port _____.

Hint: Eighty

4. HTTPS uses port _____.

Hint: Four-forty-three

Show All Answers

Answers

  1. firewall
  2. incoming
  3. 80
  4. 443

// User Management

×

Creating a New User

Never use root for daily operations. Create a regular user with sudo privileges:

# Create new user # adduser username Adding user 'username' ... Adding new group 'username' (1001) ... Creating home directory '/home/username' ... Enter new UNIX password: Retype new UNIX password:

Grant Sudo Privileges

# Add user to sudo group # usermod -aG sudo username # Verify $ groups username username : username sudo

Secure Sudo Configuration

# visudo
# Require password for sudo Defaults passwd_timeout=5 Defaults timestamp_timeout=5 Defaults logfile="/var/log/sudo.log" Defaults log_input,log_output

Disable Root Login

# Lock root password # passwd -l root # Alternative: Set root shell to nologin # usermod -s /usr/sbin/nologin root
WARNING: Before disabling root, ensure you have a working sudo user. Otherwise, you may lock yourself out completely.

Password Policies

# Install password quality checking # apt install libpam-pwquality -y # Edit password policy # nano /etc/security/pwquality.conf
# Password quality requirements minlen = 12 minclass = 3 maxrepeat = 2 gecoscheck = 1 dictcheck = 1

Account Management Commands

# List all users $ cat /etc/passwd | grep -v nologin | grep -v false # Check user activity $ last # View failed login attempts $ lastb # Disable user account # passwd -l username # Delete user and home directory # userdel -r username

Quiz

1. Add users to the _____ group for sudo access.

Hint: Super user do

2. Use _____ to safely edit sudoers file.

Hint: vi + sudo

3. Lock root with passwd -_____.

Hint: Letter L

4. Minimum password length should be at least _____ characters.

Hint: Twelve

Show All Answers

Answers

  1. sudo
  2. visudo
  3. l
  4. 12

// Automatic Updates

×

Why Automatic Updates?

Unpatched vulnerabilities are a leading cause of server compromises. Automatic security updates ensure critical patches are applied without delay, closing windows of opportunity for attackers.

RISK: Many servers are compromised within 24 hours of a vulnerability disclosure because attackers know many administrators delay updates.

Install unattended-upgrades

# apt install unattended-upgrades apt-listchanges -y Reading package lists... Done Setting up unattended-upgrades (2.8ubuntu1) ...

Configure Automatic Updates

# dpkg-reconfigure -plow unattended-upgrades
SELECT: Yes when prompted to enable automatic updates

Edit Configuration

# nano /etc/apt/apt.conf.d/50unattended-upgrades
// Automatically upgrade security updates Unattended-Upgrade::Allowed-Origins { "${distro_id}:${distro_codename}-security"; }; // Send email on errors Unattended-Upgrade::Mail "admin@example.com"; Unattended-Upgrade::MailOnlyOnError "true"; // Auto-remove unused dependencies Unattended-Upgrade::Remove-Unused-Kernel-Packages "true"; Unattended-Upgrade::Remove-Unused-Dependencies "true"; // Auto-reboot if required Unattended-Upgrade::Automatic-Reboot "true"; Unattended-Upgrade::Automatic-Reboot-Time "03:00";

Configure Update Schedule

# nano /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Download-Upgradeable-Packages "1"; APT::Periodic::AutocleanInterval "7"; APT::Periodic::Unattended-Upgrade "1";

Test and Verify

# Dry run to test configuration # unattended-upgrade --dry-run --debug # Check status $ systemctl status unattended-upgrades # View logs $ tail -f /var/log/unattended-upgrades/unattended-upgrades.log

Manual Update Commands

# Update package lists # apt update # Upgrade installed packages # apt upgrade # Full distribution upgrade # apt dist-upgrade # Remove unused packages # apt autoremove

Quiz

1. _____-upgrades handles automatic updates.

Hint: Not watched

2. Enable _____ reboot for critical kernel updates.

Hint: Auto

3. apt _____ downloads package lists.

Hint: Refresh

4. apt _____ installs new versions.

Hint: Level up

Show All Answers

Answers

  1. unattended
  2. automatic
  3. update
  4. upgrade

// Fail2ban Setup

×

What is Fail2ban?

Fail2ban is an intrusion prevention framework that monitors log files for malicious activity and automatically bans IP addresses that show suspicious behavior—such as multiple failed login attempts.

PROTECTION: Fail2ban reduces brute force attacks by automatically blocking IPs after a defined number of failed attempts, typically within minutes.

Install Fail2ban

# apt install fail2ban -y Reading package lists... Done Setting up fail2ban (0.11.2-2) ... Created symlink /etc/systemd/system/multi-user.target.wants/fail2ban.service

Configure Jail Settings

# cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local # nano /etc/fail2ban/jail.local
# Fail2ban jail configuration [DEFAULT] # Ban IP after 3 failed attempts maxretry = 3 # Ban for 1 hour bantime = 3600 # Look back 10 minutes findtime = 600 # Send email alerts (optional) destemail = admin@example.com sendername = Fail2ban mta = sendmail # Enable SSH jail [sshd] enabled = true port = ssh,2222 filter = sshd logpath = /var/log/auth.log maxretry = 3

Enable and Start Fail2ban

# systemctl enable fail2ban Created symlink /etc/systemd/system/multi-user.target.wants/fail2ban.service # systemctl start fail2ban # Check status # systemctl status fail2ban ● fail2ban.service - Fail2ban Service Active: active (running) since Mon 2024-01-01 12:00:00 UTC

Monitor and Manage Bans

# View active jails $ fail2ban-client status Status |- Number of jail: 1 `- Jail list: sshd # View SSH jail details $ fail2ban-client status sshd # View banned IPs $ fail2ban-client status sshd | grep "Banned IP list" # Unban an IP manually # fail2ban-client set sshd unbanip 192.168.1.100

Additional Jails

# Enable Apache/Nginx jails [apache-auth] enabled = true [nginx-http-auth] enabled = true # Custom filter for WordPress [wordpress] enabled = true filter = wordpress logpath = /var/log/apache2/access.log maxretry = 5

Quiz

1. Fail2ban monitors _____ files for attacks.

Hint: System records

2. Bantime is measured in _____.

Hint: 3600 = 1 hour

3. Maxretry sets the number of _____ attempts allowed.

Hint: Unsuccessful

4. Use fail2ban-_____ to manage bans.

Hint: Command interface

Show All Answers

Answers

  1. log
  2. seconds
  3. failed
  4. client

// File Permissions

×

Understanding Permissions

Linux file permissions control who can read, write, or execute files. Understanding and properly setting permissions is essential for system security.

Permission Structure

$ ls -la /etc/passwd -rw-r--r-- 1 root root 2845 Jan 1 12:00 /etc/passwd | [Owner][Group][Others] | rw- r-- r-- | ↓ ↓ ↓ | 6 4 4
  • r (read): View file contents or list directory
  • w (write): Modify file or directory contents
  • x (execute): Run files or access directories

Numeric Permissions

7 = rwx (read, write, execute) 6 = rw- (read, write) 5 = r-x (read, execute) 4 = r-- (read only) 0 = --- (no permissions)

chmod Commands

# Set permissions (owner:rw, group:r, others:r) $ chmod 644 file.txt # Set executable $ chmod 755 script.sh # Add execute permission for owner $ chmod u+x script.sh # Remove write for group $ chmod g-w file.txt # Make read-only for all $ chmod a-w file.txt # Recursive change $ chmod -R 755 /var/www/html

Change Ownership

# Change owner # chown user:group file.txt # Change only owner # chown user file.txt # Change only group # chgrp group file.txt # Recursive # chown -R www-data:www-data /var/www

Special Permissions

# SUID - Run with file owner's permissions $ chmod u+s /usr/bin/somebinary -rwsr-xr-x 1 root root ... # SGID - Run with group's permissions $ chmod g+s /shared/directory # Sticky Bit - Only owner can delete $ chmod +t /shared/tmp drwxrwxrwt 10 root root ...
SECURITY NOTE: SUID binaries are high-value targets. Avoid creating new SUID programs and regularly audit existing ones with: find / -perm -4000 -type f 2>/dev/null

umask Configuration

# Check current umask $ umask 0022 # Set restrictive umask (files: 644, dirs: 755) $ umask 022 # Very restrictive (files: 600, dirs: 700) $ umask 077 # Add to ~/.bashrc or /etc/profile umask 027

Secure File Locations

# SSH keys - must be 600 $ chmod 600 ~/.ssh/id_rsa $ chmod 644 ~/.ssh/id_rsa.pub $ chmod 700 ~/.ssh # Password files - must be 640 or 600 # chmod 640 /etc/shadow

Quiz

1. chmod _____ gives owner read and write.

Hint: rw-------

2. _____ changes file owner.

Hint: Change owner

3. _____ sets default permissions for new files.

Hint: User mask

4. Sticky bit is set with chmod _____.

Hint: Plus T

Show All Answers

Answers

  1. 600
  2. chown
  3. umask
  4. +t

// Services & Ports

×

Audit Running Services

Every running service is a potential attack vector. Regularly audit what services are running and disable those you don't need.

List Listening Ports

# Modern replacement for netstat $ ss -tulpn Netid State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=1234,fd=3)) tcp LISTEN 0 128 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=5678,fd=6)) tcp LISTEN 0 128 0.0.0.0:443 0.0.0.0:* users:(("nginx",pid=5678,fd=7)) # Alternative: show all connections $ ss -tulpan
ANALYSIS: Each LISTEN port represents a service accepting connections. Review each one and ask: "Do I need this service? Can it be restricted?"

Check Installed Services

# List all systemd services $ systemctl list-units --type=service --state=running # Check specific service $ systemctl status sshd # List enabled services (start on boot) $ systemctl list-unit-files --state=enabled

Disable Unnecessary Services

# Stop and disable a service # systemctl stop cups # systemctl disable cups # Mask to prevent accidental starting # systemctl mask cups # Verify it's disabled $ systemctl is-enabled cups masked

Common Services to Disable

# Bluetooth (if not needed on server) # systemctl stop bluetooth && systemctl disable bluetooth # CUPS printing # systemctl stop cups && systemctl disable cups # Avahi (mDNS/DNS-SD) # systemctl stop avahi-daemon && systemctl disable avahi-daemon # Modem manager # systemctl stop ModemManager && systemctl disable ModemManager

Package Management

# List installed packages $ dpkg -l | wc -l # Remove unnecessary packages # apt remove package-name # Purge (remove config too) # apt purge package-name # Clean up unused dependencies # apt autoremove # Clean package cache # apt clean

Minimal Installation

# When installing Debian/Ubuntu, choose: [ ] Debian desktop environment [ ] GNOME [ ] ... other desktop environments ... [X] SSH server [ ] Standard system utilities
BEST PRACTICE: Start with minimal installation. Add only what you need. Every installed package is potential attack surface.

Port Scanning (Self-Audit)

# Install nmap # apt install nmap -y # Scan localhost $ nmap -sV localhost PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.9 80/tcp open http nginx 1.18 443/tcp open https nginx 1.18 # Scan from external host to test firewall $ nmap -Pn external-server-ip

Quiz

1. Use _____ command to list listening ports.

Hint: Socket statistics

2. _____ a service to prevent it from starting.

Hint: Hide/disable

3. apt _____ removes unused packages.

Hint: Clean up

4. _____ is a tool for port scanning.

Hint: Network mapper

Show All Answers

Answers

  1. ss
  2. mask
  3. autoremove
  4. nmap

// Log Monitoring

×

Why Log Monitoring Matters

Logs are your window into server activity. They record who accessed your system, what they did, when they did it, and whether they succeeded or failed. Without log monitoring, you're flying blind.

DETECTION: Most breaches are discovered months after they occur. Active log monitoring helps detect attacks in progress and investigate past incidents.

journalctl - Systemd Journal

# View all logs $ journalctl # View last 100 lines $ journalctl -n 100 # Follow logs in real-time (like tail -f) $ journalctl -f # Logs since today $ journalctl --since today # Logs for specific service $ journalctl -u sshd # Logs for specific boot $ journalctl -b

Traditional Log Files

# Authentication attempts $ tail -f /var/log/auth.log # System messages $ tail -f /var/log/syslog # Failed login attempts $ grep "Failed password" /var/log/auth.log # Successful logins $ grep "Accepted" /var/log/auth.log # Log rotation (keeps logs manageable) $ ls /var/log/*.log* auth.log auth.log.1 auth.log.2.gz auth.log.3.gz

Install Logwatch

# apt install logwatch -y # Run manually to see output $ logwatch --detail high --range today # Configure daily reports # nano /etc/cron.daily/00logwatch

Logwatch Configuration

# nano /usr/share/logwatch/default.conf/logwatch.conf
# Logwatch configuration LogDir = /var/log TmpDir = /var/cache/logwatch MailTo = admin@example.com Print = Yes Range = yesterday Detail = Med Service = All

rsyslog Configuration

# nano /etc/rsyslog.conf # Common directives *.info;mail.none;authpriv.none;cron.none /var/log/messages authpriv.* /var/log/secure mail.* -/var/log/maillog cron.* /var/log/cron *.emerg :omusrmsg:* # Restart to apply # systemctl restart rsyslog

Log Analysis Commands

# Count failed SSH attempts by IP $ grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | head # Find sudo usage $ grep sudo /var/log/auth.log # Check for port scanning $ grep "Invalid user" /var/log/auth.log | wc -l # Failed login by user $ grep "authentication failure" /var/log/auth.log

Log Retention

# nano /etc/logrotate.conf
weekly rotate 4 create dateext compress include /etc/logrotate.d

Quiz

1. journalctl -f follows logs like _____.

Hint: End of file

2. auth.log tracks _____ attempts.

Hint: Login

3. logwatch sends daily _____ reports.

Hint: Electronic mail

4. _____ rotates logs to prevent disk fill.

Hint: Turn around

Show All Answers

Answers

  1. tail
  2. authentication
  3. email
  4. logrotate

// Security Scanning

×

Why Security Scanning?

Regular security scans help identify vulnerabilities before attackers do. They provide an objective assessment of your server's security posture and track improvements over time.

Lynis - Security Auditing Tool

# Install Lynis # apt install lynis -y # Run basic audit # lynis audit system # Run with more details # lynis audit system --verbose # Create report file # lynis audit system --report-file /tmp/lynis-report.dat

Understanding Lynis Output

[+] Initializing program ------------------------------------ - Detecting OS... [ DONE ] - Checking profiles... [ DONE ] [+] Boot and services ------------------------------------ - Service Manager... [ systemd ] [+] Security Frameworks ------------------------------------ - Checking AppArmor status... [ ENABLED ] Lynis security scan details: Hardening index : 72 [WARNING] Tests performed : 238 Plugins enabled : 1
GOAL: Aim for a hardening index of 80+. Lynis provides specific recommendations for each warning. Review the full report at /var/log/lynis-report.dat

Rootkit Detection with rkhunter

# Install rkhunter # apt install rkhunter -y # Update definitions # rkhunter --update # Run system check # rkhunter --check # Run in background and create log # rkhunter --check --sk --rwo

chkrootkit - Alternative Rootkit Scanner

# Install chkrootkit # apt install chkrootkit -y # Run scan # chkrootkit # Quiet mode (only show warnings) # chkrootkit -q # Check specific directory # chkrootkit -r /path/to/check

Automated Security Updates

# Install debsecan # apt install debsecan -y # List vulnerable packages $ debsecan # Only show fixed vulnerabilities $ debsecan --suite bookworm --format report

Setting Up Automated Scans

# Add to cron for weekly scans # crontab -e
# Weekly security scans 0 2 * * 0 /usr/bin/lynis audit system --quick > /var/log/lynis-weekly.log 2>&1 0 3 * * 0 /usr/bin/rkhunter --check --sk --rwo > /var/log/rkhunter-weekly.log 2>&1

Interpreting Results

  • [OK] - Test passed, no action needed
  • [WARNING] - Potential issue, review recommended
  • [SUGGESTION] - Improvement possible
  • [FOUND] - Rootkit or malware detected (investigate immediately)

Quiz

1. _____ audits system security configuration.

Hint: Security scanner

2. rkhunter detects _____.

Hint: Hidden malware

3. Target hardening index is _____ or higher.

Hint: Eighty

4. Run scans _____ to detect issues early.

Hint: Often/Scheduled

Show All Answers

Answers

  1. lynis
  2. rootkits
  3. 80
  4. regularly

// Backup Strategies

×

Why Backups Matter

Backups are your insurance policy against data loss. Whether from hardware failure, ransomware, human error, or malicious attacks, having reliable backups ensures you can recover quickly.

RULE OF THREE: 3 copies of your data, on 2 different media, with 1 copy offsite. Never rely on a single backup.

Basic rsync Backup

# Basic file copy with archive mode $ rsync -av /source/directory/ /backup/directory/ # Backup to remote server $ rsync -avz -e ssh /local/data/ user@backup-server:/remote/backup/ # Exclude certain files $ rsync -av --exclude='*.tmp' --exclude='cache/' /source/ /backup/ # Delete files in backup that no longer exist in source $ rsync -av --delete /source/ /backup/

Incremental Backups

# Create timestamped backup $ rsync -av /var/www/html/ /backup/html-$(date +%Y%m%d)/ # Link to previous backup (hard links for deduplication) $ rsync -av --link-dest=/backup/html-$(date -d yesterday +%Y%m%d) /var/www/html/ /backup/html-$(date +%Y%m%d)/

Database Backups

# MySQL/MariaDB backup $ mysqldump -u root -p database_name > backup-$(date +%Y%m%d).sql # PostgreSQL backup $ pg_dump -U postgres database_name > backup-$(date +%Y%m%d).sql # Compress backup $ mysqldump -u root -p database_name | gzip > backup-$(date +%Y%m%d).sql.gz

Automated Backups with Cron

# Edit crontab $ crontab -e
# Daily backup at 2 AM 0 2 * * * /usr/bin/rsync -av --delete /var/www/ /backup/www/ # Weekly database backup on Sundays at 3 AM 0 3 * * 0 /usr/bin/mysqldump -u root -p'password' mydb > /backup/db-$(date +\%Y\%m\%d).sql # Clean up backups older than 30 days 0 4 * * * /usr/bin/find /backup -name "*.sql" -mtime +30 -delete

Offsite Backup Options

# Rsync to remote server $ rsync -avz -e "ssh -i /backup/.ssh/key" /local/backup/ backup@remote-server:/backups/server1/ # Using rclone for cloud storage $ rclone sync /local/backup remote:bucket-name # Encrypted backup with duplicity $ duplicity --encrypt-key KEY_ID /source sftp://user@backup-server/backups

Backup Verification

# Check backup integrity $ rsync -avnc /source/ /backup/ | grep -c "^<" # List backup contents $ ls -lah /backup/ # Test restore (critical!) $ rsync -av /backup/test-restore/ /tmp/test-restore/ $ diff -r /source/test-data/ /tmp/test-restore/
CRITICAL: A backup you haven't tested restoring from is a gamble. Regularly test your restore process to ensure backups work when you need them.

System Backup with tar

# Full system backup (excludes unnecessary directories) # tar -cvpzf /backup/full-backup-$(date +%Y%m%d).tar.gz --exclude=/backup --exclude=/proc --exclude=/tmp --exclude=/mnt --exclude=/sys --exclude=/dev --exclude=/run / # Restore from backup # tar -xvpzf /backup/full-backup-20240101.tar.gz -C /

Quiz

1. Use _____ for efficient file backups.

Hint: Remote sync

2. mysqldump backups _____ databases.

Hint: Popular SQL database

3. Keep one backup _____.

Hint: Remote location

4. _____ backups periodically to ensure they work.

Hint: Verify

Show All Answers

Answers

  1. rsync
  2. mysql
  3. offsite
  4. test

// Security Checklist

×

Pre-Deployment Checklist

Complete these tasks before putting any server into production. This checklist represents the minimum security baseline.

System Hardening

  • [ ] Install minimal OS (no desktop environment)
  • [ ] Apply all security updates
  • [ ] Configure automatic security updates
  • [ ] Set strong root password or disable root
  • [ ] Create non-root user with sudo privileges
  • [ ] Configure password policies (min 12 chars)

SSH Configuration

# SSH Checklist verification $ grep -E "^(PermitRootLogin|PasswordAuthentication|Port|MaxAuthTries)" /etc/ssh/sshd_config PermitRootLogin no PasswordAuthentication no Port 2222 MaxAuthTries 3
  • [ ] Change default SSH port (if desired)
  • [ ] Disable root SSH login
  • [ ] Disable password authentication
  • [ ] Configure SSH key authentication only
  • [ ] Set MaxAuthTries to 3 or less
  • [ ] Configure ClientAliveInterval
  • [ ] Allow only specific users (AllowUsers)

Firewall Configuration

$ sudo ufw status verbose
  • [ ] Enable UFW or iptables
  • [ ] Set default deny incoming
  • [ ] Allow only necessary ports (SSH, HTTP, HTTPS)
  • [ ] Rate limit SSH port
  • [ ] Log firewall activity

Intrusion Prevention

$ systemctl status fail2ban $ fail2ban-client status sshd
  • [ ] Install fail2ban
  • [ ] Enable SSH jail
  • [ ] Configure maxretry (3 recommended)
  • [ ] Set appropriate bantime (1+ hours)
  • [ ] Enable additional jails if needed

Services & Ports

$ ss -tulpn | grep LISTEN
  • [ ] Audit all listening ports
  • [ ] Disable unnecessary services
  • [ ] Remove unused packages
  • [ ] Configure services to listen on localhost only when possible

File Permissions

$ find / -perm -4000 -type f 2>/dev/null | wc -l $ stat -c "%a %n" /etc/shadow
  • [ ] Review SUID/SGID binaries
  • [ ] Set restrictive umask (027 or 077)
  • [ ] Verify sensitive file permissions
  • [ ] Configure SSH directory permissions (700)

Logging & Monitoring

$ ls -la /var/log/*.log | head
  • [ ] Verify rsyslog is running
  • [ ] Configure log rotation
  • [ ] Install logwatch for daily reports
  • [ ] Set up centralized logging if multiple servers
  • [ ] Configure logwatch or similar for alerts

Security Scanning

# lynis audit system --quick 2>&1 | grep "Hardening index"
  • [ ] Run Lynis security audit
  • [ ] Review and address all warnings
  • [ ] Run rkhunter rootkit scan
  • [ ] Run chkrootkit scan
  • [ ] Schedule regular security scans
  • [ ] Target hardening index: 80+

Backup Strategy

  • [ ] Configure automated backups
  • [ ] Include databases in backup plan
  • [ ] Set up offsite backup
  • [ ] Test restore procedures
  • [ ] Document recovery process
  • [ ] Set backup retention policy

Maintenance Schedule

Daily: Check logs, review fail2ban bans Weekly: Run security scans (Lynis, rkhunter) Weekly: Verify backup integrity Monthly: Review user accounts Monthly: Audit installed packages Quarterly: Full security review
REMEMBER: Security is not a one-time task but an ongoing process. Regular maintenance and vigilance are essential to maintaining a secure server over time.

Quiz

1. Minimum target hardening index is _____.

Hint: Eighty

2. Set maxretry to _____ or less.

Hint: Three

3. Minimum password length should be _____ characters.

Hint: Twelve

4. Security is an ongoing _____, not a one-time task.

Hint: Continuous activity

Show All Answers

Answers

  1. 80
  2. 3
  3. 12
  4. process