Module 7: Security Fundamentals
Learning Objectives
By the end of this module, you will be able to:
- Implement effective security update management practices
- Configure and harden SSH for secure remote access
- Set up file integrity monitoring using AIDE
- Perform security audits with Lynis
- Implement basic intrusion detection mechanisms
- Apply industry best practices for securing Linux servers
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:
- Security researchers or users discover and report the vulnerability
- Developers create a patch to fix the issue
- Distribution maintainers package the patched software
- The update is pushed to official repositories
- 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:
- APT (Advanced Package Tool) - Used by Debian, Ubuntu, and derivatives
- YUM/DNF (Yellowdog Updater, Modified/Dandified YUM) - Used by Red Hat, CentOS, Fedora
- Zypper - Used by SUSE and openSUSE
These package managers maintain databases of installed packages, available packages, and their dependencies. When you run an update command, the package manager:
- Contacts repository servers to get the latest package information
- Compares available package versions with installed versions
- Creates a list of packages that need updating
- Downloads the necessary packages
- Verifies package integrity using cryptographic signatures
- 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:
- Install the unattended-upgrades package if you're using a Debian-based system, or dnf-automatic for Red Hat-based systems.
- Edit the configuration file to specify which updates should be applied automatically.
- Configure email notifications for applied updates.
- Test the configuration by forcing an update check.
Common Pitfalls in Update Management
- Inconsistent update scheduling: Infrequent updates leave systems vulnerable. Establish a regular update schedule.
- Failing to test updates: Some updates can break functionality. Always test updates on non-production systems first.
- Ignoring dependency conflicts: Updates can sometimes create dependency conflicts. Make sure to review the list of changes before applying updates.
- 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:
- The SSH server (
sshd
) runs on the remote system you want to access - The SSH client (
ssh
) runs on your local machine - They negotiate encryption and authenticate before establishing a secure connection
Under the Hood: SSH Authentication Methods
SSH provides several authentication methods:
- Password authentication: Simple but vulnerable to brute force attacks
- Public key authentication: Uses asymmetric cryptography with a key pair
- Host-based authentication: Authenticates based on the client's hostname
- Keyboard-interactive: Flexible authentication method often used for multi-factor
Public key authentication is the most secure method. It works as follows:
- You generate a key pair: private key (kept secret) and public key (shared)
- The public key is placed on servers you want to access
- When connecting, the server creates a challenge encrypted with your public key
- Your client decrypts this challenge using your private key, proving your identity
- 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
-
Create a backup of your current SSH configuration:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
-
Generate a new SSH key pair using Ed25519:
ssh-keygen -t ed25519 -a 100
-
Deploy your public key to the server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server
-
Modify the SSH server configuration to:
- Disable root login
- Disable password authentication
- Change the default port
- Set an idle timeout
-
Test your configuration before applying it permanently:
sudo sshd -t
- Restart the SSH service and test your connection.
Common SSH Configuration Pitfalls
- Locking yourself out: Always keep a session open when making SSH changes, so you can revert if needed.
- Weak key algorithms: Avoid using outdated algorithms like DSA or short RSA keys. Prefer Ed25519 or RSA with at least 3072 bits.
- Forgetting about firewall rules: If you change the SSH port, update your firewall rules accordingly.
- 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:
- Database creation: AIDE scans the system and creates a database containing cryptographic hashes of files and their attributes
- Regular checks: At scheduled intervals, AIDE rescans the system and compares current file states with the database
- Reporting: Changes are reported, highlighting potential security issues
AIDE uses several hash algorithms (MD5, SHA1, SHA256, etc.) and can monitor various file attributes:
- File permissions and ownership
- Inode information
- File size and type
- File content (through cryptographic hashes)
- Access, modification, and creation times
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
- Install AIDE on your system.
- Customize the configuration file to focus on critical system directories.
- Initialize the AIDE database.
- Make some controlled changes to monitored files.
- Run a check to see if AIDE detects your changes.
- Set up a cron job to run daily checks and email the results.
Troubleshooting AIDE Issues
- False positives: Regular system activities can trigger many alerts. Fine-tune your configuration to exclude frequently changing files.
- Performance impact: Initial database creation and full system checks can be resource-intensive. Schedule them during off-peak hours.
- Database maintenance: After legitimate system changes, remember to update the AIDE database. Automate this after scheduled system updates.
- 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:
- System misconfiguration
- Vulnerable software versions
- Account security
- Firewall configuration
- Malware detection
- And much more
Under the Hood: How Lynis Works
Lynis operates by running a series of tests organized into categories or modules. Each test:
- Checks a specific security control or configuration
- Compares the result against best practices
- Assigns a severity level to findings
- 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:
- Warnings: High-priority issues that should be addressed immediately
- Suggestions: Recommended improvements to enhance security
- Information: Neutral findings providing context about your system
The report includes:
- A hardening index (0-100) indicating your system's security posture
- Test results grouped by category
- Suggestions for improvement
- Data collection for baseline comparison
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
- Install Lynis on your system.
- Run a complete system audit:
sudo lynis audit system
- Identify the top 3 highest severity findings.
- Implement fixes for at least one warning and one suggestion.
- Run the audit again to verify your fixes.
- Create a simple shell script to automate regular Lynis audits and save reports.
Addressing Common Lynis Findings
- SSH Configuration: Lynis often flags SSH settings. Fix by editing
/etc/ssh/sshd_config
to disable root login, password authentication, and empty passwords. - Password Policies: Strengthen password requirements in
/etc/pam.d/common-password
or/etc/security/pwquality.conf
. - Firewall Configuration: Ensure a firewall is active and properly configured:
sudo ufw enable sudo ufw default deny incoming sudo ufw allow ssh
- 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:
- Network-based IDS (NIDS): Monitors network traffic (e.g., Snort, Suricata)
- Host-based IDS (HIDS): Monitors system logs and file integrity (e.g., OSSEC, Wazuh)
- Hybrid systems: Combine network and host monitoring
Under the Hood: How OSSEC Works
OSSEC is a popular open-source HIDS that provides comprehensive protection. Here's how it functions:
- Agent-server architecture: A central server collects and analyzes data from agents installed on monitored hosts
- Log analysis: OSSEC parses and analyzes system and application logs using rules to identify suspicious activity
- File integrity monitoring: Similar to AIDE, it checks for unauthorized file modifications
- Rootkit detection: Searches for signs of rootkits using various detection techniques
- 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
- Install OSSEC as a local installation.
- Configure file integrity monitoring for critical system directories.
- Configure email alerts for high-severity events.
- Create a custom rule to detect failed SSH login attempts.
- Test your configuration by simulating suspicious activity.
- View and interpret the resulting alerts.
Troubleshooting Intrusion Detection Systems
- False positives: Tune rules to reduce false alarms. Start with a narrow focus and gradually expand monitoring.
- Performance impact: HIDS can consume significant resources. Adjust check frequencies and monitored directories based on system capabilities.
- Log management: OSSEC generates many log entries. Implement log rotation or forwarding to prevent disk space issues.
- 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:
- Use regular user accounts instead of root
- Apply sudo for administrative tasks with specific permissions
- Use application-specific users for services (e.g.,
www-data
for web servers) - Implement SELinux or AppArmor for mandatory access control
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:
-
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
-
Disable unnecessary services:
# List all running services systemctl list-units --type=service --state=running # Disable unused services sudo systemctl disable --now unnecessary-service
-
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
- 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:
-
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)
-
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
-
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:
-
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
-
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
-
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:
-
Disk encryption for sensitive systems:
- Use LUKS for full disk encryption
- Consider encrypting specific directories with eCryptfs
-
Data-in-transit encryption:
- Configure TLS/SSL for web services
- Use VPNs for remote connections
- Implement SFTP instead of FTP
-
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
-
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
- Implement at least five items from your checklist on a test system.
- Document the before and after state for each implemented item.
- Use Lynis to verify your improvements by comparing audit scores.
Quick Reference Summary
Security Update Management
- Debian/Ubuntu:
sudo apt update && sudo apt upgrade
- RedHat/CentOS:
sudo dnf update
- Automated updates:
sudo apt install unattended-upgrades
SSH Hardening
- Disable root login:
PermitRootLogin no
- Use key authentication:
PasswordAuthentication no
- Generate keys:
ssh-keygen -t ed25519 -a 100
- Deploy keys:
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
File Integrity Monitoring (AIDE)
- Install:
sudo apt install aide
- Initialize database:
sudo aide --init
- Check integrity:
sudo aide --check
- Update database:
sudo aide --update
Security Auditing (Lynis)
- Install:
sudo apt install lynis
- Full audit:
sudo lynis audit system
- Targeted audit:
sudo lynis audit system --tests-from-group=ssh
Intrusion Detection (OSSEC)
- Start OSSEC:
sudo /var/ossec/bin/ossec-control start
- Check status:
sudo /var/ossec/bin/ossec-control status
- View alerts:
sudo tail -f /var/ossec/logs/alerts/alerts.log
Best Practices
- Principle of least privilege: Use sudo with specific permissions
- Network hardening: Enable firewall, disable unnecessary services
- Account security: Strong passwords, account lockout, MFA
- Regular monitoring: Log analysis, auditing, vulnerability scanning
- Data protection: Encryption for sensitive data
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.