A default Debian install is solid, but it’s built to work everywhere, not to resist an attacker who already has a foothold. This guide hardens a Debian 13 “trixie” virtual machine, layer by layer: boot chain, kernel, filesystems, network stack, SSH, accounts and authentication, auditing, logging, time, and the VM integration itself. Every section explains why, gives you a drop-in file instead of editing package-owned configs, and ends with a check that proves the setting is active.
Read this first.
- Take a VM snapshot before you start, and keep a hypervisor console open the whole time. Several steps (SSH, PAM, firewall, GRUB) can lock you out if you get them wrong.
- Apply the sections one at a time and run each section’s check before moving on.
- “Hardcore” settings have trade-offs. Each one says what it breaks, so you can decide per system.
- Know the limits of VM hardening: whoever controls the hypervisor controls the VM. They can read its memory and disks and bypass everything below. This guide protects the VM from the network, from its own users and services, and from attackers who get in through them.
Tested on: Debian 13 “trixie” (kernel 6.12, systemd 257, OpenSSH 10.0) as a KVM/QEMU guest. All commands run as root.
Table of contents
- Placeholders
- Baseline: measure before you harden
- Packages and updates
- Boot chain: Secure Boot, GRUB password, kernel parameters
- Filesystems and mount options
- Kernel modules
- Kernel sysctl hardening
- Network sysctl hardening
- Core dumps
- AppArmor
- systemd hardening
- Firewall
- SSH
- Accounts, sudo and su
- Password policy and lockout
- Auditing with auditd
- Logging with journald
- Time synchronisation with NTS
- VM-specific hardening
- Cron, at and login banners
- Detection and verification
- Checklist
1. Placeholders
| Placeholder | Meaning |
|---|---|
10.20.0.0/16 | Your management network (SSH allowed from here only) |
ssh-users | Group whose members may log in over SSH |
sugroup | Group allowed to use su (deliberately left empty) |
grubadmin | GRUB superuser name |
log.example.org | Central log collector |
2. Baseline: measure before you harden
Know what the system looks like before you change it, so you can see what each step achieved:
apt install lynis debsecan
lynis audit system --quick | tail -n 30 # note the "Hardening index"
ss -tulpn # every listening socket
systemctl list-unit-files --state=enabled # every enabled service
debsecan --suite trixie --only-fixed # vulnerabilities with a fix availableCode language: PHP (php)
Remove what the VM doesn’t need. Every package, service and listening port you remove is attack surface you never have to harden:
apt purge <unneeded-packages>
apt autoremove --purgeCode language: HTML, XML (xml)
Production servers don’t need compilers.
build-essential,gccandmakelet an attacker build exploits locally. Remove them unless the system actually builds software.
3. Packages and updates
Unpatched software is how most systems get breached, so automate it:
- Automatic security updates with
unattended-upgradesandneedrestart, plus a reboot policy for kernels. (See my separate guide Unattended Upgrades on Debian 13.) - Only signed repositories, each bound to its own key with
Signed-Byin deb822.sourcesfiles. Never put keys in/etc/apt/trusted.gpg.d/, where they’re trusted for every repository. - Track open vulnerabilities with
debsecan(above), from cron or your monitoring.
4. Boot chain: Secure Boot, GRUB password, kernel parameters
4.1 UEFI Secure Boot and a virtual TPM
Create the VM with UEFI (OVMF) firmware, Secure Boot enabled, and a virtual TPM 2.0. Debian’s shim, GRUB and kernel are signed, so this works out of the box. It has two effects:
- Only signed bootloaders and kernels start, so a bootkit can’t slip in below the OS.
- The Debian kernel automatically enables
lockdown=integrityunder Secure Boot. Even root can no longer modify the running kernel (no/dev/mem, no unsigned modules, no unsigned kexec).
mokutil --sb-state # SecureBoot enabled
cat /sys/kernel/security/lockdown # [integrity] is selectedCode language: PHP (php)
DKMS modules (out-of-tree drivers) must be signed with your own MOK key under Secure Boot. Plan for that before you enable it on systems that need them.
4.2 GRUB password
A GRUB password stops anyone with VM console access (but not hypervisor admin rights) from editing kernel parameters at boot, for example adding init=/bin/bash to get a root shell, or apparmor=0 to switch off AppArmor.
Generate a password hash:
grub-mkpasswd-pbkdf2
# PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.ABC...Code language: CSS (css)
Files in /etc/grub.d/ are shell scripts whose output becomes grub.cfg. A file that just contains GRUB commands is ignored, or breaks update-grub. Create /etc/grub.d/01_password:
#!/bin/sh
# Emit the GRUB superuser definition into grub.cfg
cat <<'EOF'
set superusers="grubadmin"
password_pbkdf2 grubadmin grub.pbkdf2.sha512.10000.ABC...
EOFCode language: PHP (php)
chmod 0755 /etc/grub.d/01_password
By default this also demands the password for every normal boot, which unattended reboots can’t supply. To protect only editing and the GRUB shell, mark Debian’s boot entries as unrestricted:
sed -i 's/^CLASS="--class gnu-linux --class gnu --class os"$/CLASS="--class gnu-linux --class gnu --class os --unrestricted"/' /etc/grub.d/10_linux
grep '^CLASS=' /etc/grub.d/10_linuxCode language: JavaScript (javascript)
10_linux is a conffile. On GRUB package upgrades, dpkg asks about it, so keep your version.
4.3 Kernel command-line hardening
Debian reads drop-ins from /etc/default/grub.d/. Create /etc/default/grub.d/50-hardening.cfg:
# Kernel hardening parameters (appended to the existing command line)
GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX audit=1 audit_backlog_limit=8192"
GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX init_on_alloc=1 init_on_free=1"
GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX slab_nomerge page_alloc.shuffle=1 randomize_kstack_offset=on"
GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX vsyscall=none debugfs=off"
GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX lockdown=integrity"Code language: PHP (php)
update-grub
reboot
cat /proc/cmdline
| Parameter | Effect | Trade-off |
|---|---|---|
audit=1, audit_backlog_limit=8192 | Audits processes that start before auditd, and doesn’t lose events at boot | None |
init_on_alloc=1, init_on_free=1 | Zeroes memory on allocation and free, so no data leaks between users of memory | init_on_free costs a few percent of performance |
slab_nomerge | Keeps kernel object caches separate, which makes heap exploits harder | Slightly more memory |
page_alloc.shuffle=1, randomize_kstack_offset=on | Randomises memory layout and the kernel stack offset per syscall | Negligible |
vsyscall=none | Removes the legacy fixed-address vsyscall page, a classic exploitation aid | Breaks only binaries from roughly 2012 and earlier |
debugfs=off | Disables debugfs, a large and rarely needed kernel interface | Some tracing tools need it |
lockdown=integrity | Even without Secure Boot: no kernel memory writes, no unsigned modules, no unsigned kexec | Unsigned DKMS modules no longer load |
The
GRUB_CMDLINE_LINUXvalue in/etc/default/grubis applied first, and your drop-in appends to it. Don’t removequietor other existing values.
5. Filesystems and mount options
5.1 Separate filesystems
Separate filesystems contain resource exhaustion (a full log can’t stop the database) and allow restrictive mount options per area. Plan them at installation. LVM makes later changes painless.
| Mount point | Why separate |
|---|---|
/boot, /boot/efi | Read-mostly, no executables or devices needed |
/home | Users can’t fill the root filesystem |
/var | Services, caches and spools can’t fill the root filesystem |
/var/tmp | World-writable and persistent: contain it and make it noexec |
/var/log | Logs can’t fill /var, and /var can’t wipe out logging |
/var/log/audit | auditd needs reliable free-space accounting (section 16) |
/tmp | tmpfs by default on Debian 13, configured in 5.3 |
5.2 Mount options
| Option | Meaning |
|---|---|
nodev | Device files on this filesystem are ignored. Nobody can create a raw-disk device node in /tmp. |
nosuid | SUID and SGID bits are ignored. A planted SUID binary gives no privileges. |
noexec | Nothing on this filesystem can be executed directly. Dropped payloads in /tmp or /dev/shm don’t run. |
An /etc/fstab for an LVM layout (adjust device names; use UUID= for non-LVM partitions):
# <device> <mount> <type> <options> <dump> <pass>
/dev/mapper/vg0-root / ext4 defaults,errors=remount-ro 0 1
UUID=<boot-uuid> /boot ext4 defaults,nodev,nosuid,noexec 0 2
UUID=<esp-uuid> /boot/efi vfat umask=0077,nodev,nosuid,noexec 0 1
/dev/mapper/vg0-home /home ext4 defaults,nodev,nosuid 0 2
/dev/mapper/vg0-var /var ext4 defaults,nodev,nosuid 0 2
/dev/mapper/vg0-vartmp /var/tmp ext4 defaults,nodev,nosuid,noexec 0 2
/dev/mapper/vg0-varlog /var/log ext4 defaults,nodev,nosuid,noexec 0 2
/dev/mapper/vg0-varlogaudit /var/log/audit ext4 defaults,nodev,nosuid,noexec 0 2
tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0Code language: HTML, XML (xml)
systemctl daemon-reload
mount -a && findmnt -o TARGET,OPTIONS /boot /home /var /var/tmp /var/log /var/log/audit /dev/shmCode language: JavaScript (javascript)
TRIM on virtual disks: don’t use the
discardmount option, which trims synchronously on every delete. The weeklyfstrim.timerdoes the same job in batches:systemctl enable --now fstrim.timer.
noexecon/homeis possible for pure servers, but it breaks users’ own scripts and tools. Add it only if nobody works interactively on the VM.
5.3 /tmp: tmpfs with noexec
Debian 13 mounts /tmp as tmpfs through systemd’s tmp.mount, with nosuid,nodev but without noexec. Add it with a drop-in (in unit files, % must be written as %%):
systemctl edit tmp.mountCode language: CSS (css)
[Mount]
Options=mode=1777,strictatime,nosuid,nodev,noexec,size=25%%,nr_inodes=1m
systemctl daemon-reload && systemctl restart tmp.mount
findmnt -o TARGET,FSTYPE,OPTIONS /tmp # tmpfs ... nosuid,nodev,noexecCode language: PHP (php)
size=25% keeps a runaway process from using half the RAM for temporary files. Debian 13 also cleans /tmp (after 10 days) and /var/tmp (after 30 days) automatically through systemd-tmpfiles.
If a package installation fails because a maintainer script executes from
/tmp(rare these days), allow it only during dpkg runs. Create/etc/apt/apt.conf.d/50tmp-exec:DPkg::Pre-Invoke { "mount -o remount,exec /tmp || true"; }; DPkg::Post-Invoke { "mount -o remount,noexec /tmp || true"; };Code language: PHP (php)
6. Kernel modules
Every loadable module is kernel code an attacker can trigger, often just by opening a socket of an unusual protocol family. Many kernel privilege escalations of recent years were in exactly such rarely used modules (DCCP, RDS, TIPC, CAN, n_hdlc). Disable what a server VM never uses.
Two lines per module do two different jobs:
blacklist Xstops automatic loading (for example, when a program opens a socket of that type).install X /bin/falsemakes every load attempt fail, including an explicitmodprobe X, andmodprobereports the failure.
Create /etc/modprobe.d/90-hardening.conf:
# ===== Rare filesystems ========================================================
install cramfs /bin/false
blacklist cramfs
install freevxfs /bin/false
blacklist freevxfs
install hfs /bin/false
blacklist hfs
install hfsplus /bin/false
blacklist hfsplus
install jffs2 /bin/false
blacklist jffs2
# NOT disabled on purpose:
# vfat - the EFI system partition (/boot/efi) is vfat; disabling it breaks UEFI boot
# udf, iso9660 - cloud-init config drives and attached ISO images use them
# squashfs - snaps and some appliances use it
# ===== Rare network protocols ==================================================
install dccp /bin/false
blacklist dccp
install sctp /bin/false
blacklist sctp
install rds /bin/false
blacklist rds
install tipc /bin/false
blacklist tipc
install ax25 /bin/false
blacklist ax25
install netrom /bin/false
blacklist netrom
install rose /bin/false
blacklist rose
install x25 /bin/false
blacklist x25
install appletalk /bin/false
blacklist appletalk
install atm /bin/false
blacklist atm
install can /bin/false
blacklist can
install ieee802154 /bin/false
blacklist ieee802154
install n_hdlc /bin/false
blacklist n_hdlc
# ===== Hardware a server VM doesn't have =======================================
install usb-storage /bin/false
blacklist usb-storage
install firewire-core /bin/false
blacklist firewire-core
install thunderbolt /bin/false
blacklist thunderbolt
install bluetooth /bin/false
blacklist bluetooth
install btusb /bin/false
blacklist btusb
install uvcvideo /bin/false
blacklist uvcvideo
# ===== Test drivers with a history of exploits =================================
install vivid /bin/false
blacklist vividCode language: PHP (php)
update-initramfs -u
modprobe -n -v sctp # prints "install /bin/false"
lsmod | grep -E 'sctp|dccp|usb_storage|firewire' || echo "none loaded"Code language: PHP (php)
Need SCTP (telephony, some clustering) or CAN? Remove those lines. Older guides also listed
decnet,econetandipx: those protocols were removed from the kernel long ago, so the lines do nothing.
6.1 Expert option: no module loading after boot
kernel.modules_disabled = 1 blocks all module loading until the next reboot, even for root. It’s very strong, but it has real consequences: hot-plugged devices, new nftables features and filesystem types that weren’t loaded at boot will fail. Only consider it for single-purpose VMs, after you’ve confirmed that every needed module is loaded at boot (lsmod).
/etc/systemd/system/lock-kernel-modules.service:
[Unit]
Description=Disable kernel module loading until next boot
After=multi-user.target nftables.service
[Service]
Type=oneshot
ExecStart=/usr/sbin/sysctl -w kernel.modules_disabled=1
[Install]
WantedBy=multi-user.targetCode language: JavaScript (javascript)
7. Kernel sysctl hardening
systemd only reads files that end in
.confin/etc/sysctl.d/. A file named98_harden_kernelis silently ignored.
Create /etc/sysctl.d/90-hardening-kernel.conf:
# ===== Information leaks =======================================================
# Hide kernel pointers from everyone, including root
kernel.kptr_restrict = 2
# Only root may read the kernel log (it contains addresses and hardware details)
kernel.dmesg_restrict = 1
# Don't print kernel messages on the console
kernel.printk = 3 3 3 3
# ===== Attack surface ==========================================================
# No eBPF for unprivileged users, and harden the JIT
kernel.unprivileged_bpf_disabled = 1
net.core.bpf_jit_harden = 2
# No loading a different kernel at runtime (also disables kdump)
kernel.kexec_load_disabled = 1
# Disable the magic SysRq key (use the hypervisor to reset a hung VM)
kernel.sysrq = 0
# Restrict perf events to root (Debian-specific level 3)
kernel.perf_event_paranoid = 3
# io_uring: a large attack surface with many CVEs; 2 = off for everyone
kernel.io_uring_disabled = 2
# No unprivileged user namespaces (Debian-specific switch)
kernel.unprivileged_userns_clone = 0
# No userfaultfd for unprivileged users (used to stabilise kernel exploits)
vm.unprivileged_userfaultfd = 0
# No automatic loading of TTY line disciplines, and no TIOCSTI keystroke injection
dev.tty.ldisc_autoload = 0
dev.tty.legacy_tiocsti = 0
# ===== Process isolation =======================================================
# ptrace only for processes with CAP_SYS_PTRACE (root): no debugging other processes as a user
kernel.yama.ptrace_scope = 2
# Full address-space layout randomisation, with maximum entropy
kernel.randomize_va_space = 2
vm.mmap_rnd_bits = 32
vm.mmap_rnd_compat_bits = 16
# ===== Filesystem protections ==================================================
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
fs.protected_fifos = 2
fs.protected_regular = 2
# No core dumps from SUID programs
fs.suid_dumpable = 0Code language: PHP (php)
sysctl --system 2>&1 | grep -iE 'error|invalid|unknown' || echo "all applied"
sysctl kernel.kptr_restrict kernel.dmesg_restrict kernel.unprivileged_userns_clone kernel.io_uring_disabledCode language: PHP (php)
| Setting | What it breaks |
|---|---|
kernel.unprivileged_userns_clone = 0 | Rootless Podman or Docker, unprivileged browser sandboxes, unshare as a user. Services run by root and systemd sandboxing are not affected. |
kernel.io_uring_disabled = 2 | Applications that require io_uring (some databases and storage engines can use it, most fall back). Use 1 to allow only root. |
kernel.kexec_load_disabled = 1 | kdump crash capture and kexec-based fast reboots |
kernel.yama.ptrace_scope = 2 | gdb and strace on your own processes as a normal user (root still works) |
kernel.sysrq = 0 | The SysRq emergency keys on the console |
8. Network sysctl hardening
Create /etc/sysctl.d/90-hardening-network.conf:
# ===== Routing: this VM is not a router =======================================
# Set to 1 on routers, VPN gateways and container hosts (Docker, Podman, k8s)
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
# ===== Redirects: don't send them, don't accept them ===========================
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
# ===== Source routing: never ==================================================
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0
# ===== Spoofing protection ====================================================
# Strict reverse-path filtering (use 2 = loose with asymmetric routing)
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Log packets with impossible source addresses
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# ===== ICMP ===================================================================
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
# ===== TCP ====================================================================
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_rfc1337 = 1
# ===== IPv6 router advertisements ==============================================
# Only for VMs with STATIC IPv6 configuration. Most VMs get IPv6 via SLAAC,
# which needs router advertisements: setting 0 there silently removes IPv6.
#net.ipv6.conf.all.accept_ra = 0
#net.ipv6.conf.default.accept_ra = 0Code language: PHP (php)
sysctl --system 2>&1 | grep -iE 'error|invalid' || echo "all applied"
sysctl net.ipv4.conf.all.rp_filter net.ipv6.conf.all.accept_redirectsCode language: PHP (php)
9. Core dumps
A core dump is a copy of a process’s memory, including passwords, keys and session tokens. On a server, nobody needs them by default. You have to block them in three places, because each covers a different path.
For SUID programs: fs.suid_dumpable = 0 (section 7).
For login sessions (pam_limits), create /etc/security/limits.d/90-coredump.conf:
* hard core 0
root hard core 0
For systemd services, which ignore limits.conf, create /etc/systemd/system.conf.d/90-coredump.conf:
[Manager]
DefaultLimitCORE=0
If systemd-coredump is installed, create /etc/systemd/coredump.conf.d/90-disable.conf:
[Coredump]
Storage=none
ProcessSizeMax=0
systemctl daemon-reexec
ulimit -Hc # 0 (in a new login session)
systemctl show -p LimitCORE ssh.service # LimitCORE=0Code language: PHP (php)
10. AppArmor
Debian enables AppArmor by default. It confines programs to the files and capabilities their profile allows, so a compromised service can’t wander through the system. Make the most of it:
apt install apparmor-utils apparmor-profiles apparmor-profiles-extra
aa-status
aa-status lists profiles in enforce mode (blocking) and complain mode (only logging). For every complain-mode profile that belongs to a service you run, check the log for violations:
journalctl -k | grep -i 'apparmor="ALLOWED"' | tailCode language: JavaScript (javascript)
When nothing legitimate shows up, enforce it:
aa-enforce /etc/apparmor.d/<profile>Code language: HTML, XML (xml)
Also check which running processes have no profile at all. Those are the next candidates (aa-unconfined --paranoid).
Never boot with
apparmor=0to “fix” a problem. Switch the one profile to complain mode (aa-complain), find the denied access in the log, and fix the profile.
11. systemd hardening
11.1 Console and debug shell
# Ctrl+Alt+Del from the VM console must not reboot the server
systemctl mask ctrl-alt-del.target
# The debug shell on tty9 gives root without a password; make sure it can never start
systemctl mask debug-shell.serviceCode language: PHP (php)
11.2 Service sandboxing
systemd can confine every service in the same way containers do. Check how exposed your services are:
systemd-analyze security # overview; "UNSAFE" and "EXPOSED" deserve attention
systemd-analyze security ssh.serviceCode language: CSS (css)
For your own services and exposed daemons, add a drop-in with systemctl edit <service>. This set suits most network daemons that don’t need to write outside their own data directory:
[Service]
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
# Directories the service must be able to write to:
ReadWritePaths=/var/lib/<service>Code language: PHP (php)
Restart the service, test it properly, and check the journal. Then run systemd-analyze security again: the exposure score should drop clearly.
12. Firewall
Default deny inbound, allow only what’s needed, and allow SSH from the management network only. Create /etc/nftables.conf:
#!/usr/sbin/nft -f
# /etc/nftables.conf: default-deny host firewall
# "destroy table" instead of "flush ruleset", so reloads don't wipe
# tables owned by other tools (e.g. fail2ban's inet f2b-table).
destroy table inet filter
table inet filter {
set mgmt_v4 {
type ipv4_addr
flags interval
elements = { 10.20.0.0/16 }
}
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
ct state invalid drop
iif "lo" accept
# ICMP / ICMPv6: needed for path MTU discovery and IPv6 neighbour discovery
ip protocol icmp icmp type { echo-request, destination-unreachable, time-exceeded } limit rate 10/second accept
ip6 nexthdr ipv6-icmp accept
# SSH from the management network only
tcp dport 22 ip saddr @mgmt_v4 ct state new accept
# Services this VM offers (example: web server)
# tcp dport { 80, 443 } accept
# Log what's dropped (rate-limited)
limit rate 5/minute log prefix "nft-drop: " level info
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
include "/etc/nftables.d/*.nft"Code language: PHP (php)
nft -c -f /etc/nftables.conf && systemctl enable --now nftables && systemctl reload nftables
nft list ruleset | head -n 40Code language: PHP (php)
Test SSH from a second session before you close the first. If you’re locked out, use the hypervisor console and run
nft flush ruleset.
Hardcore: egress filtering. Setting the
outputpolicy todropand allowing only DNS, NTP (UDP 123 and TCP 4460 for NTS), your package mirrors and your log collector stops a compromised VM from downloading tools or reaching a command-and-control server. It takes maintenance, but it’s one of the most effective controls there is.
13. SSH
OpenSSH 10 has excellent defaults, including post-quantum key exchange. Hardening means removing everything except key-based logins for named users, and limiting what a session can do.
13.1 Who may log in
Create the group and add every admin before you restart sshd:
groupadd --system ssh-users
usermod -aG ssh-users <your-admin-user>Code language: HTML, XML (xml)
13.2 The configuration
Debian’s sshd_config includes /etc/ssh/sshd_config.d/*.conf at the top, and for sshd the first value wins, so drop-ins override the main file. Create /etc/ssh/sshd_config.d/50-hardening.conf:
# --- Authentication: keys only, named users only -----------------------------
PermitRootLogin no
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitEmptyPasswords no
HostbasedAuthentication no
IgnoreRhosts yes
GSSAPIAuthentication no
AllowGroups ssh-users
# --- Brute-force and DoS limits ----------------------------------------------
MaxAuthTries 3
LoginGraceTime 30
MaxStartups 10:30:60
MaxSessions 4
# --- What a session may do ---------------------------------------------------
# Disables X11, agent, TCP and Unix-socket forwarding in one line
DisableForwarding yes
PermitTunnel no
PermitUserEnvironment no
# --- Cryptography (OpenSSH 10) -----------------------------------------------
# Post-quantum hybrid key exchange first, classic curve25519 as fallback
KexAlgorithms mlkem768x25519-sha256,sntrup761x25519-sha512,sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
HostKeyAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512,rsa-sha2-256
PubkeyAcceptedAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,rsa-sha2-512,rsa-sha2-256
# --- Timeouts ----------------------------------------------------------------
# Drop connections whose client stopped answering (3 x 300 s)
ClientAliveInterval 300
ClientAliveCountMax 3
# Close interactive sessions after 30 minutes without traffic
ChannelTimeout session=30m
UnusedConnectionTimeout 15m
# --- Logging and banner ------------------------------------------------------
# VERBOSE logs the fingerprint of the key used for every login
LogLevel VERBOSE
Banner /etc/issue.netCode language: PHP (php)
sshd -t && systemctl reload ssh
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|allowgroups|kexalgorithms|disableforwarding)'Code language: JavaScript (javascript)
Keep your current session open, and log in from a second terminal to test before closing it.
| Setting | Why |
|---|---|
AuthenticationMethods publickey | Passwords can’t be guessed if they’re never accepted. Combine with FIDO2 keys (sk-ssh-ed25519) for phishing-proof hardware-backed logins. |
AllowGroups ssh-users | Service accounts and new users can’t log in over SSH, even with a key |
DisableForwarding yes | No tunnels into your network, and no agent hijacking through the server |
mlkem768x25519-sha256 | Hybrid post-quantum key exchange: recorded traffic stays safe even against future quantum computers |
ChannelTimeout / UnusedConnectionTimeout | Really closes idle sessions. ClientAliveCountMax 0, the old advice, disables this check in OpenSSH 8.2 and later instead of enforcing it. |
LogLevel VERBOSE | Every login names the exact key used, which is invaluable when investigating an incident |
13.3 Audit the result
apt install ssh-audit
ssh-audit localhost # no red (fail) or yellow (warn) entriesCode language: PHP (php)
14. Accounts, sudo and su
14.1 Root
Admins work with their own accounts and sudo, which gives a clear audit trail of who did what. Lock root’s password once at least one sudo user works:
passwd -l root
With a locked root password, the emergency and rescue targets can’t ask for one. In a VM that’s fine: recovery happens from the hypervisor console with a rescue ISO.
14.2 sudo
Create /etc/sudoers.d/50-hardening (always edit it with visudo -f):
# Run commands in a pseudo-terminal: background processes can't take over your terminal
Defaults use_pty
# Separate, complete log of everything run via sudo
Defaults logfile="/var/log/sudo.log"
Defaults log_input, log_output
Defaults iolog_dir="/var/log/sudo-io/%{user}"
# Ask for the password again after 5 minutes
Defaults timestamp_timeout=5
Defaults passwd_tries=3Code language: PHP (php)
chmod 0440 /etc/sudoers.d/50-hardening
visudo -c
log_input and log_output record entire sudo sessions, which you can replay with sudoreplay. That’s powerful for forensics, but it also records anything typed, including secrets. Decide deliberately.
Cutting edge: Debian 13 also ships
sudo-rs, a memory-safe Rust reimplementation of sudo. It supports the common sudoers features (notlog_input/log_output), and it’s worth evaluating for systems that only need basic sudo.
14.3 Restrict su
Allow su only for members of an (empty) group. Admins use sudo, and su becomes useless to an attacker who learns a password. Run groupadd sugroup, then add this line in /etc/pam.d/su, below the existing pam_rootok line:
auth required pam_wheel.so use_uid group=sugroup
14.4 Default permissions and idle shells
In /etc/login.defs, set:
UMASK 027
HOME_MODE 0750
Create /etc/profile.d/90-hardening.sh:
# Files: owner rw, group r, others nothing
umask 027
# Log out idle interactive shells after 15 minutes
TMOUT=900
readonly TMOUT
export TMOUTCode language: PHP (php)
15. Password policy and lockout
With SSH keys only, passwords matter for sudo and the console. Make them strong, block reuse, and lock accounts under attack.
15.1 Password quality
apt install libpam-pwquality
Installing it adds pam_pwquality to /etc/pam.d/common-password automatically through pam-auth-update. Don’t edit that file by hand: pam-auth-update would overwrite or refuse your edits.
Create /etc/security/pwquality.conf.d/50-hardening.conf:
# Long passphrases beat complex short passwords (NIST SP 800-63B)
minlen = 15
# Reject dictionary words and passwords containing the user name
dictcheck = 1
usercheck = 1
# No "aaaa" or "1111" sequences
maxrepeat = 3
# At least 4 characters different from the old password
difok = 4
# Apply the rules to root as well
enforce_for_root
retry = 3Code language: PHP (php)
15.2 Password history
pam_pwhistory prevents reusing recent passwords. Debian ships the module but no pam-auth-update profile for it. Create /usr/share/pam-configs/local-pwhistory:
Name: Password history (pam_pwhistory, local)
Default: yes
Priority: 1023
Password-Type: Primary
Password:
requisite pam_pwhistory.so use_authtokCode language: CSS (css)
Configure it in /etc/security/pwhistory.conf:
remember = 24
enforce_for_root
Priority 1023 places it after pam_pwquality (1024) and before pam_unix (256): first quality, then history, then the actual change.
15.3 Account lockout with pam_faillock
Editing /etc/security/faillock.conf alone does nothing: Debian doesn’t add pam_faillock to the PAM stack by default. Two profiles add it in the right places.
/usr/share/pam-configs/local-faillock:
Name: Lock accounts after failed logins (pam_faillock, local)
Default: yes
Priority: 0
Auth-Type: Primary
Auth:
[default=die] pam_faillock.so authfailCode language: PHP (php)
/usr/share/pam-configs/local-faillock-notify:
Name: Check lockout before authentication, reset on success (pam_faillock, local)
Default: yes
Priority: 1024
Auth-Type: Primary
Auth:
requisite pam_faillock.so preauth
Account-Type: Primary
Account:
required pam_faillock.soCode language: CSS (css)
The settings go in /etc/security/faillock.conf:
deny = 5
fail_interval = 900
unlock_time = 900
audit
Enable all three local profiles:
pam-auth-update --enable local-pwhistory local-faillock local-faillock-notify
grep -E 'faillock|pwhistory|pwquality' /etc/pam.d/common-auth /etc/pam.d/common-account /etc/pam.d/common-passwordCode language: JavaScript (javascript)
Test it with a second root session open: enter a wrong sudo password five times as a test user, and check the lock with faillock --user <user>. Reset it with faillock --user <user> --reset.
even_deny_rootalso locks root after failed attempts. With root’s password locked (section 14.1), it adds nothing. On systems with a root password, it turns console brute force into a denial of service. Leave it off unless your policy demands it.
15.4 Password ageing: modern guidance vs. compliance
NIST SP 800-63B no longer recommends forced periodic password changes: they lead to predictable passwords (“Summer2026!” becomes “Autumn2026!”). Require a change only on evidence of compromise. Lock accounts that aren’t used:
useradd -D -f 30 # new accounts: lock 30 days after password expiryCode language: PHP (php)
If your compliance framework (for example older CIS benchmark versions) still demands ageing, set it in /etc/login.defs and apply it to existing users:
PASS_MAX_DAYS 365
PASS_MIN_DAYS 1
PASS_WARN_AGE 14
chage --maxdays 365 --mindays 1 --warndays 14 <user>Code language: HTML, XML (xml)
Debian 13 hashes passwords with yescrypt by default. Check it with grep ENCRYPT_METHOD /etc/login.defs. Hashes in /etc/shadow start with $y$.
16. Auditing with auditd
auditd records security-relevant kernel events: who changed which file, who ran which privileged command, who loaded a kernel module. It’s the forensic record after an incident.
apt install auditd audispd-plugins
Debian starts auditd on install. The kernel parameters audit=1 audit_backlog_limit=8192 (section 4.3) make sure nothing before auditd’s start is missed.
16.1 auditd.conf
Edit /etc/audit/auditd.conf:
# 100 MB per file, 20 files = 2 GB on the dedicated /var/log/audit filesystem
max_log_file = 100
num_logs = 20
max_log_file_action = rotate
# Free-space alarms
space_left = 25%
space_left_action = syslog
admin_space_left = 10%
admin_space_left_action = suspend
disk_full_action = suspend
disk_error_action = syslogCode language: PHP (php)
rotate with a fixed number of files makes disk usage predictable. Ship the logs off the host (section 17.3) for long-term retention. If your policy requires that audit data is never lost locally, use max_log_file_action = keep_logs together with admin_space_left_action = single or halt. That way the system stops rather than running unaudited, but a full disk then means downtime.
16.2 Audit rules
Create /etc/audit/rules.d/50-hardening.rules. Every syscall rule exists twice, because on amd64 a 32-bit program could otherwise bypass a 64-bit-only rule:
## ===== Time changes ==========================================================
-a always,exit -F arch=b64 -S adjtimex,settimeofday,clock_settime -k time-change
-a always,exit -F arch=b32 -S adjtimex,settimeofday,clock_settime,stime -k time-change
-w /etc/localtime -p wa -k time-change
## ===== Identity: users, groups, passwords ===================================
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/security/opasswd -p wa -k identity
## ===== Network and system identity ==========================================
-a always,exit -F arch=b64 -S sethostname,setdomainname -k system-locale
-a always,exit -F arch=b32 -S sethostname,setdomainname -k system-locale
-w /etc/hosts -p wa -k system-locale
-w /etc/hostname -p wa -k system-locale
-w /etc/issue -p wa -k system-locale
-w /etc/issue.net -p wa -k system-locale
-w /etc/network/ -p wa -k system-locale
-w /etc/systemd/network/ -p wa -k system-locale
-w /etc/nftables.conf -p wa -k firewall
-w /etc/nftables.d/ -p wa -k firewall
## ===== Mandatory access control ============================================
-w /etc/apparmor/ -p wa -k MAC-policy
-w /etc/apparmor.d/ -p wa -k MAC-policy
## ===== Logins and sessions (Debian 13: lastlog2 and wtmpdb) =================
-w /var/lib/lastlog/ -p wa -k logins
-w /var/lib/wtmpdb/ -p wa -k session
-w /run/faillock/ -p wa -k logins
## ===== Privilege: sudo, su, SSH config ======================================
-w /etc/sudoers -p wa -k scope
-w /etc/sudoers.d/ -p wa -k scope
-w /var/log/sudo.log -p wa -k actions
-w /etc/ssh/sshd_config -p wa -k sshd
-w /etc/ssh/sshd_config.d/ -p wa -k sshd
-w /etc/pam.d/ -p wa -k pam
-w /etc/security/ -p wa -k pam
# Commands run as another user (sudo, su, setuid)
-a always,exit -F arch=b64 -C euid!=uid -F auid!=unset -S execve -k user_emulation
-a always,exit -F arch=b32 -C euid!=uid -F auid!=unset -S execve -k user_emulation
## ===== Permission and ownership changes =====================================
-a always,exit -F arch=b64 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=unset -k perm_mod
-a always,exit -F arch=b32 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=unset -k perm_mod
-a always,exit -F arch=b64 -S chown,fchown,lchown,fchownat -F auid>=1000 -F auid!=unset -k perm_mod
-a always,exit -F arch=b32 -S chown,fchown,lchown,fchownat -F auid>=1000 -F auid!=unset -k perm_mod
-a always,exit -F arch=b64 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=unset -k perm_mod
-a always,exit -F arch=b32 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=unset -k perm_mod
## ===== Failed file access ====================================================
-a always,exit -F arch=b64 -S creat,open,openat,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -k access
-a always,exit -F arch=b32 -S creat,open,openat,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -k access
-a always,exit -F arch=b64 -S creat,open,openat,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -k access
-a always,exit -F arch=b32 -S creat,open,openat,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -k access
## ===== Mounts and deletions ==================================================
-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=unset -k mounts
-a always,exit -F arch=b32 -S mount -F auid>=1000 -F auid!=unset -k mounts
-a always,exit -F arch=b64 -S unlink,unlinkat,rename,renameat -F auid>=1000 -F auid!=unset -k delete
-a always,exit -F arch=b32 -S unlink,unlinkat,rename,renameat -F auid>=1000 -F auid!=unset -k delete
## ===== Kernel modules ========================================================
-a always,exit -F arch=b64 -S init_module,finit_module,delete_module -k kernel_modules
-a always,exit -F arch=b32 -S init_module,finit_module,delete_module -k kernel_modules
-w /usr/bin/kmod -p x -k kernel_modulesCode language: PHP (php)
Add a rule for every SUID and SGID program on the system, generated rather than typed:
find / -xdev \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null | sort | \
awk '{print "-a always,exit -F path=" $1 " -F perm=x -F auid>=1000 -F auid!=unset -k privileged"}' \
> /etc/audit/rules.d/55-privileged.rulesCode language: JavaScript (javascript)
Run it again after installing software that adds SUID programs.
16.3 Make the rules immutable
Create /etc/audit/rules.d/99-finalize.rules:
## Lock the audit configuration: changing rules now requires a reboot
-e 2Code language: PHP (php)
An attacker with root can then no longer switch auditing off or remove rules to hide their tracks without a reboot, which itself is visible.
augenrules --check && augenrules --load
auditctl -s # enabled 2 = immutable
auditctl -l | wc -l # number of loaded rulesCode language: PHP (php)
16.4 Using the audit trail
ausearch -k identity -i --start today # who changed users or passwords today
ausearch -k privileged -i --start recent # privileged commands, last 10 minutes
aureport --summary # overview
aureport --auth --failed # failed authenticationsCode language: PHP (php)
17. Logging with journald
Debian 13 doesn’t install rsyslog. The systemd journal is the system log, stored persistently in /var/log/journal. Forwarding to syslog (ForwardToSyslog=yes) only makes sense if you deliberately install rsyslog.
17.1 Configuration
Create /etc/systemd/journald.conf.d/50-hardening.conf:
[Journal]
Storage=persistent
Compress=yes
# Forward-secure sealing (17.2): tampering with old entries becomes detectable
Seal=yes
# Size limits, so the journal can't fill /var/log
SystemMaxUse=2G
SystemKeepFree=1G
MaxFileSec=1month
# Rate limiting against log flooding
RateLimitIntervalSec=30s
RateLimitBurst=10000Code language: PHP (php)
systemctl restart systemd-journald
journalctl --disk-usage
17.2 Forward-secure sealing
Sealing signs the journal at regular intervals with a key that evolves forward. An attacker who gets root later can’t forge older entries without detection.
journalctl --setup-keys
The command prints a verification key. Store it off the host (password manager, printout in the safe), never on the VM itself. To verify the journal later:
journalctl --verify --verify-key=<verification-key>Code language: HTML, XML (xml)
17.3 Ship logs off the host
Logs on a compromised machine can’t be trusted. Send them to a central collector as they’re written, for example with systemd-journal-upload (package systemd-journal-remote) to https://log.example.org:19532, or with your log agent of choice. The collector’s copy is the one that counts during an investigation.
18. Time synchronisation with NTS
Correct time matters for logs, certificates, Kerberos and TOTP. Classic NTP is unauthenticated, so an attacker on the path can shift your clock. NTS (Network Time Security) authenticates the time servers. Debian 13’s chrony supports it.
apt install chrony # replaces systemd-timesyncdCode language: PHP (php)
Create /etc/chrony/sources.d/nts.sources:
server time.cloudflare.com iburst nts
server nts.netnod.se iburst nts
server ptbtime1.ptb.de iburst ntsCode language: CSS (css)
To use only authenticated sources, comment out the pool line in /etc/chrony/chrony.conf. Then:
systemctl restart chrony
chronyc -N authdata # Mode "NTS", KeyID and Cook values > 0 for each server
chronyc trackingCode language: PHP (php)
NTS needs outbound TCP 4460 (key exchange) in addition to UDP 123. Remember this if you filter egress.
19. VM-specific hardening
19.1 The QEMU guest agent
qemu-guest-agent lets the hypervisor freeze filesystems for consistent backups and read the IP address. It can also execute commands, read and write files, change passwords and add SSH keys inside the VM. That’s a direct root channel for anyone with access to the hypervisor API. Block what you don’t need.
Create /etc/qemu/qemu-ga.conf:
[general]
block-rpcs=guest-exec;guest-exec-status;guest-file-open;guest-file-close;guest-file-read;guest-file-write;guest-file-seek;guest-file-flush;guest-set-user-password;guest-ssh-add-authorized-keys;guest-ssh-remove-authorized-keys;guest-ssh-get-authorized-keysCode language: JavaScript (javascript)
systemctl restart qemu-guest-agent
qemu-ga -D | grep block-rpcs # shows the effective listCode language: PHP (php)
Filesystem freeze and thaw (guest-fsfreeze-*) stay allowed, so snapshot backups keep working.
19.2 cloud-init
If the VM was provisioned with cloud-init and doesn’t need it afterwards, switch it off. Otherwise a modified config drive or metadata service can reconfigure the system (users, SSH keys, commands) on the next boot:
touch /etc/cloud/cloud-init.disabled
19.3 Snapshots, templates and secrets
- VM snapshots contain memory (with RAM state) and disks: keys, passwords, sessions. Protect them like the running system, and delete old ones.
- VMs cloned from a template share SSH host keys,
/etc/machine-idand possibly the random seed. Regenerate them on the first boot of every clone:
rm -f /etc/ssh/ssh_host_* && dpkg-reconfigure openssh-server
rm -f /etc/machine-id /var/lib/dbus/machine-id && systemd-machine-id-setupCode language: JavaScript (javascript)
- Encrypt disks (LUKS2) if the VM’s storage is outside your control. With a virtual TPM,
systemd-cryptenroll --tpm2-device=autounlocks them at boot without a passphrase prompt.
20. Cron, at and login banners
20.1 Restrict cron and at
Only root should schedule jobs. Users’ cron jobs are a classic persistence mechanism:
echo root > /etc/cron.allow && chmod 0600 /etc/cron.allow
rm -f /etc/cron.deny
chmod 0600 /etc/crontab
chmod 0700 /etc/cron.d /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly
# Only if 'at' is installed:
[ -x /usr/bin/at ] && { echo root > /etc/at.allow; chmod 0600 /etc/at.allow; rm -f /etc/at.deny; }Code language: PHP (php)
20.2 Banners without system information
/etc/issue (console) and /etc/issue.net (SSH banner) are shown before login. They should warn, not reveal the OS and kernel version:
cat > /etc/issue.net <<'EOF'
Authorised access only. All activity is logged and monitored.
EOF
cp /etc/issue.net /etc/issueCode language: JavaScript (javascript)
Debian’s default /etc/motd is legal boilerplate. Replace it with your own text or empty it.
21. Detection and verification
Hardening reduces the chance of a breach. Detection makes sure you notice one. Combine this guide with these posts:
- AIDE for file integrity monitoring: every changed binary or config gets reported. (See my guide AIDE on Debian 13.)
- Fail2Ban to cut down brute force noise. (See my guide Fail2Ban with nftables on Debian 13.)
- Unattended upgrades for patching. (See my guide Unattended Upgrades on Debian 13.)
- Central logging (section 17.3) and monitoring of the systems themselves.
Then measure again:
lynis audit system | tail -n 40 # compare the hardening index with section 2
debsecan --suite trixie --only-fixed # nothing open
systemd-analyze security | tail -n 20
ssh-audit localhostCode language: PHP (php)
Lynis suggestions are a to-do list, not a score to max out. Decide on each one, and document the ones you consciously skip.
22. Checklist
Boot and kernel
- โ VM snapshot taken, hypervisor console available
- โ UEFI Secure Boot and a vTPM are on, and
/sys/kernel/security/lockdownshowsintegrity - โ The GRUB password is set through an executable
/etc/grub.d/01_password, and normal boot is--unrestricted - โ Hardening kernel parameters are in
/etc/default/grub.d/50-hardening.cfgand visible in/proc/cmdline - โ Rare filesystem and protocol modules are disabled (
install /bin/false+blacklist), withvfat,udfandiso9660kept - โ Kernel and network sysctls are in
*.conffiles, andsysctl --systemreports no errors
Filesystems
- โ Separate filesystems for
/boot,/home,/var,/var/tmp,/var/logand/var/log/audit - โ
nodev,nosuid,noexecwhere applicable,/tmptmpfs withnoexecviatmp.mount, and/dev/shmwithnoexec - โ
fstrim.timerinstead ofdiscard
Services and network
- โ Unneeded packages, services and compilers are removed
- โ AppArmor profiles are enforced for your services, and nothing runs with
apparmor=0 - โ
ctrl-alt-del.targetanddebug-shell.serviceare masked, and exposed services are sandboxed - โ nftables is default-deny inbound, SSH comes from the management network only, and reloads don’t flush other tables
- โ Core dumps are off for sessions, services and SUID programs
Access
- โ SSH: keys only,
AllowGroups, no forwarding, OpenSSH 10 crypto with PQ key exchange,ssh-auditclean - โ Root’s password is locked, sudo logs to
/var/log/sudo.logwithuse_pty, andsuis restricted to an empty group - โ
pam_pwquality(minlen 15),pam_pwhistoryandpam_faillockare active through pam-auth-update profiles - โ
UMASK 027,HOME_MODE 0750,TMOUT=900
Audit, logging and time
- โ auditd rules for identity, privilege, permissions, modules, time and network are loaded, plus SUID program rules
- โ The audit configuration is immutable (
-e 2), and auditd.conf space actions are set - โ journald is persistent, size-limited and sealed, with the verification key stored off-host
- โ Logs are shipped to a central collector
- โ chrony with NTS sources, and
chronyc -N authdatashows NTS
VM and detection
- โ The QEMU guest agent blocks exec, file and password RPCs
- โ cloud-init is disabled after provisioning, and template clones have new SSH host keys and machine IDs
- โ cron and at are restricted to root, and banners reveal no OS details
- โ AIDE, Fail2Ban, unattended-upgrades and central logging are in place
- โ The Lynis hardening index is compared before and after, and skipped suggestions are documented