Security: A Beginner's Guide to Hardening Your Linux Server from Scratch

Automated English translation of the original Spanish article. Code examples keep their original identifiers.

Protecting your Linux server is always essential. It is a fundamental step to keep your data safe and ensure that your project—whether it’s a personal blog, a web application, or a staging environment—does not fall victim to cyberattacks. This guide is designed for beginners who are taking their first steps as systems administrators (sysadmins) and want to establish a solid security baseline on a Linux server, such as a virtual machine in AWS, DigitalOcean, or a local VPS. Here, I’ll walk you through how to implement essential security measures step by step, using a practical, approachable mindset without sacrificing technical precision.

A practical example to get started: Suppose you just rented a budget Linux server to experiment with, perhaps to host a WordPress blog or a personal web application. Before installing any software, you want to make sure the server is a secure environment to avoid issues like unauthorized access, malware, or attacks that could compromise your project. This guide will walk you through securing your server from scratch, allowing you to work with confidence and prepare for more complex environments down the road.

1. Keep Your Server Up to Date

The first step in protecting any Linux server is to ensure that both the operating system and the installed packages are up to date with the latest security patches. Vulnerabilities in outdated software are one of the primary entry points for attackers, as exploits for known flaws are often widely documented.

How to do it based on your distribution:

Debian/Ubuntu:

Update the package list and apply available updates:

sudo apt-get update && sudo apt-get upgrade -y

For more critical upgrades that include kernel updates, use:

sudo apt-get dist-upgrade -y

CentOS/Red Hat/Fedora:

On Red Hat-based distributions, use the corresponding package manager:

sudo dnf update -y

On older versions of CentOS:

sudo yum update -y

Practical tip: Configure automatic updates for security patches (for example, with unattended-upgrades on Ubuntu or dnf-automatic on Fedora) to reduce the risk of forgetting this step. However, review major updates manually—such as those affecting the kernel—to prevent unexpected compatibility issues.

Why it matters: Patches fix security bugs that attackers could exploit. For example, a vulnerability in a web server like Apache could allow remote code execution if it is not patched in time.

2. Create Strong Passwords and Protect Them

Weak passwords are an open invitation to attackers. Use long passwords (at least 12 characters, though I prefer 20) that combine uppercase letters, lowercase letters, numbers, and symbols. Avoid common words or personal information, such as names or birthdates.

Best practices:

  • Use a password manager: Tools like Bitwarden or KeePass help you generate and store strong passwords conveniently.
  • Test your password strength: A solid password might look like X9m#kP2$vL8nQw!. Avoid predictable patterns such as Password123!.
  • Change the default root password: If your server came with a pre-assigned password, change it immediately:
sudo passwd

Additional note: Consider implementing password policies on the server (for example, using pam_pwquality on Debian-based systems) to enforce minimum complexity requirements for all users.

3. Disable Unnecessary Services

Every active service running on your server (such as an FTP server, a mail daemon, or a database) represents a potential attack vector. Reducing your attack surface means stopping and disabling or uninstalling any service that is not strictly required for your project.

Steps to identify and manage services:

List active services:

sudo systemctl list-units --type=service --state=running

This will show you which services are currently running. For instance, if you don’t need a mail server like postfix, disable it.

Stop and disable an unnecessary service:

sudo systemctl stop nombre_del_servicio
sudo systemctl disable nombre_del_servicio

For example, if you don’t need a web server like Apache, disable it:

sudo systemctl stop apache2
sudo systemctl disable apache2

Practical example: If your server is intended for a WordPress blog, you likely only need sshd (for remote access), a web server (nginx or apache2), and a database (mysql). Services like telnet or rpcbind are usually unnecessary and should be disabled.

Tip: Review running services after installing new software, as some applications enable background daemons automatically.

4. Configure a Basic Firewall

A firewall acts as a gatekeeper that inspects network traffic, allowing only necessary connections and blocking unauthorized access attempts. Setting up a firewall is one of the most effective security measures you can take.

Using UFW (Uncomplicated Firewall) on Debian/Ubuntu:

  1. Install UFW if it is not already installed:
sudo apt-get install ufw
  1. Enable the firewall (make sure to allow SSH first so you don’t lose remote access):
sudo ufw allow ssh
sudo ufw enable
  1. Add specific rules according to your needs, for example, for a web server:
sudo ufw allow http
sudo ufw allow https

Using firewalld on CentOS/Red Hat/Fedora:

  1. Install and enable firewalld:
sudo dnf install firewalld
sudo systemctl enable --now firewalld
  1. Allow SSH access:
sudo firewall-cmd --add-service=ssh --permanent
sudo firewall-cmd --reload
  1. Add other services as needed, such as HTTP:
sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --reload

