LinuxPublished on August 29, 202634 min read

How to secure a Linux VPS

Linux VPS security takes more than installing UFW and Fail2ban. This hardening checklist covers Debian 12 and 13 and Ubuntu 22.04, 24.04 and 26.04 LTS, from SSH access to backups. Every sensitive change comes with a check and a safeguard against locking yourself out. Try these settings on a test server first.

Check that your system is still supported

Debian 13 "trixie" is the current stable release. It gets full support until 9 August 2028, then LTS until 30 June 2030 on fewer architectures. Full support for Debian 12 ended on 11 July 2026. Its LTS phase runs until 30 June 2028, limited to some architectures. The Debian 13 and Debian 12 pages list these dates.

Ubuntu 22.04, 24.04 and 26.04 are LTS releases. 26.04 came out in April 2026. Canonical publishes the maintenance dates in its Ubuntu release cycle.

SystemStatus in November 2026Recommended action
Debian 13current stable, full support until August 2028Debian choice for a new install
Debian 12LTS until June 2028, on some architecturesplan the upgrade to Debian 13
Ubuntu 26.04 LTSlatest LTS, standard support until May 2031Ubuntu choice, once your applications are validated
Ubuntu 24.04 LTSstandard support until May 2029good choice for a stack already validated
Ubuntu 22.04 LTSstandard support until May 2027plan the release upgrade
end-of-life releaseno more regular fixesmigrate, a firewall does not make up for an unmaintained system

Do not judge a system's security from uname -r alone. Debian and Ubuntu backport fixes without changing the upstream version number. To check a specific flaw, use the Debian Security Tracker or Ubuntu CVE reports, with your release and the installed package.


Define what you are protecting

A public VPS gets automated scans and login attempts all the time. This baseline also targets these risks.

  • Exploitation of an unpatched service or dependency.

  • Theft of an SSH key, an API token or an application secret.

  • A mistake in the firewall, in permissions or in a Docker port mapping.

  • Privilege escalation after an application has been taken over.

  • Deletion or encryption of data and of the backups the server can reach.

  • Log deletion by an attacker who became an administrator.

  • Human error during an update or a network change.

This baseline does not make the VPS bulletproof. It lowers the odds of an intrusion and limits the damage of a first foothold. It improves detection and makes a controlled rebuild possible. It does not make the server compliant with CIS or any other framework either. Compliance needs a scope, evidence, documented exceptions and an audit.

Pick the level that matches your use.

LevelMinimum measuresUse
Baselineinventory, updates, named account, SSH key, root and SSH passwords disabled, firewall, backup off the serverany VPS exposed to the internet
Productionmonitored updates, AppArmor, Fail2ban depending on risk, persistent logs shipped elsewhere, external alerts, tested restoresite or service in production
Hardenedadmin access through a VPN or bastion, FIDO2 key or MFA, reviewed outbound filtering, auditd and AIDE, append-only backup repository, declarative configurationsensitive data or strict requirements

Do not apply every measure blindly. Turning off IP forwarding, for example, breaks a router, a VPN or some container networks. Hardening always starts from the server's role.

Once you have worked through this guide, you will be able to answer these questions.

  • Which release is running, and how long is it supported?

  • Which services listen on IPv4 and IPv6?

  • Who can log in over SSH, with which method and from which network?

  • Which firewall rules are actually enforced?

  • Are security fixes installed, and are failures reported?

  • Do logs survive a reboot, and are they copied off the VPS?

  • When did you last restore a backup successfully?

  • What will you do if a key, an account or the whole server is compromised?

A security measure that is not checked, monitored or restorable is not a guarantee. It is an assumption.


Keep an emergency access route

A mistake in SSH or in the firewall can lock you out of the server. The console on the VPS page is then your way back in. It shows the VPS screen in your browser and works even when SSH no longer responds. Test it before you change anything.

  1. In My Services, open the VPS page. Click the Console button at the top right.

  2. The Open the remote console? window appears. Click Open the console.

  3. Log in with the user and password shown in the Password tab.

Open the remote console window with the Open the console button

After hardening, SSH will refuse root, but the console still accepts a local account with its password. So keep a working password for root or for your admin account. The guide How to manage your VPS from the client area covers the console and the Password tab.

Before each change to SSH or the firewall, also take these precautions.

  • Keep your current SSH session open.

  • Open another window to test each change.

  • Note the SSH address and port actually in use.

  • Copy the files you are about to edit.

  • If your VPS has the backup option, click Create a backup in the Backups tab.

  • Only remove the old access once the new one works.

A backup taken right before a change makes rollback easier. It does not replace a copy managed somewhere else. It may be inconsistent if a database is writing at that moment. It is also controlled from the same client account as the server.


Take an inventory of the system

Start with a read-only collection.

cat /etc/os-release
uname -a
hostnamectl
systemd-detect-virt

ip -brief address
ip route
ip -6 route

sudo ss -lntup
sudo systemctl --type=service --state=running --no-pager
sudo systemctl list-unit-files --state=enabled --no-pager

df -hT
df -ih
findmnt
timedatectl

ss -lntup lists listening sockets. To see established TCP connections, including outbound ones, run this command.

sudo ss -tpn state established

Record the results in a server runbook.

