Chapter 22: Linux Security Basics

In this chapter, we’ll explore Linux security basics, including securing remote access, configuring firewalls, encrypting data, and implementing network security measures. By the end of this chapter, you’ll have a solid foundation for keeping your Linux system secure, both locally and over the network.


1. Why Learn Linux Security?

Security is a critical aspect of system administration and development. Whether you’re managing a personal machine or a production server, understanding Linux security tools and practices will help you protect your system from unauthorized access, data breaches, and network-based attacks. Linux security encompasses both local system security and network security, as the two are deeply interconnected.


2. Securing Remote Access with SSH

SSH (Secure Shell) is the standard tool for securely accessing remote systems. It ensures that communication between your local machine and the remote server is encrypted, protecting against eavesdropping and unauthorized access.

Generating SSH Keys

SSH keys provide a more secure alternative to password-based authentication. Here’s how to generate and use them:

Generate an RSA Key:

$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  • -t rsa: Specifies the key type (RSA).
  • -b 4096: Specifies the key length (4096 bits).
  • -C: Adds a comment (usually your email).

Generate an ed25519 Key:

$ ssh-keygen -t ed25519 -C "your_email@example.com"
  • -t ed25519: Specifies the key type (ed25519, a modern and secure algorithm).

Copy the Public Key to a Remote Server:

$ ssh-copy-id user@remote_host

SSH Configuration File

Customize SSH behavior using the ~/.ssh/config file. For example:

Host myserver
  HostName 192.168.1.100
  User amar
  IdentityFile ~/.ssh/id_ed25519

Now, you can connect using:

$ ssh myserver

SSH Best Practices

  • Disable Root Login: Edit /etc/ssh/sshd_config and set: ini PermitRootLogin no
  • Disable Password Authentication: Add the following to /etc/ssh/sshd_config: ini PasswordAuthentication no
  • Restart SSH Service: $ sudo systemctl restart ssh

3. Configuring Firewalls

Firewalls control incoming and outgoing network traffic, acting as a barrier between your system and potential threats. Linux provides tools like ufw (Uncomplicated Firewall) and iptables for configuring firewalls.

Using ufw

ufw is a user-friendly frontend for iptables. Here’s how to use it:

  • Enable ufw: $ sudo ufw enable
  • Allow SSH: $ sudo ufw allow ssh
  • Allow a Specific Port: $ sudo ufw allow 8080/tcp
  • Check Status: $ sudo ufw status

Using iptables

iptables is a powerful but complex firewall tool. Here’s an example of allowing SSH traffic:

$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Save the rules:

$ sudo iptables-save > /etc/iptables/rules.v4

4. Encrypting Data

Encryption protects sensitive data from unauthorized access. Linux provides tools like gpg (GNU Privacy Guard) for file encryption.

Encrypting a File with gpg

Encrypt a File: $ gpg -c file.txt This creates an encrypted file named file.txt.gpg.

Decrypt a File: $ gpg -d file.txt.gpg > file.txt

Managing Encryption Keys

  • Generate a GPG Key: $ gpg --full-generate-key
  • List Keys: $ gpg --list-keys
  • Export a Public Key: $ gpg --export -a "Your Name" > public.key
  • Import a Public Key: $ gpg --import public.key

5. Network Security Basics

Network security is essential to protect systems from unauthorized access, data breaches, and other threats. It complements local security measures by ensuring that communication over the network is secure.

Key Concepts

  • Confidentiality: Ensuring that information is not accessed by unauthorized individuals.
  • Integrity: Protecting information from being altered.
  • Availability: Ensuring reliable access to information.

Common Threats

  • Malware: Includes viruses, worms, and trojans.
  • Phishing: Attempting to acquire sensitive information by masquerading as a trustworthy entity.
  • Denial-of-Service (DoS) Attacks: Overloading a system to make it unavailable.

Basic Network Security Measures

  • Firewalls: Use ufw or iptables to control traffic.
  • Secure Protocols: Use HTTPS, SFTP, and SSH instead of insecure alternatives like HTTP or FTP.
  • Regular Updates: Keep the system updated to patch security vulnerabilities: 
    $ sudo apt update && sudo apt upgrade
  • Monitoring and Logging: Use tools like fail2ban to monitor logs and block suspicious activity: bash $ sudo apt install fail2ban

6. Practical Examples

Set Up SSH Key Authentication

  1. Generate an SSH key:  $ ssh-keygen -t ed25519 -C "your_email@example.com"
  2. Copy the public key to a remote server: $ ssh-copy-id user@remote_host
  3. Test the connection:  $ ssh user@remote_host

Configure a Firewall with ufw

  1. Enable ufw: $ sudo ufw enable
  2. Allow SSH, HTTP, and HTTPS: 
    $ sudo ufw allow ssh $ sudo ufw allow 80/tcp $ sudo ufw allow 443/tcp
  3. Check the status:  $ sudo ufw status

Encrypt a File with gpg

  1. Encrypt a file: $ gpg -c secret.txt
  2. Decrypt the file:  $ gpg -d secret.txt.gpg > secret.txt

7. Advanced Security Tools

