Bookmarks

Linux server hardening

Linux server hardening is configuring a server to resist break-ins and data leaks. This reference covers key-based SSH, sudo, updates, the firewall, AppArmor and SELinux, fail2ban and auditing.

checked 6 Nov · next check 13 Nov · 61 min read

Sections
12
Reading
61 min
Current version
Debian 13.7
Written from
ubuntu.com/security/notices

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Linux server hardening is and how it works

Server hardening reduces the attack surface: you close unnecessary entry points and limit both process privileges and the damage a break-in can do. You start by answering three questions: what you are protecting, from whom, and at what cost. Then you build several layers of defence, from the firewall to kernel restrictions.

Ubuntu and Debian already enable much of the protection: a minimal installation has no open ports, AppArmor is running, and address space layout randomisation (ASLR) and automatic security updates are on. On top of that, you configure SSH, the firewall, user accounts and monitoring.

Policy: what you protect and from whom

Hardening starts with questions, not tools. Which data and services are you protecting? Where do you expect the threat to come from: a mistake by one of your own users or a determined group? How much convenience and performance are you willing to give up? The answers form a risk model, and the risk model produces a security policy: a list of concrete measures. Policy comes first and tools second; otherwise it is easy to secure the wrong side.

The answers depend on the system. A home VPS holding a site backup needs only a basic set of measures; a server with a database of personal data needs stricter ones. The more valuable the asset, the more layers are justified.

Defence in depth

No single measure is 100% reliable, so protection is built in layers: a mistake in, or a bypass of, one layer does not hand the attacker the whole server. From the network to the process:

  • the firewall lets through only the ports you need;
  • SSH logins use keys, not passwords;
  • people work under their own accounts and raise privileges with sudo;
  • the server runs only the services it needs;
  • services run in AppArmor profiles with minimal privileges;
  • the kernel is restricted with sysctl parameters.

Two continuous tasks run through all the layers: updates close known vulnerabilities, and auditing and monitoring show what is happening on the server. Each layer is covered in detail in the sections “SSH”, “Firewall”, “Accounts and sudo”, “Minimal services and open ports”, “AppArmor and SELinux” and “Kernel and sysctl”.

Breaking through one layer does not open up the whole server: an attacker has to get past each following layer separately.

What is already enabled by default

A minimal Ubuntu or Debian installation is better protected than most people assume. It has no open network ports: services do not listen on the network until you install and enable them. Passwords are stored with strong hashing, and Ubuntu installs security updates automatically.

The kernel and the way packages are compiled add layers you cannot see from the console: process address space is randomised (ASLR), memory is marked non-executable, and the stack is protected by canaries. Mandatory access control confines processes: Ubuntu and Debian run AppArmor by default, which keeps each program in a profile listing the operations it may perform. To check the state of the profiles, run sudo aa-status.

How hardening differs from basic setup

AspectBasic setupHardeningCIS compliance
Goalthe server works and can be maintainedkeeps working under attackworks and passes an audit
Source of the measuresdistribution guidesthe server’s risk modela third-party benchmark checklist
Key questionhow to enable itwhether to enable itwhat the benchmark requires
Who assessesthe administratorthe administratoran auditor, against the checklist

Basic setup is covered in the Linux reference: SSH access, user accounts, packages. Hardening answers the question “what should be strengthened and what restricted”, while the CIS Benchmark is an independent checklist from the Center for Internet Security, used to audit servers against compliance requirements. For your own server the first two are usually enough; you bring in CIS when a regulator or a customer requires compliance.

What you need to know first

  • SSH login and keys, working on the command line: Linux reference, section “SSH access”;
  • file permissions, user accounts, sudo: Linux reference, section “Users and permissions”;
  • installing and updating packages with apt: Linux reference, section “Packages”;
  • systemd and units, at the level of concepts: systemctl manages a service and its configuration lives in unit files; for details, see the systemd reference.

Section sources

the section is written from these pages

Checklist

This Linux server hardening checklist has sixteen checks that close the typical gaps left at commissioning. Go through it when you put a server into service and then once a month: SSH, accounts, updates, network, services, AppArmor, monitoring.

Each item is a verifiable statement plus the command that confirms it. If the command prints what you expect, the item is done; if it prints anything extra, go back to the section of this reference that covers that area and fix it. The checks are listed in the order in which a server is usually commissioned.

Commissioning

Seven groups of checks cover the basics: SSH, accounts, updates, network, services, AppArmor and monitoring. Each area is configured in detail in its own section of the reference.

  1. Key-based login: /etc/ssh/sshd_config.d/ contains a file with PasswordAuthentication no and PermitRootLogin no.
  2. Check: sudo sshd -T | grep -e passwordauthentication -e permitrootlogin prints no for both.
basheffective sshd configuration
sudo sshd -T | grep -e passwordauthentication -e permitrootlogin
  1. There are no shared accounts: each administrator has their own user, and root privileges are granted through sudo by group membership, not by logging in as root.
  2. Check: getent passwd lists no users with UID 0 other than root, and getent group sudo lists only the server’s administrators.
bashwho has UID 0
sudo getent passwd | awk -F: '$3 == 0 {print $1}'
  1. Automatic updates are on: the unattended-upgrades package is installed and by default checks for security updates once a day.
  2. After a kernel update the server has been rebooted: the marker file /var/run/reboot-required is absent and uname -r shows the new kernel.
bashrunning kernel and reboot marker
uname -rcat /var/run/reboot-required 2>/dev/null || echo reboot not required
  1. The firewall is enabled and starts at boot: sudo ufw status verbose reports Status: active.
  2. Only the ports you need are open: incoming connections are denied by default, and each service has an explicit allow rule.
bashfirewall status and rules
sudo ufw status verbose
  1. Listening ports match the plan: the output shows no services that should not be there.
bashall listening TCP ports and their processes
sudo ss -tlnp
  1. There are no unnecessary packages: databases, compilers and other tools this server does not need have been removed.
  2. AppArmor profiles are in enforce mode: sudo aa-status shows the loaded profiles and none in complain mode.
bashAppArmor profile modes
sudo aa-status
  1. Logs are collected and kept: journalctl shows events since installation, and there is space to store them.
  2. Auditing of logins and sudo calls is on: logins and privilege escalations are visible in the log when you investigate an incident.
bashlogs of the latest boots
sudo journalctl --list-boots | tail -5

Monthly check

Once a month, repeat the same checks and add three more: a comparison with last month’s records, a package integrity check and an audit report. They catch changes that administrators and packages made over the month.

  1. The list of listening ports and the firewall rules still match what you expect: compare sudo ss -tlnp and sudo ufw status with last month’s records.
  2. Package integrity: sudo dpkg --verify prints nothing, meaning the package files match the dpkg database.
  3. Compliance report: sudo usg audit cis_level1_server builds a report and shows the compliance status; the report is kept in /var/lib/usg/. For installing USG and its profiles, see “Auditing and monitoring”.
bashCIS Level 1 audit
sudo usg audit cis_level1_server

Section sources

the section is written from these pages

SSH

Leave an SSH server on the network only with key-based authentication: disable passwords and root login in sshd_config, check the configuration with sshd -t, and let fail2ban cut off brute-force attempts. That leaves guessing with nothing to aim at, because the server has no password to guess.

