SSH Guru Blog.
← SSH Guru Blog
Server Monitoring
·11 min read

Patch Your PHP Stack: Inventory, Updates, and Post-Patch Checks

phppatchingself-hostedsecurityserver administration
Close-up of HTML and PHP code on screen showing error message and login form data.
Photo: Markus Spiske on Pexels

HKCERT flagged critical PHP vulnerabilities under the "PHP2Shell" label and warned that AI is shrinking the window between disclosure and exploitation. Hong Kong Computer Emergency Response Team Coordination Centre made it clear: patch immediately. If you self-host PHP, whether it's a Nextcloud instance, a Laravel app, a legacy WordPress site, or a custom internal tool, this is your checklist.

Inventory every PHP runtime

Start with what you actually run. Don't assume.

# System PHP
php -v

# FPM pools
systemctl list-units 'php*-fpm.service' --no-legend

# Container images
docker images --format '{{.Repository}}:{{.Tag}}' | grep -i php

# Composer lock files (shows required PHP version)
find /var/www -name 'composer.lock' -exec grep -H 'php' {} \;

Record each finding: version, SAPI (FPM, CLI, embed), path, and which service or container owns it. A spreadsheet works. So does a text file in your ops repo. The point is a single source of truth before you touch anything.

Check for end-of-life branches. PHP 8.1 reached EOL Dec 2024. PHP 8.2 EOL is Dec 2025. If you're on 8.1 or older, you're not just unpatched, you're unsupported. Plan an upgrade path alongside the emergency patch.

Don't forget the runtimes hiding in odd places. A cron job that calls /usr/bin/php8.1 directly. A systemd timer that spawns a PHP worker. A legacy box running php-fpm7.4 because one plugin never migrated. The find / -name 'php*' -type f -executable 2>/dev/null | xargs -r file | grep ELF command catches binaries outside package management. Run it once. You'll probably find something you forgot.

Update the packages

Debian / Ubuntu

apt update
apt list --upgradable | grep -i php
apt upgrade -y php*  # or target specific packages: php8.3-fpm php8.3-cli php8.3-common ...

Pinning matters. If you pinned php8.3-fpm=8.3.12-1 to avoid a regression, unpin it first:

apt-mark unhold php8.3-fpm php8.3-cli php8.3-common

After the upgrade, verify the pin is gone: apt-mark showhold | grep php. Empty output means clean. If you use aptitude, the equivalent is aptitude unhold php8.3-fpm.

RHEL / Alma / Rocky / Fedora

dnf update php*  # or: dnf module reset php && dnf module install php:8.3

On RHEL derivatives, the module stream dictates which minor version you receive. dnf module list php shows the active stream. Switching streams (say from 8.2 to 8.3) requires a reset first, then an install. The reset removes all packages from the old stream, so read the transaction summary carefully before confirming.

Alpine (common in containers)

apk update && apk upgrade php83 php83-fpm php83-ctype php83-curl php83-dom php83-openssl

Alpine packages are split fine-grained. php83 pulls the common dependencies, but extensions are separate packages. List what you actually need: apk info -e php83-* | sort. Upgrade that explicit list rather than a wildcard, so you don't accidentally pull in php83-ldap or php83-snmp if you don't use them.

Docker images

Rebuild from updated base images. Don't just apt upgrade inside a running container.

# Dockerfile
FROM php:8.3-fpm-alpine3.20  # check for newer alpine tag
RUN apk update && apk upgrade && docker-php-ext-install pdo_mysql opcache
docker compose build --pull

The --pull flag forces a fresh base image. Without it you're layering patches on a stale foundation.

If you pin base images by digest ( FROM php:8.3-fpm-alpine3.20@sha256:... ), update the digest in the Dockerfile before building. docker pull php:8.3-fpm-alpine3.20 fetches the latest, then docker inspect php:8.3-fpm-alpine3.20 | jq -r '.[0].RepoDigests[0]' gives you the new digest to pin.

Multi-stage builds that copy vendor/ from a composer stage need the same treatment. The composer stage base image must also be refreshed, otherwise you're installing packages against an old PHP patch level and copying the result forward.

Restart every PHP process

A patched binary on disk does nothing until the old process dies. This is where people miss things.

# Systemd FPM pools
systemctl restart php8.3-fpm
# If you run multiple pools:
systemctl restart php8.3-fpm php8.2-fpm

# Apache with mod_php
systemctl restart apache2

# Nginx + FPM (nginx doesn't run PHP, but restart it anyway for good measure)
systemctl restart nginx