ItemWhat to record
distribution and releaseoutput of /etc/os-release
kernel and architectureoutput of uname -a
public IPv4 and IPv6addresses actually routed
main interfacename, address, gateway
expected portsfor example TCP 22, 80 and 443
expected servicesSSH, Nginx, application, monitoring agent
authorized administratorsnamed accounts, keys and source network
critical datafiles, databases, secrets and configuration
RPOmaximum acceptable data loss
RTOmaximum acceptable downtime

Investigate a port with no owner or purpose before closing it. A service can listen on 127.0.0.1 only, on a private address, on every IPv4 interface with 0.0.0.0 or on IPv6 with ::. Check both address families.


Create named admin accounts

Do not run day-to-day administration as root or from a shared account. Create one account per administrator. Logs and revocations then stay tied to one person. Here is an example with the adminops account.

sudo adduser adminops
sudo usermod -aG sudo adminops

sudo groupadd --force ssh-admins
sudo usermod -aG ssh-admins adminops

id adminops
getent group ssh-admins

On Debian and Ubuntu, members of the sudo group get admin rights under the local policy. The ssh-admins group will be used later to restrict SSH access.

On your own computer, generate an Ed25519 key protected by a passphrase, then copy it to the VPS.

ssh-keygen -t ed25519 -a 100 -C "adminops@organisation"
ssh-copy-id -i ~/.ssh/id_ed25519.pub adminops@203.0.113.10

The address 203.0.113.10 is an example. Replace it with the main IP shown on the VPS page. Ubuntu recommends the Ed25519 key type. The -a option raises the number of rounds that protect the private key with its passphrase. It does not change the algorithm. The guide Set up an SSH key on a Linux VPS walks you through it on Windows, macOS and Linux.

For a hardened setup, an ed25519-sk FIDO2 key requires a compatible hardware authenticator.

ssh-keygen -t ed25519-sk -C "adminops-fido2@organisation"

Keep a recovery method that is protected and tested. With a single hardware key and no fallback, losing it means losing access.

Test the login in a new window.

ssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519 adminops@203.0.113.10
sudo -v
id

Do not go further until key login and sudo both work.

Audit existing accounts

getent passwd
awk -F: '($3 == 0) {print $1}' /etc/passwd

# Debian 12, Ubuntu 22.04 and 24.04
sudo lastlog
# Debian 13 and Ubuntu 26.04 (lastlog2 package)
sudo lastlog2

sudo passwd -S root

Debian 13 and Ubuntu 26.04 no longer ship lastlog. The Debian 13 release notes point to lastlog2, from the package of the same name.

Only one account should have UID 0. Lock or remove accounts you no longer need. First check their files, scheduled tasks, processes and the applications that rely on them.


Harden the SSH configuration

OpenSSH reads /etc/ssh/sshd_config and the snippets in /etc/ssh/sshd_config.d/. Debian and Ubuntu include that folder at the top of the main file. For most directives, OpenSSH keeps the first value it reads. A file named 00-hardening.conf therefore wins over a snippet created later, by cloud-init for example.

First check the include line.

grep -nE '^[[:space:]]*Include' /etc/ssh/sshd_config
sudo sshd -T | sort

Copy the current configuration, then create the snippet.

sudo cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.before-hardening
sudo install -d -m 755 /etc/ssh/sshd_config.d
sudoedit /etc/ssh/sshd_config.d/00-hardening.conf

Add these lines.

PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
AuthenticationMethods publickey

AllowGroups ssh-admins
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
PermitTunnel no

Before reloading, test the syntax and read the effective configuration.

sudo sshd -t
sudo sshd -T | grep -E '^(port|permitrootlogin|pubkeyauthentication|passwordauthentication|kbdinteractiveauthentication|authenticationmethods|allowgroups|maxauthtries|logingracetime|x11forwarding|permittunnel) '

If the file has Match blocks, also check the configuration that applies to your account and admin address.

sudo sshd -T \
  -C user=adminops,host="$(hostname -f)",addr=198.51.100.10 |
  grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|authenticationmethods|allowgroups) '

The address 198.51.100.10 belongs to a range reserved for documentation. Replace it with the address you administer the server from.

If sshd -t prints nothing, the syntax is valid. Reload the service without closing your current session.

sudo systemctl reload ssh
sudo systemctl status ssh --no-pager
sudo journalctl -u ssh -n 50 --no-pager

Right away, test a new login with the key, then sudo -v. Only close the old session after this test.

Never close your SSH session before a new login has worked. If the configuration locks you out, only the console on the VPS page will let you fix it.

Settings to keep only when needed

  • AllowTcpForwarding no and AllowAgentForwarding no are useful if you use no SSH tunnel or jump host. They break those uses.

  • Restricting SSH to one IP address or a VPN cuts exposure sharply. You then need a fallback path, such as the console on the VPS page.

  • Moving off port 22 cuts bot noise and log size. It adds no authentication barrier and replaces neither the key, nor the firewall, nor patching. On Ubuntu 24.04 and later, SSH starts through a systemd socket. After changing Port, run sudo systemctl daemon-reload then sudo systemctl restart ssh.socket.

  • TOTP-based MFA can complement the key. Ubuntu describes the AuthenticationMethods publickey,keyboard-interactive combination in its TOTP and HOTP guide.


Install security updates