sshd looks up a user’s keys in the ~/.ssh/authorized_keys file. Create a key pair with ssh-keygen -t ed25519 and copy the public key to the server with ssh-copy-id user@203.0.113.10; for details, see the Linux reference, section “Access and initial setup”.

Permissions on ~/.ssh

The StrictModes option makes sshd check permissions: if the home directory, ~/.ssh or authorized_keys is writable by anyone else, key-based login is rejected. The check is on by default; fix the permissions on the directory and file like this:

bashon the server, as your own user
chmod go-w ~chmod 700 ~/.sshchmod 600 ~/.ssh/authorized_keys

Minimal sshd configuration

The main file /etc/ssh/sshd_config pulls in the sshd_config.d/ directory with an Include line at the very top, and for most options the first occurrence wins, so values from the included files override the main ones. Files are applied in alphabetical order, so keep your changes in a single file with a low number.

bashon the server
sudo tee /etc/ssh/sshd_config.d/20-hardening.conf >/dev/null <<'EOF'PasswordAuthentication noPermitRootLogin noAllowGroups sudoMaxAuthTries 3EOF
OptionWhat it doesDefault
PasswordAuthenticationpassword login; no disables it entirelyyes
PermitRootLoginroot login; no forbids every method, including keysprohibit-password
AllowUsers, AllowGroupsallowlist: only these users or groups can log ineveryone is allowed
MaxAuthTrieslogin attempts per connection; after that the connection is closed6

For root, the default is prohibit-password, which lets root in with a key. An explicit no closes that path too: people log in as ordinary users and raise privileges with sudo (see “Accounts and sudo”). In the example, login is allowed for the sudo group; before restarting, run groups to confirm your user is a member, or name your own group.

Checking and restarting without losing access

Losing SSH access means losing the server. Follow this order:

  1. Copy the key and make sure key-based login works.
  2. Write the file to sshd_config.d/ and run sudo sshd -t.
  3. Restart ssh.service without closing the current session.
  4. Open a second window and log in with a new connection.
  5. Close the old session only after that login succeeds.
bashon the server
sudo sshd -tsudo systemctl restart ssh.service
bashfrom your workstation
# do not close the current session until you have checkedssh user@203.0.113.10

Second factor: a one-time code

A key stops guessing, but not theft of the key itself. A second factor is a one-time code (TOTP, Time-based One-Time Password) from an authenticator app such as Google Authenticator: the code depends on a shared secret and the current time, is valid for a short while and changes by itself. Stealing the key or the code alone does not get an attacker in.

Set up keys and codes before you enable the second factor: once it is on, nobody can log in without a configured code. The first factor remains the key, and the password is disabled completely. The pam_google_authenticator module checks the code, and the AuthenticationMethods line requires both factors in sequence. Each user creates their own secret for the app: the google-authenticator command prints a QR code.

bashthe first with sudo, the second as your own user
sudo apt install libpam-google-authenticatorgoogle-authenticator
bashon the server
sudo tee /etc/ssh/sshd_config.d/30-totp.conf >/dev/null <<'EOF'KbdInteractiveAuthentication yesPasswordAuthentication noAuthenticationMethods publickey,keyboard-interactiveEOFsudo sshd -t && sudo systemctl restart ssh.service

Prepare in advance for losing the phone with the app: during setup, google-authenticator prints backup codes for that case. Store them like a password, because they let you in without the second factor.

Password guessing and fail2ban

With passwords disabled, guessing has nothing to latch onto: sshd does not accept a password at all. fail2ban watches for failed sshd logins and, after several in a row, adds the source address to the firewall rules for the period set in the jail. On current Debian and Ubuntu it reads them from the systemd journal; the file /var/log/auth.log exists only if rsyslog is installed. This reduces the rate of attempts but does not remove the risk of weak authentication, as the fail2ban documentation itself warns, so key-based login remains the foundation.

bashon the server
sudo apt install fail2bansudo systemctl enable --now fail2bansudo fail2ban-client status sshd

Another approach is the firewall: allow connections to the SSH port only from known addresses, such as your office, and guessing never reaches the daemon. Firewall rules are covered in the section “Firewall”.

Changing the port

Port sets the port sshd listens on; the default is 22. Changing it removes most automated attempts from the log, but it does not hide the service: on connection, sshd sends a banner like SSH-2.0-OpenSSH_… before any authentication, so a scanner recognises SSH on any port. Change the port for a cleaner log, not instead of keys and disabled passwords.

Password guessing is possible only where sshd accepts passwords.

To verify the result, watch the daemon log: sudo journalctl -fu ssh.service shows every login attempt and its method, and a successful key login appears as Accepted publickey. Once passwords are disabled, Failed password lines disappear from the log.

Section sources

the section is written from these pages

Accounts and sudo

A separate account for each administrator and precise sudo rules limit the damage when a password or key leaks. The log shows who did what, and a stolen login gives only part of the privileges, not the whole server.

On Ubuntu and Debian, root privileges come not from logging in as root but from membership of the sudo group, which is allowed in /etc/sudoers (for the basics, see the Linux reference, section “Users, groups and permissions”). This section covers custom rules in /etc/sudoers.d/, password policy and locking unused accounts.

One person, one account

Shared logins such as deploy and admin destroy accountability: every action in the log appears under one name, and you cannot revoke one person’s access. Create an account for each administrator and do not reuse it on other servers.

basha new administrator
sudo adduser aishasudo adduser aisha sudo

Give services their own accounts without a shell: /usr/sbin/nologin forbids login, and a UID below 1000 sets them apart from people (human users start at 1000). That way php-fpm or postgres does not become a way in.

CheckWhat it shows
sudo -lwhich commands this user can run through sudo
sudo lastlogwhen each user last logged in
lasta history of past logins and reboots
sudo chage -l aishathe password expiry settings for this account

Precise sudo rules

Put your own rules in /etc/sudoers.d/: package updates leave them alone, and visudo -f checks the syntax before saving. Files are read in lexical order, so number them with a leading zero: 01-aisha.

bashcreate a rule file
sudo visudo -f /etc/sudoers.d/01-backup
propertiesfile /etc/sudoers.d/01-backup
# backup-job: archive and rsync only, no shellbackup ALL=(root) NOPASSWD: /usr/bin/rsync, /usr/local/sbin/backup # aisha: full root, with a passwordaisha ALL=(ALL:ALL) ALL

A rule reads “who where = (as whom) what”. Grant the minimum: an exact path, and arguments only where they cannot be avoided. NOPASSWD: ALL removes the password, which is the last barrier against a stolen session; allow it only for automation tasks with fixed commands.

Passwords and account lifetimes

Set a password lifetime and a minimum length: chage sets the expiry, while the pam_pwquality module (Debian: the libpam-pwquality package) in /etc/pam.d/common-password sets the length and quality checks.

bashpassword expiry
sudo chage -M 180 -m 1 -W 14 aishasudo chage -l aisha
iniminimum password length
# /etc/pam.d/common-password, the pam_pwquality line:password requisite pam_pwquality.so retry=3 minlen=12

Lock a departing employee’s account the same day: passwd -l locks the password, and chage -E 0 sets the account expiry date in the past. Locking the password does not stop a key-based login, so check ~/.ssh/authorized_keys and active sessions with w, and remove the keys.

