Hardening PHP-FPM with systemd
Published:
Updated:
How to harden your PHP-FPM service using systemd.
This has been tested on Debian 13 (trixie).
Initial state
The initial nginx.service is as follows:
[Unit]
Description=The PHP 8.4 FastCGI Process Manager
Documentation=man:php-fpm8.4(8)
After=network.target
[Service]
Type=notify
ExecStart=/usr/sbin/php-fpm8.4 --nodaemonize --fpm-config /etc/php/8.4/fpm/php-fpm.conf
ExecStartPost=-/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/8.4/fpm/pool.d/www.conf 84
ExecStopPost=-/usr/lib/php/php-fpm-socket-helper remove /run/php/php-fpm.sock /etc/php/8.4/fpm/pool.d/www.conf 84
ExecReload=/bin/kill -USR2 $MAINPID
Restart=on-failure
[Install]
WantedBy=multi-user.target
Which gives (systemd-analyze security php8.4-fpm.service):
→ Overall exposure level for php8.4-fpm.service: 9.6 UNSAFE 😨
Systemd hardening
We can harden NGINX with a systemd drop-in (eg. /etc/systemd/system/php8.4-fpm.service.d/50-hardening.conf).
I came up with:
[Service]
NoNewPrivileges=yes
RestrictSUIDSGID=true
ProtectSystem=strict
ProtectHome=yes
ProtectProc=invisible
ProcSubset=pid
PrivateTmp=true
PrivateDevices=yes
InaccessiblePaths=/opt /mnt /media /boot /lost+found
TemporaryFileSystem=/srv:ro /var:ro
BindPaths=/var/log /var/run/php /var/lib/php/sessions /srv/foo.example.com
BindReadOnlyPaths=/var/lib/php/modules
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ProtectControlGroups=strict
ProtectKernelTunables=yes
LockPersonality=true
ProtectClock=true
ProtectHostname=true
ProtectKernelModules=yes
ProtectKernelLogs=yes
RestrictRealtime=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
RestrictNamespaces=true
PrivateIPC=true
SystemCallFilter=@system-service
CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_KILL CAP_DAC_OVERRIDE CAP_CHOWN
SocketBindAllow=
SocketBindDeny=any
NoExecPaths=/
ExecPaths=/usr/sbin/php-fpm8.4 /usr/bin/php /usr/lib/php/php-fpm-socket-helper /bin /usr/bin /usr/lib
And now we get (after systemctl daemon-reload && systemctl restart php8.4-fpm):
→ Overall exposure level for php8.4-fpm.service: 2.5 OK 🙂
There are a lot of things you might need to adjust here such as:
- Exposed path (
BindPaths)
Things which were not done:
- I did make
/varunreachable. On Debian, the PHP-FPN logs are in/var/log/php8.4-fpm.log. I could have moved all the logs to/var/php/and made the rest of/var/loginvisible to PHP-FPM. This would require changing the configuration of both PHP-FPM and logrotate (/etc/logrotate.d/php8.4-fpm). - If your PHP application does not need to write in its directory (eg. it does not auto-updates itself), you might use declare it in
BindPathsinstead ofBindReadOnlyPaths.
References
- man systemd.exec
- man systemd.service
- systemd for Developers I (socket activation)