The -y flag is handy on a test server. For a first pass in production, read the proposed changes first.

sudo apt update
apt list --upgradable
sudo apt-get -s upgrade
sudo apt upgrade

sudo apt autoremove --dry-run

Only run apt autoremove after reading the list. A new kernel, a driver or a business package may need a reboot and an application test.

Turn on automatic security updates

Ubuntu Server installs unattended-upgrades and normally enables security updates by default. Check it anyway. The Ubuntu documentation on automatic updates covers the files, timers, allowed origins and logs.

On Debian, install and enable the mechanism yourself.

sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

systemctl list-timers 'apt-daily*' --all
sudo unattended-upgrade --dry-run --debug
sudo journalctl -u apt-daily-upgrade.service -n 100 --no-pager

Then check the schedule and the allowed origins.

grep -RhsE 'APT::Periodic::(Update-Package-Lists|Unattended-Upgrade)' \
  /etc/apt/apt.conf.d/

sudo sed -n '/Allowed-Origins/,/};/p' \
  /etc/apt/apt.conf.d/50unattended-upgrades

An automatic update can break an application, like any change. Skipping a fix is often riskier, though. A critical application needs staging, maintenance windows, targeted holds when justified, monitoring and a rollback plan. Ubuntu points out that unattended-upgrades is not a full fleet management tool.

Check third-party repositories

A third-party repository is not covered by automatic updates by default. List the repositories your packages come from.

grep -RhsE '^[[:space:]]*(deb |Types:|URIs:|Suites:|Signed-By:)' \
  /etc/apt/sources.list /etc/apt/sources.list.d 2>/dev/null

apt-cache policy

On Debian 13, the release notes also suggest this search for installed packages that do not come from Debian.

apt list '?narrow(?installed, ?not(?origin(Debian)))'

A repository added for one package widens your chain of trust. It can also ship updates for other packages. Prefer official or vendor repositories, with a dedicated key declared through Signed-By. Remove sources you no longer use. Never run a curl ... | sh without downloading, checking and reading the script first.

Watch reboots and failures

On Ubuntu, a file signals that a reboot is recommended.

if [ -f /var/run/reboot-required ]; then
  cat /var/run/reboot-required
  cat /var/run/reboot-required.pkgs 2>/dev/null
fi

Automatic updates without monitoring are only half the job. Set up at least an alert for these cases.

  • The update timer or service fails.

  • The last successful run is too old.

  • A reboot has been pending for too long.

  • A package is held back, or an origin is not covered.

  • The release is close to end of life.


Configure the system firewall

A firewall is no substitute for an inventory. Define the legitimate traffic first. A firewall adds to service hardening but does not replace it. The OuiHeberg client area has no network firewall for VPS. Filtering therefore happens inside the VPS operating system.

Pick a single tool to manage the rules.

ContextRecommended choice
Ubuntu, simple rulesUFW
Debian, native and advanced policynftables
Docker Engine installedstudy Docker's rules first (next section)

UFW is the default tool documented by Ubuntu. nftables is the default framework recommended by Debian. Do not stack UFW, a hand-written nftables ruleset and other managers without knowing the order they run in.

Whatever the tool, stick to these rules.

  • SSH open only to your admin addresses or your VPN, when possible.

  • HTTP and HTTPS open to the internet if the server hosts a public site.

  • Databases and admin panels never open to everyone.

  • The same rules for IPv4 and IPv6.

UFW for simple needs

Find the SSH port actually in use.

sudo sshd -T | awk '$1 == "port" {print $2; exit}'

The example below assumes SSH on port 22 and a web server. Adjust the ports before enabling the firewall.

sudo apt install ufw

sudo ufw default deny incoming
sudo ufw default allow outgoing

sudo ufw allow 22/tcp comment 'SSH administration'
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'

sudo ufw show added
sudo ufw enable
sudo ufw status verbose
sudo ufw status numbered

Keep your session open and test a new SSH login.

If you manage the server from a fixed IPv4 address, first add a rule limited to that address.

sudo ufw allow from 198.51.100.10 to any port 22 proto tcp \
  comment 'SSH admin workstation'
sudo ufw status numbered

Test the login from that address. Then delete the SSH rule open to everyone, by its number. Replace N with the number shown by ufw status numbered.

sudo ufw delete N

Do the same for IPv6 if your computer uses it. Do not disable IPv6 just to avoid writing its rules. Filter and monitor it like IPv4. A forgotten AAAA record or IPv6 interface exposes something other than what you tested over IPv4.

The guide How to set up the UFW firewall on Ubuntu or Debian covers rule management in detail.

nftables on Debian without Docker

This example targets a fresh web VPS without Docker, which does not route traffic, with SSH on port 22. It replaces the whole ruleset. Do not use it if another program already manages netfilter.

Save the current state first. The backup file itself starts by flushing the ruleset.

sudo sh -c '{
  printf "%s\n" "flush ruleset"
  nft list ruleset
} > /root/nftables.before-hardening.nft'
sudoedit /etc/nftables.conf

Write this content to /etc/nftables.conf.

#!/usr/sbin/nft -f

flush ruleset

define ssh_port = 22