bashlocking and reviewing logins
sudo passwd -l aisha && sudo chage -E 0 aishaw | grep aishalast aisha

Review the accounts once a month. sudo -l shows who has which privileges, and lastlog and last show who logged in, when and from where. It is better to delete an account nobody uses than to lock it.

Section sources

the section is written from these pages

Security updates

Security updates should install themselves. On Ubuntu, unattended-upgrades does this and is enabled by default; on Debian the package is usually installed, but you enable it yourself. The file /var/run/reboot-required tells you a reboot is needed after a kernel update, and needrestart reports services still running outdated libraries.

Vulnerability fixes arrive from the security pocket of the official repository: -security on Ubuntu and security.debian.org on Debian. Every fix comes with a security notice: a USN (Ubuntu Security Notice) on Ubuntu or a DSA (Debian Security Advisory) on Debian, listing the CVE (Common Vulnerabilities and Exposures) numbers and affected packages. To update manually, run two commands: sudo apt update && sudo apt upgrade.

Enabling automatic updates

On Ubuntu, unattended-upgrades is part of the default installation and applies security updates daily. On Debian the package is usually installed but may be switched off: run dpkg-reconfigure unattended-upgrades to check its state and enable automatic updates. If the package is missing, install it first:

bashenabling on Debian
sudo apt install unattended-upgradessudo dpkg-reconfigure unattended-upgrades

The file 20auto-upgrades sets the frequency: Update-Package-Lists refreshes the package lists and Unattended-Upgrade installs the updates; 1 means “once a day” and 0 means off. These steps are run by the systemd timers apt-daily.timer and apt-daily-upgrade.timer with a random delay; if the machine was off at the scheduled time, the timer runs the missed job on the next boot. The installation behaviour (allowed pockets, exclusions, reboots) is configured in 50unattended-upgrades. To test your changes without installing anything, run sudo unattended-upgrade --dry-run, which shows what would be installed; the log of every run is in /var/log/unattended-upgrades.

bashthe 20auto-upgrades file
sudo tee /etc/apt/apt.conf.d/20auto-upgrades >/dev/null <<'EOF'APT::Periodic::Update-Package-Lists "1";APT::Periodic::Unattended-Upgrade "1";EOF

The allowed pockets are listed in the Allowed-Origins section of 50unattended-upgrades: by default these are -security and the ESM (Expanded Security Maintenance) pockets if a subscription is attached. The -updates line is commented out; uncomment it if you want regular updates installed automatically as well as security fixes. The Package-Blacklist list excludes packages by regular expression: the pattern linux- blocks updates to every package whose name starts with linux-. Note that a blocked package can prevent the packages that depend on it from updating.

Keep your changes to the defaults in a separate file, /etc/apt/apt.conf.d/52unattended-upgrades-local. The Debian documentation suggests copying 50unattended-upgrades and editing the copy rather than the original. The reboot settings from the next subsection go into the same file.

Reboots and service restarts

The kernel and some libraries take full effect only after a reboot: such an update marks the system with the file /var/run/reboot-required. unattended-upgrades can reboot the server itself: Automatic-Reboot set to true allows a reboot without confirmation, and Automatic-Reboot-Time sets when it happens, for example during the night. Without automatic reboots, check the file yourself and reboot the server in your maintenance window.

SettingWhat it doesDefault
Unattended-Upgrade::Automatic-Rebootreboots the server without confirmation if an update requests a rebootfalse
Automatic-Reboot-WithUsersreboots even when users are logged intrue
Automatic-Reboot-Timewhen to reboot: now or HH:MM in server timenow
bashreboot at night
sudo tee /etc/apt/apt.conf.d/52unattended-upgrades-local >/dev/null <<'EOF'Unattended-Upgrade::Automatic-Reboot "true";Unattended-Upgrade::Automatic-Reboot-Time "02:00";EOF

An updated library takes effect in a service only after it restarts; until then the process keeps the old version in memory. needrestart finds such processes, and unattended-upgrades calls it after every run. The $nrconf{restart} setting controls the behaviour: a restarts services automatically (the default since Ubuntu 24.04 LTS), and l only lists them and leaves the restart to you. Cases that are never restarted automatically, such as the login manager, are listed in /etc/needrestart/needrestart.conf.

bashkeeping the postgresql service out of automatic restarts
sudo tee /etc/needrestart/conf.d/60-postgresql.conf <<'EOF'$nrconf{override_rc} = {    qr(^postgresql\.service$) => 0,};EOF

Ubuntu Pro, ESM and Livepatch

Free standard support for Ubuntu LTS covers the Main repository; Universe packages are updated by the community and Debian. An Ubuntu Pro subscription extends this to ESM: fixes for the whole archive for 10 years. The ESM pockets are already listed in Allowed-Origins, so automatic updates pick up an attached subscription on their own. Ubuntu Pro also includes Livepatch, which applies kernel vulnerability fixes to a running system without a reboot.

TierCoverageDuration
Standard supportMain; Universe is covered by the community and Debian5 years
Ubuntu Pro (ESM)the whole archive, Main and Universe; free for personal use on up to 5 machines10 years
Legacy add-onthe same packages for another 5 years15 years in total

For the support periods of specific Ubuntu and Debian releases, see the section “Versions and what’s new”.

Checking whether a vulnerability is fixed

For every CVE, Ubuntu has a page with the status for each supported release: whether the package is vulnerable and in which version the fix shipped (the status Fixed comes with a package version). The fix reaches the archive together with a USN. For automated checks, OVAL data is available: a machine-readable set for each release. To apply the fix for a specific CVE, run sudo pro fix; updating individual packages selectively is not recommended, so keep the whole system up to date.

bashfixing a single vulnerability
sudo pro fix CVE-2026-109518

On Debian, serious vulnerabilities get a DSA on the debian-security-announce mailing list; the Debian Security Tracker follows the status of every CVE by package and release, including vulnerabilities that did not get a DSA. After a DSA, it is enough to update all packages: sudo apt update && sudo apt upgrade. To see which processes are still using old libraries after an update, run checkrestart from the debian-goodies package.

If apt upgrade holds back some packages (kept back), these are phased updates: apt releases a regular update to a small share of machines first and gradually widens it until everyone has it. Security updates are never phased. apt policy libc6 shows a package’s phasing share: next to the priority you will see a value such as (phased 20%).

Section sources

the section is written from these pages

Firewall

A firewall is a packet filter at the server’s entrance: incoming traffic is denied by default, and you allow only the ports you need. On Ubuntu you turn it on with ufw enable after allowing SSH; on Debian you use nftables rules in nftables.service.

Filtering is done by the kernel’s netfilter subsystem; ufw and nftables are just interfaces to it. Allow SSH before enabling the firewall, or you risk locking yourself out. The order of commands below takes this into account.

Rules are checked from top to bottom; the first match decides the packet’s fate.

Policy and order of enabling

A “deny everything except what is needed” policy (default deny) means incoming traffic is dropped by default and you open ports one at a time, as needed. This also closes the port you forgot about: a service from the section “Minimal services and open ports” stays invisible. Outgoing connections are not restricted, because the server itself goes online for updates and packages.