# Docker Compose
docker compose up -d --force-recreate

# Kubernetes
kubectl rollout restart deployment/<your-php-deployment>

Verify the restart picked up the new version:

php -v
# or inside container
docker exec <container> php -v

Check the patch version in the output. If it still shows the old patch number, something didn't restart.

Systemd drop-in units can run multiple pools from one package install. systemctl list-units 'php*-fpm.service' shows each pool as a separate unit ( php8.3-fpm@www.service, php8.3-fpm@api.service ). Restart each one. A single systemctl restart php8.3-fpm only restarts the default pool.

For Kubernetes, rollout restart creates new pods. If your deployment uses maxSurge: 0 and maxUnavailable: 0, the rollout waits for new pods to pass readiness probes before terminating old ones. Watch kubectl rollout status deployment/<name> to confirm completion. If readiness probes hit a PHP endpoint, they'll fail until the new pod's FPM is up, which is the behavior you want.

Reduce exposure while you work

Patching takes time. Reduce the blast radius in the meantime.

Block external access to PHP-FPM status pages

Many pools ship with /status and /ping enabled. If those are reachable from the internet, they leak process info and can be abused.

# In your pool config or nginx location block
location ~ ^/(status|ping)$ {
    access_log off;
    allow 127.0.0.1;
    allow 10.0.0.0/8;  # your VPN / management CIDR
    deny all;
    include fastcgi_params;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}

The same logic applies to the FPM pool configuration itself. In /etc/php/8.3/fpm/pool.d/www.conf (or your pool file), set:

pm.status_path = /status
ping.path = /ping
ping.response = pong

Then restrict those paths in nginx as shown. If you don't need the status page at all, comment out pm.status_path and ping.path in the pool config and reload FPM. Less code exposed, less to worry about.

Disable dangerous functions

If your app doesn't need exec, shell_exec, proc_open, passthru, system, popen, pcntl_exec, disable them in php.ini:

disable_functions = exec,shell_exec,proc_open,passthru,system,popen,pcntl_exec,proc_get_status,proc_nice,proc_terminate

This doesn't fix the vulnerability. It limits what an exploit can do if it lands.

Add pcntl_fork, pcntl_signal, pcntl_alarm to the list if you don't run daemon-style workers. Add ld, dl if you don't load dynamic extensions at runtime. The phpinfo() output shows the current disable_functions value. Confirm it matches your php.ini after restart.