table inet filter {
    chain input {
        type filter hook input priority filter; policy drop;

        iifname "lo" accept
        ct state invalid drop
        ct state established,related accept

        ip protocol icmp accept
        ip6 nexthdr ipv6-icmp accept

        tcp dport $ssh_port ct state new accept comment "SSH"
        tcp dport { 80, 443 } ct state new accept comment "Web"

        counter drop
    }

    chain forward {
        type filter hook forward priority filter; policy drop;
    }

    chain output {
        type filter hook output priority filter; policy accept;
    }
}

Let ICMP and ICMPv6 through. They handle IPv6 neighbor discovery, diagnostics and path MTU discovery. Do not copy a rule that blocks all ICMP.

Check the syntax before applying.

sudo nft -c -f /etc/nftables.conf
sudo nft -f /etc/nftables.conf
sudo nft list ruleset
sudo systemctl enable nftables

Test a new SSH session and the web service. To roll back, load the backup file.

sudo nft -f /root/nftables.before-hardening.nft

This file also starts with flush ruleset. Loading it replaces the current policy instead of adding duplicate rules. If SSH is already cut off, run the command from the console on the VPS page.

If the VPS routes traffic, runs a VPN, has several interfaces or runs Docker, design the forward and NAT chains for that case. A drop policy copied as is can take the service down.


Check the ports Docker publishes

Docker writes its own filtering and NAT rules to publish container ports. Traffic to a published port is diverted before the INPUT and OUTPUT chains that UFW uses. A Docker port can therefore stay reachable even when a UFW rule seems to block it. Docker explains this on its Packet filtering and firewalls page.

List the published ports.

sudo docker ps --format 'table {{.Names}}\t{{.Ports}}'
sudo ss -lntup
sudo iptables -S DOCKER-USER 2>/dev/null

The port declaration makes all the difference.

# Published on every interface of the VPS
ports:
  - "8080:80"

# Reachable only from the VPS, for example through Nginx
ports:
  - "127.0.0.1:8080:80"

For a database, Redis, an admin panel or an application behind a reverse proxy, bind the port to 127.0.0.1 or to a private address. Do it whenever public access is not needed.

Docker recommends the DOCKER-USER chain for rules that must run before its own. It advises against turning off its iptables management, which usually breaks container networking. Its install documentation states that it works with iptables-nft and iptables-legacy, not with rules written directly with nft. So do not mix the nftables example above with Docker without a tested design. Docker Engine 29 offers an nftables mode, still experimental.

The guide Install Docker on a Linux VPS covers installing and configuring the daemon. After each container deployment, scan the VPS again from outside. The Compose file describes the intent. The network you observe shows the reality.


Reduce services and privileges

Go back to the list of running services and ports from the inventory. For each service, ask yourself these questions.

  • Is it essential?

  • Does it need to start automatically?

  • Does it need to listen on a public interface?

  • Does it run under a dedicated, unprivileged account?

  • Which files, Linux capabilities and networks does it need?

  • Are its logs and status monitored?

Stopping and disabling a service is safer than removing it straight away. Replace myapp.service with the service name.

sudo systemctl disable --now myapp.service
sudo systemctl status myapp.service --no-pager

After an observation period and a dependency check, remove the package if nothing misses it.

Do not run the application as root

An application service needs a dedicated system account, limited directories and no interactive shell unless it uses one. A database listens on loopback or on a private address, unless there is an explicit and filtered need.

With systemd, start by measuring how well the service is sandboxed.

sudo systemd-analyze security --no-pager myapp.service
sudo systemctl cat myapp.service

The systemd-analyze security score only measures the systemd protections the tool knows about. A high score does not prove a vulnerability. A low score does not validate the application code.

For an internal application without just-in-time compilation (JIT) that only writes to two directories, a drop-in can look like this.

[Service]
User=myapp
Group=myapp
NoNewPrivileges=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectSystem=strict
ProtectHome=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
LockPersonality=yes
CapabilityBoundingSet=
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
ReadWritePaths=/var/lib/myapp /var/log/myapp

Create the drop-in with systemctl edit, then verify and restart the service.

sudo systemctl edit myapp.service
sudo systemd-analyze verify myapp.service
sudo systemctl daemon-reload
sudo systemctl restart myapp.service
sudo systemctl status myapp.service --no-pager
sudo journalctl -u myapp.service -n 100 --no-pager

Add the options one at a time. MemoryDenyWriteExecute=yes, ProtectHome=yes, address family restrictions or dropped capabilities can break a JIT runtime, a binary that loads modules or a service that expects specific access. The full reference is the systemd.exec page.


Keep AppArmor enabled

AppArmor enforces mandatory access control, program by program. Ubuntu installs and loads it by default. Check its status.

sudo aa-status
systemctl status apparmor --no-pager

The enforce mode blocks forbidden operations and logs them. The complain mode logs without blocking, which helps when building a profile. aa-status also tells confined processes apart from those without a profile.

On Debian, the tools and the presence of profiles depend on the installed image and kernel.

sudo apt install apparmor apparmor-utils
sudo systemctl enable --now apparmor
sudo aa-status

Do not disable AppArmor to "fix" an application. Read the denials instead.

sudo journalctl -k -g 'apparmor="DENIED"' --since today

Create or adjust the profile in staging. Switch it to complain while it learns if needed, then go back to enforce. A profile that is too broad, or left in complain, does not protect as intended.