Enable things in this order: first the SSH rule, then the firewall:

  1. Allow SSH: sudo ufw allow OpenSSH.
  2. Set the policy: sudo ufw default deny incoming.
  3. Enable the firewall: sudo ufw enable.
  4. Check: sudo ufw status verbose.
bashon the server
sudo ufw allow OpenSSHsudo ufw default deny incomingsudo ufw enablesudo ufw status verbose

ufw is installed on Ubuntu by default but disabled. ufw allow OpenSSH and ufw allow 22/tcp mean the same thing; use the second when the daemon listens on a non-standard port, as described in the section “SSH”. The firewall lets return traffic of already open connections (established, related) through based on connection state, so it needs no separate rule. When you enable it over SSH, ufw warns that the connection may be interrupted: a rule added before ufw enable keeps your access, and a second session in case of a mistake does no harm.

Rate limiting for SSH

The limit rule allows connections but cuts off brute-force attempts: if one address makes six or more connections within 30 seconds, further connections are rejected until the address leaves the window. For a port facing the internet, use this instead of a plain allow:

bashon the server
sudo ufw limit ssh/tcp

This does not replace the keys and disabled passwords from the section “SSH”; it only reduces noise, so mass brute-force attempts no longer reach the daemon.

Nftables: how the rules are structured

On Debian the standard approach is nftables: rules are defined as tables in /etc/nftables.conf, and nftables.service loads them at startup. A table belongs to an address family; inet covers both IPv4 and IPv6 in one chain. A chain is a sequence of rules; a base chain is attached to a kernel hook, for example hook input, and sees incoming packets. Each rule matches a packet against conditions and gives a verdict: accept, drop or reject.

bash/etc/nftables.conf
#!/usr/sbin/nft -fflush ruleset table inet filter {    chain input {        type filter hook input priority filter;        policy drop;         iifname lo accept        ct state established,related accept        ct state invalid drop        tcp dport 22 ct state new limit rate 15/minute accept        tcp dport { 80, 443 } accept        icmp type echo-request limit rate 4/second accept        icmpv6 type { nd-neighbor-solicit, nd-router-advert, nd-neighbor-advert } accept        icmpv6 type echo-request limit rate 4/second accept    }}

policy drop decides the fate of packets that no rule matched; the rules above it allow only what is needed. priority filter is the standard processing point for incoming traffic. Keep the ICMP rules: without echo requests you lose diagnostic tools, and without neighbor discovery IPv6 itself does not work. The rules for nd-neighbor-solicit, nd-router-advert and nd-neighbor-advert in the example are there for exactly this reason.

Check the file, then enable the service:

bashon the server
sudo nft -c -f /etc/nftables.confsudo systemctl enable --now nftables.servicesudo nft list ruleset

nft list ruleset shows everything the kernel is applying right now. You can see the load on a chain in the counters: add counter to a rule to track how many packets matched it.

Docker bypasses the rules

IPv6

Rules in an inet table apply to both IPv4 and IPv6, so the minimal set above closes both stacks; the neighbor discovery rule is kept, because otherwise IPv6 will not work. ufw handles both as well: IPv6 is enabled by default in /etc/default/ufw. Check both addresses of the server: a closed IPv4 address protects nothing if IPv6 is open.

Checking from outside

A local ufw status shows what is configured, not what actually arrives over the network. Do the final check from another host: a scanner shows the open ports as an outside observer sees them.

bashfrom another machine
nc -zv -w 2 203.0.113.10 22 2>&1nmap -Pn -p 22,80,443 203.0.113.10

Expected result: only the allowed ports respond. A closed port stays silent because the packet is dropped without a reply, so in the nc output such a connection hangs until it times out. The remaining checks are in the section “Checklist”.

Section sources

the section is written from these pages

Minimal services and open ports

An open port is a port that a service is bound to and that accepts incoming connections. Every running service and every open port adds to the attack surface. The method has three steps: find out what is listening on the network, disable what you do not need, and bind the rest to 127.0.0.1 and remove versions from banners.

Inventory: what is listening on the network

Ubuntu and Debian install with almost no network services: since Ubuntu 6.06 LTS the policy has been “no open ports”, and network-listening daemons such as SSH end up on the server mostly when you pick a role during installation. First, see what is listening right now:

bashon the server
sudo ss -tulpn | grep -vE '127\.[0-9]+|\[::1\]'

ss -tulpn shows listening sockets: TCP and UDP (-t, -u), listening only (-l), with port numbers (-n) and process names (-p). Without sudo, the output hides process names. The grep -vE filter removes the addresses 127.0.0.1 and ::1: they are reachable only by processes on the server itself, so services on them are not part of the external surface.

This is what the output looks like on a server with three services: Apache listens on port 80 on all addresses (*:80), SSH on port 22 on its own address, and PostgreSQL is bound to 127.0.0.1 and therefore filtered out:

textexample output
Netid State  Recv-Q Send-Q Local Address:Port  Processudp   UNCONN 0      0      192.168.122.37:68  systemd-networktcp   LISTEN 0      4096   192.168.122.37:22  sshdtcp   LISTEN 0      511    *:80               apache2

The asterisk in *:80 means all addresses of the host, both IPv4 and IPv6. A service that should answer only on its own addresses does not need such a binding. Next, the list of running units:

bashon the server
systemctl list-units --type=service --state=runningsystemctl list-sockets

list-units with the filter --type=service --state=running shows the units systemd keeps in memory, that is, the running services. list-sockets shows listening sockets together with the .socket units that activate them: a service may not appear among the running ones, yet its socket unit still holds the port.

Disabling unneeded services

A service you are not going to remove should be disabled: the unit stays on disk but does not start, either at boot or by hand.

bashon the server
sudo systemctl disable --now nginx.servicesudo systemctl mask nginx.service

disable --now removes the unit’s autostart and stops it in one step; separate stop and disable commands give the same result in two steps. mask is a stronger block: it symlinks the unit to /dev/null, after which the service cannot start in any way, whether at boot, by hand or as a dependency of another service. Use it for something you do not need at all but have not removed: the package may be needed later, or the service is installed as a dependency and apt will not let you remove it. systemctl unmask reverses it.

A disabled service can still start at boot if another enabled unit pulls it in, that is, if the unit you disabled is listed in Wants= or Requires= of another enabled unit. Check what keeps the unit in its dependencies and, if necessary, disable that one too:

bashon the server
systemctl list-dependencies --reverse nginx.service

Before disabling anything, read the unit description: something that looks unnecessary may be doing work for a service. Disabling systemd-networkd or systemd-resolved on a server breaks networking and name resolution.

Removing unneeded packages

Every package is a potential part of the attack surface, which is why hardening guides recommend a minimal set of installed packages. Packages are either manually installed (part of the default installation or installed by hand) or automatically installed, that is, dependencies. apt autoremove removes orphaned automatic packages that nothing depends on any more; it also cleans old kernels off the system, which helps with updates:

bashon the server
sudo apt autoremove --purgesudo apt purge '?config-files'

Remove unneeded manually installed packages with a plain apt remove: apt marks the dependencies that become free as automatic and lists them in the next autoremove. Do not remove Essential packages or packages with the priority required: without them the system and the package database itself break.

Metapackages such as ubuntu-server keep long lists of dependencies behind them marked as manual. If you do not need the whole set, hand its dependencies over to apt and remove them in one go:

bashon the server
sudo apt-mark minimize-manualsudo apt autoremove

Read the list before confirming: metapackages cover things you need, and a server where the system’s standard packages are treated as surplus is another story. As a guide, start from a minimal installation that suits the task and add the packages you need; Ubuntu does not recommend mass removal of the default installation without good reason.

Binding services to 127.0.0.1

A service that nothing reaches over the network does not belong on an external interface. The address 0.0.0.0 means all IPv4 addresses of the host, [::] means all IPv6 addresses, and 127.0.0.1 means loopback only: the port is available to processes on the same server and unreachable from outside. This keeps a database and a cache behind the firewall from the section “Firewall”, even if a rule is lost there.

inipostgresql.conf and nginx.conf
listen_addresses = 'localhost' # nginx.confserver {    listen 127.0.0.1:8080;    ...}

In PostgreSQL listen_addresses = 'localhost' is the default: the server listens on loopback. Nginx listens on all addresses by default; listen 127.0.0.1:8080 closes the port to the network. MariaDB on Debian and Ubuntu is bound to 127.0.0.1 out of the box.

How to decide for each listening port:

  • The service is needed over the network: keep it bound to its own address and restrict access with the firewall.
  • The service is needed only on this server: bind it to 127.0.0.1.
  • The service is not needed: remove the package or disable the unit.

Service version banners

A version banner is a string in which a service reports its version: in protocol responses, in the HTTP Server header, on error pages. Any scanner can probe versions, and a daemon that already listens on the network is better off not revealing this string.

Disabling a banner takes a single setting. The version is removed completely by the ServerTokens Prod and ServerSignature Off directives in Apache and by server_tokens off; in Nginx:

bashon the server
echo "server_tokens off;" | sudo tee /etc/nginx/conf.d/no-banner.confsudo systemctl reload nginx.service

In OpenSSH, DebianBanner no in a drop-in config removes the distribution version from the banner; the service always reports the base OpenSSH protocol version:

bashon the server
echo "DebianBanner no" | sudo tee /etc/ssh/sshd_config.d/no-banner.confsudo systemctl reload ssh.service

Ubuntu does not move packages to new upstream versions within a release; it backports fixes instead, so the banner keeps the version to which the patches were applied. Two caveats follow. First, a hidden banner is security through obscurity: the vulnerability exists without it, and a patched daemon matters more than a quiet one. Second, vulnerability scanners rely on the same banners and give false positives without them. The compensation is to keep packages up to date: see the section “Security updates”.

Isolating the remaining services

For services that stay listening on the network, the next layer is unit isolation with systemd options: NoNewPrivileges=, ProtectSystem=strict, PrivateTmp= and related ones. A single sentence is enough here; they are covered in full in the systemd reference, section “Service sandboxing”.

Let ss itself confirm the result: after your changes, only the ports you decided to open should be visible from outside. Check from another machine too, as described in the section “Firewall”. The inventory is not a one-off: it is worth looking at again after installing packages.

Section sources

the section is written from these pages

AppArmor and SELinux

AppArmor is mandatory access control (MAC) on top of ordinary permissions: the kernel allows a process only what is written in its program’s profile, even with root rights. AppArmor is enabled by default on Ubuntu and Debian; if a program stops working, look for a DENIED entry in the log and fix the profile.

Ordinary permissions (DAC, discretionary access control) decide by file owner: whoever has write access can write to all of that owner’s files. A profile, by contrast, is tied to the program and is the same for every user who runs it. The kernel checks each request against the profile: file path, network port, capability, signal, library loading. Ordinary permissions still apply; the profile only narrows them.

Look for denials in the kernel log by the word DENIED.

A confined process opens a file only when both the ordinary permissions and the profile allow access. A violation is logged in enforce mode (an apparmor="DENIED" entry) and in complain mode (an apparmor="ALLOWED" entry, and the operation still goes through), so the log shows exactly which rule is getting in the way.

Profile status and modes

On Ubuntu, AppArmor is installed and loaded by default; on Debian, install the packages apparmor, apparmor-profiles and apparmor-utils. Profiles are text files in /etc/apparmor.d/, named after the program’s path with / replaced by a dot: for /usr/sbin/nginx it is usr.sbin.nginx. aa-status shows the state of profiles and processes.

bashchecking MAC
sudo aa-status
textexample output
apparmor module is loaded.42 profiles are loaded.26 profiles are in enforce mode.   /usr/bin/man...16 profiles are in complain mode.   /usr/sbin/dnsmasq

A profile has two working modes. enforce denies everything that is not in the profile; complain allows it but writes the denial to the log. Extra profiles from the apparmor-profiles package ship in complain mode: you test them against your own set of services and then switch them to enforce.

ModeWhat it doesWhen to use it
enforcedenies operations outside the profile and logs the denialsfor a profile that has been tested
complainallows operations and logs themtraining a new profile, finding missing rules
disablethe profile is unloaded, with no restrictionswhen the service does not work at all without it
bashswitching a profile’s mode
# temporarily unrestricted, denials are loggedsudo aa-complain /usr/sbin/nginx# back to normal modesudo aa-enforce /usr/sbin/nginx

Access denied: DENIED in the log

When a profile does not allow an attempt, the kernel writes it to the dmesg log and other system message collectors; search for the word DENIED. The exception is an explicit deny rule in the profile, which rejects the request silently.

bashsearching for denials
sudo dmesg | grep 'apparmor="DENIED"'
textexample output
audit: type=1400 apparmor="DENIED" operation="open"  profile="/usr/sbin/cups-browsed" name="/var/lib/libvirt/dnsmasq/"  pid=1128 comm="cups-browsed" requested_mask="r" denied_mask="r"

Reading the line: operation is what the program tried to do (open means open a file); profile is the profile that matched, and the profile file name is obtained by replacing / with dots; name is the path the request was for; requested_mask and denied_mask are the permissions that were requested and denied. Then you edit the file of that particular profile.

Editing a profile instead of disabling it

It is better not to edit a profile head-on. Files in /etc/apparmor.d/local/ are the place for your own rules, and package updates do not touch them; not every profile has one. Typical sets of paths are configured through variables in /etc/apparmor.d/tunables/. Editing the profile file itself always works, but profiles are conffiles: a package update may ask about a conflict or restore the old content.

bashon the host
# your own rule goes in the profile’s local fileecho '  /srv/backup/ r,' \  | sudo tee -a /etc/apparmor.d/local/usr.sbin.cupsdsudo apparmor_parser -r /etc/apparmor.d/usr.sbin.cupsd
bashon the host
# reload all profiles at oncesudo systemctl reload apparmor

Your own profile: aa-genprof

Start by finding which programs have no profile. aa-unconfined lists programs with open network ports that have no profile. These are the ones to profile: programs facing the network are the main target of a remote attacker.

aa-genprof creates an empty profile, switches it to complain and waits while you work with the program in another window. On the scan command (S) it turns log entries into rules and offers a choice for each event: allow, deny or include a ready-made abstraction. After F, the profile is switched to enforce.

bashon the host
# programs with open ports and no profilesudo aa-unconfined# run the program, then scan the logsudo aa-genprof /usr/sbin/myapp

