Module 7: Security Fundamentals

Learning Objectives

By the end of this module, you will be able to:

1. Security Update Management

Understanding the Linux Update Ecosystem

Security updates are the foundation of system security. Most vulnerabilities are discovered after software is released, making regular updates essential. Linux distributions maintain repositories of packages that are regularly updated with security patches.

When a vulnerability is discovered, the following process typically occurs:

  1. Security researchers or users discover and report the vulnerability
  2. Developers create a patch to fix the issue
  3. Distribution maintainers package the patched software
  4. The update is pushed to official repositories
  5. System administrators apply the update

Under the Hood: Package Management Systems

Linux distributions use package managers to handle software installation, updates, and removal. The most common package management systems are:

These package managers maintain databases of installed packages, available packages, and their dependencies. When you run an update command, the package manager:

  1. Contacts repository servers to get the latest package information
  2. Compares available package versions with installed versions
  3. Creates a list of packages that need updating
  4. Downloads the necessary packages
  5. Verifies package integrity using cryptographic signatures
  6. Installs the updated packages, often running pre and post-installation scripts

Practical Examples: Updating Systems

For Debian/Ubuntu systems:

# Update package lists
sudo apt update

# Apply all updates
sudo apt upgrade

# Apply only security updates
sudo apt-get upgrade -s | grep -i security

For Red Hat/CentOS systems:

# Update package lists and apply updates
sudo dnf update

# Apply only security updates
sudo dnf update --security

Automating Security Updates

For critical systems, automated security updates can be configured:

On Debian/Ubuntu:

# Install unattended-upgrades package
sudo apt install unattended-upgrades

# Configure automatic updates
sudo dpkg-reconfigure unattended-upgrades

This creates a service that periodically checks for and applies security updates. The configuration file is located at /etc/apt/apt.conf.d/50unattended-upgrades.

Let's examine a portion of this file:

Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
    // Extended Security Maintenance; doesn't necessarily exist for
    // every release and this system may not have it installed, but if
    // available, the policy for updates is such that unattended-upgrades
    // should also install from here by default.
    "${distro_id}ESMApps:${distro_codename}-apps-security";
    "${distro_id}ESM:${distro_codename}-infra-security";
};

This configuration specifies which types of updates should be automatically applied. In this case, it's set to only apply security updates.

Exercise 1: Setting Up Automated Security Updates

In this exercise, you'll configure automated security updates on your system:

  1. Install the unattended-upgrades package if you're using a Debian-based system, or dnf-automatic for Red Hat-based systems.
  2. Edit the configuration file to specify which updates should be applied automatically.
  3. Configure email notifications for applied updates.
  4. Test the configuration by forcing an update check.

Common Pitfalls in Update Management

  1. Inconsistent update scheduling: Infrequent updates leave systems vulnerable. Establish a regular update schedule.
  2. Failing to test updates: Some updates can break functionality. Always test updates on non-production systems first.
  3. Ignoring dependency conflicts: Updates can sometimes create dependency conflicts. Make sure to review the list of changes before applying updates.
  4. Outdated repositories: Using end-of-life distributions means no security updates. Keep systems on supported versions.

2. SSH Configuration and Hardening

Understanding SSH Architecture

Secure Shell (SSH) is a cryptographic network protocol used for secure remote access to systems. It replaces insecure protocols like Telnet by encrypting all traffic.

The SSH protocol works through a client-server model:

Under the Hood: SSH Authentication Methods

SSH provides several authentication methods:

  1. Password authentication: Simple but vulnerable to brute force attacks
  2. Public key authentication: Uses asymmetric cryptography with a key pair
  3. Host-based authentication: Authenticates based on the client's hostname
  4. Keyboard-interactive: Flexible authentication method often used for multi-factor

Public key authentication is the most secure method. It works as follows:

  1. You generate a key pair: private key (kept secret) and public key (shared)
  2. The public key is placed on servers you want to access
  3. When connecting, the server creates a challenge encrypted with your public key
  4. Your client decrypts this challenge using your private key, proving your identity
  5. No passwords are transmitted over the network

