What this is about
A Docker image locks in a specific PHP version at build time. If the image isn't rebuilt, that version stays frozen, even after upstream maintainers have long since released a security patch. This affects not just official images but also custom Dockerfiles that pin a PHP version via a package manager.
The technical challenge is straightforward: you need to read the running PHP version per container and check it against a reference list of known patch levels. The organizational side is harder, because the number of containers tends to grow over time, at which point manual checks stop scaling. This is exactly where automation helps: a collector that regularly queries all containers, a store for the history, and a notification for deviations.
Requirements
Before integrating an audit script into a pipeline, it's worth looking at the requirements. First, the collector needs access to the Docker engine, either through the Unix socket or via the Docker API. Second, you need a reference list of current patch versions per PHP minor release, which you either maintain yourself or source from a trustworthy provider.
Third, you should store state over time rather than just the current snapshot. Without a history, you can't tell how long a container has been vulnerable or whether an update actually took effect. A simple SQLite database is entirely sufficient here and avoids the operational overhead of running an external database server.
Fourth, you need classification logic that decides whether a given version counts as safe or vulnerable. This can be a simple version comparison, or, for more complex cases, a lookup against a CVE list via a local model. Fifth, you need a notification that only fires when the state actually changes, not on every single run.
Comparing your options
There are basically three ways to check PHP versions in containers. The first is a manual script you run as needed, as described in the original case. That works fine for a one-time inventory, but it provides no continuity. As soon as a new container is added or an image is updated, you have to remember to check again yourself.
The second option is a cronjob or systemd timer that runs the script periodically and writes the result to a file. That's already considerably more robust, but it remains reactive: someone still has to read the log file to notice a regression. With five containers that's manageable; with twenty or more it becomes tedious.
The third option integrates the check into an existing watch-and-alert pipeline with a collector, storage, classification, and notification. This approach requires more upfront effort, but it pays off once several checks (PHP version, but also other container metadata) run through the same mechanism. The right choice depends on how many containers you're monitoring and how fast you need to react.
Implementation
The following reference architecture uses a collector that queries the Docker engine over the local socket, stores results in SQLite, runs a simple version classification, and triggers a notification on deviations. The collector runs via a daily systemd timer or cronjob.
"""Collector: prüft PHP-Versionen in laufenden Docker-Containern."""
from __future__ import annotations
import logging
import sqlite3
import subprocess
from dataclasses import dataclass
from pathlib import Path
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("php_audit")
DB_PATH = Path("php_audit.db")
# Beispielhafte Referenzliste gepatchter Minor-Versionen.
# Diese Liste muss regelmäßig von Hand aktualisiert werden.
PATCHED_VERSIONS: dict[str, str] = {
"8.4": "8.4.17",
"8.3": "8.3.32",
"8.2": "8.2.26",
}
@dataclass
class ContainerResult:
name: str
php_version: str | None
vulnerable: bool
def init_db(db_path: Path) -> sqlite3.Connection:
conn = sqlite3.connect(db_path)
conn.execute(
"""
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
container_name TEXT NOT NULL,
php_version TEXT,
vulnerable INTEGER NOT NULL,
checked_at TEXT DEFAULT CURRENT_TIMESTAMP
)
"""
)
conn.commit()
return conn
def list_running_containers() -> list[str]:
result = subprocess.run(
["docker", "ps", "--format", "{{.Names}}"],
capture_output=True,
text=True,
check=True,
)
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
def get_php_version(container: str) -> str | None:
try:
result = subprocess.run(
["docker", "exec", container, "php", "-r", "echo PHP_VERSION;"],
capture_output=True,
text=True,
timeout=10,
check=True,
)
version = result.stdout.strip()
return version or None
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
logger.debug("Kein PHP in Container %s gefunden", container)
return None
def is_vulnerable(version: str) -> bool:
major_minor = ".".join(version.split(".")[:2])
patched = PATCHED_VERSIONS.get(major_minor)
if patched is None:
# Unbekannte Minor-Version: vorsichtig als unklar behandeln.
logger.warning("Keine Referenz für PHP %s hinterlegt", major_minor)
return False
return _version_tuple(version) < _version_tuple(patched)
def _version_tuple(version: str) -> tuple[int, ...]:
return tuple(int(part) for part in version.split("."))
def audit_containers() -> list[ContainerResult]:
results: list[ContainerResult] = []
for name in list_running_containers():
version = get_php_version(name)
if version is None:
continue
vulnerable = is_vulnerable(version)
results.append(ContainerResult(name, version, vulnerable))
return results
def store_results(conn: sqlite3.Connection, results: list[ContainerResult]) -> None:
for r in results:
conn.execute(
"INSERT INTO audit_log (container_name, php_version, vulnerable) "
"VALUES (?, ?, ?)",
(r.name, r.php_version, int(r.vulnerable)),
)
conn.commit()
def notify_if_vulnerable(results: list[ContainerResult]) -> None:
vulnerable = [r for r in results if r.vulnerable]
if not vulnerable:
logger.info("Keine verwundbaren Container gefunden.")
return
lines = [
f"{r.name}: PHP {r.php_version} veraltet" for r in vulnerable
]
message = "PHP-Audit meldet veraltete Versionen:\n" + "\n".join(lines)
logger.warning(message)
# An dieser Stelle würdest du ntfy, Telegram oder E-Mail aufrufen.
# Beispiel: send_ntfy(message) oder send_telegram(message)
def main() -> None:
conn = None
try:
conn = init_db(DB_PATH)
results = audit_containers()
store_results(conn, results)
notify_if_vulnerable(results)
except Exception:
logger.exception("Audit-Lauf fehlgeschlagen")
finally:
if conn is not None:
conn.close()
if __name__ == "__main__":
main()
This collector keeps a clean separation between data collection, storage, and notification. For classification, a simple version comparison is sufficient here. For more complex questions, for example whether a particular PHP module is active, it's worth adding an intermediate step using a local model via Ollama that interprets the context (module list, configuration) before the notification fires.
In practice, the systemd timer for the daily run looks like this: a service unit starts the Python script, and a timer unit triggers it once a day. This is more robust than a classic cronjob because systemd logs failures and lets you configure retries if needed.
Common pitfalls
The biggest pitfall is an outdated reference list. If PATCHED_VERSIONS isn't maintained, the script will eventually report false security because it doesn't know about newer patches. This list belongs in its own configuration file, kept separate from the code and updated independently, ideally with a timestamp for the last review.
Another pitfall is calling docker exec directly without a timeout. If a container is stuck in a broken state, the entire audit run blocks until someone intervenes manually. The timeout parameter in subprocess.run is therefore not cosmetic, it's necessary for the pipeline to run reliably.
Containers without a PHP binary in their path return an error instead of a version. The script has to catch this case explicitly, otherwise a single non-PHP container will abort the entire run. The catch clause for CalledProcessError and TimeoutExpired covers this, but shouldn't be widened into silently swallowing every kind of error.
Finally: notifications shouldn't fire on every run if the state hasn't actually changed. Without comparing against the last stored state, daily alerts quickly become noise, and genuinely new incidents get lost in the flood of repeats.
When this is worth it (and when it isn't)
An automated check is worth setting up once you're running more than a handful of containers with PHP applications that don't all go through the same update mechanism. As soon as images come from different sources, community images, custom Dockerfiles, or older snapshots, the risk increases that a version quietly goes stale without anyone noticing.
For a small setup with just a few centrally managed containers that get rebuilt regularly through a unified deployment system, building a dedicated pipeline probably isn't worth the effort. In that case, an automated image rebuild using an up-to-date base image is often enough.
The effort of building a collector, SQLite storage, and notifications pays off especially if you're already using this kind of infrastructure for other purposes, such as monitoring certificates or services. PHP version checking then becomes just another collector module in an existing pipeline, instead of staying an isolated script that eventually gets forgotten.