The profile will be complete only if you run the program through all its working scenarios: started manually, via systemd, on a timer. A missed scenario shows up as a DENIED entry; add it with aa-logprof, which reads the accumulated denials and suggests changes.

SELinux: the same idea, different rules

SELinux (Security-Enhanced Linux) is a MAC system on the same LSM interface, known from Fedora and RHEL, where it is enabled by default. SELinux rules are not tied to a program’s path: every process is assigned a context (user, role, domain), every file is assigned a type, and the policy describes which operations a domain may perform on which types. An executable carries its own type label, and when it starts, the process automatically transitions into the domain for that label.

On Debian, SELinux is installed separately: the packages selinux-basics, selinux-policy-default and auditd, then the selinux-activate script and a reboot. The default policy confines a small number of widely exposed services and does not confine user sessions.

FeatureAppArmorSELinux
What rules are tied tothe path of the executablethe process context and the file type
Modesenforce, complain, disableenforcing, permissive, disabled
Configurationediting a text profilepolicy modules, semanage, booleans
Default onUbuntu, DebianFedora and RHEL; installed separately on Debian
bashon the host
# the context of your own sessionid -Z# the context of a filels -Z /etc/ssh/sshd_config# enable a boolean permanentlysudo setsebool -P httpd_enable_homedirs on

AppArmor and SELinux denials end up in the common kernel log; for how to collect and filter them, see the section “Auditing and monitoring”. The sandboxing options of an individual systemd unit are described in the systemd reference, section “Service sandboxing”.

Section sources

the section is written from these pages

Auditing and monitoring

Auditing answers the question of what is happening on a server: who logged in, which files changed, and whether the settings match the rules. The sshd log, auditd event auditing, file integrity checks and periodic CIS compliance checks together leave a noticeable trail of almost anything an attacker does.

Who logged in

The first trace of a login is the sshd service log. It records every connection: whether it was accepted, by which method, from which address and as which user. It is worth reading the successful logins once a day: an unfamiliar address or user name is a reason to investigate.

bashon the server
sudo journalctl -u ssh -S today --no-pager | grep -e Accepted -e Failed
bashif rsyslog keeps the log
sudo grep -h -e 'Accepted' -e 'Failed' /var/log/auth.log | tail

The list of recent logins is kept in the wtmp and btmp files: last reads the successful ones and sudo lastb the failed login attempts. For more on logs and how long to keep them, see the Linux reference, section “Logs”; it also covers copying them to another host.

Event auditing: auditd

The kernel audit subsystem records events that service logs do not contain: who changed a file, when and with what, and what was run as root. The user-space part is the auditd daemon; rules are set with auditctl, the log is searched with ausearch and summarised with aureport (all three come from the auditd package).

bashon the server
sudo apt install auditdsudo systemctl enable --now auditdsudo auditctl -s | head -3

A watch rule is attached to a path: -w names the file to watch and -p wa the operations to react to: w for writes, a for attribute changes, r for reads and x for execution. The -k option tags events with a key that you can search for later:

bashon the server
sudo auditctl -w /etc/passwd -p wa -k identitysudo auditctl -lsudo ausearch -k identity -i | tail
CommandWhat it does
auditctl -w path -p wa -k namewatch a file or directory for writes and attribute changes
auditctl -llist the active rules
auditctl -Ddelete all rules
ausearch -k name -ievents for a rule, with values shown as names
aureport --authsummary of authentication attempts

For rules to survive a reboot, put them in files in /etc/audit/rules.d/: one set per file, one rule per line. At boot, /etc/audit/audit.rules is assembled from them. Rules are processed in order: exclusions first, then watches:

bashon the server
sudo tee /etc/audit/rules.d/40-identity.conf >/dev/null <<'EOF'-w /etc/passwd -p wa -k identity-w /etc/shadow -p wa -k identity-w /etc/sudoers -p wa -k identityEOFsudo augenrules --load

File integrity

Changes to system files are also shown by dpkg --verify: it compares the checksums of package files with the dpkg database. The lines it prints show which files were edited after installation. Edited configuration files are normal; a replaced binary is not.

bashon the server
sudo dpkg --verify

The dpkg database lives on the same disk as the files it checks, so a skilled attacker will update it too. AIDE (Advanced Intrusion Detection Environment) keeps a reference snapshot of the files separately, with permissions, sizes and checksums. aideinit creates the snapshot; the daily check runs from cron.daily and writes its result to /var/log/aide.

bashon the server, once at installation
sudo apt install aidesudo aideinitsudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.dbsudo aide --check | tail -20

After planned updates, refresh the snapshot, otherwise every check will keep repeating the old differences. The outdated debsums checks files against copies from the packages, but it is too slow for regular checks. Tripwire and Samhain offer more: Tripwire has a signed configuration, and Samhain can detect rootkits.

CIS compliance

A CIS Benchmark is a set of configuration recommendations: password length, sudo policy, file permissions. On Ubuntu they are checked by the Ubuntu Security Guide (USG): usg audit scores the system against a profile and writes HTML and XML reports to /var/lib/usg/. USG is installed through Ubuntu Pro, which is free for personal machines.

bashon the server
sudo pro enable usgsudo apt install usgsudo usg audit cis_level1_server
ProfileWhat it checks
cis_level1_serverlevel 1: baseline server protection
cis_level2_serverlevel 2: everything in level 1 plus more
cis_level1_workstationlevel 1 for workstations

The report has hundreds of items and not all of them suit your environment. You can edit the profile, disabling rules that do not apply and changing values; otherwise chasing a compliance percentage turns into a source of noise. For what exactly to configure at each level, see the USG documentation.

If you suspect a break-in

A break-in is often visible from side effects: a process named like a service but not from a package, a full /tmp, a login from an unfamiliar address. /proc helps you check a suspicious process: the exe link shows which file is actually running.

bashon the server
ls -al /proc/3719/exe

The steps then go as follows:

  1. Capture the minimum state of the live system: open connections (netstat -tupan), the process list (ps auxf) and the contents of /proc/[0-9]*. Record each command together with its output.
  2. Prepare a copy of the disk: remount the partitions read-only, or shut the server down and boot it from a rescue disk. Take partition images with dd and send them to another host.
  3. Pull the daily AIDE snapshot: it shows what has changed over the last few days.
  4. Restore the service: install a clean system from installation media and restore only the data. Backups made after the break-in are no good, because whatever the attacker left behind would come back with them.
  5. Install the updates that close the way in, then examine the disk copies: command history in .bash_history, recent files, strings in executables (strings) and the logs in /var/log.

The logs of a local server can be trusted only until an attacker gets root: after that they can edit or delete them. That is why the audit log and service logs are sent to a separate server that the compromised host can write to but cannot delete anything from. Forwarding is set up in rsyslog or journald; the Linux reference, section “Logs”, explains how.

Section sources

the section is written from these pages

Kernel and sysctl