Add Fail2ban

Fail2ban reads failed logins and adds a temporary blocking rule. It cuts noise and some repeated attacks. It fixes neither a weak password, nor a software flaw, nor a stolen credential. With SSH passwords disabled, it still helps against noise. It matters less if SSH is only reachable through a VPN or from an allowlist, but it replaces none of those measures.

Install it and open the SSH jail file.

sudo apt update
sudo apt install fail2ban
sudoedit /etc/fail2ban/jail.d/sshd.local

On a system that logs through systemd, use this configuration.

[sshd]
enabled = true
backend = systemd
maxretry = 5
findtime = 10m
bantime = 1h

The systemd backend reads the journal. Do not give it a logpath. Validate the configuration before starting the service.

sudo fail2ban-client -t
sudo systemctl enable --now fail2ban
sudo fail2ban-client ping
sudo fail2ban-client status
sudo fail2ban-client status sshd
sudo journalctl -u fail2ban -n 100 --no-pager

An allowlist only makes sense for a stable address you control. A range that is too wide bypasses the very check you just added. With Docker, make sure the action works in the chain the traffic actually goes through.

The guide How to install and configure Fail2ban covers recent Debian logs, unbanning and filter tests.


Tune a few kernel parameters

Do not copy hundreds of sysctl values from a generic list. The kernel documentation warns that some settings can make a system unusable. Understand each setting before you apply it.

Read the current values first.

sysctl kernel.dmesg_restrict
sysctl kernel.kptr_restrict
sysctl fs.protected_hardlinks
sysctl fs.protected_symlinks
sysctl fs.protected_fifos
sysctl fs.protected_regular
sysctl net.ipv4.conf.all.accept_redirects
sysctl net.ipv6.conf.all.accept_redirects

For a regular VPS that does not route traffic, this cautious snippet is a good starting point. Open the file.

sudoedit /etc/sysctl.d/60-local-hardening.conf

Add these settings.

# Limit the information exposed by the kernel
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2

# Protect files created in shared temporary directories
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
fs.protected_fifos = 2
fs.protected_regular = 2

# A VPS that does not route has no need to accept ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# Nor to send IPv4 redirects
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

Load the file, then reload all settings.

sudo sysctl -p /etc/sysctl.d/60-local-hardening.conf
sudo sysctl --system

The kernel documentation explains each value on its IP sysctl page. This guide deliberately leaves several settings out.

  • net.ipv4.ip_forward=0, because Docker, WireGuard or a router may rely on forwarding.

  • rp_filter=1, because asymmetric routing, some VPNs and policy routing need a closer look.

  • Disabling IPv6.

  • Irreversibly disabling modules or kexec.

  • Any BPF or io_uring setting without an inventory of applications and agents.


Keep usable logs

Local logs help with troubleshooting. Yet an attacker who gets root can edit or wipe them. Combine bounded local retention, a reliable clock, shipping off the VPS and alerts.

Make journald persistent

Create a configuration snippet.

sudo install -d -m 755 /etc/systemd/journald.conf.d
sudoedit /etc/systemd/journald.conf.d/60-persistent.conf

Here is an example to adapt to your disk size.

[Journal]
Storage=persistent
Compress=yes
SystemMaxUse=500M
SystemKeepFree=1G
MaxRetentionSec=30day

Apply it, then check.

sudo systemd-tmpfiles --create --prefix /var/log/journal
sudo systemctl restart systemd-journald
sudo journalctl --flush

sudo journalctl --disk-usage
sudo journalctl --verify
sudo journalctl -p warning..alert --since today

The journald.conf page documents SystemMaxUse, SystemKeepFree and persistence. A fixed limit must leave enough room for the system and the application.

Ship logs off the VPS

On a production server, send at least these events to a collector.

  • SSH logins and sudo use.

  • Kernel and firewall events.

  • Changes to accounts and groups.

  • Reverse proxy and application logs.

  • Automatic updates, backups and security agents.

Two setups are common. systemd-journal-upload sends journal entries to systemd-journal-remote. rsyslog, with its omfwd module, handles UDP, TCP and TLS, and recommends TCP with TLS.

A solid setup ticks these boxes.

  • The collector is authenticated by certificate, with its name and certificate authority checked.

  • Transport uses TLS, never plain-text UDP syslog over the internet.

  • Events are queued during an outage.

  • The source VPS cannot delete the collector's archives.

  • An alert fires if the stream or heartbeat stops.

  • Access to logs is restricted, since they often hold sensitive data.

Synchronize the clock

timedatectl status
timedatectl timesync-status 2>/dev/null || true
systemctl status systemd-timesyncd chrony --no-pager 2>/dev/null || true

Keep a single, properly configured time sync mechanism. A drifting clock makes it harder to correlate events and can break certificates, tokens and sometimes authentication.


Audit changes and integrity

Watch sensitive files with auditd

auditd collects events produced by the kernel audit subsystem. Debian provides the tools to store and search them.

sudo apt install auditd audispd-plugins
sudo systemctl enable --now auditd
sudoedit /etc/audit/rules.d/50-local.rules

Start with these minimal rules.

-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/sudoers -p wa -k privilege
-w /etc/sudoers.d -p wa -k privilege
-w /etc/ssh/sshd_config -p wa -k ssh_config
-w /etc/ssh/sshd_config.d -p wa -k ssh_config