Practical tip: Before enabling the firewall, verify that you have explicitly allowed SSH access (port 22 or whichever port you use) to avoid locking yourself out of the server. If you use a custom SSH port, allow that specific port:

sudo ufw allow 2222/tcp

Why it matters: A properly configured firewall reduces the risk of port scanning and brute-force attacks.

5. Implement SSH Keys for More Secure Access

Password-based remote authentication is inherently vulnerable to brute-force attacks. SSH keys provide a significantly more secure alternative using public-key cryptography.

How to set up SSH keys:

  1. Generate a key pair on your local machine:
ssh-keygen -t rsa -b 4096

This creates a private key (id_rsa) and a public key (id_rsa.pub). Accept the default file path and set a passphrase for added security.

  1. Copy the public key to your server:
ssh-copy-id usuario@direccion_del_servidor

This appends your public key to the user’s ~/.ssh/authorized_keys file on the server.

  1. Disable password-based logins on the server:

Edit the SSH configuration file (/etc/ssh/sshd_config):

sudo nano /etc/ssh/sshd_config

Ensure the following directives are present and properly set:

PasswordAuthentication no
PermitRootLogin no

Optionally, change the default SSH port (22) to something non-standard, like 2222:

Port 2222
  1. Restart the SSH service to apply changes:
sudo systemctl reload sshd

Extra enhancement: Consider enabling two-factor authentication (2FA) for SSH using tools like Google Authenticator or Authy. This adds an extra layer of defense by requiring a time-based code in addition to your SSH key.

Practical example: If you change the SSH port to 2222, make sure to update your firewall rules and your local SSH client command (e.g., ssh -p 2222 user@server).

6. Apply the Principle of Least Privilege

Do not use the root account for day-to-day administrative tasks. A minor mistake or an exploit could have catastrophic consequences. Instead, create non-root users with limited privileges and use sudo when administrative rights are required.

How to create a limited user with sudo privileges:

  1. Create a new user account:
sudo adduser nuevo_usuario

Follow the prompts to set a password and standard user information.

  1. Grant administrative privileges via sudo:
sudo usermod -aG sudo nuevo_usuario
  1. Log in with the new user to test the configuration:
ssh nuevo_usuario@direccion_del_servidor

Practical tip: If your project involves multiple people (such as a development team), create individual accounts with tailored permissions and avoid sharing a single user account.

Why it matters: Restricting privileges minimizes the blast radius of unauthorized access. For example, an attacker who compromises an account without sudo access will have a much harder time modifying system files or taking full control.

7. Monitor Your Server to Detect Anomalies

Continuous monitoring allows you to spot suspicious activity early on, such as failed login spikes or abnormal resource usage.

Basic tools and commands:

View active processes:

top

Or, if installed, use htop for an interactive, user-friendly view:

sudo apt-get install htop
htop

Inspect system logs:

To review authentication attempts (particularly useful for identifying brute-force attempts):

sudo tail -f /var/log/auth.log

Or for general system logs on systemd environments:

sudo journalctl -xe

Install Fail2ban for automated protection:

Fail2ban monitors log files for repeated failed login attempts and temporarily or permanently bans offending IP addresses using firewall rules:

sudo apt-get install fail2ban

Configure your custom rules in /etc/fail2ban/jail.local and restart the daemon:

sudo systemctl restart fail2ban

Advanced tools worth exploring:

  • OSSEC or Snort: These Intrusion Detection Systems (IDS) can alert you to suspicious activity. While their initial configuration can be complex, they are well worth exploring as your administration skills grow.
  • SELinux or AppArmor: These security modules are integrated into many modern distributions (SELinux on CentOS/RHEL/Fedora, AppArmor on Ubuntu/Debian) to enforce Mandatory Access Control (MAC), restricting what each binary can do. For example, AppArmor can prevent a compromised web server from reading files outside its designated document root. While there is a learning curve, understanding what they do is a great starting point.

Practical tip: Review system logs on a regular basis (e.g., once a week) and set up basic log-monitoring tools like logwatch to send daily summaries directly to your inbox.

Final Thoughts on Hardening Your Linux Server

Securing a Linux server is not a one-time checklist item; it is an ongoing process that combines sound engineering practices, proactive monitoring, and continuous learning. The core steps covered in this guide—keeping the system updated, using strong credentials, disabling unnecessary services, configuring a firewall, using SSH keys, enforcing the principle of least privilege, and monitoring logs—form the foundation of any secure environment. Over time, you can branch out into advanced tooling like intrusion detection systems or custom SELinux profiles to take your infrastructure’s resilience to the next level.

This guide serves as a practical starting point for anyone stepping into Linux systems administration. As you gain more experience, you’ll be able to tailor these defenses to your specific workloads, whether you are hosting a personal blog, deploying a web application, or running production infrastructure. Keep this guide bookmarked for future setups and share it with others entering the world of Linux server administration.