Mandatory Access Control

  • AppArmor and SELinux: These frameworks restrict program access to resources, enhancing system security. For example, to install AppArmor:
    $ sudo apt install apparmor

Intrusion Detection

  • Fail2Ban: Monitors logs for failed login attempts and bans suspicious IPs:  
    $ sudo apt install fail2ban

System Auditing

  • Lynis: A security auditing tool to identify misconfiguration: 
    $ sudo apt install lynis

8. Summary

Implementing robust Linux and network security practices is essential for protecting your system from threats. By securing remote access with SSH, configuring firewalls, encrypting sensitive data, and monitoring network activity, you can create a layered defense that significantly reduces the risk of breaches. Regular updates, user management, and file permissions further enhance security.


9. Advanced Firewall Configuration with iptables

iptables is a powerful tool for configuring the Linux kernel firewall. While ufw provides a simpler interface, iptables offers granular control over network traffic. Here’s how to use it effectively:

Basic iptables Commands

Allow SSH Traffic
$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT 
This rule allows incoming SSH traffic on port 22.

Allow HTTP and HTTPS Traffic
$ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT $ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Block an IP Address
$ sudo iptables -A INPUT -s 192.168.1.50 -j DROP 
This blocks all traffic from the IP address 192.168.1.50.

Allow Established Connections
$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT 
This allows traffic for already established connections.

Set Default Policies
$ sudo iptables -P INPUT DROP $ sudo iptables -P FORWARD DROP $ sudo iptables -P OUTPUT ACCEPT 
This sets the default policy to drop all incoming and forwarded traffic while allowing outgoing traffic.

Saving iptables Rules

To ensure your iptables rules persist after a reboot, save them to a file:

$ sudo iptables-save > /etc/iptables/rules.v4

To restore the rules:

$ sudo iptables-restore < /etc/iptables/rules.v4

Example iptables Configuration

Here’s an example of a basic iptables configuration for a web server:

# Allow loopback traffic
$ sudo iptables -A INPUT -i lo -j ACCEPT

# Allow SSH
$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS
$ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
$ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow established connections
$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Drop all other incoming traffic
$ sudo iptables -P INPUT DROP

10. Configuring /etc/ssh/sshd_config

The /etc/ssh/sshd_config file controls the behavior of the SSH server. Proper configuration is essential for securing remote access. Here’s a guide to the most important settings:

Key Configuration Options

Disable Root Login: Prevent direct root login via SSH: ini PermitRootLogin no

Disable Password Authentication: Enforce key-based authentication: ini PasswordAuthentication no

Change the Default SSH Port: Reduce the risk of automated attacks by changing the default port (22): ini Port 2222

Limit User Access: Restrict SSH access to specific users: ini AllowUsers amar user1 user2

Enable Public Key Authentication: Ensure public key authentication is enabled: ini PubkeyAuthentication yes

Set Idle Timeout: Automatically disconnect idle sessions: ini ClientAliveInterval 300 ClientAliveCountMax 0 This disconnects users after 5 minutes (300 seconds) of inactivity.

Restrict SSH Protocol Version: Use only SSH protocol version 2: ini Protocol 2

Disable Empty Passwords: Prevent login attempts with empty passwords: ini PermitEmptyPasswords no

Limit Maximum Authentication Attempts: Reduce the risk of brute-force attacks: ini MaxAuthTries 3

Log Verbose Messages: Enable detailed logging for troubleshooting: ini LogLevel VERBOSE

Example /etc/ssh/sshd_config File

Here’s an example configuration for a secure SSH server:

Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers amar user1 user2
ClientAliveInterval 300
ClientAliveCountMax 0
Protocol 2
PermitEmptyPasswords no
MaxAuthTries 3
LogLevel VERBOSE

Applying Changes

After editing /etc/ssh/sshd_config, restart the SSH service to apply the changes:

$ sudo systemctl restart ssh

11. Summary of Advanced Configurations

  • iptables: A powerful tool for configuring firewalls with granular control over network traffic. Use it to allow or block specific ports, IP addresses, and protocols.
  • /etc/ssh/sshd_config: The configuration file for the SSH server. Properly configuring this file is critical for securing remote access. Key settings include disabling root login, enforcing key-based authentication, and changing the default SSH port.

What are pros and cons of fail2ban or iptables or ufw ? Which should a novice start with ?

Each of these tools—Fail2Ban, iptables, and ufw—serves a specific purpose in Linux security. Here’s a breakdown of their pros and cons, along with recommendations for novices.


1. Fail2Ban

Purpose:

Fail2Ban is an intrusion prevention tool that monitors logs (e.g., SSH, Apache) for repeated failed login attempts and bans the offending IP addresses temporarily or permanently.

Pros:

  • Automated Protection: Automatically detects and blocks brute-force attacks.
  • Customizable: Can be configured to monitor various services (SSH, FTP, web servers, etc.).
  • Easy to Set Up: Simple configuration files for basic use cases.
  • Dynamic Blocking: Temporarily bans IPs, reducing the risk of locking out legitimate users permanently.
  • Log Monitoring: Works with system logs, making it versatile for different applications.