Load them and check.

sudo augenrules --check
sudo augenrules --load
sudo auditctl -s
sudo auditctl -l

sudo ausearch -k ssh_config -ts today -i
sudo aureport --auth --summary

Limit the rules to truly critical files. Overly broad auditing fills the disk and drowns the signal. Set up rotation, a disk-full alert and shipping off the VPS.

Verify packages and set up AIDE

This command lists package files that have been modified.

sudo dpkg -V

Output does not prove a compromise. Configuration files change for legitimate reasons. Compare them with your approved changes.

AIDE builds a file integrity database.

sudo apt install aide
sudo aideinit
sudo aide --check

Initialize the database on a server you trust, after hardening. Read the aideinit output to see which database is active on your distribution. Copy the database, or at least its checksum, off the VPS. Otherwise an attacker with root can change both the files and their reference.

Neither auditd nor AIDE is a full EDR. They add traces and checks, provided someone reads and protects their output.

What about antivirus?

It depends on the service. ClamAV can scan files uploaded by visitors or a mail flow. An EDR agent brings telemetry and response to a sensitive server. No antivirus makes up for an unpatched system, an application running as root or exposed secrets.


Protect files, keys and secrets

Look for anomalies without fixing them automatically.

sudo find /etc -xdev -type f -perm -0002 -ls
sudo find / -xdev \( -perm -4000 -o -perm -2000 \) -type f -print

sudo find /root /home -path '*/.ssh/authorized_keys' -type f \
  -exec stat -c '%a %U:%G %n' {} \;

sudo find /etc/cron.d /etc/cron.daily /etc/cron.hourly \
  /etc/cron.monthly /etc/cron.weekly /var/spool/cron \
  -maxdepth 2 -type f -ls 2>/dev/null

systemctl list-timers --all --no-pager

An unusual permission is not necessarily malicious. Identify the package, the owner and the purpose before changing it.

Follow these basic rules for secrets.

  • No secrets in Git, a Docker image, the shell history or a URL.

  • Secret files readable only by the account that needs them.

  • A separate token per service and per environment.

  • Least privilege for DNS, backup, database and API access.

  • Scheduled rotation, and immediate rotation after a leak.

  • Old authorized_keys entries removed.

  • No private key pasted into documentation or a ticket.

For recent systemd services, prefer systemd credentials to global environment variables. A variable can stay visible to privileged processes and end up in a debug dump.


Encrypt public services with TLS

HTTPS protects traffic between the client and the server. It does not fix a vulnerable application. For a site on Nginx or Apache, check these points.

  • The DNS A record, and the AAAA record if there is one, points to the right server.

  • TCP ports 80 and 443 are open as the ACME challenge requires.

  • Renewal is automatic and tested.

  • An alert warns you before expiry.

  • HSTS is only enabled once HTTPS has been validated for good on the names concerned.

Follow the guide Certbot: install a Let's Encrypt SSL certificate on a VPS, then check the result.

sudo certbot certificates
sudo certbot renew --dry-run
systemctl list-timers '*certbot*' --all

openssl s_client \
  -connect example.com:443 \
  -servername example.com \
  -verify_return_error </dev/null

Redirecting HTTP to HTTPS helps browsers. Still, keep port 80 open if HTTP-01 renewal depends on it. The DNS-01 challenge is required for a wildcard certificate and removes that dependency. In exchange, it needs a DNS API secret that you must protect.


Back up and test restores

The 3-2-1 rule is a sound baseline. Keep three copies on two different media, one of them offline. Also set the maximum data loss and the maximum downtime you can accept.

Know the types of copies

MechanismUseful forLimit
tar archive on the same diskone-off copy of fileslost along with the VPS or the disk
full copy of the VPSquick rollback, recovery after a failuresame client account, database consistency to check
replication or syncavailability or fast copyalso copies deletions and corruption
versioned off-site backuprecovery after a failure, an error or a compromisemust be encrypted, monitored and restored
offline or immutable copyresistance to deletion and ransomwareneeds a retention policy and tests

At OuiHeberg, automatic VPS backups are a paid option. A full copy of the server is made every night and stored outside the server. You choose how many copies to keep, and the oldest makes way for the newest. Restores start from the Backups tab of the VPS page. The guide How to set up automatic VPS backups explains how to add it.

Backups tab of a VPS with the option, the daily schedule and the backups kept

This option does not remove the need for two precautions. A full copy of a running VPS is not always consistent for a database. So produce a dump right before it, as shown below. The option is also controlled from the same client account as the server. To guard against a compromise, keep another copy in a separate admin domain, append-only or offline depending on the risk. The guide Rclone: cloud synchronization on a Linux VPS shows how to send files to remote storage. In every case, test the restore. A backup history is only worth something if a restore really brings the application back.

Set the target before the tool

DataRPORTORetention
system configuration24 h4 h30 days
customer files1 h2 h30 days and 12 months
transactional database15 min1 hlogs and daily backups
security logsper policyimmediate access90 days or as required

These values drive the frequency and the technology. A daily backup cannot meet a fifteen-minute RPO.

Back up with restic

restic encrypts and deduplicates backups. It supports several backends, and the example uses SFTP. Install the distribution package and prepare the secret files.