Hardening SSH Configuration

The SSH server configuration file is located at /etc/ssh/sshd_config. Here are key settings to modify:

# Disable root login
PermitRootLogin no

# Use protocol version 2 only (more secure)
Protocol 2

# Disable password authentication (use keys only)
PasswordAuthentication no
ChallengeResponseAuthentication no

# Limit user access
AllowUsers username1 username2

# Change default port (provides obscurity)
Port 2222

# Set idle timeout (disconnects inactive sessions)
ClientAliveInterval 300
ClientAliveCountMax 2

# Restrict SSH to specific interfaces if needed
ListenAddress 192.168.1.100

After making changes, restart the SSH service:

sudo systemctl restart sshd

Setting Up Key-Based Authentication

Generate a key pair on your client machine:

# Generate a strong Ed25519 key
ssh-keygen -t ed25519 -a 100

# Or an RSA key with 4096 bits (more compatible)
ssh-keygen -t rsa -b 4096

The -a 100 option increases the number of key derivation function rounds, making the key more resistant to brute-force attacks.

Copy your public key to the server:

ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server

This command appends your public key to the ~/.ssh/authorized_keys file on the server.

Exercise 2: Hardening SSH Configuration

  1. Create a backup of your current SSH configuration:
    sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
    
  2. Generate a new SSH key pair using Ed25519:
    ssh-keygen -t ed25519 -a 100
    
  3. Deploy your public key to the server:
    ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server
    
  4. Modify the SSH server configuration to:
    • Disable root login
    • Disable password authentication
    • Change the default port
    • Set an idle timeout
  5. Test your configuration before applying it permanently:
    sudo sshd -t
    
  6. Restart the SSH service and test your connection.

Common SSH Configuration Pitfalls

  1. Locking yourself out: Always keep a session open when making SSH changes, so you can revert if needed.
  2. Weak key algorithms: Avoid using outdated algorithms like DSA or short RSA keys. Prefer Ed25519 or RSA with at least 3072 bits.
  3. Forgetting about firewall rules: If you change the SSH port, update your firewall rules accordingly.
  4. Neglecting SSH client configuration: The client configuration (~/.ssh/config) is just as important for security.

3. File Integrity Monitoring with AIDE

Understanding File Integrity Monitoring

File Integrity Monitoring (FIM) is a security practice that validates the integrity of operating system and application files by comparing their current state against a known, trusted baseline.

If a file is altered – whether by legitimate system updates, administrators, or malicious attackers – the FIM system detects and reports these changes.

Under the Hood: How AIDE Works

Advanced Intrusion Detection Environment (AIDE) is a popular open-source FIM tool for Linux. Here's how it works:

  1. Database creation: AIDE scans the system and creates a database containing cryptographic hashes of files and their attributes
  2. Regular checks: At scheduled intervals, AIDE rescans the system and compares current file states with the database
  3. Reporting: Changes are reported, highlighting potential security issues

AIDE uses several hash algorithms (MD5, SHA1, SHA256, etc.) and can monitor various file attributes:

Setting Up AIDE

Install AIDE:

# On Debian/Ubuntu
sudo apt install aide

# On RedHat/CentOS
sudo dnf install aide

Initialize the AIDE database:

# Configure AIDE (edit /etc/aide/aide.conf as needed)
sudo nano /etc/aide/aide.conf

# Initialize the database (this can take a while)
sudo aide --init

# Move the initial database to the active location
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Let's examine a part of the AIDE configuration file:

# AIDE configuration

# The default rule
All = p+i+n+u+g+s+m+c+acl+selinux+xattrs+sha256

# Define what directories to check
/etc p+i+u+g+sha256
/bin All
/sbin All
/usr/bin All
/usr/sbin All

This configuration monitors different attributes for different directories. The All rule checks permissions, inode data, user/group ownership, size, modification time, content hashes, and more.

Running AIDE Checks

Perform a manual integrity check:

sudo aide --check

The output will show any changes to monitored files since the last database update. After legitimate changes (like system updates), update the database:

sudo aide --update
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Automating AIDE with Cron

Create a daily cron job to run AIDE checks:

sudo nano /etc/cron.daily/aide-check

Add the following content:

#!/bin/bash
/usr/bin/aide --check | mail -s "AIDE integrity check report" root@localhost

Make the script executable:

sudo chmod +x /etc/cron.daily/aide-check

Exercise 3: Setting Up Basic File Integrity Monitoring

  1. Install AIDE on your system.
  2. Customize the configuration file to focus on critical system directories.
  3. Initialize the AIDE database.
  4. Make some controlled changes to monitored files.
  5. Run a check to see if AIDE detects your changes.
  6. Set up a cron job to run daily checks and email the results.

Troubleshooting AIDE Issues

  1. False positives: Regular system activities can trigger many alerts. Fine-tune your configuration to exclude frequently changing files.
  2. Performance impact: Initial database creation and full system checks can be resource-intensive. Schedule them during off-peak hours.
  3. Database maintenance: After legitimate system changes, remember to update the AIDE database. Automate this after scheduled system updates.
  4. Storage requirements: AIDE databases can grow large on systems with many files. Monitor disk space accordingly.

4. Security Auditing with Lynis

Understanding Security Auditing

Security auditing is the process of systematically evaluating the security of a system against established criteria or baselines. It helps identify vulnerabilities, misconfigurations, and areas for improvement.

Lynis is an open-source security auditing tool specifically designed for Linux systems. It performs hundreds of security checks covering:

Under the Hood: How Lynis Works

Lynis operates by running a series of tests organized into categories or modules. Each test:

  1. Checks a specific security control or configuration
  2. Compares the result against best practices
  3. Assigns a severity level to findings
  4. Suggests remediation steps

Lynis is non-intrusive and does not modify system files. It simply reads configurations, checks settings, and reports findings.

Installing and Running Lynis

Install Lynis:

# On Debian/Ubuntu
sudo apt install lynis

# On RedHat/CentOS
sudo dnf install lynis

# Alternative: clone from GitHub
git clone https://github.com/CISOfy/lynis
cd lynis

Run a basic system audit:

sudo lynis audit system

For a more focused audit:

# Audit authentication mechanisms
sudo lynis audit system --tests-from-group=authentication

# Audit SSH configuration
sudo lynis audit system --tests-from-group=ssh

Interpreting Lynis Results

A Lynis audit produces a detailed report with findings categorized by severity:

The report includes:

Let's look at a sample section of Lynis output:

[+] Boot and services
------------------------------------
[+] Service Manager
  [INFO] Init system: systemd
[+] Boot loader
  [SUGGESTION] Set a password on GRUB bootloader to prevent altering boot configuration (e.g. boot in single user mode without password) [BOOT-5122]

Exercise 4: Conducting a Security Audit with Lynis

  1. Install Lynis on your system.
  2. Run a complete system audit:
    sudo lynis audit system
    
  3. Identify the top 3 highest severity findings.
  4. Implement fixes for at least one warning and one suggestion.
  5. Run the audit again to verify your fixes.
  6. Create a simple shell script to automate regular Lynis audits and save reports.

Addressing Common Lynis Findings

  1. SSH Configuration: Lynis often flags SSH settings. Fix by editing /etc/ssh/sshd_config to disable root login, password authentication, and empty passwords.
  2. Password Policies: Strengthen password requirements in /etc/pam.d/common-password or /etc/security/pwquality.conf.
  3. Firewall Configuration: Ensure a firewall is active and properly configured:
    sudo ufw enable
    sudo ufw default deny incoming
    sudo ufw allow ssh
    
  4. File Permissions: Fix overly permissive permissions on sensitive files:
    sudo chmod 600 /etc/shadow
    sudo chmod 644 /etc/passwd
    

5. Basic Intrusion Detection

Understanding Intrusion Detection Systems (IDS)

An Intrusion Detection System monitors network traffic or system activities for suspicious patterns that might indicate unauthorized access or security policy violations.

Linux systems can employ several types of IDS:

Under the Hood: How OSSEC Works

