| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475 |
- #!/usr/bin/env python3
- """Audit public web assets and third-party script references for the ZQ site group."""
- from __future__ import annotations
- import argparse
- import concurrent.futures
- import hashlib
- import json
- import os
- import re
- import subprocess
- import sys
- import urllib.parse
- import urllib.request
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- ROOT = Path(__file__).resolve().parents[2]
- DEFAULT_MANIFEST = ROOT / "security" / "web-assets.json"
- SCAN_ROOTS = (
- "WebRoot/main",
- "WebRoot/apps",
- "WebRoot/web/upload/ffkj-template",
- "WebRoot/web/subassembly/website",
- )
- EXCLUDED_PREFIXES = (
- "WebRoot/main/dev/",
- "WebRoot/apps/space/plug-in/ueditor/dialogs/",
- )
- TEXT_SUFFIXES = {".jsp", ".html", ".htm", ".js", ".css", ".xml", ".json", ".txt"}
- SCRIPT_RE = re.compile(r"<script\b[^>]*>", re.IGNORECASE)
- SRC_RE = re.compile(r"\bsrc\s*=\s*[\"']([^\"']+)", re.IGNORECASE)
- INTEGRITY_RE = re.compile(r"\bintegrity\s*=", re.IGNORECASE)
- HTTP_URL_RE = re.compile(r"https?://[^\s\"'<>)]+", re.IGNORECASE)
- SUPERSLIDE_CALL_RE = re.compile(
- r"\.(?:slideTxtBox|slideBox|picSlideBox)[^;\n]*\.slide\s*\(",
- re.IGNORECASE,
- )
- MAX_FILE_BYTES = 8 * 1024 * 1024
- def load_manifest(path: Path) -> dict[str, Any]:
- with path.open(encoding="utf-8") as handle:
- return json.load(handle)
- def sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def is_skipped(path: Path, include_backups: bool) -> bool:
- parts = set(path.parts)
- if ".git" in parts or "node_modules" in parts:
- return True
- if not include_backups and "backup" in parts:
- return True
- try:
- return path.stat().st_size > MAX_FILE_BYTES
- except OSError:
- return True
- def external_script_records(text: str, page_url: str) -> list[dict[str, Any]]:
- records: list[dict[str, Any]] = []
- text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
- for tag in SCRIPT_RE.findall(text):
- match = SRC_RE.search(tag)
- if not match:
- continue
- raw_url = match.group(1).strip()
- if (
- not raw_url
- or raw_url.startswith(("#", "javascript:", "data:"))
- or "${" in raw_url
- ):
- continue
- absolute = urllib.parse.urljoin(page_url, raw_url)
- parsed = urllib.parse.urlparse(absolute)
- if parsed.scheme not in ("http", "https"):
- continue
- page_host = (urllib.parse.urlparse(page_url).hostname or "").lower()
- script_host = (parsed.hostname or "").lower()
- records.append(
- {
- "url": absolute,
- "host": script_host,
- "path": parsed.path,
- "hasIntegrity": bool(INTEGRITY_RE.search(tag)),
- "isExternal": bool(script_host and script_host != page_host),
- "tag": tag,
- }
- )
- return records
- def exception_for(host: str, path: str, manifest: dict[str, Any]) -> dict[str, Any] | None:
- for item in manifest.get("externalScriptExceptions", []):
- if host == item.get("host", "").lower() and path.startswith(item.get("pathPrefix", "")):
- return item
- return None
- def scan_text_file(path: Path, manifest: dict[str, Any]) -> dict[str, Any]:
- relative = path.relative_to(ROOT).as_posix()
- result: dict[str, Any] = {
- "path": relative,
- "bannedDomains": [],
- "externalScripts": [],
- "superSlideCalls": 0,
- }
- try:
- text = path.read_text(encoding="utf-8", errors="replace")
- except OSError as exc:
- result["readError"] = str(exc)
- return result
- lowered = text.lower()
- for domain in manifest.get("bannedDomains", []):
- if domain.lower() in lowered:
- result["bannedDomains"].append(domain)
- if path.suffix.lower() in {".jsp", ".html", ".htm"}:
- result["externalScripts"] = [
- script
- for script in external_script_records(text, "https://local.invalid/")
- if script["isExternal"]
- ]
- result["superSlideCalls"] = len(SUPERSLIDE_CALL_RE.findall(text))
- return result
- def scan_static(manifest: dict[str, Any], include_backups: bool) -> dict[str, Any]:
- files: list[dict[str, Any]] = []
- violations: list[dict[str, Any]] = []
- warnings: list[dict[str, Any]] = []
- for root_name in SCAN_ROOTS:
- root = ROOT / root_name
- if not root.exists():
- continue
- for path in root.rglob("*"):
- if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES:
- continue
- relative = path.relative_to(ROOT).as_posix()
- if relative.startswith(EXCLUDED_PREFIXES):
- continue
- if is_skipped(path, include_backups):
- continue
- record = scan_text_file(path, manifest)
- if not record["bannedDomains"] and not record["externalScripts"] and not record["superSlideCalls"]:
- continue
- files.append(record)
- if record["bannedDomains"]:
- violations.append(
- {
- "type": "banned-domain",
- "path": record["path"],
- "domains": record["bannedDomains"],
- }
- )
- for script in record["externalScripts"]:
- exception = exception_for(script["host"], script["path"], manifest)
- if exception is None:
- violations.append(
- {
- "type": "unapproved-external-script",
- "path": record["path"],
- "url": script["url"],
- }
- )
- elif not script["hasIntegrity"]:
- warnings.append(
- {
- "type": "external-script-without-integrity",
- "path": record["path"],
- "url": script["url"],
- "owner": exception.get("owner", ""),
- }
- )
- if record["superSlideCalls"]:
- warnings.append(
- {
- "type": "legacy-superslide-call",
- "path": record["path"],
- "count": record["superSlideCalls"],
- }
- )
- for asset in manifest.get("approvedLocalAssets", []):
- path = ROOT / asset["path"]
- if not path.exists():
- violations.append({"type": "approved-asset-missing", "path": asset["path"]})
- continue
- actual = sha256(path)
- if actual != asset["sha256"]:
- violations.append(
- {
- "type": "approved-asset-hash-mismatch",
- "path": asset["path"],
- "expected": asset["sha256"],
- "actual": actual,
- }
- )
- return {"files": files, "violations": violations, "warnings": warnings}
- def mysql_command(args: argparse.Namespace) -> list[str]:
- command = [
- args.mysql,
- "--batch",
- "--skip-column-names",
- "--default-character-set=utf8mb4",
- "--user",
- args.db_user,
- ]
- if args.db_socket:
- command.extend(["--socket", args.db_socket])
- else:
- command.extend(["--host", args.db_host, "--port", str(args.db_port)])
- if args.db_password:
- command.append(f"--password={args.db_password}")
- command.append(args.db_name)
- return command + ["--execute", args.db_query]
- def scan_db(manifest: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
- env = os.environ.copy()
- password = args.db_password or env.get("ZQ_DB_PASSWORD") or env.get("ZQ_APP_DB_PASSWORD")
- if password:
- env["MYSQL_PWD"] = password
- try:
- completed = subprocess.run(
- mysql_command(args),
- cwd=ROOT,
- env=env,
- text=True,
- capture_output=True,
- check=False,
- )
- except OSError as exc:
- return {"error": str(exc), "paths": [], "findings": [], "warnings": []}
- if completed.returncode != 0:
- return {
- "error": completed.stderr.strip() or f"mysql exited {completed.returncode}",
- "paths": [],
- "findings": [],
- "warnings": [],
- }
- paths: list[dict[str, Any]] = []
- findings: list[dict[str, Any]] = []
- warnings: list[dict[str, Any]] = []
- for line in completed.stdout.splitlines():
- if not line.strip():
- continue
- fields = line.split("\t")
- if len(fields) != 4:
- continue
- article_id, website_id, content_path, edit_content_path = fields
- for kind, value in (("content", content_path), ("editContent", edit_content_path)):
- if not value:
- continue
- candidate = ROOT / "WebRoot" / value.lstrip("/")
- record = {
- "articleId": article_id,
- "websiteId": website_id,
- "kind": kind,
- "registeredPath": value,
- "resolvedPath": candidate.relative_to(ROOT).as_posix(),
- "exists": candidate.exists(),
- }
- paths.append(record)
- if not candidate.exists():
- warnings.append({"type": "db-content-file-missing", **record})
- continue
- scanned = scan_text_file(candidate, manifest)
- if scanned["bannedDomains"]:
- findings.append(
- {
- "type": "banned-domain-in-db-content",
- **record,
- "domains": scanned["bannedDomains"],
- }
- )
- return {"error": "", "paths": paths, "findings": findings, "warnings": warnings}
- def fetch_live(url: str, timeout: int) -> tuple[int, str, str]:
- request = urllib.request.Request(
- url,
- headers={"User-Agent": "Mozilla/5.0 (compatible; ZQ-security-audit/1.0)"},
- )
- with urllib.request.urlopen(request, timeout=timeout) as response:
- charset = response.headers.get_content_charset() or "utf-8"
- return response.status, response.geturl(), response.read(4_000_000).decode(charset, "replace")
- def scan_live(manifest: dict[str, Any], timeout: int) -> dict[str, Any]:
- def scan_site(site: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
- site_violations: list[dict[str, Any]] = []
- record: dict[str, Any] = {"name": site["name"], "url": site["url"]}
- try:
- status, final_url, body = fetch_live(site["url"], timeout)
- scripts = external_script_records(body, final_url)
- bad_domains = [domain for domain in manifest.get("bannedDomains", []) if domain.lower() in body.lower()]
- record.update(
- {
- "status": status,
- "finalUrl": final_url,
- "bannedDomains": bad_domains,
- "externalScripts": scripts,
- }
- )
- if bad_domains:
- site_violations.append(
- {"type": "banned-domain-live", "site": site["name"], "domains": bad_domains}
- )
- for script in scripts:
- if not script["isExternal"]:
- continue
- exception = exception_for(script["host"], script["path"], manifest)
- if exception is None:
- site_violations.append(
- {
- "type": "unapproved-external-script-live",
- "site": site["name"],
- "url": script["url"],
- }
- )
- seen_scripts: set[str] = set()
- same_origin_urls: list[str] = []
- for script in scripts:
- if script["isExternal"] or script["url"] in seen_scripts:
- continue
- seen_scripts.add(script["url"])
- same_origin_urls.append(script["url"])
- def fetch_script(script_url: str) -> dict[str, Any]:
- try:
- _, _, script_body = fetch_live(script_url, timeout)
- except Exception as exc:
- return {
- "url": script_url,
- "status": 0,
- "error": f"{type(exc).__name__}: {exc}",
- }
- script_bad_domains = [
- domain for domain in manifest.get("bannedDomains", []) if domain.lower() in script_body.lower()
- ]
- return {
- "url": script_url,
- "status": 200,
- "sha256": hashlib.sha256(script_body.encode("utf-8")).hexdigest(),
- "bannedDomains": script_bad_domains,
- }
- same_origin_assets: list[dict[str, Any]] = []
- if same_origin_urls:
- with concurrent.futures.ThreadPoolExecutor(max_workers=min(6, len(same_origin_urls))) as executor:
- same_origin_assets = list(executor.map(fetch_script, same_origin_urls))
- for asset in same_origin_assets:
- script_bad_domains = asset.get("bannedDomains", [])
- if script_bad_domains:
- site_violations.append(
- {
- "type": "banned-domain-live-script",
- "site": site["name"],
- "url": asset["url"],
- "domains": script_bad_domains,
- }
- )
- record["sameOriginScripts"] = same_origin_assets
- except Exception as exc: # network failures are reported, not hidden
- record.update({"status": 0, "error": f"{type(exc).__name__}: {exc}"})
- return record, site_violations
- sites = manifest.get("websites", [])
- if not sites:
- return {"records": [], "violations": []}
- with concurrent.futures.ThreadPoolExecutor(max_workers=min(6, len(sites))) as executor:
- results = list(executor.map(scan_site, sites))
- records: list[dict[str, Any]] = []
- violations: list[dict[str, Any]] = []
- for record, site_violations in results:
- records.append(record)
- violations.extend(site_violations)
- return {"records": records, "violations": violations}
- def parse_args() -> argparse.Namespace:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
- parser.add_argument("--json", type=Path, help="write the full JSON report")
- parser.add_argument("--include-backups", action="store_true")
- parser.add_argument("--verbose", action="store_true")
- parser.add_argument("--live", action="store_true")
- parser.add_argument("--live-timeout", type=int, default=20)
- parser.add_argument("--db", action="store_true")
- parser.add_argument("--mysql", default=os.environ.get("ZQ_MYSQL_BIN", "mysql"))
- parser.add_argument("--db-host", default=os.environ.get("ZQ_DB_HOST", "127.0.0.1"))
- parser.add_argument("--db-port", type=int, default=int(os.environ.get("ZQ_DB_PORT", "3318")))
- parser.add_argument("--db-socket", default=os.environ.get("ZQ_DB_SOCKET", ""))
- parser.add_argument("--db-user", default=os.environ.get("ZQ_DB_USER", "zq_local"))
- parser.add_argument("--db-password", default=os.environ.get("ZQ_DB_PASSWORD", ""))
- parser.add_argument("--db-name", default=os.environ.get("ZQ_APPS_DB_NAME", "spaceappsv1"))
- parser.add_argument(
- "--db-query",
- default="SELECT articleid,websiteid,content,COALESCE(edit_content,'') FROM article ORDER BY articleid",
- )
- return parser.parse_args()
- def main() -> int:
- args = parse_args()
- manifest = load_manifest(args.manifest)
- static = scan_static(manifest, args.include_backups)
- db = (
- scan_db(manifest, args)
- if args.db
- else {"error": "", "paths": [], "findings": [], "warnings": []}
- )
- live = scan_live(manifest, args.live_timeout) if args.live else {"records": [], "violations": []}
- violations = static["violations"] + db["findings"] + live["violations"]
- if args.db and db["error"]:
- violations.append({"type": "database-audit-failed", "error": db["error"]})
- warnings = static["warnings"] + db["warnings"]
- report = {
- "generatedAt": datetime.now(timezone.utc).isoformat(),
- "manifest": (
- args.manifest.relative_to(ROOT).as_posix()
- if args.manifest.is_relative_to(ROOT)
- else str(args.manifest)
- ),
- "summary": {
- "websites": len(manifest.get("websites", [])),
- "filesWithSignals": len(static["files"]),
- "dbContentPaths": len(db["paths"]),
- "liveChecked": len(live["records"]),
- "violations": len(violations),
- "warnings": len(warnings),
- "dbError": db["error"],
- },
- "violations": violations,
- "warnings": warnings,
- "staticFiles": static["files"],
- "db": db,
- "live": live,
- }
- if args.json:
- args.json.parent.mkdir(parents=True, exist_ok=True)
- args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- print(
- "sites={websites} signals={filesWithSignals} dbPaths={dbContentPaths} "
- "live={liveChecked} violations={violations} warnings={warnings}".format(**report["summary"])
- )
- if db["error"]:
- print(f"database: {db['error']}", file=sys.stderr)
- for violation in violations:
- print(f"VIOLATION {json.dumps(violation, ensure_ascii=False)}", file=sys.stderr)
- if args.verbose:
- for warning in warnings:
- print(f"WARNING {json.dumps(warning, ensure_ascii=False)}", file=sys.stderr)
- return 1 if violations else 0
- if __name__ == "__main__":
- raise SystemExit(main())
|