Some applications (Laravel's optimize:clear, Symfony's cache warmers, Composer's run-script hooks) need proc_open or exec during deployment. Keep a separate php-cli.ini with a shorter disable list for CLI, and restrict the FPM pool to the stricter set. The php_admin_value[disable_functions] directive in the pool config overrides the global value for that pool only.

Move admin panels behind VPN or SSH tunnel

If you expose phpMyAdmin, Adminer, or custom admin dashboards directly, stop. Put them behind WireGuard, Tailscale, or an SSH tunnel. If you use SSH Guru, the browser client lets you reach those interfaces from a Chromebook or iPad without opening ports.

The ESP32-S3 bridge dials outbound from your LAN, so the admin panel stays on a private IP ( 192.168.x.x, 10.x.x.x ) with no inbound firewall rules. The browser client connects over WebSocket to the SSH Guru relay, the relay reaches the bridge, and the bridge forwards to the admin panel's local port. Your laptop, phone, or locked-down work machine never touches the public internet to reach it.

Rate-limit PHP endpoints

limit_req_zone $binary_remote_addr zone=php_limit:10m rate=10r/s;

location ~ \.php$ {
    limit_req zone=php_limit burst=20 nodelay;
    # ... fastcgi params
}

Tune the rate to your traffic profile. A public API might need 100r/s. A login endpoint should be far lower ( 5r/s ). Use separate zones per location block so a burst on /login doesn't starve /api/health.

Add limit_req_status 429; to return a proper status code. Monitor the nginx error log for limiting requests entries. A sudden spike suggests either a misconfigured client or someone probing.

Post-patch verification

Don't assume the update worked. Prove it.

1. Confirm the patched version runs

php -r 'echo PHP_VERSION . PHP_EOL;'
# Check each pool
curl -s http://127.0.0.1/status?json | jq .version  # if status page enabled locally

2. Run your test suite

If you have CI, run it against the patched stack. If you don't, at minimum hit the critical paths:

  • Login / authentication
  • File upload (if applicable)
  • API endpoints that accept user input
  • Background workers / queue consumers

Run the test suite in a staging environment that mirrors production (same PHP version, same extensions, same opcache config). If you lack staging, run the tests against a single production pod/container pulled from rotation. docker compose exec php vendor/bin/phpunit or kubectl exec -it <pod> -- vendor/bin/phpunit.

3. Check error logs for new noise

journalctl -u php8.3-fpm --since "1 hour ago" | grep -i error
# or
ls -la /var/log/php*
tail -n 100 /var/log/php8.3-fpm.log

Look for deprecation warnings, missing extensions, or segmentation faults. A patch can expose latent bugs in your code.

Pay attention to PHP Warning: Module 'xyz' already loaded or Unable to load dynamic library. The patch may have upgraded a shared library ( libxml2, openssl, libcurl ) that an extension was compiled against. If an extension fails to load, the function it provides disappears silently until code calls it. Run php -m and compare against your pre-patch module list.

4. Verify opcache cleared

Opcode cache can serve stale bytecode.

php -r 'opcache_reset();'
# or restart FPM (already done)
# Verify
php -r 'var_dump(opcache_get_configuration()["directives"]["opcache.enable"]);'

If you use opcache.validate_timestamps=0 (common in production for performance), the cache never revalidates. A restart is the only way to flush it. The opcache_reset() call only works from the same SAPI. CLI opcache is separate from FPM opcache. Restarting FPM clears FPM's cache. Running php -r 'opcache_reset();' from CLI clears CLI's cache. Do both if you run CLI workers.

5. Scan for webshells

If the vulnerability was exploited before you patched, you may have persistence. Run a quick scan:

# Look for recently modified PHP files in web roots
find /var/www -name '*.php' -mtime -7 -ls

# Common webshell patterns
grep -r "eval\|base64_decode\|gzinflate\|shell_exec\|proc_open" /var/www --include="*.php" | head -20

If you find anything suspicious, treat it as a compromise. Restore from known-good backups, rotate credentials, and investigate laterally.

Extend the scan to writable directories outside the web root: /tmp, /var/tmp, /dev/shm, and any custom upload paths. Attackers often drop a small stager in a writable temp directory, then fetch the real payload. find /tmp -type f -name '*.php' -o -name '*.phtml' -o -name '*.php5' -o -name '*.php7' -o -name '*.php8' 2>/dev/null catches non-standard extensions.

Check for suspicious cron entries: crontab -l for each user, plus /etc/cron.d/, /etc/cron.daily/, and systemd timers (systemctl list-timers --all). A single @reboot line calling a PHP script in /tmp is persistence.

Automate the next one

Manual patching doesn't scale. Set up:

  • Unattended upgrades for security packages only:
    apt install unattended-upgrades
    dpkg-reconfigure -plow unattended-upgrades
    # Edit /etc/apt/apt.conf.d/50unattended-upgrades to allow only security origin
    
  • Container image scanning in CI (Trivy, Grype, or Docker Scout)
  • Watchdog alerts for PHP version drift. A simple cron that emails you if php -v doesn't match your pinned version.
  • Scheduled reboots or rolling restarts for kernel/library updates that need a full restart.

For the watchdog, a five-line script in /etc/cron.daily/check-php-version:

#!/bin/bash
EXPECTED="8.3.14"
ACTUAL=$(php -r 'echo PHP_VERSION;')
if [ "$ACTUAL" != "$EXPECTED" ]; then
    echo "PHP version drift: expected $EXPECTED, got $ACTUAL" | mail -s "PHP version mismatch on $(hostname)" ops@example.com
fi

Make it executable. Point EXPECTED at a version file you control ( /etc/php-target-version ), so updating the target doesn't require editing the script.

For container scanning, Trivy in GitLab CI:

trivy-scan:
  image: aquasec/trivy:latest
  script:
    - trivy image --exit-code 1 --severity HIGH,CRITICAL $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  only:
    - main

Fails the pipeline if the built image contains high/critical CVEs. Run it on every push.

What to tell your team

Write a one-pager:

  1. Which runtimes were patched (versions before/after)
  2. Which services restarted and when
  3. Any exposure reductions applied (VPN gating, disabled functions, rate limits)
  4. Test results, pass/fail per critical path
  5. Open items: EOL migrations, tech debt, missing test coverage

Store it in your ops repo. Next time a CERT advisory drops, you'll know exactly where you stand.


Need to reach your PHP hosts from a locked-down laptop or phone? The SSH Guru browser client connects over an ESP32-S3 bridge without port forwarding, and the AI Guru can help you draft the patch commands for your specific distro. Try it free.

Comments

No comments yet. Be the first.

Leave a comment

Comments appear once the author approves them.