OSSEC is a popular open-source HIDS that provides comprehensive protection. Here's how it functions:

  1. Agent-server architecture: A central server collects and analyzes data from agents installed on monitored hosts
  2. Log analysis: OSSEC parses and analyzes system and application logs using rules to identify suspicious activity
  3. File integrity monitoring: Similar to AIDE, it checks for unauthorized file modifications
  4. Rootkit detection: Searches for signs of rootkits using various detection techniques
  5. Active response: Can automatically block attack sources by configuring firewall rules

OSSEC's detection is rule-based. Rules define patterns in logs that indicate potential security issues, with different severity levels.

Installing and Configuring OSSEC

Install prerequisites:

sudo apt install build-essential make gcc libevent-dev zlib1g-dev libssl-dev libpcre2-dev

Download and install OSSEC:

wget https://github.com/ossec/ossec-hids/archive/3.7.0.tar.gz
tar -xzf 3.7.0.tar.gz
cd ossec-hids-3.7.0
sudo ./install.sh

During installation, you'll select the installation type (local, agent, or server) and configure monitoring options.

The main configuration file is located at /var/ossec/etc/ossec.conf. Let's examine a sample section:

<ossec_config>
  <global>
    <email_notification>yes</email_notification>
    <email_to>admin@example.com</email_to>
    <smtp_server>mail.example.com</smtp_server>
    <email_from>ossec@example.com</email_from>
  </global>

  <syscheck>
    <frequency>43200</frequency>
    <directories check_all="yes">/etc,/usr/bin,/usr/sbin</directories>
    <directories check_all="yes">/bin,/sbin</directories>
    <ignore>/etc/mtab</ignore>
    <ignore>/etc/hosts.deny</ignore>
  </syscheck>
</ossec_config>

This configuration enables email notifications for alerts and sets up file integrity monitoring for important system directories, with checks every 12 hours (43200 seconds).

Monitoring and Responding to Alerts

Start OSSEC:

sudo /var/ossec/bin/ossec-control start

Check OSSEC status:

sudo /var/ossec/bin/ossec-control status

View alerts:

sudo tail -f /var/ossec/logs/alerts/alerts.log

OSSEC can be configured to take automatic actions in response to specific alerts, such as blocking IP addresses that show malicious behavior:

<command>
  <name>firewall-drop</name>
  <executable>firewall-drop.sh</executable>
  <expect>srcip</expect>
  <timeout_allowed>yes</timeout_allowed>
</command>

<active-response>
  <command>firewall-drop</command>
  <location>local</location>
  <level>6</level>
  <timeout>600</timeout>
</active-response>

This configuration blocks source IP addresses associated with alerts of level 6 or higher for 10 minutes (600 seconds).

Exercise 5: Setting Up Basic Intrusion Detection

  1. Install OSSEC as a local installation.
  2. Configure file integrity monitoring for critical system directories.
  3. Configure email alerts for high-severity events.
  4. Create a custom rule to detect failed SSH login attempts.
  5. Test your configuration by simulating suspicious activity.
  6. View and interpret the resulting alerts.

Troubleshooting Intrusion Detection Systems

  1. False positives: Tune rules to reduce false alarms. Start with a narrow focus and gradually expand monitoring.
  2. Performance impact: HIDS can consume significant resources. Adjust check frequencies and monitored directories based on system capabilities.
  3. Log management: OSSEC generates many log entries. Implement log rotation or forwarding to prevent disk space issues.
  4. Alert fatigue: Too many alerts can lead to overlooking important ones. Prioritize critical systems and adjust alert thresholds.

6. Security Best Practices for Linux Servers

Principle of Least Privilege

The principle of least privilege means giving users and processes only the minimum permissions needed to perform their functions. This limits potential damage from accidents or attacks.

Practical implementations:

Example of configuring sudo for limited privileges:

# Allow user to restart specific services only
echo "username ALL=(ALL) NOPASSWD: /bin/systemctl restart apache2, /bin/systemctl restart nginx" | sudo tee /etc/sudoers.d/user-services