Cons:

  • Reactive: Only acts after an attack has been detected.
  • False Positives: May block legitimate users if configured incorrectly.
  • Limited to Logged Events: Cannot block traffic that doesn’t generate logs (e.g., port scans).
  • Resource Intensive: Can consume system resources if monitoring many logs or services.

Best For:

  • Protecting services like SSH, web servers, and email servers from brute-force attacks.
  • Users who want automated, log-based intrusion prevention.

2. iptables

Purpose:

iptables is a powerful firewall tool that allows granular control over incoming, outgoing, and forwarded network traffic.

Pros:

  • Granular Control: Can define complex rules for filtering traffic based on IPs, ports, protocols, etc.
  • Highly Customizable: Suitable for advanced users who need fine-tuned firewall configurations.
  • Built into the Linux Kernel: No additional software required.
  • Supports NAT and Port Forwarding: Useful for routers and gateways.

Cons:

  • Complex Syntax: Difficult for beginners to learn and use effectively.
  • No Default Configuration: Requires manual setup, which can be error-prone.
  • No Logging by Default: Requires additional rules to log blocked traffic.
  • Persistence: Rules are not saved by default and must be manually saved and restored.

Best For:

  • Advanced users who need full control over network traffic.
  • Configuring complex firewall rules for servers, routers, or gateways.

3. ufw (Uncomplicated Firewall)

Purpose:

ufw is a user-friendly frontend for iptables, designed to simplify firewall configuration.

Pros:

  • Easy to Use: Simple commands for common tasks (e.g., allowing or blocking ports).
  • Beginner-Friendly: Abstracts the complexity of iptables while providing basic functionality.
  • Preconfigured Profiles: Includes default profiles for common services (e.g., SSH, HTTP).
  • Logging: Enables logging of blocked traffic by default.
  • Persistence: Automatically saves and applies rules on reboot.

Cons:

  • Limited Flexibility: Less customizable than iptables for advanced use cases.
  • Dependent on iptables: Still relies on iptables under the hood, so it inherits some of its limitations.
  • Not Suitable for Complex Configurations: May not meet the needs of advanced users.

Best For:

  • Beginners who need a simple way to configure a firewall.
  • Users who want basic firewall protection without the complexity of iptables.

Comparison Table

FeatureFail2Baniptablesufw
Ease of UseModerateDifficultEasy
PurposeIntrusion preventionFirewall managementSimplified firewall management
GranularityLog-based blockingHighly granularBasic to moderate
AutomationYes (blocks IPs automatically)NoNo
LoggingYes (monitors logs)Requires manual setupYes (enabled by default)
Best ForBrute-force protectionAdvanced firewall configurationsBeginners and basic firewall needs

Which Should a Novice Start With?

Recommendation for Novices:

  1. Start with ufw:
  2. It’s the easiest tool to learn and provides sufficient protection for most basic use cases.

Use it to allow or block ports, enable logging, and set up basic firewall rules.

Add Fail2Ban Later:

Once you’re comfortable with ufw, consider adding Fail2Ban to protect against brute-force attacks on services like SSH.

Learn iptables as You Advance:

  1. If you need more control over your firewall or are managing a complex network, gradually learn iptables.

Step-by-Step Guide for Novices

1. Start with ufw

  • Enable ufw: $ sudo ufw enable
  • Allow SSH:  $ sudo ufw allow ssh
  • Allow HTTP and HTTPS: 
    $ sudo ufw allow 80/tcp $ sudo ufw allow 443/tcp
  • Check status: $ sudo ufw status

2. Add Fail2Ban

  • Install Fail2Ban: $ sudo apt install fail2ban
  • Configure basic settings in /etc/fail2ban/jail.local: ini [sshd] enabled = true maxretry = 3 bantime = 1h
  • Restart Fail2Ban:  $ sudo systemctl restart fail2ban

3. Explore iptables

  • Start with basic rules, such as allowing SSH: 
    $ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  • Save and restore rules: 
    $ sudo iptables-save > /etc/iptables/rules.v4 
    $ sudo iptables-restore < /etc/iptables/rules.v4

Final Thoughts

  • For Beginners: Start with ufw for basic firewall needs and add Fail2Ban for brute-force protection.
  • For Advanced Users: Use iptables for granular control and complex configurations.
  • For Everyone: Regularly update your system and monitor logs to stay ahead of potential threats.

By starting with ufw and gradually exploring Fail2Ban and iptables, you’ll build a strong foundation in Linux security without feeling overwhelmed.


Practice Time!

Let’s put your new skills to the test:

Configure iptables to allow SSH, HTTP, and HTTPS traffic while blocking all other incoming traffic.

Edit /etc/ssh/sshd_config to disable root login, enforce key-based authentication, and change the default SSH port.

Restart the SSH service and test your configuration.


That’s it for chapter 22! You’ve now learned how to secure your Linux system using SSH, firewalls, encryption, and advanced configurations like iptables and /etc/ssh/sshd_config. In the next chapter, we’ll dive into performance monitoring—how to monitor system resources using tools like htop, btop, and vmstat. Until then, practice these security techniques to keep your system safe.


Prev: Chapter 21 | Next: Chapter 23