php-vuln-check 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
php_vuln_check.py ADDED
@@ -0,0 +1,1563 @@
1
+ #!/usr/bin/env python3
2
+ """php-vuln-check: find PHP installs exposed to known PHP vulnerabilities.
3
+
4
+ Starts with PHP2Shell (CVE-2026-109618 / CVE-2026-109619). Checks servers,
5
+ Docker images, Kubernetes and CI pipelines without sending exploit traffic: it
6
+ reads versions, vendor changelogs and config, and never probes a target into
7
+ failing.
8
+
9
+ Single file, standard library only, Python 3.6+.
10
+ https://github.com/ethoic-inc/php-vuln-check (MIT License)
11
+ """
12
+ import argparse
13
+ import csv
14
+ import datetime
15
+ import glob
16
+ import gzip
17
+ import io
18
+ import json
19
+ import os
20
+ import re
21
+ import shlex
22
+ import signal
23
+ import socket
24
+ import stat
25
+ import subprocess
26
+ import sys
27
+ import threading
28
+ import urllib.error
29
+ import urllib.parse
30
+ import urllib.request
31
+ from concurrent.futures import ThreadPoolExecutor
32
+
33
+ __version__ = "0.2.0"
34
+ REPO_URL = "https://github.com/ethoic-inc/php-vuln-check"
35
+
36
+ VULNERABLE, REVIEW, PATCHED, ERROR, NONE = "VULNERABLE", "REVIEW", "PATCHED", "ERROR", "NONE"
37
+ STATUS_ORDER = {VULNERABLE: 0, ERROR: 1, REVIEW: 2, PATCHED: 3, NONE: 4}
38
+
39
+ # One entry per advisory. Adding the next PHP CVE means adding one dict here.
40
+ ADVISORIES = [
41
+ {
42
+ "id": "PHP2SHELL",
43
+ "name": "PHP2Shell",
44
+ "cves": ["CVE-2026-109618", "CVE-2026-109619"],
45
+ "severity": "critical",
46
+ "cvss": "9.2 (CVSS v4.0)",
47
+ "published": "2026-10-21",
48
+ # PHP's own advisories list only 8.2 to 8.5; Sansec reports exposure back to 5.4 (older branches get no release).
49
+ "min_affected": "5.4.0",
50
+ # 8.6 is not in PHP's advisories: 8.6.0 (2026-11-19) is its first release and contains the fix (php-src 3584a98bda).
51
+ "fixed": {"8.2": "8.2.35", "8.3": "8.3.36", "8.4": "8.4.27", "8.5": "8.5.12", "8.6": "8.6.0"},
52
+ "summary": (
53
+ "Unauthenticated remote code execution in the PHP engine (Apache mod_php "
54
+ "and PHP-FPM), triggered by a fatal error such as running out of memory "
55
+ "while PHP parses a request, for example a multipart/form-data upload."
56
+ ),
57
+ # Ordered as PHP's advisory ranks them: memory_limit=-1 is its primary config mitigation.
58
+ "mitigations": [
59
+ "Update PHP to a fixed release, or to a vendor build whose changelog lists both CVEs, then restart PHP-FPM / Apache.",
60
+ "PHP 7.4, 8.0 and 8.1 are end of life with no release, but PHP published source backports on php-src branches (PHP-7.4-CVE-2026-109618-109619, PHP-8.0-CVE-2026-109618-109619 and PHP-8.1-CVE-2026-109618-109619). Build from them or use a vendor backport; older branches get nothing, so upgrade.",
61
+ "Temporary and partial: enforce memory_limit=-1 in admin config (php.ini or php_admin_value, not .user.ini) and cap request body size at the web server; watch memory use.",
62
+ "Temporary and partial: set session.upload_progress.enabled=0, and on PHP 8.5 also fatal_error_backtraces=0, then restart every worker.",
63
+ "Temporary and partial: if the application takes no uploads, block multipart/form-data requests at the web server.",
64
+ ],
65
+ # Distro builds that fix both CVEs without a new upstream version, from each vendor notice.
66
+ # Used when the package changelog is not installed: Docker's ubuntu and debian images strip /usr/share/doc.
67
+ # Debian's fixes (DSA-6574-1 and the bookworm update) are upstream releases, so the version check covers them.
68
+ "vendor_fixed": {
69
+ "USN-8948-1": {
70
+ "php8.5": ["8.5.9-0ubuntu2.1", "8.5.4-0ubuntu1.5"],
71
+ "php8.3": ["8.3.6-0ubuntu0.24.04.13"],
72
+ "php8.1": ["8.1.2-1ubuntu2.28"],
73
+ },
74
+ },
75
+ "references": [
76
+ {"title": "PHP advisory for CVE-2026-109618", "url": "https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w"},
77
+ {"title": "PHP advisory for CVE-2026-109619", "url": "https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp"},
78
+ {"title": "PHP source backports for 7.4, 8.0 and 8.1", "url": "https://github.com/php/php-src/tree/PHP-8.1-CVE-2026-109618-109619"},
79
+ {"title": "Ubuntu USN-8948-1", "url": "https://ubuntu.com/security/notices/USN-8948-1"},
80
+ {"title": "Sansec research", "url": "https://sansec.io/research/php2shell"},
81
+ {"title": "Help Net Security", "url": "https://www.helpnetsecurity.com/2026/10/21/php2shell-php-vulnerabilities-patched-cve-2026-109618-cve-2026-109619/"},
82
+ {"title": "watchTowr FAQ", "url": "https://watchtowr.com/intelligence/php-cve-2026-109618-faq/"},
83
+ ],
84
+ },
85
+ {
86
+ "id": "PHP85-BACKTRACE",
87
+ "name": "PHP 8.5 backtrace use-after-free",
88
+ "cves": ["CVE-2026-129182"],
89
+ "severity": "critical",
90
+ "cvss": "9.2 (CVSS v4.0)",
91
+ "published": "2026-11-19",
92
+ # Follow-up to CVE-2026-109619: the global was added in 8.5.0, so 8.4 and older are not affected.
93
+ "min_affected": "8.5.0",
94
+ "older_unaffected": True,
95
+ # 8.6.0 contains the fix (php-src 38c29ecfb9), though PHP's advisory lists only 8.5.
96
+ "fixed": {"8.5": "8.5.13", "8.6": "8.6.0"},
97
+ "summary": (
98
+ "Use-after-free in PHP 8.5 when shutdown work recreates the fatal-error backtrace, "
99
+ "which a later request on the same PHP-FPM or mod_php worker can read. A follow-up "
100
+ "to CVE-2026-109619; 8.5.12 does not fix it."
101
+ ),
102
+ "mitigations": [
103
+ "Update PHP 8.5 to 8.5.13 or later (or 8.6), then restart PHP-FPM / Apache.",
104
+ "Temporary: set fatal_error_backtraces=0 in admin config, make sure no request-specific config re-enables it, and restart every worker.",
105
+ ],
106
+ "references": [
107
+ {"title": "PHP advisory for CVE-2026-129182", "url": "https://github.com/php/php-src/security/advisories/GHSA-2fjv-p558-g82m"},
108
+ ],
109
+ },
110
+ ]
111
+ ADVISORIES_BY_ID = {a["id"]: a for a in ADVISORIES}
112
+ # The day ADVISORIES (fixed versions and vendor builds) was last checked against the vendors.
113
+ # Bump it with every data update; reports warn once it is older than STALE_AFTER_DAYS.
114
+ DATA_CHECKED = "2026-12-02"
115
+ STALE_AFTER_DAYS = 30
116
+
117
+ CONFIG_KEYS = ("session.upload_progress.enabled", "memory_limit", "fatal_error_backtraces")
118
+
119
+ # Digit runs are capped at 6 and must end there, so an absurdly long number is rejected rather than truncated.
120
+ VERSION_RE = re.compile(r"^(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?!\d)(.*)$", re.S)
121
+ PRERELEASE_RE = re.compile(r"(?<![A-Za-z])(alpha|beta|rc|dev)(?![A-Za-z])", re.I)
122
+ DASH_V_RE = re.compile(r"^PHP (\d{1,6}\.\d{1,6}\.\d{1,6}(?!\d))(\S*)\s+\(([^)]+)\)")
123
+ STATIC_RE = re.compile(rb"X-Powered-By: PHP/(\d{1,6}\.\d{1,6}\.\d{1,6}(?!\d)[0-9A-Za-z.+~_-]*)")
124
+ HEADER_RE = re.compile(r"PHP/(\d{1,6}\.\d{1,6}\.\d{1,6}(?!\d)[0-9A-Za-z.+~_-]*)")
125
+ CONTROL_RE = re.compile(r"[\x00-\x1f\x7f-\x9f]")
126
+
127
+ MAX_TEXT_FILE = 2 * 1024 * 1024
128
+ BIN = {"dpkg": "/usr/bin/dpkg", "dpkg-query": "/usr/bin/dpkg-query", "rpm": "/usr/bin/rpm"}
129
+
130
+
131
+ # Reason text for a version older than an advisory's affected range (advisories with older_unaffected).
132
+ UNAFFECTED = "is not affected: the bug was introduced in"
133
+
134
+
135
+ def drop_unaffected(findings):
136
+ """Drop 'not affected' findings for a target that another advisory already reports on.
137
+
138
+ With several advisories, a PHP 8.3 install would otherwise show a second PATCHED line for a
139
+ PHP 8.5-only bug. One is kept when it is all a target has, so the target never disappears."""
140
+ def key(f):
141
+ return (f.get("host"), f["kind"], f["target"], json.dumps(f.get("location"), sort_keys=True))
142
+ covered = set(key(f) for f in findings if UNAFFECTED not in (f.get("reason") or ""))
143
+ out, seen = [], set()
144
+ for f in findings:
145
+ if UNAFFECTED in (f.get("reason") or ""):
146
+ if key(f) in covered or key(f) in seen:
147
+ continue
148
+ seen.add(key(f))
149
+ out.append(f)
150
+ return out
151
+
152
+
153
+ class UsageError(Exception):
154
+ """A problem with how the tool was invoked; reported with exit code 3."""
155
+
156
+
157
+ def clean(value, limit=500):
158
+ """Make a value safe to print: no control characters, bounded length."""
159
+ return CONTROL_RE.sub("?", "" if value is None else str(value))[:limit]
160
+
161
+
162
+ # --------------------------------------------------------------------------
163
+ # Version logic
164
+ # --------------------------------------------------------------------------
165
+
166
+ def parse_version(text):
167
+ """'8.2.30-1ubuntu1' -> (8, 2, 30, '-1ubuntu1'); None when unparsable."""
168
+ m = VERSION_RE.match((text or "").strip())
169
+ if not m:
170
+ return None
171
+ return (int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4))
172
+
173
+
174
+ def _tuple(text):
175
+ return tuple(int(p) for p in text.split(".")[:3])
176
+
177
+
178
+ def _branch_data(adv):
179
+ fixed = adv["fixed"]
180
+ newest = max(_tuple(b) for b in fixed)
181
+ floor = _tuple(adv["min_affected"])[:2]
182
+ return fixed, newest, floor
183
+
184
+
185
+ def evaluate(adv, version, backports=None, packaged=False, tail=True):
186
+ """Judge one PHP version against one advisory.
187
+
188
+ backports: the advisory's CVE ids found in the vendor changelog (a set, empty
189
+ when a changelog was read and named none), or None when no changelog was read.
190
+ packaged: the install belongs to a distro package. tail: add a note about
191
+ vendor backports when the version is below the fix.
192
+ Returns (status, reason).
193
+ """
194
+ major, minor, patch, extra = version
195
+ shown = "%d.%d.%d" % (major, minor, patch)
196
+ branch = "%d.%d" % (major, minor)
197
+ if PRERELEASE_RE.search(extra):
198
+ return REVIEW, "%s looks like a pre-release build; compare it with the PHP release notes" % shown
199
+ fixed_map, newest, floor = _branch_data(adv)
200
+ cves = adv["cves"]
201
+ found = [c for c in cves if backports and c in backports]
202
+
203
+ fixed = fixed_map.get(branch)
204
+ if fixed:
205
+ if (major, minor, patch) >= _tuple(fixed):
206
+ if shown == fixed:
207
+ return PATCHED, "%s is the fixed release" % shown
208
+ return PATCHED, "%s is newer than the fixed release %s" % (shown, fixed)
209
+ why = "%s is below the fixed release %s" % (shown, fixed)
210
+ else:
211
+ if (major, minor) > newest:
212
+ return REVIEW, "branch %s is newer than this tool's advisory data; check the PHP release notes" % branch
213
+ if (major, minor) < floor and adv.get("older_unaffected"):
214
+ return PATCHED, "%s %s PHP %s" % (shown, UNAFFECTED, adv["min_affected"].rsplit(".", 1)[0])
215
+ if (major, minor) < floor:
216
+ return REVIEW, "%s is older than the documented affected range (PHP %s+) but long end-of-life; upgrade" % (shown, adv["min_affected"].rsplit(".", 1)[0])
217
+ why = "branch %s is end-of-life and has no upstream release" % branch
218
+
219
+ if len(found) == len(cves):
220
+ return PATCHED, "%s, but the vendor changelog lists fixes for %s" % (why, " and ".join(cves))
221
+ if found:
222
+ return VULNERABLE, "%s; the vendor changelog only mentions %s" % (why, ", ".join(found))
223
+ if backports is not None:
224
+ return VULNERABLE, "%s; no vendor backport found in the changelog" % why
225
+ if packaged:
226
+ return REVIEW, ("%s; the vendor changelog could not be read here, so a backport cannot be "
227
+ "ruled out (check the vendor's security advisory)" % why)
228
+ if not tail:
229
+ return VULNERABLE, why
230
+ return VULNERABLE, "%s; not installed from a distro package, so no vendor backport applies" % why
231
+
232
+
233
+ def evaluate_branch_only(adv, major, minor):
234
+ """Judge a floating tag such as php:8.3-apache where the patch level is unknown."""
235
+ fixed_map, newest, floor = _branch_data(adv)
236
+ branch = "%d.%d" % (major, minor)
237
+ if branch in fixed_map:
238
+ return REVIEW, (
239
+ "floating tag: resolves to the newest %s.x at pull time. Pin it to %s or later "
240
+ "and rebuild with --pull" % (branch, fixed_map[branch])
241
+ )
242
+ if (major, minor) > newest:
243
+ return REVIEW, "branch %s is newer than this tool's advisory data" % branch
244
+ if (major, minor) < floor and adv.get("older_unaffected"):
245
+ return PATCHED, "branch %s %s PHP %s" % (branch, UNAFFECTED, adv["min_affected"].rsplit(".", 1)[0])
246
+ if (major, minor) < floor:
247
+ return REVIEW, "branch %s is older than the documented affected range but long end-of-life; upgrade" % branch
248
+ return VULNERABLE, "branch %s is end-of-life with no upstream release; pulling a newer image on this branch cannot fix it" % branch
249
+
250
+
251
+ def package_upstream_version(pkg_version):
252
+ """'1:8.2.30+dfsg-1~deb12u1' -> '8.2.30+dfsg-1~deb12u1' (epoch dropped)."""
253
+ return re.sub(r"^\d+:", "", pkg_version or "")
254
+
255
+
256
+ # --------------------------------------------------------------------------
257
+ # Running commands and reading the host
258
+ # --------------------------------------------------------------------------
259
+
260
+ def _drain(pipe, sink, cap):
261
+ kept = 0
262
+ try:
263
+ while True:
264
+ chunk = pipe.read(65536)
265
+ if not chunk:
266
+ break
267
+ if kept < cap:
268
+ sink.append(chunk[:cap - kept])
269
+ kept += len(chunk)
270
+ except (OSError, ValueError):
271
+ pass
272
+
273
+
274
+ def _feed(pipe, data):
275
+ try:
276
+ pipe.write(data)
277
+ except (OSError, ValueError):
278
+ pass
279
+ finally:
280
+ try:
281
+ pipe.close()
282
+ except (OSError, ValueError):
283
+ pass
284
+
285
+
286
+ def run(cmd, timeout=20, stdin=None, cap=8 * 1024 * 1024):
287
+ """Run a command with no terminal input, a capped output and a hard timeout.
288
+
289
+ The child gets its own session so a timeout kills grandchildren too.
290
+ Returns (exit_code, stdout, stderr); exit_code is None on failure or timeout.
291
+ """
292
+ try:
293
+ proc = subprocess.Popen(
294
+ cmd, stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
295
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
296
+ except (OSError, ValueError) as exc:
297
+ return None, "", str(exc)
298
+ out, err = [], []
299
+ threads = [threading.Thread(target=_drain, args=(proc.stdout, out, cap), daemon=True),
300
+ threading.Thread(target=_drain, args=(proc.stderr, err, 65536), daemon=True)]
301
+ if stdin is not None:
302
+ threads.append(threading.Thread(target=_feed, args=(proc.stdin, stdin.encode("utf-8")), daemon=True))
303
+ for t in threads:
304
+ t.start()
305
+ code = None
306
+ try:
307
+ code = proc.wait(timeout=timeout)
308
+ except subprocess.TimeoutExpired:
309
+ try:
310
+ os.killpg(proc.pid, signal.SIGKILL)
311
+ except OSError:
312
+ proc.kill()
313
+ proc.wait()
314
+ err.append(b"timed out")
315
+ for t in threads:
316
+ t.join(timeout=2)
317
+ for pipe in (proc.stdout, proc.stderr):
318
+ try:
319
+ pipe.close()
320
+ except (OSError, ValueError):
321
+ pass
322
+ return (code, b"".join(out).decode("utf-8", "replace"), b"".join(err).decode("utf-8", "replace"))
323
+
324
+
325
+ def exec_allowed(path):
326
+ """May we run this binary? Only if it and every parent directory belong to root
327
+ (or to us) and are not writable by group or others."""
328
+ try:
329
+ me = os.geteuid()
330
+ current = os.path.realpath(path)
331
+ while True:
332
+ st = os.stat(current)
333
+ if st.st_uid not in (0, me) or st.st_mode & 0o022:
334
+ return False
335
+ parent = os.path.dirname(current)
336
+ if parent == current:
337
+ return True
338
+ current = parent
339
+ except OSError:
340
+ return False
341
+
342
+
343
+ def static_version(path, limit=512 * 1024 * 1024):
344
+ """Read the version PHP embeds in its own binary, without running it."""
345
+ read, tail = 0, b""
346
+ try:
347
+ with open(path, "rb") as fh:
348
+ while read < limit:
349
+ chunk = fh.read(8 * 1024 * 1024)
350
+ if not chunk:
351
+ break
352
+ read += len(chunk)
353
+ window = tail + chunk
354
+ m = STATIC_RE.search(window)
355
+ if m and m.end() < len(window):
356
+ return m.group(1).decode("ascii", "replace")
357
+ # A match touching the end of the window may be cut short: keep it for the next read.
358
+ tail = window[m.start():] if m else window[-256:]
359
+ if tail:
360
+ m = STATIC_RE.search(tail)
361
+ if m:
362
+ return m.group(1).decode("ascii", "replace")
363
+ except OSError:
364
+ return None
365
+ return None
366
+
367
+
368
+ def php_dash_v(path):
369
+ """Run `php -n -v`; return (version_text, sapi) or (None, None)."""
370
+ code, out, _ = run([path, "-n", "-v"], timeout=15, cap=65536)
371
+ if code != 0 or not out:
372
+ return None, None
373
+ m = DASH_V_RE.match(out.splitlines()[0])
374
+ if not m:
375
+ return None, None
376
+ return m.group(1) + m.group(2), m.group(3)
377
+
378
+
379
+ def parse_ini_dump(text):
380
+ values = {}
381
+ for key in CONFIG_KEYS:
382
+ m = re.search(r"^%s\s*=>\s*([0-9A-Za-z_.-]{1,32})" % re.escape(key), text, re.M)
383
+ if m:
384
+ values[key] = m.group(1)
385
+ return values
386
+
387
+
388
+ def php_config(path):
389
+ code, out, _ = run([path, "-i"], timeout=30, cap=8 * 1024 * 1024)
390
+ return parse_ini_dump(out) if code == 0 else {}
391
+
392
+
393
+ POOL_SECTION_RE = re.compile(r"^\s*\[([^\]]{1,64})\]\s*$")
394
+ POOL_VALUE_RE = re.compile(r"^\s*php(?:_admin)?_(?:value|flag)\[([\w.]{1,64})\]\s*=\s*['\"]?([0-9A-Za-z_.-]{1,32})['\"]?\s*$")
395
+ FPM_INCLUDE_RE = re.compile(r"^\s*include\s*=\s*(\S+)\s*$")
396
+
397
+
398
+ def fpm_main_config(path):
399
+ """The php-fpm.conf this binary reads by packaging convention.
400
+
401
+ shortcut: follows the packaging layout only, not a custom -y/--fpm-config; add a --fpm-config
402
+ option if users report pools it misses.
403
+ """
404
+ m = re.match(r"^php-fpm(\d+\.\d+)$", os.path.basename(path))
405
+ if m: # Debian, Ubuntu and Sury: /usr/sbin/php-fpm8.3
406
+ return "/etc/php/%s/fpm/php-fpm.conf" % m.group(1)
407
+ prefix = os.path.dirname(os.path.dirname(path)) # <root>/usr/sbin/php-fpm -> <root>/usr
408
+ if prefix.endswith("/usr"):
409
+ prefix = prefix[:-len("/usr")] # RHEL, Remi and cPanel keep etc/ beside usr/
410
+ return os.path.join(prefix or "/", "etc", "php-fpm.conf")
411
+
412
+
413
+ def fpm_pool_overrides(path, max_files=200):
414
+ """Pool-level php_value / php_admin_value settings for CONFIG_KEYS, which `php -i` cannot see.
415
+
416
+ Returns {"pool www: memory_limit": "-1"}. Includes are resolved relative to the FPM prefix
417
+ (the folder above etc/), as php-fpm does.
418
+ """
419
+ main = fpm_main_config(path)
420
+ prefix = os.path.dirname(os.path.dirname(main))
421
+ files, values, pending = [], {}, [main]
422
+ while pending and len(files) < max_files:
423
+ conf = pending.pop(0)
424
+ if conf in files:
425
+ continue
426
+ text, _ = read_text_file(conf, limit=1024 * 1024)
427
+ if text is None:
428
+ continue
429
+ files.append(conf)
430
+ pool = None
431
+ for line in text.splitlines():
432
+ m = POOL_SECTION_RE.match(line)
433
+ if m:
434
+ pool = m.group(1)
435
+ continue
436
+ m = FPM_INCLUDE_RE.match(line)
437
+ if m:
438
+ pattern = m.group(1).replace("${prefix}", prefix).replace("$prefix", prefix)
439
+ pending.extend(sorted(glob.glob(os.path.join(prefix, pattern)))[:max_files])
440
+ continue
441
+ m = POOL_VALUE_RE.match(line)
442
+ if m and pool and pool != "global" and m.group(1) in CONFIG_KEYS:
443
+ values["pool %s: %s" % (pool, m.group(1))] = m.group(2)
444
+ return values
445
+
446
+
447
+ def guess_sapi(path):
448
+ name = os.path.basename(path).lower()
449
+ if "fpm" in name:
450
+ return "fpm-fcgi"
451
+ if "cgi" in name:
452
+ return "cgi-fcgi"
453
+ if name.startswith("lsphp"):
454
+ return "litespeed"
455
+ return None
456
+
457
+
458
+ def _dpkg_owner(path):
459
+ if not os.path.exists(BIN["dpkg"]):
460
+ return None
461
+ code, out, _ = run([BIN["dpkg"], "-S", path])
462
+ if code != 0:
463
+ return None
464
+ line = next((l for l in out.splitlines() if l.strip() and not l.startswith("diversion by")), "")
465
+ if ": " not in line:
466
+ return None
467
+ pkg = line.rsplit(": ", 1)[0].split(",")[0].strip().split(":")[0]
468
+ if not pkg:
469
+ return None
470
+ lines = []
471
+ if os.path.exists(BIN["dpkg-query"]):
472
+ code, info, _ = run([BIN["dpkg-query"], "-W", "-f", "${Version}\n${source:Package}\n", pkg])
473
+ lines = info.splitlines() if code == 0 else []
474
+ return {
475
+ "manager": "dpkg", "name": pkg,
476
+ "version": lines[0] if lines else "",
477
+ "source": lines[1] if len(lines) > 1 else "",
478
+ }
479
+
480
+
481
+ def _rpm_owner(path):
482
+ if not os.path.exists(BIN["rpm"]):
483
+ return None
484
+ code, out, _ = run([BIN["rpm"], "-qf", "--qf", "%{NAME}\t%{VERSION}-%{RELEASE}\n", path])
485
+ if code != 0 or "\t" not in out:
486
+ return None
487
+ name, version = out.splitlines()[0].split("\t", 1)
488
+ return {"manager": "rpm", "name": name, "version": version, "source": ""}
489
+
490
+
491
+ def package_owner(path):
492
+ """Which distro package owns this file? Tries dpkg, then rpm."""
493
+ for probe in (_dpkg_owner, _rpm_owner):
494
+ for candidate in dict.fromkeys([path, os.path.realpath(path)]):
495
+ info = probe(candidate)
496
+ if info:
497
+ return info
498
+ return None
499
+
500
+
501
+ def read_text_file(path, limit=MAX_TEXT_FILE):
502
+ """Read a regular text file of at most `limit` bytes. Returns (text, problem)."""
503
+ try:
504
+ if not stat.S_ISREG(os.stat(path).st_mode):
505
+ return None, "not a regular file"
506
+ with io.open(path, "rb") as fh:
507
+ data = fh.read(limit + 1)
508
+ except OSError as exc:
509
+ return None, "cannot read it (%s)" % (exc.strerror or exc)
510
+ if len(data) > limit:
511
+ return None, "larger than %d MiB" % (limit // (1024 * 1024))
512
+ return data.decode("utf-8-sig", "replace"), None
513
+
514
+
515
+ def _read_gz_or_text(path, limit=20 * 1024 * 1024):
516
+ try:
517
+ if path.endswith(".gz"):
518
+ with gzip.open(path, "rb") as fh:
519
+ data = fh.read(limit)
520
+ else:
521
+ with io.open(path, "rb") as fh:
522
+ data = fh.read(limit)
523
+ except (OSError, EOFError):
524
+ return None
525
+ return data.decode("utf-8", "replace")
526
+
527
+
528
+ # A changelog line that names a CVE only counts as a fix when it is not saying the opposite.
529
+ NEGATIVE_RE = re.compile(
530
+ r"revert|not affected|unaffected|not vulnerable|pending|todo|not yet|postpone|"
531
+ r"wont ?fix|won't fix|ignore|\bdrop|\bskip", re.I)
532
+
533
+
534
+ def cves_named_in(text, cves):
535
+ """The subset of `cves` that a changelog names on a line that reads like a fix."""
536
+ found = set()
537
+ lines = text.splitlines()
538
+ for cve in cves:
539
+ pattern = re.compile(r"(?<![\w-])%s(?!\d)" % re.escape(cve))
540
+ for line in lines:
541
+ if len(line) < 2000 and pattern.search(line) and not NEGATIVE_RE.search(line):
542
+ found.add(cve)
543
+ break
544
+ return found
545
+
546
+
547
+ def dpkg_changelog(owner, doc_root="/usr/share/doc"):
548
+ names = [owner["name"], owner.get("source") or "",
549
+ re.sub(r"-[a-z0-9]+$", "-common", owner["name"])]
550
+ for name in dict.fromkeys(n for n in names if n):
551
+ for fname in ("changelog.Debian.gz", "changelog.gz", "changelog"):
552
+ text = _read_gz_or_text(os.path.join(doc_root, name, fname))
553
+ if text:
554
+ return text
555
+ return None
556
+
557
+
558
+ def vendor_changelog(owner, path, cves):
559
+ """Return the set of `cves` the owning package's changelog names as fixed, or None."""
560
+ if owner["manager"] == "dpkg":
561
+ text = dpkg_changelog(owner)
562
+ else:
563
+ code, out, _ = run([BIN["rpm"], "-qf", path, "--changelog"], timeout=90)
564
+ text = out if code == 0 else None
565
+ if not text:
566
+ return None
567
+ return cves_named_in(text, cves)
568
+
569
+
570
+ def vendor_fixed_build(adv, owner):
571
+ """(status, reason) from the advisory's list of fixed distro builds, or None without evidence.
572
+
573
+ A fixed build only speaks for installs of the same build line: 8.3.6-0ubuntu0.24.04.13 says
574
+ nothing about a Sury 8.3.6-1+ubuntu24.04.1 or about 8.5.9-0ubuntu2 versus 8.5.4-0ubuntu1.5.
575
+ """
576
+ if owner["manager"] != "dpkg" or not owner.get("version"):
577
+ return None
578
+ m = re.search(r"php\d+\.\d+", owner.get("source") or owner["name"])
579
+ installed = package_upstream_version(owner["version"])
580
+ for notice, builds in sorted(adv.get("vendor_fixed", {}).items()):
581
+ for build in builds.get(m.group(0) if m else "", []):
582
+ if not installed.startswith(build.rstrip("0123456789")):
583
+ continue
584
+ code, _, _ = run([BIN["dpkg"], "--compare-versions", installed, "ge", build])
585
+ shown = "package %s %s" % (owner["name"], installed)
586
+ if code == 0:
587
+ return PATCHED, "%s is at or above %s, the fixed build in %s" % (shown, build, notice)
588
+ if code == 1:
589
+ return VULNERABLE, "%s is below %s, the fixed build in %s" % (shown, build, notice)
590
+ return None
591
+
592
+
593
+ def stale_processes(proc_root="/proc"):
594
+ """Running processes that still use a replaced PHP file: {realpath: [pids]}.
595
+
596
+ A package update fixes the files on disk, but PHP-FPM and Apache keep running
597
+ the old code until restarted. Linux only; needs root to see other users' processes.
598
+ """
599
+ stale = {}
600
+ try:
601
+ entries = os.listdir(proc_root)
602
+ except OSError:
603
+ return stale
604
+ for name in entries:
605
+ if not name.isdigit():
606
+ continue
607
+ base = os.path.join(proc_root, name)
608
+ try:
609
+ exe = os.readlink(os.path.join(base, "exe"))
610
+ except OSError:
611
+ continue
612
+ if exe.endswith(" (deleted)"):
613
+ old = exe[:-len(" (deleted)")]
614
+ if BIN_NAME_RE.match(os.path.basename(old)):
615
+ stale.setdefault(os.path.realpath(old), []).append(int(name))
616
+ if os.path.basename(exe).lower().startswith(("apache2", "httpd")):
617
+ try:
618
+ with io.open(os.path.join(base, "maps"), "r", errors="replace") as fh:
619
+ for line in fh:
620
+ parts = line.rstrip("\n").split(None, 5)
621
+ if len(parts) == 6 and parts[5].endswith(" (deleted)"):
622
+ old = parts[5][:-len(" (deleted)")]
623
+ if LIBPHP_RE.match(os.path.basename(old)):
624
+ pids = stale.setdefault(os.path.realpath(old), [])
625
+ if int(name) not in pids:
626
+ pids.append(int(name))
627
+ except OSError:
628
+ continue
629
+ return stale
630
+
631
+
632
+ # --------------------------------------------------------------------------
633
+ # Finding model
634
+ # --------------------------------------------------------------------------
635
+
636
+ def fixed_in(adv, version):
637
+ """The release that fixes this branch, or the list of fixed releases when it is unknown."""
638
+ fixed = adv["fixed"]
639
+ parts = (version or "").split(".")
640
+ if len(parts) >= 2 and parts[0].isdigit() and parts[1].isdigit():
641
+ branch = ".".join(parts[:2])
642
+ if branch in fixed:
643
+ return fixed[branch]
644
+ oldest = min(fixed, key=_tuple)
645
+ if (int(parts[0]), int(parts[1])) < _tuple(oldest)[:2]:
646
+ return "no upstream release; move to %s or later, or use a vendor backport" % fixed[oldest]
647
+ return ", ".join(fixed[b] for b in sorted(fixed, key=_tuple))
648
+
649
+
650
+ def make_finding(adv, kind, target, status, reason, **extra):
651
+ finding = {
652
+ "advisory": adv["id"], "host": None, "kind": kind, "target": target,
653
+ "status": status, "reason": reason, "sapi": None, "version": None,
654
+ "package": None, "confidence": None, "config": {}, "location": None,
655
+ }
656
+ finding.update(extra)
657
+ finding["fixed_in"] = fixed_in(adv, finding["version"])
658
+ return finding
659
+
660
+
661
+ def error_finding(adv, kind, target, reason, **extra):
662
+ return make_finding(adv, kind, target, ERROR, reason, **extra)
663
+
664
+
665
+ # --------------------------------------------------------------------------
666
+ # scan: a server's own PHP installs
667
+ # --------------------------------------------------------------------------
668
+
669
+ # php, php8.2, php5-fpm, php-fpm8.2, php-cgi, lsphp83 ... but not php-config or phpize
670
+ BIN_NAME_RE = re.compile(r"^(?:lsphp[0-9.]*|php[0-9.]*(?:-(?:fpm|cgi)[0-9.]*)?)$")
671
+ LIBPHP_RE = re.compile(r"^libphp[0-9.\-]*\.so$")
672
+ REAL_NAME_RE = re.compile(r"^(?:lsphp|php|libphp)")
673
+ SKIP_DIRS = {".git", "node_modules", ".venv"}
674
+ PSEUDO_FS = ("proc", "sys", "dev", "run")
675
+
676
+ STD_BIN_DIRS = ["/usr/bin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin", "/bin", "/sbin",
677
+ "/opt/homebrew/bin"]
678
+ GLOB_BIN_DIRS = [
679
+ "/opt/remi/php*/root/usr/bin", "/opt/remi/php*/root/usr/sbin",
680
+ "/opt/plesk/php/*/bin", "/opt/plesk/php/*/sbin",
681
+ "/opt/cpanel/ea-php*/root/usr/bin", "/opt/cpanel/ea-php*/root/usr/sbin",
682
+ "/opt/alt/php*/usr/bin", "/opt/alt/php*/usr/sbin",
683
+ "/usr/local/php*/bin", "/usr/local/php*/sbin", "/opt/php*/bin", "/opt/php*/sbin",
684
+ "/usr/local/lsws/lsphp*/bin", "/opt/homebrew/opt/php*/bin", "/opt/homebrew/opt/php*/sbin",
685
+ ]
686
+ GLOB_MODULE_DIRS = [
687
+ "/usr/lib/apache2/modules", "/usr/lib64/httpd/modules", "/usr/lib/httpd/modules",
688
+ "/usr/libexec/apache2", "/usr/local/apache2/modules",
689
+ "/opt/homebrew/opt/php*/lib/httpd/modules", "/usr/local/opt/php*/lib/httpd/modules",
690
+ ]
691
+
692
+
693
+ def _consider(path, seen, found):
694
+ name = os.path.basename(path)
695
+ kind = "mod_php" if LIBPHP_RE.match(name) else "binary" if BIN_NAME_RE.match(name) else None
696
+ if not kind:
697
+ return
698
+ real = os.path.realpath(path)
699
+ if real in seen or not os.path.isfile(real):
700
+ return
701
+ # The link's name matched, but what it points at must still look like PHP: a file called
702
+ # "php" that is really a symlink to /bin/sh must not be treated as (or run as) PHP.
703
+ if not REAL_NAME_RE.match(os.path.basename(real)):
704
+ return
705
+ seen.add(real)
706
+ found.append((real, kind))
707
+
708
+
709
+ def _scan_dir(directory, seen, found):
710
+ try:
711
+ names = sorted(os.listdir(directory))
712
+ except OSError:
713
+ return
714
+ for name in names:
715
+ _consider(os.path.join(directory, name), seen, found)
716
+
717
+
718
+ def discover(extra_paths=(), defaults=True):
719
+ seen, found = set(), []
720
+ if defaults:
721
+ dirs = list(STD_BIN_DIRS)
722
+ for pattern in GLOB_BIN_DIRS + GLOB_MODULE_DIRS:
723
+ dirs.extend(sorted(glob.glob(pattern)))
724
+ dirs.extend(p for p in os.environ.get("PATH", "").split(os.pathsep) if p and os.path.isabs(p))
725
+ for directory in dict.fromkeys(dirs):
726
+ _scan_dir(directory, seen, found)
727
+ for root in extra_paths:
728
+ if os.path.isfile(root):
729
+ real = os.path.realpath(root)
730
+ if real not in seen:
731
+ seen.add(real)
732
+ found.append((real, "mod_php" if LIBPHP_RE.match(os.path.basename(real)) else "binary"))
733
+ continue
734
+ base_depth = root.rstrip(os.sep).count(os.sep)
735
+ for dirpath, dirnames, filenames in os.walk(root):
736
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS
737
+ and not (dirpath == os.sep and d in PSEUDO_FS)]
738
+ if dirpath.count(os.sep) - base_depth >= 6:
739
+ dirnames[:] = []
740
+ for fname in sorted(filenames):
741
+ _consider(os.path.join(dirpath, fname), seen, found)
742
+ return found
743
+
744
+
745
+ def inspect_target(path, kind, exec_mode, advisories, stale=None):
746
+ """exec_mode: 'auto' runs only trusted binaries, 'always' runs any, 'never' runs none."""
747
+ stale = stale or {}
748
+ owner = package_owner(path)
749
+ sapi = "apache2handler" if kind == "mod_php" else None
750
+ version_text, method, config = None, None, {}
751
+
752
+ run_it = kind == "binary" and (exec_mode == "always" or (exec_mode == "auto" and exec_allowed(path)))
753
+ refused = kind == "binary" and exec_mode == "auto" and not run_it
754
+ if run_it:
755
+ version_text, sapi_out = php_dash_v(path)
756
+ if version_text:
757
+ method, sapi = "exec", sapi_out
758
+ config = php_config(path)
759
+ if not version_text:
760
+ version_text = static_version(path)
761
+ method = "static" if version_text else None
762
+ if not version_text and owner and owner["version"]:
763
+ version_text = package_upstream_version(owner["version"])
764
+ method = "package"
765
+ if not sapi and kind == "binary":
766
+ sapi = guess_sapi(path)
767
+ if kind == "binary" and "fpm" in os.path.basename(path).lower():
768
+ config.update(fpm_pool_overrides(path))
769
+
770
+ version = parse_version(version_text) if version_text else None
771
+ package = "%s %s" % (owner["name"], owner["version"]) if owner else None
772
+ confidence = {"exec": "high", "static": "high", "package": "medium"}.get(method)
773
+
774
+ findings = []
775
+ for adv in advisories:
776
+ if version is None:
777
+ status = REVIEW
778
+ reason = "could not determine the PHP version"
779
+ if refused:
780
+ reason += " (the binary was not run because it or a parent folder is not root-owned or is writable by others; use --exec to allow it)"
781
+ elif exec_mode == "never":
782
+ reason += " (try again without --no-exec)"
783
+ else:
784
+ status, reason = evaluate(adv, version, None, packaged=bool(owner))
785
+ if owner and evaluate(adv, version, set(), packaged=True)[0] == VULNERABLE:
786
+ status, reason = evaluate(adv, version, vendor_changelog(owner, path, adv["cves"]), packaged=True)
787
+ if status != PATCHED:
788
+ status, reason = vendor_fixed_build(adv, owner) or (status, reason)
789
+ if status == PATCHED and stale.get(path):
790
+ pids = ", ".join(str(p) for p in sorted(stale[path])[:5])
791
+ status = REVIEW
792
+ reason += ("; but running processes (pid %s) still use the old file, so restart "
793
+ "PHP-FPM / Apache to load the fix" % pids)
794
+ findings.append(make_finding(
795
+ adv, kind, path, status, reason, sapi=sapi, package=package, config=config,
796
+ version="%d.%d.%d" % version[:3] if version else None, confidence=confidence,
797
+ host=socket.gethostname(),
798
+ ))
799
+ return findings
800
+
801
+
802
+ def _require_paths(paths):
803
+ for p in paths or []:
804
+ if not os.path.exists(p):
805
+ raise UsageError("path does not exist: %s" % p)
806
+
807
+
808
+ def cmd_scan(args, advisories):
809
+ _require_paths(args.path)
810
+ exec_mode = "never" if args.no_exec else "always" if args.exec else "auto"
811
+ targets = discover(args.path or [], defaults=not args.no_defaults)
812
+ stale = stale_processes()
813
+ findings = []
814
+ for path, kind in targets:
815
+ findings.extend(inspect_target(path, kind, exec_mode, advisories, stale))
816
+ notes = []
817
+ if not targets:
818
+ notes.append("No PHP binaries or Apache mod_php modules were found in the searched locations. "
819
+ "PHP in a custom prefix, a container or a vhost folder will not appear: use --path DIR.")
820
+ return findings, notes
821
+
822
+
823
+ # --------------------------------------------------------------------------
824
+ # images: Dockerfiles, compose files, Kubernetes manifests, running containers
825
+ # --------------------------------------------------------------------------
826
+
827
+ FROM_RE = re.compile(r"^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?", re.I)
828
+ COPY_FROM_RE = re.compile(r"^\s*COPY\s+(?:--\S+\s+)*?--from=(\S+)", re.I)
829
+ ARG_RE = re.compile(r"^\s*ARG\s+([A-Za-z_]\w*)(?:=(.*))?\s*$")
830
+ YAML_IMAGE_RE = re.compile(r"^[ \t]*(?:-[ \t]+)?image:[ \t]*['\"]?([^\s'\"#]+)")
831
+ JSON_IMAGE_RE = re.compile(r'"image"\s*:\s*"([^"\s]+)"')
832
+ VAR_RE = re.compile(r"\$\{(\w+)(?::?-([^}]*))?\}|\$(\w+)")
833
+ TAG_VERSION_RE = re.compile(r"^(\d{1,6})(?!\d)(?:\.(\d{1,6})(?!\d))?(?:\.(\d{1,6})(?!\d))?(.*)$", re.S)
834
+ BUNDLED_RE = re.compile(r"php(\d{1,6})\.(\d{1,6})(?!\d)(?:\.(\d{1,6})(?!\d))?")
835
+ OFFICIAL_PHP = {"php", "library/php", "docker.io/library/php", "index.docker.io/library/php",
836
+ "registry.hub.docker.com/library/php"}
837
+ PHP_IMAGE_NAMES = {"php", "php-fpm", "php-cli", "php-apache", "php-nginx", "php-fpm-nginx"}
838
+ IMAGE_SKIP_DIRS = {".git", "node_modules", ".venv", "vendor", "__pycache__"}
839
+ MAX_LINE = 20000
840
+
841
+
842
+ def substitute(text, variables):
843
+ """Expand $VAR and ${VAR:-default}. Returns (text, used) where `used` says a
844
+ variable or a default decided part of the result."""
845
+ used = []
846
+
847
+ def repl(m):
848
+ name = m.group(1) or m.group(3)
849
+ if name in variables:
850
+ used.append(name)
851
+ return variables[name]
852
+ if m.group(2) is not None:
853
+ used.append(name)
854
+ return m.group(2)
855
+ return m.group(0)
856
+ return VAR_RE.sub(repl, text), bool(used)
857
+
858
+
859
+ def parse_image(ref):
860
+ digest = None
861
+ if "@" in ref:
862
+ ref, digest = ref.split("@", 1)
863
+ tag = None
864
+ last = ref.rsplit("/", 1)[-1]
865
+ if ":" in last:
866
+ cut = ref.rfind(":")
867
+ ref, tag = ref[:cut], ref[cut + 1:]
868
+ return ref, tag, digest
869
+
870
+
871
+ def _is_dockerfile(fname):
872
+ low = fname.lower()
873
+ return (low.startswith(("dockerfile", "containerfile"))
874
+ or low.endswith((".dockerfile", ".containerfile")))
875
+
876
+
877
+ def _logical_lines(text):
878
+ """Dockerfile lines with backslash continuations joined; yields (first_line_number, text)."""
879
+ pending, start = "", 0
880
+ for number, line in enumerate(text.splitlines(), 1):
881
+ if len(line) > MAX_LINE:
882
+ line = line[:MAX_LINE]
883
+ if not pending:
884
+ start = number
885
+ stripped = line.rstrip()
886
+ if stripped.endswith("\\"):
887
+ pending += stripped[:-1] + " "
888
+ continue
889
+ yield start, pending + line
890
+ pending = ""
891
+ if pending:
892
+ yield start, pending
893
+
894
+
895
+ def _dockerfile_refs(text):
896
+ global_args, stages, seen_from = {}, set(), False
897
+ for number, line in _logical_lines(text):
898
+ if line.lstrip().startswith("#"):
899
+ continue
900
+ arg = ARG_RE.match(line)
901
+ if arg:
902
+ if not seen_from and arg.group(2) is not None:
903
+ global_args[arg.group(1)] = arg.group(2).strip().strip("'\"")
904
+ continue
905
+ m = FROM_RE.match(line)
906
+ if m:
907
+ seen_from = True
908
+ ref, derived = substitute(m.group(1), global_args)
909
+ if m.group(2):
910
+ stages.add(m.group(2).lower())
911
+ if ref.lower() != "scratch" and ref.lower() not in stages:
912
+ yield number, ref, derived
913
+ continue
914
+ m = COPY_FROM_RE.match(line)
915
+ if m and not m.group(1).isdigit() and m.group(1).lower() not in stages:
916
+ ref, derived = substitute(m.group(1), global_args)
917
+ yield number, ref, derived
918
+
919
+
920
+ def _file_image_refs(path, text, as_yaml=None):
921
+ """Yield (line_number, ref, derived) for each image reference in one file's text."""
922
+ low = path.lower()
923
+ if as_yaml is None:
924
+ as_yaml = low.endswith((".yml", ".yaml"))
925
+ if low.endswith(".json"):
926
+ for number, line in enumerate(text.splitlines(), 1):
927
+ for m in JSON_IMAGE_RE.finditer(line[:MAX_LINE]):
928
+ ref, derived = substitute(m.group(1), {})
929
+ yield number, ref, derived
930
+ elif as_yaml:
931
+ for number, line in enumerate(text.splitlines(), 1):
932
+ m = YAML_IMAGE_RE.match(line[:MAX_LINE])
933
+ if m:
934
+ ref, derived = substitute(m.group(1), {})
935
+ yield number, ref, derived
936
+ else:
937
+ for item in _dockerfile_refs(text):
938
+ yield item
939
+
940
+
941
+ def collect_image_refs(roots, problems):
942
+ """Yield (path, line, ref, derived). Files that could not be read are appended to
943
+ `problems` as (path, message, important)."""
944
+ for root in roots:
945
+ if not os.path.isdir(root):
946
+ text, problem = read_text_file(root)
947
+ if problem:
948
+ problems.append((root, problem, True))
949
+ continue
950
+ for number, ref, derived in _file_image_refs(root, text):
951
+ yield root, number, ref, derived
952
+ continue
953
+ onerror = lambda exc: problems.append((exc.filename, "cannot read it (%s)" % (exc.strerror or exc), True))
954
+ for dirpath, dirnames, filenames in os.walk(root, onerror=onerror):
955
+ dirnames[:] = sorted(d for d in dirnames if d not in IMAGE_SKIP_DIRS)
956
+ for fname in sorted(filenames):
957
+ path = os.path.join(dirpath, fname)
958
+ is_docker = _is_dockerfile(fname)
959
+ if not (is_docker or fname.lower().endswith((".yml", ".yaml"))):
960
+ continue
961
+ text, problem = read_text_file(path)
962
+ if problem:
963
+ problems.append((path, problem, is_docker))
964
+ continue
965
+ for number, ref, derived in _file_image_refs(path, text):
966
+ yield path, number, ref, derived
967
+
968
+
969
+ def _opt_int(text):
970
+ return int(text) if text else None
971
+
972
+
973
+ def evaluate_image(adv, ref, derived=False):
974
+ """Return (status, reason, version) for an image reference, or None if it is not PHP.
975
+
976
+ `derived` says the reference came from a default value or variable that a build
977
+ argument or .env file could override."""
978
+ if "$" in ref:
979
+ if "php" not in ref.lower():
980
+ return None
981
+ return REVIEW, "the image reference uses a build variable this tool cannot resolve", None
982
+ name, tag, digest = parse_image(ref)
983
+ low = name.lower()
984
+ official = low in OFFICIAL_PHP
985
+ named_php = official or low.rsplit("/", 1)[-1] in PHP_IMAGE_NAMES
986
+ match = None
987
+ if named_php:
988
+ m = TAG_VERSION_RE.match(tag or "")
989
+ if m:
990
+ match = (int(m.group(1)), _opt_int(m.group(2)), _opt_int(m.group(3)), m.group(4))
991
+ else:
992
+ # Images that bundle PHP and say so in the tag, e.g. wordpress:6.8-php8.3-apache.
993
+ m = BUNDLED_RE.search(tag or "")
994
+ if not m:
995
+ return None
996
+ match = (int(m.group(1)), int(m.group(2)), _opt_int(m.group(3)), tag[m.end():])
997
+ if match is None:
998
+ what = "pinned only by digest" if digest and not tag else "using an unpinned tag"
999
+ return REVIEW, "PHP image %s; the PHP version cannot be read from the reference" % what, None
1000
+
1001
+ major, minor, patch, rest = match
1002
+ if PRERELEASE_RE.search(rest):
1003
+ return REVIEW, "pre-release PHP image tag; compare it with the release notes", None
1004
+ if minor is not None and patch is not None:
1005
+ status, reason = evaluate(adv, (major, minor, patch, ""), None, tail=False)
1006
+ version = "%d.%d.%d" % (major, minor, patch)
1007
+ elif minor is not None:
1008
+ status, reason = evaluate_branch_only(adv, major, minor)
1009
+ version = "%d.%d" % (major, minor)
1010
+ else:
1011
+ return REVIEW, "tag pins only the major version (PHP %d); pin a full version such as 8.3.36 or later" % major, str(major)
1012
+
1013
+ if digest:
1014
+ return REVIEW, ("pinned by digest, which Docker uses instead of the tag; the tag says %s (%s) but the "
1015
+ "digest decides what runs. Check it with `docker run --rm IMAGE php -v`" % (version, status)), version
1016
+ if named_php and not official:
1017
+ if status == PATCHED:
1018
+ return REVIEW, ("third-party image whose tag looks like PHP %s; confirm with "
1019
+ "`docker run --rm %s php -v`" % (version, ref)), version
1020
+ reason += " (third-party image: confirm with `docker run --rm IMAGE php -v`)"
1021
+ if derived:
1022
+ if status == PATCHED:
1023
+ return REVIEW, ("%s, but the version comes from a default value that a build argument or .env "
1024
+ "file can override" % reason), version
1025
+ if status == VULNERABLE:
1026
+ reason += " (taken from a default value; a build argument or .env file could override it)"
1027
+ return status, reason, version
1028
+
1029
+
1030
+ def image_findings(advisories, refs, used_by=None):
1031
+ findings = []
1032
+ cwd = os.getcwd()
1033
+ for path, number, ref, derived in refs:
1034
+ for adv in advisories:
1035
+ verdict = evaluate_image(adv, ref, derived)
1036
+ if verdict is None:
1037
+ continue
1038
+ status, reason, version = verdict
1039
+ shown = None
1040
+ if path:
1041
+ rel = os.path.relpath(path, cwd)
1042
+ shown = path if rel.startswith("..") else rel
1043
+ if used_by and ref in used_by:
1044
+ pods = sorted(used_by[ref])
1045
+ reason += "; used by %s%s" % (", ".join(pods[:3]), " and %d more" % (len(pods) - 3) if len(pods) > 3 else "")
1046
+ findings.append(make_finding(
1047
+ adv, "image", ref, status, reason, version=version,
1048
+ confidence="high" if version and version.count(".") == 2 else "medium",
1049
+ location={"file": shown, "line": number} if shown else None,
1050
+ ))
1051
+ return findings
1052
+
1053
+
1054
+ def kubectl_images(text):
1055
+ """{image: set of 'namespace/pod'} from `kubectl get pods -o json`, or None."""
1056
+ try:
1057
+ data = json.loads(text)
1058
+ except ValueError:
1059
+ return None
1060
+ used = {}
1061
+ items = data.get("items") if isinstance(data, dict) else None
1062
+ for item in items if isinstance(items, list) else []:
1063
+ if not isinstance(item, dict):
1064
+ continue
1065
+ meta, spec = item.get("metadata") or {}, item.get("spec") or {}
1066
+ pod = "%s/%s" % (clean(meta.get("namespace") or "?", 80), clean(meta.get("name") or "?", 120))
1067
+ for key in ("initContainers", "containers", "ephemeralContainers"):
1068
+ for container in spec.get(key) or []:
1069
+ image = container.get("image") if isinstance(container, dict) else None
1070
+ if isinstance(image, str) and image:
1071
+ used.setdefault(image, set()).add(pod)
1072
+ return used
1073
+
1074
+
1075
+ def cmd_images(args, advisories):
1076
+ paths = args.paths or ([] if args.image or args.docker or args.kubectl else ["."])
1077
+ _require_paths(paths)
1078
+ problems = []
1079
+ refs = list(collect_image_refs(paths, problems))
1080
+ notes, used_by = [], {}
1081
+ for ref in args.image or []:
1082
+ refs.append((None, 0, ref, False))
1083
+ if args.docker:
1084
+ code, out, err = run(["docker", "ps", "--format", "{{.Image}}"], timeout=30)
1085
+ if code != 0:
1086
+ raise UsageError("could not list running containers: %s" % (clean(err).strip() or "docker not available"))
1087
+ refs.extend((None, 0, ref.strip(), False) for ref in sorted(set(out.splitlines())) if ref.strip())
1088
+ if args.kubectl:
1089
+ cmd = ["kubectl"] + shlex.split(args.kubectl_args or "") + ["get", "pods", "--all-namespaces", "-o", "json"]
1090
+ code, out, err = run(cmd, timeout=120, cap=64 * 1024 * 1024)
1091
+ used_by = kubectl_images(out) if code == 0 else None
1092
+ if used_by is None:
1093
+ raise UsageError("could not read pods from kubectl: %s" % (clean(err).strip() or "unexpected output"))
1094
+ refs.extend((None, 0, ref, False) for ref in sorted(used_by))
1095
+ notes.append("Checked %d distinct image(s) across the cluster's pods." % len(used_by))
1096
+ findings = image_findings(advisories, refs, used_by)
1097
+
1098
+ adv = advisories[0]
1099
+ skipped = 0
1100
+ for path, message, important in problems:
1101
+ if important:
1102
+ findings.append(error_finding(adv, "file", clean(path), "skipped: %s" % message))
1103
+ else:
1104
+ skipped += 1
1105
+ if skipped:
1106
+ notes.append("Skipped %d YAML file(s) that could not be read or were too large." % skipped)
1107
+ if not [f for f in findings if f["kind"] != "file"]:
1108
+ notes.append("No PHP image references found.")
1109
+ return findings, notes
1110
+
1111
+
1112
+ # --------------------------------------------------------------------------
1113
+ # url: one ordinary GET, read the advertised version
1114
+ # --------------------------------------------------------------------------
1115
+
1116
+ class _HttpOnlyRedirect(urllib.request.HTTPRedirectHandler):
1117
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
1118
+ if not re.match(r"^https?://", newurl, re.I):
1119
+ raise urllib.error.URLError("redirect to a non-http URL was refused")
1120
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
1121
+
1122
+
1123
+ def check_url(url, advisories, timeout):
1124
+ """A banner can be set by a proxy and one request reaches one backend, so this never says PATCHED."""
1125
+ headers = {"User-Agent": "php-vuln-check/%s (+%s)" % (__version__, REPO_URL)}
1126
+ opener = urllib.request.build_opener(_HttpOnlyRedirect)
1127
+ values = []
1128
+ try:
1129
+ with opener.open(urllib.request.Request(url, headers=headers), timeout=timeout) as resp:
1130
+ values = resp.headers.get_all("X-Powered-By") or []
1131
+ except urllib.error.HTTPError as exc:
1132
+ values = (exc.headers.get_all("X-Powered-By") if exc.headers else None) or []
1133
+ except Exception as exc: # DNS, TLS, timeout, refused, refused redirect
1134
+ return [error_finding(adv, "url", url, "request failed: %s" % clean(exc)) for adv in advisories]
1135
+
1136
+ versions = []
1137
+ for value in values:
1138
+ versions.extend(parse_version(v) for v in HEADER_RE.findall(value))
1139
+ versions = sorted(v for v in versions if v)
1140
+ findings = []
1141
+ for adv in advisories:
1142
+ if not versions:
1143
+ findings.append(make_finding(
1144
+ adv, "url", url, REVIEW,
1145
+ "no PHP version is advertised (expose_php is off, or a proxy strips X-Powered-By); "
1146
+ "run `php-vuln-check scan` on the server", confidence="low"))
1147
+ continue
1148
+ lowest = versions[0]
1149
+ status, reason = evaluate(adv, lowest, None, tail=False)
1150
+ shown = "%d.%d.%d" % lowest[:3]
1151
+ if status == VULNERABLE:
1152
+ reason += "; distro backports are invisible from outside, so confirm on the host with `php-vuln-check scan`"
1153
+ elif status == PATCHED:
1154
+ reason += "; a banner cannot prove the server is patched, so confirm on the host with `php-vuln-check scan`"
1155
+ findings.append(make_finding(
1156
+ adv, "url", url, REVIEW, "the server advertises PHP/%s: %s" % (shown, reason),
1157
+ version=shown, confidence="low"))
1158
+ return findings
1159
+
1160
+
1161
+ def cmd_url(args, advisories):
1162
+ findings = []
1163
+ for url in args.urls:
1164
+ if not re.match(r"^https?://", url, re.I):
1165
+ raise UsageError("URLs must start with http:// or https:// (got %r)" % clean(url, 80))
1166
+ findings.extend(check_url(url, advisories, args.timeout))
1167
+ return findings, []
1168
+
1169
+
1170
+ # --------------------------------------------------------------------------
1171
+ # fleet: run `scan` on many hosts over SSH, nothing installed remotely
1172
+ # --------------------------------------------------------------------------
1173
+
1174
+ HOST_RE = re.compile(r"^[A-Za-z0-9_:][A-Za-z0-9_.@:%-]*$") # never starts with "-", so it cannot be an ssh option
1175
+
1176
+
1177
+ def read_hosts(path):
1178
+ hosts = []
1179
+ try:
1180
+ fh = io.open(path, "r", errors="replace")
1181
+ except OSError as exc:
1182
+ raise UsageError("cannot read hosts file %s: %s" % (path, exc.strerror or exc))
1183
+ with fh:
1184
+ for line in fh:
1185
+ host = line.split("#", 1)[0].strip()
1186
+ if not host:
1187
+ continue
1188
+ if not HOST_RE.match(host):
1189
+ raise UsageError("refusing suspicious host entry %r in %s" % (clean(host, 80), path))
1190
+ hosts.append(host)
1191
+ return hosts
1192
+
1193
+
1194
+ def extract_report(text):
1195
+ """Find the tool's JSON report in ssh output that may carry a login banner."""
1196
+ decoder = json.JSONDecoder()
1197
+ for m in re.finditer(r"(?m)^\{", text):
1198
+ try:
1199
+ obj, _ = decoder.raw_decode(text[m.start():])
1200
+ except ValueError:
1201
+ continue
1202
+ if isinstance(obj, dict) and obj.get("tool") == "php-vuln-check" and isinstance(obj.get("findings"), list):
1203
+ return obj
1204
+ return None
1205
+
1206
+
1207
+ def validate_finding(raw, host):
1208
+ """Rebuild a finding from untrusted remote JSON: known keys, bounded strings, valid status."""
1209
+ if not isinstance(raw, dict):
1210
+ return None
1211
+ status = raw.get("status")
1212
+ reason = clean(raw.get("reason"))
1213
+ if status not in STATUS_ORDER:
1214
+ status, reason = ERROR, "the host returned a malformed result"
1215
+ advisory = raw.get("advisory") if raw.get("advisory") in ADVISORIES_BY_ID else ADVISORIES[0]["id"]
1216
+ out = {"advisory": advisory, "host": host, "status": status, "reason": reason,
1217
+ "kind": clean(raw.get("kind"), 40) or "?", "target": clean(raw.get("target")) or "?"}
1218
+ for key in ("sapi", "version", "package", "confidence", "fixed_in"):
1219
+ value = raw.get(key)
1220
+ out[key] = clean(value) if isinstance(value, str) else None
1221
+ config = raw.get("config")
1222
+ out["config"] = dict((clean(k, 60), clean(v, 40)) for k, v in list(config.items())[:20]
1223
+ if isinstance(k, str) and isinstance(v, str)) if isinstance(config, dict) else {}
1224
+ loc = raw.get("location")
1225
+ out["location"] = ({"file": clean(loc.get("file")), "line": loc.get("line") if isinstance(loc.get("line"), int) else 0}
1226
+ if isinstance(loc, dict) and isinstance(loc.get("file"), str) else None)
1227
+ return out
1228
+
1229
+
1230
+ def fleet_one(host, script, args, advisory_ids):
1231
+ adv = ADVISORIES_BY_ID[advisory_ids[0]]
1232
+ remote = ["python3", "-", "scan", "--format", "json", "--quiet"]
1233
+ if args.no_exec:
1234
+ remote.append("--no-exec")
1235
+ if args.exec:
1236
+ remote.append("--exec")
1237
+ for adv_id in advisory_ids:
1238
+ remote.extend(["--advisory", adv_id])
1239
+ cmd = (["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=%d" % args.connect_timeout]
1240
+ + shlex.split(args.ssh_opts or "") + ["--", host, " ".join(shlex.quote(p) for p in remote)])
1241
+ code, out, err = run(cmd, timeout=args.timeout, stdin=script)
1242
+ report = extract_report(out)
1243
+ if report is None:
1244
+ first = (clean(err).strip().splitlines() or ["no output"])[0]
1245
+ return [error_finding(adv, "host", host, "ssh or scan failed: %s" % first, host=host)]
1246
+ findings = [f for f in (validate_finding(r, host) for r in report["findings"]) if f]
1247
+ if not findings:
1248
+ # Nothing found is not the same as patched: PHP may live somewhere the scan does not look.
1249
+ return [make_finding(adv, "host", host, NONE,
1250
+ "no PHP found in the standard locations; PHP in a custom prefix, container "
1251
+ "or vhost folder would not appear (re-run with --path on that host)", host=host)]
1252
+ return findings
1253
+
1254
+
1255
+ def cmd_fleet(args, advisories):
1256
+ hosts = read_hosts(args.hosts_file)
1257
+ if not hosts:
1258
+ raise UsageError("no hosts found in %s" % args.hosts_file)
1259
+ with io.open(os.path.abspath(__file__), "r", encoding="utf-8") as fh:
1260
+ script = fh.read()
1261
+ ids = [a["id"] for a in advisories]
1262
+ with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool:
1263
+ results = list(pool.map(lambda h: fleet_one(h, script, args, ids), hosts))
1264
+ findings = [f for batch in results for f in batch]
1265
+ return findings, ["Checked %d host(s) over SSH." % len(hosts)]
1266
+
1267
+
1268
+ # --------------------------------------------------------------------------
1269
+ # Output
1270
+ # --------------------------------------------------------------------------
1271
+
1272
+ def summarize(findings):
1273
+ counts = dict((s, 0) for s in STATUS_ORDER)
1274
+ for f in findings:
1275
+ counts[f["status"]] = counts.get(f["status"], 0) + 1
1276
+ return counts
1277
+
1278
+
1279
+ def stale_data_note(today=None):
1280
+ """A warning when the advisory data is old enough that newer fixes may be missing, else None."""
1281
+ checked = datetime.datetime.strptime(DATA_CHECKED, "%Y-%m-%d").date()
1282
+ age = ((today or datetime.date.today()) - checked).days
1283
+ if age <= STALE_AFTER_DAYS:
1284
+ return None
1285
+ return ("This tool's advisory data was last checked on %s (%d days ago), so newer PHP fixes or vendor "
1286
+ "builds may be missing. Get the latest release: %s/releases/latest" % (DATA_CHECKED, age, REPO_URL))
1287
+
1288
+
1289
+ def build_report(findings, notes, mode):
1290
+ counts = summarize(findings)
1291
+ stale = stale_data_note()
1292
+ notes = notes + [stale] if stale else notes
1293
+ return {
1294
+ "tool": "php-vuln-check", "version": __version__, "mode": mode,
1295
+ "generated": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
1296
+ "summary": dict((k.lower(), v) for k, v in counts.items()),
1297
+ "notes": notes,
1298
+ "findings": sorted(findings, key=lambda f: (STATUS_ORDER.get(f["status"], 9), f.get("host") or "", f["target"])),
1299
+ }
1300
+
1301
+
1302
+ def exit_code(findings, fail_on):
1303
+ counts = summarize(findings)
1304
+ if fail_on == "never":
1305
+ return 0
1306
+ if counts[VULNERABLE]:
1307
+ return 1
1308
+ if counts[ERROR]:
1309
+ return 3
1310
+ if counts[REVIEW] and fail_on == "review":
1311
+ return 2
1312
+ return 0
1313
+
1314
+
1315
+ COLORS = {VULNERABLE: "1;31", ERROR: "1;35", REVIEW: "1;33", PATCHED: "1;32", NONE: "2"}
1316
+
1317
+
1318
+ def render_text(report, advisories, color, quiet):
1319
+ def paint(status, text):
1320
+ return "\033[%sm%s\033[0m" % (COLORS[status], text) if color else text
1321
+
1322
+ out = []
1323
+ if not quiet:
1324
+ names = "; ".join("%s (%s)" % (a["name"], ", ".join(a["cves"])) for a in advisories)
1325
+ out.append("php-vuln-check %s | checking %s" % (__version__, names))
1326
+ out.append("")
1327
+ for f in report["findings"]:
1328
+ head = clean(f["target"])
1329
+ if f.get("host") and report["mode"] == "fleet":
1330
+ head = "%s %s" % (clean(f["host"]), head)
1331
+ if len(advisories) > 1 and f.get("advisory") in ADVISORIES_BY_ID:
1332
+ head += " (%s)" % ", ".join(ADVISORIES_BY_ID[f["advisory"]]["cves"])
1333
+ out.append("%s %s" % (paint(f["status"], "%-10s" % f["status"]), head))
1334
+ detail = [clean(d) for d in (
1335
+ ("PHP %s" % f["version"]) if f.get("version") else None,
1336
+ f.get("sapi"), f.get("package")) if d]
1337
+ if detail:
1338
+ out.append(" " + " | ".join(detail))
1339
+ out.append(" " + clean(f["reason"], 1000))
1340
+ if f.get("location"):
1341
+ out.append(" at %s:%s" % (clean(f["location"]["file"]), clean(f["location"]["line"], 12)))
1342
+ cfg = f.get("config") or {}
1343
+ if cfg:
1344
+ out.append(" config: " + " ".join("%s=%s" % (clean(k), clean(v)) for k, v in sorted(cfg.items())))
1345
+ out.append("")
1346
+ for note in report["notes"]:
1347
+ out.append(clean(note, 1000))
1348
+ s = report["summary"]
1349
+ line = "Summary: %d vulnerable | %d need review | %d patched" % (s["vulnerable"], s["review"], s["patched"])
1350
+ if s["error"]:
1351
+ line += " | %d error" % s["error"]
1352
+ if s["none"]:
1353
+ line += " | %d with no PHP found" % s["none"]
1354
+ out.append(line)
1355
+ if not quiet and s["patched"]:
1356
+ out.append("PATCHED describes the files on disk. After an update, restart PHP-FPM or Apache so running workers load them.")
1357
+ if not quiet and (s["vulnerable"] or s["review"]):
1358
+ out.append("")
1359
+ out.append("What to do:")
1360
+ open_ids = set(f["advisory"] for f in report["findings"] if f["status"] in (VULNERABLE, REVIEW))
1361
+ for adv in advisories:
1362
+ if adv["id"] not in open_ids:
1363
+ continue
1364
+ for step in adv["mitigations"]:
1365
+ out.append(" - " + step)
1366
+ out.append(" - Details: " + adv["references"][0]["url"])
1367
+ out.append(" - REVIEW means the tool could not prove either way; it is not a clean bill of health.")
1368
+ return "\n".join(out) + "\n"
1369
+
1370
+
1371
+ def _csv_cell(value):
1372
+ """Neutralise spreadsheet formulas in untrusted text."""
1373
+ if value is None:
1374
+ return ""
1375
+ if isinstance(value, str):
1376
+ value = clean(value, 2000)
1377
+ if value[:1] in ("=", "+", "-", "@"):
1378
+ return "'" + value
1379
+ return value
1380
+
1381
+
1382
+ def render_csv(report):
1383
+ buf = io.StringIO()
1384
+ cols = ["host", "advisory", "status", "kind", "target", "sapi", "version", "package",
1385
+ "fixed_in", "confidence", "reason", "file", "line"]
1386
+ writer = csv.writer(buf)
1387
+ writer.writerow(cols)
1388
+ for f in report["findings"]:
1389
+ loc = f.get("location") or {}
1390
+ row = [f.get(c) for c in cols[:-2]] + [loc.get("file"), loc.get("line")]
1391
+ writer.writerow([_csv_cell(v) for v in row])
1392
+ return buf.getvalue()
1393
+
1394
+
1395
+ def render_sarif(report, advisories):
1396
+ """SARIF for GitHub code scanning. Only findings with a file location are included:
1397
+ code scanning needs a location in the repository, and a host or URL has none."""
1398
+ severities = {VULNERABLE: "9.0", REVIEW: "5.0"}
1399
+ rules = []
1400
+ for a in advisories:
1401
+ for status in (VULNERABLE, REVIEW):
1402
+ rules.append({
1403
+ "id": "%s/%s" % (a["id"], status.lower()), "name": "%s%s" % (a["name"], status.title()),
1404
+ "shortDescription": {"text": "%s (%s): %s" % (a["name"], ", ".join(a["cves"]), status.lower())},
1405
+ "fullDescription": {"text": a["summary"]},
1406
+ "helpUri": a["references"][0]["url"],
1407
+ "properties": {"tags": ["security"] + a["cves"], "security-severity": severities[status]},
1408
+ })
1409
+ results = []
1410
+ for f in report["findings"]:
1411
+ loc = f.get("location")
1412
+ if f["status"] not in severities or not loc:
1413
+ continue
1414
+ results.append({
1415
+ "ruleId": "%s/%s" % (f["advisory"], f["status"].lower()),
1416
+ "level": "error" if f["status"] == VULNERABLE else "warning",
1417
+ "message": {"text": clean("%s: %s" % (f["target"], f["reason"]), 1500)},
1418
+ "locations": [{"physicalLocation": {
1419
+ "artifactLocation": {"uri": urllib.parse.quote(loc["file"])},
1420
+ "region": {"startLine": max(1, int(loc.get("line") or 1))},
1421
+ }}],
1422
+ })
1423
+ return json.dumps({
1424
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
1425
+ "runs": [{"tool": {"driver": {
1426
+ "name": "php-vuln-check", "version": __version__, "informationUri": REPO_URL, "rules": rules}},
1427
+ "results": results}],
1428
+ }, indent=2) + "\n"
1429
+
1430
+
1431
+ def emit(text, output):
1432
+ if output:
1433
+ with io.open(output, "w", encoding="utf-8") as fh:
1434
+ fh.write(text)
1435
+ return
1436
+ try:
1437
+ sys.stdout.write(text)
1438
+ except UnicodeEncodeError: # an ASCII-only locale
1439
+ sys.stdout.write(text.encode("ascii", "replace").decode("ascii"))
1440
+
1441
+
1442
+ # --------------------------------------------------------------------------
1443
+ # CLI
1444
+ # --------------------------------------------------------------------------
1445
+
1446
+ class Parser(argparse.ArgumentParser):
1447
+ """Usage errors exit 3 so they cannot be mistaken for 'vulnerable' (1) or 'review' (2)."""
1448
+
1449
+ def error(self, message):
1450
+ self.print_usage(sys.stderr)
1451
+ sys.stderr.write("%s: error: %s\n" % (self.prog, message))
1452
+ raise SystemExit(3)
1453
+
1454
+
1455
+ def common_options():
1456
+ p = argparse.ArgumentParser(add_help=False)
1457
+ p.add_argument("--format", choices=["text", "json", "csv", "sarif"], default="text",
1458
+ help="output format (default: text)")
1459
+ p.add_argument("--json", dest="format", action="store_const", const="json", help="shortcut for --format json")
1460
+ p.add_argument("-o", "--output", metavar="FILE", help="write the report to FILE instead of stdout")
1461
+ p.add_argument("--advisory", action="append", metavar="ID", choices=sorted(ADVISORIES_BY_ID),
1462
+ help="check only this advisory (default: all). See `php-vuln-check advisories`")
1463
+ p.add_argument("--fail-on", choices=["review", "vulnerable", "never"], default="review",
1464
+ help="exit non-zero for REVIEW and VULNERABLE (default), only VULNERABLE, or never")
1465
+ p.add_argument("-q", "--quiet", action="store_true", help="omit the banner and the what-to-do block")
1466
+ p.add_argument("--no-color", action="store_true", help="never use colors")
1467
+ return p
1468
+
1469
+
1470
+ def exec_options(p):
1471
+ group = p.add_mutually_exclusive_group()
1472
+ group.add_argument("--no-exec", action="store_true",
1473
+ help="never run PHP binaries; read versions from the files and the package manager instead")
1474
+ group.add_argument("--exec", action="store_true",
1475
+ help="run every PHP binary found, even ones that are not root-owned or are writable by others")
1476
+
1477
+
1478
+ def build_parser():
1479
+ common = common_options()
1480
+ parser = Parser(
1481
+ prog="php-vuln-check",
1482
+ description="Find PHP installs exposed to PHP2Shell (CVE-2026-109618 / CVE-2026-109619) and "
1483
+ "other tracked PHP vulnerabilities. Reads versions, vendor changelogs and config; "
1484
+ "never sends exploit traffic.",
1485
+ epilog="Exit codes: 0 clean, 1 vulnerable, 2 needs review, 3 error or bad usage. Docs: " + REPO_URL)
1486
+ parser.add_argument("--version", action="version", version="php-vuln-check " + __version__)
1487
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND")
1488
+
1489
+ p = sub.add_parser("scan", parents=[common], help="audit PHP installs on this machine (default)")
1490
+ p.add_argument("--path", action="append", metavar="DIR", help="also search DIR (or check this file); repeatable")
1491
+ p.add_argument("--no-defaults", action="store_true", help="skip the standard install locations")
1492
+ exec_options(p)
1493
+
1494
+ p = sub.add_parser("images", parents=[common], help="check Dockerfiles, compose files, k8s manifests, images")
1495
+ p.add_argument("paths", nargs="*", metavar="PATH", help="files or folders to scan (default: .)")
1496
+ p.add_argument("--image", action="append", metavar="REF", help="check one image reference such as php:8.3-fpm")
1497
+ p.add_argument("--docker", action="store_true", help="also check images of running containers")
1498
+ p.add_argument("--kubectl", action="store_true", help="also check images of pods in the current cluster")
1499
+ p.add_argument("--kubectl-args", default="", metavar="ARGS", help='extra kubectl arguments, e.g. "--context prod"')
1500
+
1501
+ p = sub.add_parser("url", parents=[common], help="read the PHP version a website advertises (one GET each)")
1502
+ p.add_argument("urls", nargs="+", metavar="URL")
1503
+ p.add_argument("--timeout", type=int, default=15)
1504
+
1505
+ p = sub.add_parser("fleet", parents=[common], help="run `scan` on many hosts over SSH")
1506
+ p.add_argument("hosts_file", metavar="HOSTS_FILE", help="one [user@]host per line; # starts a comment")
1507
+ p.add_argument("--jobs", type=int, default=8, help="hosts to check in parallel (default: 8)")
1508
+ p.add_argument("--ssh-opts", default="", help='extra ssh options, e.g. "-i ~/.ssh/key -p 2222"')
1509
+ p.add_argument("--connect-timeout", type=int, default=10)
1510
+ p.add_argument("--timeout", type=int, default=300, help="seconds to wait for each host")
1511
+ exec_options(p)
1512
+
1513
+ sub.add_parser("advisories", help="list the advisories this version knows about")
1514
+ return parser
1515
+
1516
+
1517
+ def cmd_advisories():
1518
+ for a in ADVISORIES:
1519
+ print("%s %s %s severity %s published %s" % (a["id"], a["name"], ", ".join(a["cves"]), a["cvss"], a["published"]))
1520
+ print(" fixed in: " + ", ".join(a["fixed"][b] for b in sorted(a["fixed"])) + "; older branches need a vendor backport")
1521
+ print(" " + a["summary"])
1522
+ return 0
1523
+
1524
+
1525
+ def main(argv=None):
1526
+ argv = list(sys.argv[1:] if argv is None else argv)
1527
+ if not argv or (argv[0].startswith("-") and argv[0] not in ("-h", "--help", "--version")):
1528
+ argv.insert(0, "scan")
1529
+ try:
1530
+ args = build_parser().parse_args(argv)
1531
+ if args.command == "advisories":
1532
+ return cmd_advisories()
1533
+
1534
+ advisories = [ADVISORIES_BY_ID[i] for i in args.advisory] if args.advisory else list(ADVISORIES)
1535
+ handlers = {"scan": cmd_scan, "images": cmd_images, "url": cmd_url, "fleet": cmd_fleet}
1536
+ findings, notes = handlers[args.command](args, advisories)
1537
+ findings = drop_unaffected(findings)
1538
+ report = build_report(findings, notes, args.command)
1539
+
1540
+ color = (not args.no_color and not args.output and sys.stdout.isatty() and "NO_COLOR" not in os.environ)
1541
+ if args.format == "json":
1542
+ text = json.dumps(report, indent=2) + "\n"
1543
+ elif args.format == "csv":
1544
+ text = render_csv(report)
1545
+ elif args.format == "sarif":
1546
+ text = render_sarif(report, advisories)
1547
+ else:
1548
+ text = render_text(report, advisories, color, args.quiet)
1549
+ emit(text, args.output)
1550
+ return exit_code(findings, args.fail_on)
1551
+ except UsageError as exc:
1552
+ sys.stderr.write("php-vuln-check: %s\n" % exc)
1553
+ return 3
1554
+ except KeyboardInterrupt:
1555
+ return 130
1556
+ except Exception as exc: # never let a crash look like 'vulnerable' (1) or 'review' (2)
1557
+ sys.stderr.write("php-vuln-check: internal error: %s: %s\nPlease report it at %s/issues\n"
1558
+ % (type(exc).__name__, exc, REPO_URL))
1559
+ return 3
1560
+
1561
+
1562
+ if __name__ == "__main__":
1563
+ sys.exit(main())