Network Security Hardening

Secure network configurations reduce the attack surface of your Linux servers:

  1. Use a firewall: Configure a host-based firewall using iptables, nftables, or ufw:
    # Allow only necessary services
    sudo ufw allow ssh
    sudo ufw allow http
    sudo ufw allow https
    sudo ufw enable
    
  2. Disable unnecessary services:
    # List all running services
    systemctl list-units --type=service --state=running
    
    # Disable unused services
    sudo systemctl disable --now unnecessary-service
    
  3. Network interface hardening:
    # Edit sysctl configuration
    sudo nano /etc/sysctl.conf
    
    # Add or modify these lines
    net.ipv4.conf.all.accept_redirects = 0
    net.ipv4.conf.all.accept_source_route = 0
    net.ipv4.conf.all.log_martians = 1
    net.ipv4.icmp_echo_ignore_broadcasts = 1
    
    # Apply changes
    sudo sysctl -p
    
  4. Use encrypted communications: Replace plain-text protocols with encrypted alternatives (SSH instead of Telnet, HTTPS instead of HTTP).

Regular Security Monitoring

Establish a continuous security monitoring practice:

  1. Log monitoring and management:
    • Centralize logs using rsyslog or journald
    • Configure log rotation with logrotate
    • Consider a log management solution like ELK (Elasticsearch, Logstash, Kibana)
  2. System auditing:
    • Use auditd to monitor system calls and detect suspicious activities
    • Configure specific audit rules for critical files:
      echo "-w /etc/passwd -p wa -k identity" | sudo tee -a /etc/audit/rules.d/audit.rules
      echo "-w /etc/shadow -p wa -k identity" | sudo tee -a /etc/audit/rules.d/audit.rules
      sudo service auditd restart
      
  3. Regular vulnerability scanning:
    • Schedule periodic scans with tools like OpenVAS or Nessus
    • Subscribe to security mailing lists for your distribution

Account and Authentication Security

Strong account security is fundamental:

  1. Enforce strong password policies:
    # Install libpam-pwquality
    sudo apt install libpam-pwquality
    
    # Edit the configuration
    sudo nano /etc/security/pwquality.conf
    
    # Set minimum requirements
    minlen = 12
    minclass = 3
    maxrepeat = 2
    
  2. Implement account lockout:
    # Edit PAM configuration
    sudo nano /etc/pam.d/common-auth
    
    # Add this line
    auth required pam_tally2.so deny=5 unlock_time=1800
    
  3. Use multi-factor authentication for critical systems:
    # Install Google Authenticator PAM module
    sudo apt install libpam-google-authenticator
    
    # Configure SSH to use it
    sudo nano /etc/pam.d/sshd
    # Add: auth required pam_google_authenticator.so
    
    sudo nano /etc/ssh/sshd_config
    # Set: ChallengeResponseAuthentication yes
    

Data Protection

Protect sensitive data with encryption:

  1. Disk encryption for sensitive systems:
    • Use LUKS for full disk encryption
    • Consider encrypting specific directories with eCryptfs
  2. Data-in-transit encryption:
    • Configure TLS/SSL for web services
    • Use VPNs for remote connections
    • Implement SFTP instead of FTP
  3. Secure deletion when removing sensitive data:
    # Install secure deletion tools
    sudo apt install secure-delete
    
    # Securely wipe a file
    srm -v sensitive_file.txt
    

Exercise 6: Creating a Server Hardening Checklist

  1. Create a hardening checklist for your specific environment, including:
    • User account and authentication security measures
    • Network security configurations
    • Service hardening steps
    • Monitoring and logging setup
  2. Implement at least five items from your checklist on a test system.
  3. Document the before and after state for each implemented item.
  4. Use Lynis to verify your improvements by comparing audit scores.

Quick Reference Summary

Security Update Management

SSH Hardening

File Integrity Monitoring (AIDE)

Security Auditing (Lynis)

Intrusion Detection (OSSEC)

Best Practices

Remember that security is a continuous process, not a one-time task. Regularly review and update your security measures as new threats emerge and systems change.