sudo apt update
sudo apt install restic

sudo install -d -m 700 /root/.config/restic
sudo touch /root/.config/restic/password
sudo chown root:root /root/.config/restic/password
sudo chmod 600 /root/.config/restic/password
sudoedit /root/.config/restic/password

sudo touch /etc/restic-vps.env
sudo chown root:root /etc/restic-vps.env
sudo chmod 600 /etc/restic-vps.env
sudoedit /etc/restic-vps.env

Write this content to /etc/restic-vps.env.

RESTIC_REPOSITORY=sftp:backup@backup.example:/srv/restic/vps-01
RESTIC_PASSWORD_FILE=/root/.config/restic/password

The repository passphrase must be long and random. Store it in a separate password manager and test it. Without it, the encrypted repository cannot be restored.

Initialize the repository by hand, in a root session. First validate the SSH fingerprint of the backup server.

sudo -i
set -a
. /etc/restic-vps.env
set +a

restic init
restic backup /etc /srv /var/www /var/backups/databases
restic snapshots
restic check
exit

Export databases

Copying the directory of a live database is not always consistent. Produce a dump, or follow the physical backup method and logs the engine recommends. For MariaDB, with local root authentication over the socket, run this command.

sudo install -d -m 700 /var/backups/databases
sudo sh -c 'mariadb-dump --single-transaction --routines --events --triggers --all-databases | gzip -9 > "/var/backups/databases/mariadb-$(date -u +%F-%H%M%S).sql.gz"'

For PostgreSQL, use this one.

sudo install -d -m 700 -o postgres -g postgres \
  /var/backups/databases/postgresql
sudo -u postgres sh -c 'pg_dumpall | gzip -9 > "/var/backups/databases/postgresql/all-$(date -u +%F-%H%M%S).sql.gz"'

Test the restore on a separate database. --single-transaction improves consistency for MariaDB transactional tables (InnoDB). It is no guarantee for every engine and every operation.

Automate with a systemd timer

Create the file /etc/systemd/system/restic-backup.service.

[Unit]
Description=restic backup of the VPS
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
EnvironmentFile=/etc/restic-vps.env
ExecStart=/usr/bin/restic backup /etc /srv /var/www /var/backups/databases
Nice=10
IOSchedulingClass=best-effort
IOSchedulingPriority=7

Create the file /etc/systemd/system/restic-backup.timer.

[Unit]
Description=Daily restic backup of the VPS

[Timer]
OnCalendar=*-*-* 02:30:00
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target

Enable the timer and check a first run.

sudo systemd-analyze verify \
  /etc/systemd/system/restic-backup.service \
  /etc/systemd/system/restic-backup.timer

sudo systemctl daemon-reload
sudo systemctl enable --now restic-backup.timer
sudo systemctl start restic-backup.service

sudo systemctl status restic-backup.service --no-pager
sudo journalctl -u restic-backup.service -n 100 --no-pager
systemctl list-timers restic-backup.timer --all

The database dump must run right before this service. Hand it to a dedicated unit ordered with Requires and After, or to a backup orchestrator. An old dump backed up every night gives a false sense of freshness.

Separate write and delete rights

A compromised VPS must not be able to erase older backups. If the backend allows it, give the VPS append-only access. Run retention from a separate admin machine that holds the delete rights.

restic forget \
  --keep-daily 7 \
  --keep-weekly 4 \
  --keep-monthly 12 \
  --prune

restic check --read-data-subset=5%

The restic documentation on forget and prune notes that prune can take a long time and locks the repository. Schedule it and check the repository after cleanup. With an append-only repository, study the risks specific to retention and keep the maintenance client truly separate.

Test a restore

At least once a quarter, restore to a separate machine.

sudo -i
set -a
. /etc/restic-vps.env
set +a

restic snapshots
install -d -m 700 /mnt/restic-restore-test
restic restore latest --target /mnt/restic-restore-test
exit

Then check these points.

  • The files are there, with the right permissions.

  • Decryption works with the documented credentials.

  • Databases restore into a test engine.

  • The application starts and works normally.

  • The actual restore time fits within the RTO.

  • The procedure to rebuild a blank VPS is up to date.

A "successful" backup means the process finished. A reliable backup means a useful restore has been proven.


Monitor the VPS from outside

Local monitoring cannot report a VPS that is down, cut off from the network or fully compromised. Use an external service for availability, and an alert channel separate from the server.

CheckSignal to watch
availabilityTCP and HTTPS, expected content, latency
TLSexpiry date, chain and name
systemCPU, memory, swap, load
storagespace, inodes, log growth
servicesfailed systemd units, restarts
networknew ports, unusual connections
securitySSH and sudo failures, AppArmor denials, auditd
patcheslast run, failure, reboot required
backupsage of the latest copy, abnormal size, failure
timedrift or loss of sync

These commands cover the daily check.

systemctl --failed --no-pager
df -hT
df -ih
free -h
uptime

sudo ss -lntup
sudo journalctl -p warning..alert --since '-24 hours'
sudo journalctl -u ssh --since '-24 hours'
sudo fail2ban-client status sshd 2>/dev/null || true
sudo aa-status 2>/dev/null || true