The Ubuntu kernel enables the main exploit protections by default: address space layout randomisation (ASLR), ptrace restrictions, and hidden kernel addresses and dmesg log. They are controlled by sysctl parameters; persistent values go in /etc/sysctl.d/*.conf files.

What is enabled by default

Every program start gets random addresses for the stack, libraries and heap: this is ASLR (Address Space Layout Randomization). The kernel does the same for itself on every boot: this is kASLR. An exploit built for fixed addresses first has to find them.

The ptrace system call, which lets one process inspect the memory and state of another, is restricted in Ubuntu by the Yama module: a process can trace only its own descendants unless the superuser allows otherwise. Kernel addresses in /proc/kallsyms and similar places are shown as zeros, because kernel.kptr_restrict is 1. The dmesg log is available only to processes with the CAP_SYSLOG capability: kernel.dmesg_restrict has been 1 since Ubuntu 20.10. Only root can read /boot/vmlinuz*, /boot/System.map*, /sys/kernel/debug/ and /proc/slabinfo.

bashcurrent values on the server
sysctl kernel.kptr_restrict kernel.dmesg_restrictsysctl kernel.randomize_va_space kernel.yama.ptrace_scopesysctl net.ipv4.tcp_syncookies

How to set parameters

sysctl parameters are kernel settings exposed through /proc/sys; the sysctl utility reads and changes them. Keep persistent values in /etc/sysctl.d/*.conf files: systemd applies them at boot, and the network ones again whenever a new interface appears.

bashfile 70-hardening.conf
sudo tee /etc/sysctl.d/70-hardening.conf >/dev/null <<'EOF'# do not accept ICMP redirects from neighboursnet.ipv4.conf.*.accept_redirects = 0net.ipv6.conf.*.accept_redirects = 0EOFsudo sysctl --system

sysctl --system reads the directories in priority order (/etc, /run, /usr/local/lib, /usr/lib) and applies the settings. A file in /etc overrides a file of the same name in the other directories; for different names, the one later in alphabetical order wins; finally, /etc/sysctl.conf is read as well. You can also change a single parameter on the fly with sudo sysctl -w kernel.kptr_restrict=2, but after a reboot the value from the files comes back.

Network parameters

SYN cookies protect against SYN floods: the kernel answers a SYN without storing half-open connections and builds the connection entry only on the final ACK. The net.ipv4.tcp_syncookies parameter also applies to IPv6; the value 1 enables cookies only when a flood is suspected, and it has been the default since Ubuntu 9.04.

ICMP redirects tell a host about a shorter route; a neighbour on the network can abuse them to divert traffic to its own host, so accepting them is disabled. The file in the example above does this for IPv4 and IPv6. Reverse path filtering (rp_filter) drops packets that arrive on an unexpected interface; the default is 2, loose mode, which is compatible with asymmetric routing. Setting it to 0 makes sense if other filtering is in place, for example in nftables.

Parameters of the form net.ipv4.conf.* are templates for all interfaces: systemd applies them to interfaces that appear later as well. For a single interface, put its name in place of the asterisk: net.ipv4.conf.eth0.accept_redirects.

Dangerous values

Some parameters are dangerous to change: a careless value breaks things or opens a new hole. Check what a parameter does before changing it.

ParameterDangerous valueWhat it breaks
kernel.core_pattern|/bin/falsecore dumps disappear; the handler receives process memory, so set only apport or systemd-coredump
fs.suid_dumpable1dumps of setuid programs are readable by an ordinary user, leaking privileged memory
kernel.kptr_restrict0kernel addresses are visible to everyone, which weakens kASLR
kernel.dmesg_restrict0every user can read the kernel log, which is material for an exploit
kernel.yama.ptrace_scope0ptrace is available without Yama restrictions, so another process can read your process’s memory
net.ipv4.conf.*.accept_redirects1ICMP redirects are accepted, so a neighbour on the network can divert traffic to its own host
net.ipv4.conf.*.rp_filter0packets with a spoofed source address pass in from any interface, which allows spoofing
net.ipv4.tcp_timestamps0outdated advice: the TCP timestamp offset is now random, so there is no need to change it

Updating without a reboot

Kernel fixes can be applied to a running system without a reboot: this is done by Livepatch, part of the Ubuntu Pro subscription (free for up to 5 machines). It, and the /var/run/reboot-required file, are covered in the section “Security updates”.

Section sources

the section is written from these pages

Common mistakes in approach

A server is weakened more often by the administrator’s habits than by attackers: AppArmor switched off for convenience, a port open to the whole network, a package from someone else’s repository. Below, one habit at a time: what it leads to, what to do instead, and a worked example.

Switching off AppArmor because it gets in the way

A profile forbids an action that the program needs to perform, and the first impulse is to remove the restrictions altogether. That removes protection for every other program and snap package: one unvetted process gets back the access that had been taken away from it. Ubuntu explicitly advises against disabling AppArmor entirely.

The right way is to work with a single profile: report the problem, find the denial in the log and add the missing rule. As a last resort, and again following that page, disable only the problem profile, knowing exactly what this removes.

bashfind the denial and relax one profile
sudo journalctl -k | grep DENIEDsudo aa-complain /usr/sbin/nginx

Opening a port to everyone instead of one address

A service is needed by one address or one network, but the rule allows everyone: 0.0.0.0 listens on all interfaces and the firewall admits any source. An open port adds attack surface: the service may contain a vulnerability, and its reply gives away the software version used to pick an exploit.

The right way is to listen on the address you need and allow the source you need. For services used only inside the host, the address 127.0.0.1 is enough; access from the network is limited by a firewall rule with a source address.

bashwhat is listening on the network
sudo ss -utlnp | grep -vE '127(\.[0-9]+){3}|\[::1\]'
Service reachable byBadGood
everyone on the internetthe service listens on 0.0.0.0 and the firewall is openbound to the address you need, with the source address in the firewall
one networkufw allow 5432/tcpufw allow from 203.0.113.0/24 to any port 5432 proto tcp
the host itself onlythe service listens on 0.0.0.0:5432the service listens on 127.0.0.1:5432
bashport 5432 for one network only
# first allow your own network (rules are checked in order)sudo ufw allow proto tcp from 203.0.113.0/24 to any port 5432# ...then close the port to everyone elsesudo ufw deny proto tcp from any to any port 5432

Downloading a package from a random site

A link to a .deb in a forum or blog looks quicker than waiting for the package to reach the repository. Installation runs as root and lets the package execute arbitrary code: a tampered file means a captured system. The second risk is a dependency built for another release, which can leave the system broken.

The right way is to take packages from the official archive: they are built and tested for compatibility with each other. If the program is not in the repository, add the publisher’s repository by following its instructions. Do not disable signature checking: it is what distinguishes a repository from a folder of files.

basha package from the official archive
sudo apt install nginx

Leaving password login on “for now”

A server is put into service with password login so as to “get it running first and tighten it later”, and the hardening gets postponed for months. Password guessing remains the only line of defence: one weak or reused administrator password ends the story.

The right way is to enable key-based login before the first password change, then turn password login off completely in a file in /etc/ssh/sshd_config.d/ and reload the service. It takes minutes, not a week-long project.

bashon the server
sudo tee /etc/ssh/sshd_config.d/20-hardening.conf >/dev/null <<'EOF'PasswordAuthentication noPermitRootLogin noEOFsudo sshd -t && sudo systemctl reload ssh.service

By default PasswordAuthentication is allowed, and root has prohibit-password, which lets root in with a key. An explicit no for both closes off both password guessing and direct root login. sshd -t checks the configuration before the service is reloaded; the current session is not dropped, so check from a second window that your key works.

Giving everyone passwordless sudo

The line %sudo ALL=(ALL) NOPASSWD: ALL removes the last question from every administrator. A stolen session, or a malicious process inside such a session, gets root without a single obstacle: the password that could have stopped the attempt is never asked for.

The right way is to keep sudo with a password for people and grant NOPASSWD to automation selectively: specific commands with full paths, for dedicated accounts, with no shell.

propertiesfile /etc/sudoers.d/01-backup
# automation: two commands, no shellbackup ALL=(root) NOPASSWD: /usr/bin/rsync, /usr/local/sbin/backup # people: full root, but with a passwordaisha ALL=(ALL:ALL) ALL

Files in /etc/sudoers.d/ are read in lexical order, so number them with a leading zero and edit them with visudo -f, which will not save a file with a syntax error that would lock you out of sudo. A rule without arguments allows the command with any arguments, including rsync --rsh, so narrow it down where you can.

Not rebooting after a kernel update

Automatic updates install a new kernel and libraries, but running processes keep executing the old versions from memory: the package is updated, yet the vulnerability is still in memory. The /var/run/reboot-required file reminds you about a reboot; needrestart lists the services that still use old libraries.

The right way is to reboot in your own maintenance window or leave it to unattended-upgrades: Automatic-Reboot reboots the server itself and Automatic-Reboot-Time sets the time. Both are configured in the section “Security updates”.

bashwhether a reboot is needed and who holds the old libraries
cat /var/run/reboot-required 2>/dev/null || echo reboot not requiredsudo needrestart -b | grep NEEDRESTART-SVC

Changing sysctl on advice from the internet

A “for performance” recipe suggests disabling rp_filter or setting tcp_syncookies to 2, and the line goes into /etc/sysctl.conf unchecked. These parameters change kernel protection: handling of ICMP redirects, access to kernel addresses, debugging features. The rollback is then hunted down in the logs.

The right way is to check every parameter against the list of protection-relevant values, which Ubuntu collects on its “Dangerous sysctls” page, and to keep settings in /etc/sysctl.d/ files with a comment saying why. The table below follows the values on that page.

basha verifiable change with a comment
# hide kernel addresses from all usersecho 'kernel.kptr_restrict = 2' | sudo tee /etc/sysctl.d/70-hardening.confsudo sysctl -p /etc/sysctl.d/70-hardening.conf
ParameterUbuntu recommendsWhat deviating breaks
kernel.kptr_restrict1 or 2leaked kernel addresses weaken ASLR
kernel.dmesg_restrict1any user can read the kernel log
net.ipv4.conf.*.rp_filter2; 0 only deliberatelypackets with a spoofed address get through
net.ipv4.tcp_syncookies1the server has no protection against SYN floods

The defaults and the full set of kernel parameters are covered in the section “Kernel and sysctl”.

Installing everything that works

Every package increases the attack surface: more files to check, more services that may listen on the network, more updates. Removing parts of a standard installation, on the other hand, breaks functionality in unexpected ways: packages are tied together by dependencies, and a “useless” utility is needed by the system.

The right way is to start from a minimal installation that fits the task and install packages on top of it, removing only what you installed by hand and no longer need. Packages marked essential and packages with priority required must not be removed, since without them the package system itself may stop working. Review what apt autoremove is about to remove: a needed package can end up on the list.

bashpackages the system cannot work without
apt list '?essential'apt list '?priority(required) ?not(?essential)'

A port found in ss that nobody can explain belongs in the section “Minimal services and open ports”; the firewall rule for it belongs in the section “Firewall”.

Section sources

the section is written from these pages

Versions and what is new

Security updates arrive only for supported releases: Ubuntu LTS gets them for five years by default, and Debian stable for three years of full support plus two more in LTS. The examples in this reference use Ubuntu 26.04 LTS and Debian 13 (trixie); the latest point release is Debian 13.7 of 12 September 2026.

Ubuntu interim releases come out every six months and are supported for nine months; LTS releases come out every two years. After five years of standard support, updates continue in ESM (Expanded Security Maintenance) under an Ubuntu Pro subscription for another five years. Debian stable is supported by the security team for three years, then by a team of LTS volunteers: DSA advisories give way to DLA, and the list of architectures shrinks.

ReleaseStatusSecurity updates until
26.04 LTScurrent LTS, standard supportMay 2031, Pro: May 2036
24.04 LTSstandard supportMay 2029, Pro: May 2034
22.04 LTSstandard supportMay 2027, Pro: May 2032
20.04 LTSstandard support ended in May 2025Pro only: May 2030
26.10interim, nine monthsJuly 2027

A Pro subscription extends ESM to the whole archive, Main and Universe, and is free for personal use on up to five machines; to enable it, see the section “Security updates”.

ReleaseStatusSecurity updates until
13 (trixie)current stable, full supportuntil 9 August 2028, LTS until 30 June 2030
12 (bookworm)oldstable, full support ended on 11 July 2026LTS until 30 June 2028
11 (bullseye)oldoldstable, LTS ended on 31 August 2026no updates

Debian warns about its limits: there are no security updates for the qtwebengine engine, and Go and Rust packages are supported only to a limited extent. The security status of installed packages is shown by debian-security-support.

What has changed in security

The main points for server security from the release notes:

  • Ubuntu 26.04 LTS: Linux kernel 7.0; Kernel Livepatch now works on arm64 too.
  • Ubuntu 26.04 LTS: OpenSSH 10.2 dropped DSA support, enables the hybrid post-quantum key exchange mlkem768x25519-sha256 by default, and penalises addresses that do not complete login (PerSourcePenalties).
  • Ubuntu 26.04 LTS: systemd 259 does not support cgroup v1, so such an installation will not upgrade to 26.04; check the host’s mode in advance.
  • Debian 13: PAC and BTI are enabled on arm64, protecting against ROP and COP/JOP attacks; they work on their own if the processor supports them.
  • Debian 13: OpenSSH 10.0p1 does not support DSA keys even with explicit configuration; OpenSSL is updated to the 3.5 branch.
  • Debian 13: debian-repro-status checks that an installed package was built byte for byte the same as in the official archive.

How to upgrade to a new release

Ubuntu upgrades in two steps: first all updates for the current release, then do-release-upgrade. You cannot skip releases: to go from 22.04 LTS to 26.04 LTS, upgrade via 24.04 LTS. Before you start, make a backup, free up several gigabytes of space and set aside time: the process is interactive and ends with a reboot. PPAs and third-party repositories are disabled during the upgrade.

bashon the server
sudo apt updatesudo apt dist-upgrade \  -o APT::Get::Always-Include-Phased-Updates=truesudo do-release-upgrade

Debian upgrades only from the previous stable release: from Debian 12 to 13, and from older ones by first following their release notes. The version is shown by cat /etc/debian_version. The procedure: bring the system to the latest point release (12.15 for bookworm), back up /etc, /var/lib/dpkg and the output of dpkg --get-selections '*', check dpkg --audit, replace bookworm with trixie in the APT sources, and upgrade in two stages, minimal first and then full.

bashupgrading from Debian 12
sudo dpkg --auditsudo apt updatesudo apt upgrade --without-new-pkgssudo apt full-upgrade

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Linux server hardening” topic
12 sections
Another reference · DevOps & cloud

Ansible

Verified 6 Nov
All references · 61