wpchecker 0.2.2__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.
- wpchecker/__init__.py +6 -0
- wpchecker/__main__.py +104 -0
- wpchecker/advisories.py +93 -0
- wpchecker/data/wp_advisories.json +1297 -0
- wpchecker/fetch.py +268 -0
- wpchecker/scan.py +614 -0
- wpchecker/versions.py +81 -0
- wpchecker-0.2.2.dist-info/METADATA +290 -0
- wpchecker-0.2.2.dist-info/RECORD +13 -0
- wpchecker-0.2.2.dist-info/WHEEL +5 -0
- wpchecker-0.2.2.dist-info/entry_points.txt +2 -0
- wpchecker-0.2.2.dist-info/licenses/LICENSE +23 -0
- wpchecker-0.2.2.dist-info/top_level.txt +1 -0
wpchecker/scan.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
"""External WordPress scan (no credentials, read-only).
|
|
2
|
+
|
|
3
|
+
Everything the scan learns comes from what the site itself
|
|
4
|
+
discloses: the homepage's generator tag and enqueued asset URLs,
|
|
5
|
+
and three files WordPress sites serve publicly — a plugin's
|
|
6
|
+
readme.txt (its "Stable tag"), the active theme's style.css
|
|
7
|
+
header, and /readme.html. There are no exploit probes, no
|
|
8
|
+
username enumeration, no password attempts, no aggressive
|
|
9
|
+
enumeration mode: if the site does not disclose a version, the
|
|
10
|
+
component is reported "version hidden" and left unassessed.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import urllib.parse
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from . import advisories as adv
|
|
21
|
+
from . import fetch as fetchmod
|
|
22
|
+
|
|
23
|
+
_GEN_RES = (
|
|
24
|
+
re.compile(r'<meta[^>]+name=["\']generator["\'][^>]+'
|
|
25
|
+
r'content=["\']([^"\']+)', re.I),
|
|
26
|
+
re.compile(r'<meta[^>]+content=["\']([^"\']+)["\'][^>]+'
|
|
27
|
+
r'name=["\']generator', re.I),
|
|
28
|
+
)
|
|
29
|
+
_ASSET_RE = re.compile(r'wp-content/(plugins|themes)/'
|
|
30
|
+
r'([A-Za-z0-9_\-]+)/([^"\'\s<>]+)')
|
|
31
|
+
_CORE_ASSET_RE = re.compile(r'wp-includes/[^"\'\s<>]*?'
|
|
32
|
+
r'[?&]ver=([0-9][0-9A-Za-z.\-]*)')
|
|
33
|
+
_VER_QS_RE = re.compile(r'[?&]ver=([0-9][0-9A-Za-z.\-]*)')
|
|
34
|
+
_STABLE_TAG_RE = re.compile(r'(?im)^Stable tag:\s*(\S+)')
|
|
35
|
+
_CSS_VERSION_RE = re.compile(r'(?im)^\s*\*?\s*Version:\s*'
|
|
36
|
+
r'([0-9][0-9A-Za-z.\-]*)')
|
|
37
|
+
_README_VER_RE = re.compile(r'Version\s+([0-9]+(?:\.[0-9]+){0,3})')
|
|
38
|
+
|
|
39
|
+
_MAX_README_PROBES = 8
|
|
40
|
+
_MAX_THEME_PROBES = 2
|
|
41
|
+
|
|
42
|
+
# Version of the JSON report schema emitted by
|
|
43
|
+
# _scan_with_fetch (both live and snapshot modes). Part of
|
|
44
|
+
# the scanner-family contract: consumers can pin parsing
|
|
45
|
+
# to it. Bump only on a breaking report-shape change.
|
|
46
|
+
SCHEMA_VERSION = 1
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _generators(body):
|
|
50
|
+
out = []
|
|
51
|
+
for rx in _GEN_RES:
|
|
52
|
+
out += rx.findall(body or "")
|
|
53
|
+
return out
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _origin(url):
|
|
57
|
+
p = urllib.parse.urlsplit(url)
|
|
58
|
+
return f"{p.scheme}://{p.netloc}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _stable_tag(body):
|
|
62
|
+
"""The version a plugin's readme.txt declares — or None.
|
|
63
|
+
'trunk' is a development state, not a version: it is
|
|
64
|
+
reported as hidden, never parsed as one."""
|
|
65
|
+
m = _STABLE_TAG_RE.search(body or "")
|
|
66
|
+
if not m:
|
|
67
|
+
return None
|
|
68
|
+
tag = m.group(1).strip()
|
|
69
|
+
if tag.lower() == "trunk" or not re.match(r"^\d", tag):
|
|
70
|
+
return None
|
|
71
|
+
return tag
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _now():
|
|
75
|
+
return datetime.now(timezone.utc).strftime(
|
|
76
|
+
"%Y-%m-%dT%H:%M:%SZ")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _discover(body):
|
|
80
|
+
"""Components disclosed by asset URLs in the page source:
|
|
81
|
+
{(kind, slug): {"version", "version_source"}} plus
|
|
82
|
+
per-theme reference counts (the most-referenced theme is
|
|
83
|
+
the active one)."""
|
|
84
|
+
found = {}
|
|
85
|
+
theme_hits = {}
|
|
86
|
+
for kind, slug, rest in _ASSET_RE.findall(body):
|
|
87
|
+
vm = _VER_QS_RE.search(rest)
|
|
88
|
+
key = (kind, slug)
|
|
89
|
+
cur = found.setdefault(key, {"version": None,
|
|
90
|
+
"version_source": None})
|
|
91
|
+
if kind == "themes":
|
|
92
|
+
theme_hits[slug] = theme_hits.get(slug, 0) + 1
|
|
93
|
+
if vm and not cur["version"]:
|
|
94
|
+
if kind == "plugins":
|
|
95
|
+
# A plugin asset's ?ver= is the plugin's own
|
|
96
|
+
# enqueued version. (For themes it is not
|
|
97
|
+
# reliable — the style.css header is.)
|
|
98
|
+
cur["version"] = vm.group(1)
|
|
99
|
+
cur["version_source"] = "asset URL"
|
|
100
|
+
return found, theme_hits
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _probe_plan(found, db):
|
|
104
|
+
"""Plugin slugs whose hidden versions a readme.txt probe
|
|
105
|
+
may disclose — dataset-covered first (they matter most),
|
|
106
|
+
capped."""
|
|
107
|
+
db_slugs = {s.lower() for s in db.get("plugins", {})}
|
|
108
|
+
todo = [slug for (kind, slug), cur in found.items()
|
|
109
|
+
if kind == "plugins" and not cur["version"]]
|
|
110
|
+
todo.sort(key=lambda s: s.lower() not in db_slugs)
|
|
111
|
+
return todo[:_MAX_README_PROBES]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _theme_plan(found, theme_hits):
|
|
115
|
+
"""Theme slugs to style.css-probe, most-referenced
|
|
116
|
+
(active) first, capped."""
|
|
117
|
+
themes = [slug for (kind, slug) in found if kind == "themes"]
|
|
118
|
+
themes.sort(key=lambda s: -theme_hits.get(s, 0))
|
|
119
|
+
return themes[:_MAX_THEME_PROBES]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _scan_with_fetch(target, get, db):
|
|
123
|
+
"""The scan engine. `get` is any callable with the
|
|
124
|
+
fetcher's response contract — the live guarded fetcher,
|
|
125
|
+
a test double, or a snapshot replay (zero requests)."""
|
|
126
|
+
result = {"tool": "wpchecker", "version": __version__,
|
|
127
|
+
"schema_version": SCHEMA_VERSION,
|
|
128
|
+
"target": target, "final_url": None, "status": None,
|
|
129
|
+
"mode": "live", "scanned_at": _now(),
|
|
130
|
+
"error": None, "wordpress": {"detected": False,
|
|
131
|
+
"core_version": None,
|
|
132
|
+
"core_version_source": None},
|
|
133
|
+
"plugins": [], "themes": [], "hygiene": [],
|
|
134
|
+
"summary": {},
|
|
135
|
+
"dataset": {"generated": db.get("_meta", {}).get(
|
|
136
|
+
"generated"),
|
|
137
|
+
"components": len(db.get("plugins", {})),
|
|
138
|
+
"advisories": sum(
|
|
139
|
+
len(p.get("vulnerabilities", []))
|
|
140
|
+
for p in db.get("plugins",
|
|
141
|
+
{}).values())}}
|
|
142
|
+
home = get(target)
|
|
143
|
+
if not home.get("ok") or home.get("status") is None:
|
|
144
|
+
result["status"] = "unreachable"
|
|
145
|
+
result["error"] = home.get("error") or "fetch failed"
|
|
146
|
+
return result
|
|
147
|
+
result["final_url"] = home.get("final_url") or target
|
|
148
|
+
body = home.get("body") or ""
|
|
149
|
+
headers = home.get("headers") or {}
|
|
150
|
+
low = body.lower()
|
|
151
|
+
origin = _origin(result["final_url"])
|
|
152
|
+
|
|
153
|
+
gens = _generators(body)
|
|
154
|
+
gen_text = " | ".join(gens)
|
|
155
|
+
is_wp = ("wp-content" in low or "wp-includes" in low
|
|
156
|
+
or "wordpress" in gen_text.lower()
|
|
157
|
+
or "api.w.org" in headers.get("link", ""))
|
|
158
|
+
if not is_wp:
|
|
159
|
+
result["status"] = "not_wordpress"
|
|
160
|
+
return result
|
|
161
|
+
wp = result["wordpress"]
|
|
162
|
+
wp["detected"] = True
|
|
163
|
+
|
|
164
|
+
# --- Core version: generator tag, then enqueued
|
|
165
|
+
# wp-includes asset versions, then /readme.html below.
|
|
166
|
+
m = re.search(r'WordPress\s+([0-9]+(?:\.[0-9]+){0,2})',
|
|
167
|
+
gen_text)
|
|
168
|
+
if m:
|
|
169
|
+
wp["core_version"] = m.group(1)
|
|
170
|
+
wp["core_version_source"] = "generator tag"
|
|
171
|
+
else:
|
|
172
|
+
m = _CORE_ASSET_RE.search(body)
|
|
173
|
+
if m:
|
|
174
|
+
wp["core_version"] = m.group(1)
|
|
175
|
+
wp["core_version_source"] = "wp-includes asset"
|
|
176
|
+
|
|
177
|
+
# --- Components disclosed by asset URLs.
|
|
178
|
+
found, theme_hits = _discover(body)
|
|
179
|
+
|
|
180
|
+
# --- /readme.html: a version source of last resort, and
|
|
181
|
+
# itself a hygiene finding when served.
|
|
182
|
+
r = get(origin + "/readme.html")
|
|
183
|
+
if r.get("ok") and r.get("status") == 200 and \
|
|
184
|
+
"wordpress" in (r.get("body") or "").lower():
|
|
185
|
+
result["hygiene"].append({
|
|
186
|
+
"kind": "exposure",
|
|
187
|
+
"title": "readme.html is publicly served",
|
|
188
|
+
"detail": "The stock WordPress readme.html discloses "
|
|
189
|
+
"the exact core version to anyone who asks.",
|
|
190
|
+
"remediation": "Delete readme.html (it is not "
|
|
191
|
+
"needed to run WordPress) or block "
|
|
192
|
+
"it at the web server.",
|
|
193
|
+
})
|
|
194
|
+
if not wp["core_version"]:
|
|
195
|
+
m = _README_VER_RE.search(r.get("body") or "")
|
|
196
|
+
if m:
|
|
197
|
+
wp["core_version"] = m.group(1)
|
|
198
|
+
wp["core_version_source"] = "readme.html"
|
|
199
|
+
|
|
200
|
+
# --- Plugin versions the page hid: readme.txt Stable tags
|
|
201
|
+
# (dataset-covered plugins first — they matter most).
|
|
202
|
+
for slug in _probe_plan(found, db):
|
|
203
|
+
r = get(f"{origin}/wp-content/plugins/{slug}/readme.txt")
|
|
204
|
+
if r.get("ok") and r.get("status") == 200:
|
|
205
|
+
tag = _stable_tag(r.get("body"))
|
|
206
|
+
if tag:
|
|
207
|
+
found[("plugins", slug)]["version"] = tag
|
|
208
|
+
found[("plugins", slug)]["version_source"] = \
|
|
209
|
+
"plugin readme.txt"
|
|
210
|
+
|
|
211
|
+
# --- Theme versions: the style.css header.
|
|
212
|
+
themes = _theme_plan(found, theme_hits)
|
|
213
|
+
for slug in themes:
|
|
214
|
+
r = get(f"{origin}/wp-content/themes/{slug}/style.css")
|
|
215
|
+
if r.get("ok") and r.get("status") == 200:
|
|
216
|
+
m = _CSS_VERSION_RE.search((r.get("body") or "")[:8192])
|
|
217
|
+
if m:
|
|
218
|
+
found[("themes", slug)]["version"] = m.group(1)
|
|
219
|
+
found[("themes", slug)]["version_source"] = \
|
|
220
|
+
"theme style.css"
|
|
221
|
+
|
|
222
|
+
# --- Assess everything disclosed.
|
|
223
|
+
active_theme = themes[0] if themes else None
|
|
224
|
+
for (kind, slug), cur in sorted(found.items()):
|
|
225
|
+
rep = adv.assess(db, slug,
|
|
226
|
+
"theme" if kind == "themes" else "plugin",
|
|
227
|
+
cur["version"], cur["version_source"])
|
|
228
|
+
if kind == "themes":
|
|
229
|
+
rep["active"] = slug == active_theme
|
|
230
|
+
result["themes"].append(rep)
|
|
231
|
+
else:
|
|
232
|
+
result["plugins"].append(rep)
|
|
233
|
+
|
|
234
|
+
components = result["plugins"] + result["themes"]
|
|
235
|
+
result["summary"] = {
|
|
236
|
+
"plugins_found": len(result["plugins"]),
|
|
237
|
+
"themes_found": len(result["themes"]),
|
|
238
|
+
"assessed": sum(1 for c in components
|
|
239
|
+
if c["status"] not in ("version_hidden",)),
|
|
240
|
+
"version_hidden": sum(1 for c in components
|
|
241
|
+
if c["status"] == "version_hidden"),
|
|
242
|
+
"vulnerable_components": sum(
|
|
243
|
+
1 for c in components if c["status"] == "vulnerable"),
|
|
244
|
+
"findings": sum(len(c["findings"]) for c in components),
|
|
245
|
+
"hygiene_findings": len(result["hygiene"]),
|
|
246
|
+
}
|
|
247
|
+
result["status"] = "ok"
|
|
248
|
+
return result
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def scan(target, fetch=None, db=None):
|
|
252
|
+
"""Scan one live site. `fetch` (url -> response dict) and
|
|
253
|
+
`db` are injectable for tests; by default the guarded
|
|
254
|
+
fetcher (one shared deadline per scan) and the vendored
|
|
255
|
+
dataset are used."""
|
|
256
|
+
if db is None:
|
|
257
|
+
db = adv.load_db()
|
|
258
|
+
if fetch is None:
|
|
259
|
+
deadline = fetchmod.new_deadline()
|
|
260
|
+
|
|
261
|
+
def get(url):
|
|
262
|
+
return fetchmod.fetch(url, deadline=deadline)
|
|
263
|
+
else:
|
|
264
|
+
get = fetch
|
|
265
|
+
if "://" not in target:
|
|
266
|
+
target = "https://" + target
|
|
267
|
+
return _scan_with_fetch(target, get, db)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# ----------------------------------------------------------------
|
|
271
|
+
# Snapshot replay — the differentiator. A snapshot is a
|
|
272
|
+
# directory of captured evidence plus a manifest; replaying
|
|
273
|
+
# it runs the identical scan engine over the captures and
|
|
274
|
+
# makes ZERO network requests. Format (documented in the
|
|
275
|
+
# README):
|
|
276
|
+
#
|
|
277
|
+
# <dir>/snapshot.json manifest (see save_snapshot)
|
|
278
|
+
# <dir>/homepage.html the captured homepage body
|
|
279
|
+
# <dir>/readme.html captured /readme.html (optional)
|
|
280
|
+
# <dir>/components/<slug>.readme.txt (optional, per slug)
|
|
281
|
+
# <dir>/components/<slug>.style.css (optional, per slug)
|
|
282
|
+
#
|
|
283
|
+
# The manifest also records the homepage's response headers:
|
|
284
|
+
# live detection reads them (the REST `Link:` header is a
|
|
285
|
+
# WordPress signal), so a replay must see them too, or a
|
|
286
|
+
# header-only-detectable site would scan as WordPress live
|
|
287
|
+
# and not_wordpress from its own snapshot.
|
|
288
|
+
# ----------------------------------------------------------------
|
|
289
|
+
|
|
290
|
+
SNAPSHOT_TOOL = "wpchecker-snapshot"
|
|
291
|
+
SNAPSHOT_VERSION = 1
|
|
292
|
+
_README_URL_RE = re.compile(
|
|
293
|
+
r"/wp-content/plugins/([A-Za-z0-9_\-]+)/readme\.txt$")
|
|
294
|
+
_STYLE_URL_RE = re.compile(
|
|
295
|
+
r"/wp-content/themes/([A-Za-z0-9_\-]+)/style\.css$")
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _is_wp(body, headers):
|
|
299
|
+
low = (body or "").lower()
|
|
300
|
+
gen_text = " | ".join(_generators(body or ""))
|
|
301
|
+
return ("wp-content" in low or "wp-includes" in low
|
|
302
|
+
or "wordpress" in gen_text.lower()
|
|
303
|
+
or "api.w.org" in (headers or {}).get("link", ""))
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def save_snapshot(target, out_dir, fetch=None, db=None):
|
|
307
|
+
"""Capture a site's disclosed evidence into a snapshot
|
|
308
|
+
directory that scan_snapshot() can replay offline. Uses
|
|
309
|
+
the same guarded fetcher and the same probe plan as a
|
|
310
|
+
live scan, so a replay sees exactly what a scan would.
|
|
311
|
+
Returns a summary dict; {"status": "error", ...} when
|
|
312
|
+
the homepage cannot be captured."""
|
|
313
|
+
if db is None:
|
|
314
|
+
db = adv.load_db()
|
|
315
|
+
if fetch is None:
|
|
316
|
+
deadline = fetchmod.new_deadline()
|
|
317
|
+
|
|
318
|
+
def get(url):
|
|
319
|
+
return fetchmod.fetch(url, deadline=deadline)
|
|
320
|
+
else:
|
|
321
|
+
get = fetch
|
|
322
|
+
if "://" not in target:
|
|
323
|
+
target = "https://" + target
|
|
324
|
+
home = get(target)
|
|
325
|
+
if not home.get("ok") or home.get("status") is None:
|
|
326
|
+
return {"status": "error",
|
|
327
|
+
"error": home.get("error") or "fetch failed"}
|
|
328
|
+
if home.get("status") != 200:
|
|
329
|
+
return {"status": "error",
|
|
330
|
+
"error": f"homepage returned HTTP "
|
|
331
|
+
f"{home.get('status')}; nothing "
|
|
332
|
+
f"captured"}
|
|
333
|
+
final = home.get("final_url") or target
|
|
334
|
+
origin = _origin(final)
|
|
335
|
+
body = home.get("body") or ""
|
|
336
|
+
headers = home.get("headers") or {}
|
|
337
|
+
os.makedirs(os.path.join(out_dir, "components"),
|
|
338
|
+
exist_ok=True)
|
|
339
|
+
files = {"homepage": "homepage.html"}
|
|
340
|
+
written = ["homepage.html"]
|
|
341
|
+
|
|
342
|
+
def _write(rel, content):
|
|
343
|
+
with open(os.path.join(out_dir, rel), "w",
|
|
344
|
+
encoding="utf-8") as f:
|
|
345
|
+
f.write(content)
|
|
346
|
+
|
|
347
|
+
_write("homepage.html", body)
|
|
348
|
+
if _is_wp(body, home.get("headers") or {}):
|
|
349
|
+
r = get(origin + "/readme.html")
|
|
350
|
+
if r.get("ok") and r.get("status") == 200:
|
|
351
|
+
_write("readme.html", r.get("body") or "")
|
|
352
|
+
files["readme_html"] = "readme.html"
|
|
353
|
+
written.append("readme.html")
|
|
354
|
+
found, theme_hits = _discover(body)
|
|
355
|
+
readmes = {}
|
|
356
|
+
for slug in _probe_plan(found, db):
|
|
357
|
+
r = get(f"{origin}/wp-content/plugins/{slug}"
|
|
358
|
+
f"/readme.txt")
|
|
359
|
+
if r.get("ok") and r.get("status") == 200:
|
|
360
|
+
rel = f"components/{slug}.readme.txt"
|
|
361
|
+
_write(rel, r.get("body") or "")
|
|
362
|
+
readmes[slug] = rel
|
|
363
|
+
written.append(rel)
|
|
364
|
+
if readmes:
|
|
365
|
+
files["plugin_readmes"] = readmes
|
|
366
|
+
styles = {}
|
|
367
|
+
for slug in _theme_plan(found, theme_hits):
|
|
368
|
+
r = get(f"{origin}/wp-content/themes/{slug}"
|
|
369
|
+
f"/style.css")
|
|
370
|
+
if r.get("ok") and r.get("status") == 200:
|
|
371
|
+
rel = f"components/{slug}.style.css"
|
|
372
|
+
_write(rel, r.get("body") or "")
|
|
373
|
+
styles[slug] = rel
|
|
374
|
+
written.append(rel)
|
|
375
|
+
if styles:
|
|
376
|
+
files["theme_styles"] = styles
|
|
377
|
+
manifest = {"tool": SNAPSHOT_TOOL,
|
|
378
|
+
"version": SNAPSHOT_VERSION,
|
|
379
|
+
"target": target, "final_url": final,
|
|
380
|
+
"captured_at": _now(), "files": files,
|
|
381
|
+
"headers": {"homepage": headers}}
|
|
382
|
+
_write("snapshot.json",
|
|
383
|
+
json.dumps(manifest, indent=1) + "\n")
|
|
384
|
+
return {"status": "ok", "target": target,
|
|
385
|
+
"final_url": final, "path": str(out_dir),
|
|
386
|
+
"captured_at": manifest["captured_at"],
|
|
387
|
+
"files": sorted(written)}
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _load_manifest(path):
|
|
391
|
+
mpath = os.path.join(path, "snapshot.json")
|
|
392
|
+
try:
|
|
393
|
+
with open(mpath, encoding="utf-8") as f:
|
|
394
|
+
manifest = json.load(f)
|
|
395
|
+
except OSError as e:
|
|
396
|
+
raise ValueError(f"cannot read snapshot manifest "
|
|
397
|
+
f"{mpath}: {e}") from e
|
|
398
|
+
except json.JSONDecodeError as e:
|
|
399
|
+
raise ValueError(f"snapshot manifest is not valid "
|
|
400
|
+
f"JSON: {e}") from e
|
|
401
|
+
if manifest.get("tool") != SNAPSHOT_TOOL:
|
|
402
|
+
raise ValueError("not a wpchecker snapshot "
|
|
403
|
+
"(manifest tool mismatch)")
|
|
404
|
+
if manifest.get("version") != SNAPSHOT_VERSION:
|
|
405
|
+
raise ValueError(f"unsupported snapshot version "
|
|
406
|
+
f"{manifest.get('version')!r}")
|
|
407
|
+
if not manifest.get("target"):
|
|
408
|
+
raise ValueError("snapshot manifest has no target")
|
|
409
|
+
if "homepage" not in manifest.get("files", {}):
|
|
410
|
+
raise ValueError("snapshot manifest names no homepage "
|
|
411
|
+
"capture")
|
|
412
|
+
return manifest
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
# A capture can never legitimately be larger than the live
|
|
416
|
+
# fetcher's own body cap (fetch._MAX_BODY), so a bigger file
|
|
417
|
+
# is not a capture at all: it is treated as missing rather
|
|
418
|
+
# than read into memory.
|
|
419
|
+
_MAX_CAPTURE_BYTES = 1024 * 1024
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _read_captured(base, rel):
|
|
423
|
+
"""Read one captured file, refusing paths that escape
|
|
424
|
+
the snapshot directory (manifests can come from other
|
|
425
|
+
people) and files too large to be a real capture. Both
|
|
426
|
+
the snapshot root and the requested path are fully
|
|
427
|
+
resolved (symlinks included) before the containment
|
|
428
|
+
check, so a symlink inside the snapshot cannot smuggle
|
|
429
|
+
in a file from outside it. Returns None when refused,
|
|
430
|
+
oversized or unreadable."""
|
|
431
|
+
root = os.path.realpath(base)
|
|
432
|
+
full = os.path.realpath(os.path.join(root, rel))
|
|
433
|
+
if full != root and not full.startswith(root + os.sep):
|
|
434
|
+
return None
|
|
435
|
+
try:
|
|
436
|
+
with open(full, "rb") as f:
|
|
437
|
+
raw = f.read(_MAX_CAPTURE_BYTES + 1)
|
|
438
|
+
except OSError:
|
|
439
|
+
return None
|
|
440
|
+
if len(raw) > _MAX_CAPTURE_BYTES:
|
|
441
|
+
return None
|
|
442
|
+
return raw.decode("utf-8", "replace")
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _captured_headers(manifest):
|
|
446
|
+
"""The homepage response headers recorded in the
|
|
447
|
+
manifest, normalized to the live fetcher's contract
|
|
448
|
+
(lowercase names, string values). Snapshots written
|
|
449
|
+
before headers were captured — or built by hand — simply
|
|
450
|
+
have none, and replay exactly as they did before."""
|
|
451
|
+
raw = (manifest.get("headers") or {}).get("homepage") or {}
|
|
452
|
+
if not isinstance(raw, dict):
|
|
453
|
+
return {}
|
|
454
|
+
return {str(k).lower(): v for k, v in raw.items()
|
|
455
|
+
if isinstance(v, str)}
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _snapshot_fetch(manifest, base):
|
|
459
|
+
"""A fetch-contract callable backed ONLY by the captured
|
|
460
|
+
files. It opens no sockets: unknown URLs are 404s, which
|
|
461
|
+
is exactly what the scan engine expects for files the
|
|
462
|
+
site did not serve."""
|
|
463
|
+
files = manifest.get("files", {})
|
|
464
|
+
target = manifest["target"]
|
|
465
|
+
final = manifest.get("final_url") or target
|
|
466
|
+
origin = _origin(final)
|
|
467
|
+
home_headers = _captured_headers(manifest)
|
|
468
|
+
readmes = {k.lower(): v for k, v in
|
|
469
|
+
files.get("plugin_readmes", {}).items()}
|
|
470
|
+
styles = {k.lower(): v for k, v in
|
|
471
|
+
files.get("theme_styles", {}).items()}
|
|
472
|
+
|
|
473
|
+
def _resp(body, status, url, headers=None):
|
|
474
|
+
return {"ok": True, "status": status,
|
|
475
|
+
"final_url": final if status == 200 else url,
|
|
476
|
+
"headers": headers or {}, "body": body or "",
|
|
477
|
+
"error": None}
|
|
478
|
+
|
|
479
|
+
def get(url):
|
|
480
|
+
if url in (target, final):
|
|
481
|
+
body = _read_captured(base, files["homepage"])
|
|
482
|
+
if body is None:
|
|
483
|
+
return {"ok": False, "status": None,
|
|
484
|
+
"final_url": url, "headers": {},
|
|
485
|
+
"body": "",
|
|
486
|
+
"error": "homepage capture missing "
|
|
487
|
+
"from snapshot"}
|
|
488
|
+
return _resp(body, 200, url, headers=home_headers)
|
|
489
|
+
if url == origin + "/readme.html" and \
|
|
490
|
+
files.get("readme_html"):
|
|
491
|
+
body = _read_captured(base, files["readme_html"])
|
|
492
|
+
if body is not None:
|
|
493
|
+
return _resp(body, 200, url)
|
|
494
|
+
return _resp("", 404, url)
|
|
495
|
+
path = urllib.parse.urlsplit(url).path
|
|
496
|
+
m = _README_URL_RE.search(path)
|
|
497
|
+
if m and m.group(1).lower() in readmes:
|
|
498
|
+
body = _read_captured(
|
|
499
|
+
base, readmes[m.group(1).lower()])
|
|
500
|
+
if body is not None:
|
|
501
|
+
return _resp(body, 200, url)
|
|
502
|
+
return _resp("", 404, url)
|
|
503
|
+
m = _STYLE_URL_RE.search(path)
|
|
504
|
+
if m and m.group(1).lower() in styles:
|
|
505
|
+
body = _read_captured(
|
|
506
|
+
base, styles[m.group(1).lower()])
|
|
507
|
+
if body is not None:
|
|
508
|
+
return _resp(body, 200, url)
|
|
509
|
+
return _resp("", 404, url)
|
|
510
|
+
return _resp("", 404, url)
|
|
511
|
+
|
|
512
|
+
return get
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def scan_snapshot(path, db=None):
|
|
516
|
+
"""Replay a snapshot directory into the full scan
|
|
517
|
+
verdict, with zero network requests. The result is the
|
|
518
|
+
live result shape plus mode="snapshot" and a "snapshot"
|
|
519
|
+
block carrying the capture time and file count."""
|
|
520
|
+
if db is None:
|
|
521
|
+
db = adv.load_db()
|
|
522
|
+
manifest = _load_manifest(path)
|
|
523
|
+
result = _scan_with_fetch(manifest["target"],
|
|
524
|
+
_snapshot_fetch(manifest, path),
|
|
525
|
+
db)
|
|
526
|
+
result["mode"] = "snapshot"
|
|
527
|
+
files = manifest.get("files", {})
|
|
528
|
+
count = 1 + (1 if files.get("readme_html") else 0) \
|
|
529
|
+
+ len(files.get("plugin_readmes", {})) \
|
|
530
|
+
+ len(files.get("theme_styles", {}))
|
|
531
|
+
result["snapshot"] = {
|
|
532
|
+
"captured_at": manifest.get("captured_at"),
|
|
533
|
+
"path": str(path), "files": count}
|
|
534
|
+
return result
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def exit_code(result):
|
|
538
|
+
"""0 — assessed, nothing found. 1 — findings (vulnerable
|
|
539
|
+
components or hygiene). 2 — the scan could not judge:
|
|
540
|
+
unreachable, or not a WordPress site."""
|
|
541
|
+
if result["status"] != "ok":
|
|
542
|
+
return 2
|
|
543
|
+
s = result["summary"]
|
|
544
|
+
return 1 if (s["findings"] or s["hygiene_findings"]) else 0
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def render_text(result):
|
|
548
|
+
"""Human-readable rendering of a scan result."""
|
|
549
|
+
out = [f"wpchecker {__version__} — {result['target']}"]
|
|
550
|
+
if result.get("mode") == "snapshot":
|
|
551
|
+
snap = result.get("snapshot", {})
|
|
552
|
+
out.append(f"Evidence: snapshot captured "
|
|
553
|
+
f"{snap.get('captured_at')} — replayed "
|
|
554
|
+
f"offline, zero live requests")
|
|
555
|
+
if result["status"] == "unreachable":
|
|
556
|
+
out.append(f"UNREACHABLE — {result['error']}")
|
|
557
|
+
return "\n".join(out)
|
|
558
|
+
if result["status"] == "not_wordpress":
|
|
559
|
+
out.append("NOT WORDPRESS — no WordPress signals in the "
|
|
560
|
+
"homepage; nothing to assess.")
|
|
561
|
+
return "\n".join(out)
|
|
562
|
+
wp = result["wordpress"]
|
|
563
|
+
if wp["core_version"]:
|
|
564
|
+
out.append(f"WordPress core: {wp['core_version']} "
|
|
565
|
+
f"({wp['core_version_source']})")
|
|
566
|
+
else:
|
|
567
|
+
out.append("WordPress core: version hidden (the site "
|
|
568
|
+
"does not disclose it; not assessed)")
|
|
569
|
+
for label, comps in (("PLUGINS", result["plugins"]),
|
|
570
|
+
("THEMES", result["themes"])):
|
|
571
|
+
if not comps:
|
|
572
|
+
continue
|
|
573
|
+
out.append("")
|
|
574
|
+
out.append(label)
|
|
575
|
+
for c in comps:
|
|
576
|
+
ver = c["version"] or "version hidden"
|
|
577
|
+
src = f" ({c['version_source']})" if \
|
|
578
|
+
c["version_source"] else ""
|
|
579
|
+
active = " [active]" if c.get("active") else ""
|
|
580
|
+
out.append(f" {c['slug']} — {c['name']} {ver}{src}"
|
|
581
|
+
f"{active}")
|
|
582
|
+
if c["status"] == "vulnerable":
|
|
583
|
+
for f in c["findings"]:
|
|
584
|
+
kev = ", in CISA KEV" if f["kev"] else ""
|
|
585
|
+
out.append(
|
|
586
|
+
f" VULNERABLE — {f['cve']} "
|
|
587
|
+
f"({f['severity']}, CVSS {f['cvss']}{kev})")
|
|
588
|
+
out.append(
|
|
589
|
+
f" affected: {f['affected_range']} · "
|
|
590
|
+
f"installed: {f['installed_version']}")
|
|
591
|
+
out.append(
|
|
592
|
+
f" remediation: {f['remediation']}")
|
|
593
|
+
elif c["status"] == "version_hidden":
|
|
594
|
+
out.append(" version hidden — not assessed")
|
|
595
|
+
elif c["status"] == "not_in_dataset":
|
|
596
|
+
out.append(" not in the starter dataset — "
|
|
597
|
+
"not assessed")
|
|
598
|
+
else:
|
|
599
|
+
out.append(" no known vulnerabilities at "
|
|
600
|
+
"this version")
|
|
601
|
+
if result["hygiene"]:
|
|
602
|
+
out.append("")
|
|
603
|
+
out.append("HYGIENE")
|
|
604
|
+
for h in result["hygiene"]:
|
|
605
|
+
out.append(f" {h['title']} — {h['detail']}")
|
|
606
|
+
out.append(f" remediation: {h['remediation']}")
|
|
607
|
+
s = result["summary"]
|
|
608
|
+
out.append("")
|
|
609
|
+
out.append(f"Summary: {s['plugins_found']} plugins, "
|
|
610
|
+
f"{s['themes_found']} themes, "
|
|
611
|
+
f"{s['version_hidden']} version hidden, "
|
|
612
|
+
f"{s['findings']} findings, "
|
|
613
|
+
f"{s['hygiene_findings']} hygiene findings.")
|
|
614
|
+
return "\n".join(out)
|