Thresholds must fit the service. A disk alert at 80% only helps if it fires early enough given how fast the disk fills. Also alert when data stops coming in. A silent agent may be down.

Keep an operations calendar

FrequencyActions
continuouslyexternal availability, metrics, security alerts, backup failures
dailysecurity updates, backup, failed services
weeklyreview of alerts, ports, disk space, accounts and changes
monthlyreview of repositories, packages, keys, firewall rules and versions
quarterlyfull restore test, console test, incident drill
twice a yearreview of architecture, privileges, RPO, RTO and external exposure
at every changebackup, validation, external scan, documentation and rollback plan

For several VPS, manage this baseline with Ansible, a versioned repository and a CI pipeline that checks the syntax. Keep secrets out of the repository. A declarative configuration does not replace tests on the real server. It does make drift and rollbacks easier to track.


Check the result

Do not trust the written configuration. Check what is actually running.

Local checks

# System and patches
cat /etc/os-release
apt list --upgradable
systemctl list-timers 'apt-daily*' --all

# Effective SSH configuration
sudo sshd -t
sudo sshd -T | grep -E '^(port|permitrootlogin|passwordauthentication|kbdinteractiveauthentication|authenticationmethods|allowgroups) '

# Network exposure
sudo ss -lntup
sudo ufw status verbose 2>/dev/null || true
sudo nft list ruleset 2>/dev/null || true

# Security controls
sudo aa-status 2>/dev/null || true
sudo fail2ban-client status 2>/dev/null || true
sudo auditctl -s 2>/dev/null || true

# Journal and services
sudo journalctl --verify
systemctl --failed --no-pager

# Backup
sudo systemctl status restic-backup.service --no-pager

External scan

Run this scan from a computer you manage, and only against your own VPS.

sudo nmap -Pn -sS -sV -p- 203.0.113.10
sudo nmap -6 -Pn -sT -sV -p- 2001:db8::10

Replace 203.0.113.10 and 2001:db8::10 with the IPv4 and IPv6 addresses of your VPS. Compare the result with the list of allowed ports. The Nmap reference guide describes each option.

Run the scan again after the first hardening pass and after installing Docker or an admin panel. Repeat it after a firewall change or a network migration, and at regular intervals.

Acceptance checklist

TestExpected resultEvidence to keep
SSH key loginsuccess with a named accountanonymized SSH log excerpt
SSH login as rootrefusedtest excerpt
SSH passwordrefusedcommand and output
sudosuccess for the authorized administratorsudo log
SSH syntaxsshd -t without errorsdate and version
external portsapproved traffic only, Docker includedNmap report for IPv4 and IPv6
third-party repositoriesknown and justified listoutput of apt-cache policy
automatic updatesvalid dry run, active timerlog
firewallpolicy and rules as intendedUFW or nftables export
services and applicationsno needless service, no application as rootlist of units and their accounts
AppArmoractive, critical profiles in enforceoutput of aa-status
logs and timepersistent journal, synchronized clockoutput of timedatectl
backupruns without errorslog and restic snapshot
restoreapplication and data readabledated report
remote logsevent received and timestampedsearch on the collector
console on the VPS pagelogin possibledate of the last test
incident procedurecontacts available offlinedate of the last review

Respond to a compromise

A CPU spike, an unknown process or an unusual outbound connection calls for an investigation. None of them proves an intrusion on its own. Likewise, the lack of symptoms does not prove the server is clean. No single command settles it. Cross-check connections, processes, accounts, keys, tasks, remote logs, file changes, traffic and alerts.

Here are the first steps, to adapt to the severity.

  1. Work from a trusted computer and start an incident log.

  2. Restrict the VPS network traffic if this does not destroy evidence. The client area has no network firewall. Use the system firewall, from the console on the VPS page if SSH can no longer be trusted. If urgency outweighs analysis, the Shut down button on the VPS page stops the server.

  3. Avoid rebooting or "cleaning up" before collecting data if an investigation is planned.

  4. Preserve remote logs, process state, connections, scheduled tasks and a copy of the disk.

  5. From a clean system, revoke the exposed SSH keys, passwords, tokens, certificates and client area access.

  6. Protect older backups and prevent their deletion. With the backup option, rotation replaces the oldest copy every night. Quickly spot the ones taken before the intrusion.

  7. Assess the scope, including other VPS, Git repository, CI/CD, DNS, accounts and databases.

  8. Rebuild from a known-good image and configuration, for example with the Reinstall tab of the VPS page.

  9. Restore only data you have checked.

  10. Fix the root cause before going back online, and step up monitoring.

A copy of the suspect server serves to preserve or analyze a state. It does not become a clean restore point. A backup taken after the intrusion contains the intrusion too.

The French CERT (CERT-FR) advises preserving evidence and limiting the spread. It also advises securing backups and replacing a compromised system with a new or reinstalled one. NIST SP 800-61 Revision 3, published in April 2025, places incident response within overall risk management. Preparation, detection, response and recovery do not start on the day of the attack.


Need help?

Open a ticket from Tickets › Open a Ticket, or from the Contact support tile at the bottom of the VPS page. You can also ask your question on the OuiHeberg Discord.

Was this article helpful?

395 views
Share this article
Need a Linux VPS?

Root access, your choice of distribution and management from the OuiHeberg client area.

View plans →

Related Articles