audit-web-supply-chain.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. #!/usr/bin/env python3
  2. """Audit public web assets and third-party script references for the ZQ site group."""
  3. from __future__ import annotations
  4. import argparse
  5. import concurrent.futures
  6. import hashlib
  7. import json
  8. import os
  9. import re
  10. import subprocess
  11. import sys
  12. import urllib.parse
  13. import urllib.request
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. from typing import Any
  17. ROOT = Path(__file__).resolve().parents[2]
  18. DEFAULT_MANIFEST = ROOT / "security" / "web-assets.json"
  19. SCAN_ROOTS = (
  20. "WebRoot/main",
  21. "WebRoot/apps",
  22. "WebRoot/web/upload/ffkj-template",
  23. "WebRoot/web/subassembly/website",
  24. )
  25. EXCLUDED_PREFIXES = (
  26. "WebRoot/main/dev/",
  27. "WebRoot/apps/space/plug-in/ueditor/dialogs/",
  28. )
  29. TEXT_SUFFIXES = {".jsp", ".html", ".htm", ".js", ".css", ".xml", ".json", ".txt"}
  30. SCRIPT_RE = re.compile(r"<script\b[^>]*>", re.IGNORECASE)
  31. SRC_RE = re.compile(r"\bsrc\s*=\s*[\"']([^\"']+)", re.IGNORECASE)
  32. INTEGRITY_RE = re.compile(r"\bintegrity\s*=", re.IGNORECASE)
  33. HTTP_URL_RE = re.compile(r"https?://[^\s\"'<>)]+", re.IGNORECASE)
  34. SUPERSLIDE_CALL_RE = re.compile(
  35. r"\.(?:slideTxtBox|slideBox|picSlideBox)[^;\n]*\.slide\s*\(",
  36. re.IGNORECASE,
  37. )
  38. MAX_FILE_BYTES = 8 * 1024 * 1024
  39. def load_manifest(path: Path) -> dict[str, Any]:
  40. with path.open(encoding="utf-8") as handle:
  41. return json.load(handle)
  42. def sha256(path: Path) -> str:
  43. digest = hashlib.sha256()
  44. with path.open("rb") as handle:
  45. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  46. digest.update(chunk)
  47. return digest.hexdigest()
  48. def is_skipped(path: Path, include_backups: bool) -> bool:
  49. parts = set(path.parts)
  50. if ".git" in parts or "node_modules" in parts:
  51. return True
  52. if not include_backups and "backup" in parts:
  53. return True
  54. try:
  55. return path.stat().st_size > MAX_FILE_BYTES
  56. except OSError:
  57. return True
  58. def external_script_records(text: str, page_url: str) -> list[dict[str, Any]]:
  59. records: list[dict[str, Any]] = []
  60. text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
  61. for tag in SCRIPT_RE.findall(text):
  62. match = SRC_RE.search(tag)
  63. if not match:
  64. continue
  65. raw_url = match.group(1).strip()
  66. if (
  67. not raw_url
  68. or raw_url.startswith(("#", "javascript:", "data:"))
  69. or "${" in raw_url
  70. ):
  71. continue
  72. absolute = urllib.parse.urljoin(page_url, raw_url)
  73. parsed = urllib.parse.urlparse(absolute)
  74. if parsed.scheme not in ("http", "https"):
  75. continue
  76. page_host = (urllib.parse.urlparse(page_url).hostname or "").lower()
  77. script_host = (parsed.hostname or "").lower()
  78. records.append(
  79. {
  80. "url": absolute,
  81. "host": script_host,
  82. "path": parsed.path,
  83. "hasIntegrity": bool(INTEGRITY_RE.search(tag)),
  84. "isExternal": bool(script_host and script_host != page_host),
  85. "tag": tag,
  86. }
  87. )
  88. return records
  89. def exception_for(host: str, path: str, manifest: dict[str, Any]) -> dict[str, Any] | None:
  90. for item in manifest.get("externalScriptExceptions", []):
  91. if host == item.get("host", "").lower() and path.startswith(item.get("pathPrefix", "")):
  92. return item
  93. return None
  94. def scan_text_file(path: Path, manifest: dict[str, Any]) -> dict[str, Any]:
  95. relative = path.relative_to(ROOT).as_posix()
  96. result: dict[str, Any] = {
  97. "path": relative,
  98. "bannedDomains": [],
  99. "externalScripts": [],
  100. "superSlideCalls": 0,
  101. }
  102. try:
  103. text = path.read_text(encoding="utf-8", errors="replace")
  104. except OSError as exc:
  105. result["readError"] = str(exc)
  106. return result
  107. lowered = text.lower()
  108. for domain in manifest.get("bannedDomains", []):
  109. if domain.lower() in lowered:
  110. result["bannedDomains"].append(domain)
  111. if path.suffix.lower() in {".jsp", ".html", ".htm"}:
  112. result["externalScripts"] = [
  113. script
  114. for script in external_script_records(text, "https://local.invalid/")
  115. if script["isExternal"]
  116. ]
  117. result["superSlideCalls"] = len(SUPERSLIDE_CALL_RE.findall(text))
  118. return result
  119. def scan_static(manifest: dict[str, Any], include_backups: bool) -> dict[str, Any]:
  120. files: list[dict[str, Any]] = []
  121. violations: list[dict[str, Any]] = []
  122. warnings: list[dict[str, Any]] = []
  123. for root_name in SCAN_ROOTS:
  124. root = ROOT / root_name
  125. if not root.exists():
  126. continue
  127. for path in root.rglob("*"):
  128. if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES:
  129. continue
  130. relative = path.relative_to(ROOT).as_posix()
  131. if relative.startswith(EXCLUDED_PREFIXES):
  132. continue
  133. if is_skipped(path, include_backups):
  134. continue
  135. record = scan_text_file(path, manifest)
  136. if not record["bannedDomains"] and not record["externalScripts"] and not record["superSlideCalls"]:
  137. continue
  138. files.append(record)
  139. if record["bannedDomains"]:
  140. violations.append(
  141. {
  142. "type": "banned-domain",
  143. "path": record["path"],
  144. "domains": record["bannedDomains"],
  145. }
  146. )
  147. for script in record["externalScripts"]:
  148. exception = exception_for(script["host"], script["path"], manifest)
  149. if exception is None:
  150. violations.append(
  151. {
  152. "type": "unapproved-external-script",
  153. "path": record["path"],
  154. "url": script["url"],
  155. }
  156. )
  157. elif not script["hasIntegrity"]:
  158. warnings.append(
  159. {
  160. "type": "external-script-without-integrity",
  161. "path": record["path"],
  162. "url": script["url"],
  163. "owner": exception.get("owner", ""),
  164. }
  165. )
  166. if record["superSlideCalls"]:
  167. warnings.append(
  168. {
  169. "type": "legacy-superslide-call",
  170. "path": record["path"],
  171. "count": record["superSlideCalls"],
  172. }
  173. )
  174. for asset in manifest.get("approvedLocalAssets", []):
  175. path = ROOT / asset["path"]
  176. if not path.exists():
  177. violations.append({"type": "approved-asset-missing", "path": asset["path"]})
  178. continue
  179. actual = sha256(path)
  180. if actual != asset["sha256"]:
  181. violations.append(
  182. {
  183. "type": "approved-asset-hash-mismatch",
  184. "path": asset["path"],
  185. "expected": asset["sha256"],
  186. "actual": actual,
  187. }
  188. )
  189. return {"files": files, "violations": violations, "warnings": warnings}
  190. def mysql_command(args: argparse.Namespace) -> list[str]:
  191. command = [
  192. args.mysql,
  193. "--batch",
  194. "--skip-column-names",
  195. "--default-character-set=utf8mb4",
  196. "--user",
  197. args.db_user,
  198. ]
  199. if args.db_socket:
  200. command.extend(["--socket", args.db_socket])
  201. else:
  202. command.extend(["--host", args.db_host, "--port", str(args.db_port)])
  203. if args.db_password:
  204. command.append(f"--password={args.db_password}")
  205. command.append(args.db_name)
  206. return command + ["--execute", args.db_query]
  207. def scan_db(manifest: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
  208. env = os.environ.copy()
  209. password = args.db_password or env.get("ZQ_DB_PASSWORD") or env.get("ZQ_APP_DB_PASSWORD")
  210. if password:
  211. env["MYSQL_PWD"] = password
  212. try:
  213. completed = subprocess.run(
  214. mysql_command(args),
  215. cwd=ROOT,
  216. env=env,
  217. text=True,
  218. capture_output=True,
  219. check=False,
  220. )
  221. except OSError as exc:
  222. return {"error": str(exc), "paths": [], "findings": [], "warnings": []}
  223. if completed.returncode != 0:
  224. return {
  225. "error": completed.stderr.strip() or f"mysql exited {completed.returncode}",
  226. "paths": [],
  227. "findings": [],
  228. "warnings": [],
  229. }
  230. paths: list[dict[str, Any]] = []
  231. findings: list[dict[str, Any]] = []
  232. warnings: list[dict[str, Any]] = []
  233. for line in completed.stdout.splitlines():
  234. if not line.strip():
  235. continue
  236. fields = line.split("\t")
  237. if len(fields) != 4:
  238. continue
  239. article_id, website_id, content_path, edit_content_path = fields
  240. for kind, value in (("content", content_path), ("editContent", edit_content_path)):
  241. if not value:
  242. continue
  243. candidate = ROOT / "WebRoot" / value.lstrip("/")
  244. record = {
  245. "articleId": article_id,
  246. "websiteId": website_id,
  247. "kind": kind,
  248. "registeredPath": value,
  249. "resolvedPath": candidate.relative_to(ROOT).as_posix(),
  250. "exists": candidate.exists(),
  251. }
  252. paths.append(record)
  253. if not candidate.exists():
  254. warnings.append({"type": "db-content-file-missing", **record})
  255. continue
  256. scanned = scan_text_file(candidate, manifest)
  257. if scanned["bannedDomains"]:
  258. findings.append(
  259. {
  260. "type": "banned-domain-in-db-content",
  261. **record,
  262. "domains": scanned["bannedDomains"],
  263. }
  264. )
  265. return {"error": "", "paths": paths, "findings": findings, "warnings": warnings}
  266. def fetch_live(url: str, timeout: int) -> tuple[int, str, str]:
  267. request = urllib.request.Request(
  268. url,
  269. headers={"User-Agent": "Mozilla/5.0 (compatible; ZQ-security-audit/1.0)"},
  270. )
  271. with urllib.request.urlopen(request, timeout=timeout) as response:
  272. charset = response.headers.get_content_charset() or "utf-8"
  273. return response.status, response.geturl(), response.read(4_000_000).decode(charset, "replace")
  274. def scan_live(manifest: dict[str, Any], timeout: int) -> dict[str, Any]:
  275. def scan_site(site: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
  276. site_violations: list[dict[str, Any]] = []
  277. record: dict[str, Any] = {"name": site["name"], "url": site["url"]}
  278. try:
  279. status, final_url, body = fetch_live(site["url"], timeout)
  280. scripts = external_script_records(body, final_url)
  281. bad_domains = [domain for domain in manifest.get("bannedDomains", []) if domain.lower() in body.lower()]
  282. record.update(
  283. {
  284. "status": status,
  285. "finalUrl": final_url,
  286. "bannedDomains": bad_domains,
  287. "externalScripts": scripts,
  288. }
  289. )
  290. if bad_domains:
  291. site_violations.append(
  292. {"type": "banned-domain-live", "site": site["name"], "domains": bad_domains}
  293. )
  294. for script in scripts:
  295. if not script["isExternal"]:
  296. continue
  297. exception = exception_for(script["host"], script["path"], manifest)
  298. if exception is None:
  299. site_violations.append(
  300. {
  301. "type": "unapproved-external-script-live",
  302. "site": site["name"],
  303. "url": script["url"],
  304. }
  305. )
  306. seen_scripts: set[str] = set()
  307. same_origin_urls: list[str] = []
  308. for script in scripts:
  309. if script["isExternal"] or script["url"] in seen_scripts:
  310. continue
  311. seen_scripts.add(script["url"])
  312. same_origin_urls.append(script["url"])
  313. def fetch_script(script_url: str) -> dict[str, Any]:
  314. try:
  315. _, _, script_body = fetch_live(script_url, timeout)
  316. except Exception as exc:
  317. return {
  318. "url": script_url,
  319. "status": 0,
  320. "error": f"{type(exc).__name__}: {exc}",
  321. }
  322. script_bad_domains = [
  323. domain for domain in manifest.get("bannedDomains", []) if domain.lower() in script_body.lower()
  324. ]
  325. return {
  326. "url": script_url,
  327. "status": 200,
  328. "sha256": hashlib.sha256(script_body.encode("utf-8")).hexdigest(),
  329. "bannedDomains": script_bad_domains,
  330. }
  331. same_origin_assets: list[dict[str, Any]] = []
  332. if same_origin_urls:
  333. with concurrent.futures.ThreadPoolExecutor(max_workers=min(6, len(same_origin_urls))) as executor:
  334. same_origin_assets = list(executor.map(fetch_script, same_origin_urls))
  335. for asset in same_origin_assets:
  336. script_bad_domains = asset.get("bannedDomains", [])
  337. if script_bad_domains:
  338. site_violations.append(
  339. {
  340. "type": "banned-domain-live-script",
  341. "site": site["name"],
  342. "url": asset["url"],
  343. "domains": script_bad_domains,
  344. }
  345. )
  346. record["sameOriginScripts"] = same_origin_assets
  347. except Exception as exc: # network failures are reported, not hidden
  348. record.update({"status": 0, "error": f"{type(exc).__name__}: {exc}"})
  349. return record, site_violations
  350. sites = manifest.get("websites", [])
  351. if not sites:
  352. return {"records": [], "violations": []}
  353. with concurrent.futures.ThreadPoolExecutor(max_workers=min(6, len(sites))) as executor:
  354. results = list(executor.map(scan_site, sites))
  355. records: list[dict[str, Any]] = []
  356. violations: list[dict[str, Any]] = []
  357. for record, site_violations in results:
  358. records.append(record)
  359. violations.extend(site_violations)
  360. return {"records": records, "violations": violations}
  361. def parse_args() -> argparse.Namespace:
  362. parser = argparse.ArgumentParser(description=__doc__)
  363. parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
  364. parser.add_argument("--json", type=Path, help="write the full JSON report")
  365. parser.add_argument("--include-backups", action="store_true")
  366. parser.add_argument("--verbose", action="store_true")
  367. parser.add_argument("--live", action="store_true")
  368. parser.add_argument("--live-timeout", type=int, default=20)
  369. parser.add_argument("--db", action="store_true")
  370. parser.add_argument("--mysql", default=os.environ.get("ZQ_MYSQL_BIN", "mysql"))
  371. parser.add_argument("--db-host", default=os.environ.get("ZQ_DB_HOST", "127.0.0.1"))
  372. parser.add_argument("--db-port", type=int, default=int(os.environ.get("ZQ_DB_PORT", "3318")))
  373. parser.add_argument("--db-socket", default=os.environ.get("ZQ_DB_SOCKET", ""))
  374. parser.add_argument("--db-user", default=os.environ.get("ZQ_DB_USER", "zq_local"))
  375. parser.add_argument("--db-password", default=os.environ.get("ZQ_DB_PASSWORD", ""))
  376. parser.add_argument("--db-name", default=os.environ.get("ZQ_APPS_DB_NAME", "spaceappsv1"))
  377. parser.add_argument(
  378. "--db-query",
  379. default="SELECT articleid,websiteid,content,COALESCE(edit_content,'') FROM article ORDER BY articleid",
  380. )
  381. return parser.parse_args()
  382. def main() -> int:
  383. args = parse_args()
  384. manifest = load_manifest(args.manifest)
  385. static = scan_static(manifest, args.include_backups)
  386. db = (
  387. scan_db(manifest, args)
  388. if args.db
  389. else {"error": "", "paths": [], "findings": [], "warnings": []}
  390. )
  391. live = scan_live(manifest, args.live_timeout) if args.live else {"records": [], "violations": []}
  392. violations = static["violations"] + db["findings"] + live["violations"]
  393. if args.db and db["error"]:
  394. violations.append({"type": "database-audit-failed", "error": db["error"]})
  395. warnings = static["warnings"] + db["warnings"]
  396. report = {
  397. "generatedAt": datetime.now(timezone.utc).isoformat(),
  398. "manifest": (
  399. args.manifest.relative_to(ROOT).as_posix()
  400. if args.manifest.is_relative_to(ROOT)
  401. else str(args.manifest)
  402. ),
  403. "summary": {
  404. "websites": len(manifest.get("websites", [])),
  405. "filesWithSignals": len(static["files"]),
  406. "dbContentPaths": len(db["paths"]),
  407. "liveChecked": len(live["records"]),
  408. "violations": len(violations),
  409. "warnings": len(warnings),
  410. "dbError": db["error"],
  411. },
  412. "violations": violations,
  413. "warnings": warnings,
  414. "staticFiles": static["files"],
  415. "db": db,
  416. "live": live,
  417. }
  418. if args.json:
  419. args.json.parent.mkdir(parents=True, exist_ok=True)
  420. args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  421. print(
  422. "sites={websites} signals={filesWithSignals} dbPaths={dbContentPaths} "
  423. "live={liveChecked} violations={violations} warnings={warnings}".format(**report["summary"])
  424. )
  425. if db["error"]:
  426. print(f"database: {db['error']}", file=sys.stderr)
  427. for violation in violations:
  428. print(f"VIOLATION {json.dumps(violation, ensure_ascii=False)}", file=sys.stderr)
  429. if args.verbose:
  430. for warning in warnings:
  431. print(f"WARNING {json.dumps(warning, ensure_ascii=False)}", file=sys.stderr)
  432. return 1 if violations else 0
  433. if __name__ == "__main__":
  434. raise SystemExit(main())