Hardening Self Hosted Linux CMS Nodes
Most Linux server security guides read like they were written by someone who has never shipped a Friday afternoon hotfix. They hand you forty sysctl knobs, disable half the PHP standard library, and suggest setting every directory to 0400. Twenty minutes later, your CI runner breaks, Composer throws permission errors, and editors can't upload a 300KB hero image.
Real system hardening for a self-hosted CMS box has to survive routine deployments and messy editorial workflows. If you already moved off managed hosting following our notes on self-hosting web stacks on bare metal, the next step is shrinking the blast radius without breaking atomic releases. On WordPress, Drupal, Craft, or Statamic nodes, breaches rarely start with a kernel zero-day. They start with an unpatched plugin, a weak SSH password, or a writable webroot.
Here is the baseline I run on Debian 12 and Ubuntu 24.04 CMS nodes. Every rule earns its keep, and none of them break deployments.
Locking Down SSH With Ed25519 and Scoped Deploy Keys
Start with the front door. Legacy RSA keys still function, but OpenSSH has spent recent releases deprecating SHA-1 signatures, and carrying 4096-bit RSA keys buys you nothing over Ed25519. Ed25519 keys are compact, fast to verify, and free of padding quirks. Generate separate keys for admins and CI runners:
ssh-keygen -t ed25519 -a 64 -f ~/.ssh/cms_admin_ed25519 -C "owen@prod-cms-01"
Instead of editing /etc/ssh/sshd_config directly and fighting upgrade merge prompts, drop a file into /etc/ssh/sshd_config.d/10-hardening.conf. OpenSSH uses first-match-wins parsing, so a low-numbered drop-in overrides distribution defaults cleanly:
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
PubkeyAcceptedAlgorithms ssh-ed25519,sk-ssh-ed25519@openssh.com
MaxAuthTries 3
LoginGraceTime 20
AllowGroups ssh-admins deployers
Match User deploy
AllowTcpForwarding no
X11Forwarding no
AllowAgentForwarding no
PermitTTY no
That Match User deploy block matters. Your CI runner doesn't need an interactive shell, port forwarding, or full sudo rights. Give it a dedicated deploy user owning the release tree plus one narrow sudoers rule for systemctl reload php8.3-fpm. Always run sudo sshd -t and test a fresh login in a second terminal before closing your current session.
nftables Egress Filtering Without Breaking Updates
Almost everyone locks down inbound ports: TCP 22, 80, and 443—plus UDP 443 if you've enabled QUIC from our guide on HTTP/3 and QUIC tuning on origin boxes. Yet nine out of ten self-hosted boxes leave outbound traffic wide open.
Think about what happens seconds after an attacker triggers remote code execution in a plugin. Their script runs curl to fetch a second-stage binary or opens a reverse shell on port 4444. Default-deny egress turns a quiet foothold into a dead end.
Skip UFW and legacy iptables wrappers. Native nftables handles IPv4 and IPv6 in one inet table and reloads atomically from /etc/nftables.conf. The trick that prevents breaking apt or composer is filtering outbound packets by socket owner using meta skuid:
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
iifname "lo" accept
ct state established,related accept
ct state invalid drop
icmp type echo-request limit rate 5/second accept
tcp dport { 22, 80, 443 } accept
udp dport 443 accept
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy drop;
oifname "lo" accept
ct state established,related accept
udp dport 53 ip daddr { 1.1.1.1, 9.9.9.9 } accept
udp dport 123 accept
meta skuid { "root", "deploy", "_apt" } tcp dport { 80, 443 } accept
meta skuid "www-data" tcp dport 587 ip daddr 198.51.100.25 accept
log prefix "nft-egress-drop: " limit rate 10/minute counter drop
}
}
System updates under _apt, cert renewals as root, and package installs under deploy all hit HTTPS normally. Meanwhile, www-data can't phone home to arbitrary hosts—it only reaches your pinned SMTP relay at 198.51.100.25 on port 587. If your CMS calls a payment webhook or S3 bucket, allowlist those specific destination CIDRs or route outbound HTTP through a local proxy with domain filtering.
For the database layer, keep local connections on a Unix socket so no TCP port opens. If your database sits on a private VLAN—a split we weighed when comparing PostgreSQL vs MariaDB for modern CMS setups—add one explicit rule letting www-data reach that private IP on TCP 5432 or 3306.
Read-Only Webroots vs. Dedicated Upload Directories
One lazy habit wrecks self-hosted CMS security: running chown -R www-data:www-data /var/www/site so an installer stops complaining. Once the web user owns your PHP tree, any path traversal or arbitrary file-write bug lets an attacker patch index.php or plant a persistent shell inside a theme directory.
Recent enterprise CMS security research on CMS Connection confirms what incident responders see weekly: writable application codebases turn minor plugin flaws into full host takeovers. Enforcing the principle of least privilege on disk means splitting deployment ownership from runtime ownership:
- Application code belongs to
deploy:www-datawith0750directories and0640files. PHP-FPM reads scripts but can't modify a single byte of source code. - Uploads, thumbnails, and runtime caches live outside the release tree—such as
/var/lib/cms-storage/uploads—owned bywww-data:deploywith mode2770and symlinked into each release. - If
/var/lib/cms-storagelives on its own volume or bind mount, mount it withnoexec,nosuid,nodevin/etc/fstab.
Don't count on noexec alone. It stops the kernel from running binaries via execve(), but PHP-FPM is already running as an interpreter—it reads .php files rather than executing them directly. Block script execution in Nginx above your main PHP handler:
location ^~ /uploads/ {
add_header X-Content-Type-Options "nosniff" always;
location ~* \.php$ {
return 403;
}
try_files $uri =404;
}
With atomic symlink deploys (building /var/www/releases/20261201-1405, symlinking uploads, and flipping /var/www/current), releases never clash with permissions and the webroot stays read-only to www-data.
Taming PHP-FPM With open_basedir and disable_functions
Never apply the same limits to /etc/php/8.3/cli/php.ini that you put on web workers. WP-CLI, Drush, Artisan, and Composer need proc_open and broad filesystem visibility. Public HTTP workers do not.
Place runtime limits inside /etc/php/8.3/fpm/pool.d/cms.conf using php_admin_value and php_admin_flag. The admin prefix stops rogue .user.ini files or ini_set() calls from relaxing your policy:
[cms-site]
user = www-data
group = www-data
listen = /run/php/php8.3-cms.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
php_admin_flag[expose_php] = off
php_admin_flag[allow_url_include] = off
php_admin_flag[display_errors] = off
php_admin_value[open_basedir] = /var/www/current:/var/www/releases:/var/lib/cms-storage:/tmp
php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,popen,pcntl_exec,dl,show_source
Know the trade-offs before flipping these switches. Blocking exec and proc_open breaks legacy plugins that shell out to ImageMagick's convert binary; install php8.3-imagick or php8.3-gd instead of loosening disable_functions. Remember too that open_basedir isn't an airtight sandbox, and enabling it disables PHP's realpath_cache, adding extra lstat calls per request.
On busy nodes pushing 200+ requests per second, backstop PHP with kernel-enforced systemd sandboxing via systemctl edit php8.3-fpm:
[Service]
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
NoNewPrivileges=true
ReadOnlyPaths=/var/www
ReadWritePaths=/var/lib/cms-storage /run/php /var/log/php8.3-fpm.log
Systemd enforces those mount namespaces in the kernel with near-zero CPU cost, ensuring PHP-FPM can't inspect /home or write anywhere outside your allowlist.
Fail2ban Log Traps Without Locking Out Your Team
Stock Fail2ban configs still default to legacy iptables actions that clash with clean nftables setups, and they guard SSH while ignoring the HTTP credential stuffing hammering your PHP workers.
Switch Fail2ban to native nftables-multiport, read SSH events from journald, and add two HTTP traps: one for Nginx limit_req bursts and one for repeated failed CMS logins in /etc/fail2ban/jail.local:
[DEFAULT]
banaction = nftables-multiport
banaction_allports = nftables-allports
ignoreip = 127.0.0.1/8 ::1 10.44.0.0/16 203.0.113.10
bantime = 1h
bantime.increment = true
bantime.factor = 2
bantime.maxtime = 7d
findtime = 10m
maxretry = 5
[sshd]
enabled = true
backend = systemd
maxretry = 3
[nginx-limit-req]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
maxretry = 8
findtime = 2m
[cms-auth-trap]
enabled = true
port = http,https
logpath = /var/log/nginx/cms-access.log
filter = cms-auth-trap
maxretry = 6
findtime = 5m
Create /etc/fail2ban/filter.d/cms-auth-trap.conf to catch repeated POST requests to login or XML-RPC endpoints returning 401 or 403 (WordPress returns HTTP 200 on bad logins by default, so pair this with a tiny mu-plugin sending 401 on auth failure):
[Definition]
failregex = ^<HOST> - .* "POST /wp-login\.php HTTP/.*" 401
^<HOST> - .* "POST /xmlrpc\.php HTTP/.*" 403
Check your proxy headers before enabling HTTP jails. Behind Cloudflare, Fastly, or HAProxy without
set_real_ip_fromin Nginx, Fail2ban mistakes the proxy for an attacker and bans your own load balancer in thirty seconds. Verify real visitor IPs appear in column one ofcms-access.logfirst.
Keep your bastion, WireGuard subnet, and CI runner IPs in ignoreip. Exponential bantime.increment benches repeat bots for up to a week without bloating your nftables sets.
Five-Minute Smoke Test Before Cutover
Untested hardening is just a future 3:00 AM outage. Run these checks right after reloading services:
- Run a full CI deploy as
deployand verify symlink swaps and cache warmers succeed cleanly. - Upload a PNG in the CMS admin UI, then drop a harmless
test.phpinto/var/lib/cms-storage/uploadsand fetch it over HTTPS. Nginx must return403. - Run
sudo -u www-data curl -I --max-time 5 https://example.comand confirm it times out while loggingnft-egress-drop:injournalctl -k. - Execute your scheduled CLI task (
wp cron event runorphp artisan schedule:run) to confirm CLI keeps working while FPM stays restricted. - Send six bad logins from a disposable cellular IP and inspect
sudo nft list table inet f2b-tableto verify bans land cleanly alongside your baseinet filtertable.
Solid CMS security doesn't come from fragile one-liners or expensive appliances. It comes from sharp, boring boundaries: Ed25519 keys with scoped deploy users, per-UID egress rules, read-only codebases, kernel-backed PHP isolation, and log traps that catch noise early. Bake these five layers into your provisioning playbook once, and your deploys stay fast while plugin flaws lose their teeth.
Comments
Post a Comment