Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Security Hardening

Reducing the Attack Surface of a Linux Server

Start Linux hardening the practical way: find what listens on the network, remove unneeded services and packages, apply least privilege, patch quickly and tune kernel settings with sysctl.

Security work on a server is mostly subtraction. Every running service, open port, installed package and user account is something an attacker could use and something you must keep patched. Attack surface is the sum of those things. Reducing it is the cheapest, most effective hardening step, and it needs no special products.

This lesson gives you a repeatable routine: inventory, remove, restrict, patch, and verify. Commands are read-only snippets (the site cannot inspect a real machine); the Python stand-ins parse realistic command output so you can practise reading it.

Principles worth memorising

  • Least privilege. Every account, process and key gets only the access it needs.
  • Minimal install. Software you did not install cannot be exploited.
  • Defence in depth. Firewall, authentication, mandatory access control, monitoring: assume any one layer can fail.
  • Secure by default, then verify. Do not trust that a config is applied; check the result.
  • Patch fast. Most real-world breaches use known, already fixed vulnerabilities.
flowchart TB
    A["Inventory<br/>ports, services, packages, users"] --> B["Remove what is not needed"]
    B --> C["Restrict what remains<br/>bind, firewall, permissions"]
    C --> D["Patch and automate updates"]
    D --> E["Verify from outside<br/>and repeat"]
    E --> A

Hardening is a loop, not a one-time task.

Step 1: what is listening?

A service that does not listen cannot be attacked over the network. List every listening socket:

Terminal
sudo ss -tulpn          # tcp, udp, listening, process, numeric
sudo ss -tlnp           # only TCP
TEXT
Netid State  Recv-Q Send-Q Local Address:Port  Peer Address:Port Process
tcp   LISTEN 0      128          0.0.0.0:22         0.0.0.0:*     users:(("sshd",pid=701,fd=3))
tcp   LISTEN 0      511          0.0.0.0:80         0.0.0.0:*     users:(("nginx",pid=812,fd=6))
tcp   LISTEN 0      80         127.0.0.1:3306       0.0.0.0:*     users:(("mysqld",pid=930,fd=21))
tcp   LISTEN 0      4096       127.0.0.1:6379       0.0.0.0:*     users:(("redis-server",pid=944,fd=6))
tcp   LISTEN 0      128          0.0.0.0:111        0.0.0.0:*     users:(("rpcbind",pid=602,fd=4))

Read the Local Address column. 0.0.0.0 (or *, or [::]) means "all interfaces": reachable from the network. 127.0.0.1 means "this machine only". A database or cache bound to 127.0.0.1 is safe from the internet even without a firewall; bound to 0.0.0.0 it is a target. In the sample above, rpcbind on port 111 is probably something nobody needs.

Python Which listeners are exposed?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 2: remove what you do not need

For each unexpected listener, ask: what is it, who needs it, and can it go?

Terminal
systemctl list-unit-files --type=service --state=enabled
systemctl list-units --type=service --state=running
sudo systemctl disable --now rpcbind.service rpcbind.socket
sudo systemctl mask cups.service              # cannot be started by anything

disable --now stops it and prevents start at boot. mask links the unit to /dev/null so even dependencies cannot start it. Then remove the package when you are sure:

Terminal
apt list --installed | less            # Debian / Ubuntu
sudo apt purge telnetd rsh-server
rpm -qa | sort | less                  # RHEL family
sudo dnf remove telnet-server

Old, plain-text protocols (telnet, rsh, FTP, TFTP) should not exist on a server. Compilers and build tools on a production machine help an attacker who gets in, so keep them off unless needed.

Step 3: restrict what remains

  • Bind to the right interface. Databases and caches on 127.0.0.1 or a private address (bind-address in MySQL, bind in Redis, listen_addresses in PostgreSQL).
  • Firewall. Default deny, allow only the ports the service must offer (Firewalls).
  • Run services as dedicated unprivileged users, never as root. systemd units can add a sandbox: NoNewPrivileges=yes, ProtectSystem=strict, ProtectHome=yes, PrivateTmp=yes, CapabilityBoundingSet=. Check a unit with systemd-analyze security nginx.service, which scores exposure.
  • Accounts. Lock or delete users who no longer need access (sudo passwd -l user, sudo userdel -r user), review /etc/sudoers.d/, and list accounts with login shells: grep -v nologin /etc/passwd | grep -v false.
  • Permissions. Find risky files: world-writable files find / -xdev -type f -perm -0002, setuid binaries find / -xdev -perm -4000, files owned by nobody find / -xdev -nouser.

Step 4: patch and keep patching

Unpatched software is the most common root cause. Enable automatic security updates on servers where an occasional automatic restart is acceptable:

Terminal
# Debian / Ubuntu
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

# RHEL family
sudo dnf install dnf-automatic
sudo systemctl enable --now dnf-automatic-install.timer

Kernel and libc updates need a reboot (or a live-patch service) to take effect. Find processes still using deleted library files with sudo needrestart (Debian family) or sudo dnf needs-restarting -r.

Step 5: kernel settings with sysctl

A few network parameters harden the TCP/IP stack. Put them in /etc/sysctl.d/90-hardening.conf and load with sudo sysctl --system.

TEXT
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
fs.protected_symlinks = 1
fs.protected_hardlinks = 1

These suit ordinary servers; a router or container host may need forwarding or different values, so test before rolling out widely.

Python sysctl baseline checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 6: verify from outside

What matters is what an outsider can reach. From another machine, scan the server (only machines you own or are authorised to test):

Terminal
nmap -sS -p- -T4 server.example.org
nc -vz server.example.org 3306

Compare the result with the list you expected. A surprise open port is a finding to fix today.

The hardening loop

Inventory ss, systemctl, packages.
Remove Disable, mask, purge.
Restrict Bind, firewall, sandbox.
Patch Automate updates.

Then scan from outside, and repeat.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In ss -tlnp output, what does Local Address 127.0.0.1:3306 mean?

    127.0.0.1 is loopback; 0.0.0.0 or [::] would mean all interfaces.
  2. 2. What is the difference between systemctl disable --now and systemctl mask?

    Masked units are linked to /dev/null and cannot be started, even as a dependency.
  3. 3. Which tool gives a systemd service an exposure score so you can sandbox it further?

    systemd-analyze security rates a unit's sandboxing settings and suggests directives to add.
  4. 4. Why scan your own server from another machine after hardening?

    Verification from outside catches published Docker ports, forgotten services and firewall mistakes.

Summary

  • Attack surface is every running service, open port, package and account; reduce it first.
  • Inventory with ss -tulpn and systemctl; disable, mask and purge what is unneeded.
  • Bind internal services to loopback or private addresses, add a default-deny firewall, run services unprivileged and sandbox units.
  • Automate security updates and restart for kernel and library fixes.
  • Harden kernel parameters with sysctl and verify results by scanning from outside.

Next: SSH Hardening and fail2ban