|
|
@@ -0,0 +1,452 @@
|
|
|
+#!/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 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]:
|
|
|
+ records: list[dict[str, Any]] = []
|
|
|
+ violations: list[dict[str, Any]] = []
|
|
|
+ for site in manifest.get("websites", []):
|
|
|
+ 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:
|
|
|
+ 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:
|
|
|
+ violations.append(
|
|
|
+ {
|
|
|
+ "type": "unapproved-external-script-live",
|
|
|
+ "site": site["name"],
|
|
|
+ "url": script["url"],
|
|
|
+ }
|
|
|
+ )
|
|
|
+ same_origin_assets: list[dict[str, Any]] = []
|
|
|
+ seen_scripts: set[str] = set()
|
|
|
+ for script in scripts:
|
|
|
+ if script["isExternal"] or script["url"] in seen_scripts:
|
|
|
+ continue
|
|
|
+ seen_scripts.add(script["url"])
|
|
|
+ try:
|
|
|
+ _, _, script_body = fetch_live(script["url"], timeout)
|
|
|
+ except Exception as exc:
|
|
|
+ same_origin_assets.append(
|
|
|
+ {
|
|
|
+ "url": script["url"],
|
|
|
+ "status": 0,
|
|
|
+ "error": f"{type(exc).__name__}: {exc}",
|
|
|
+ }
|
|
|
+ )
|
|
|
+ continue
|
|
|
+ script_bad_domains = [
|
|
|
+ domain for domain in manifest.get("bannedDomains", []) if domain.lower() in script_body.lower()
|
|
|
+ ]
|
|
|
+ asset = {
|
|
|
+ "url": script["url"],
|
|
|
+ "status": 200,
|
|
|
+ "sha256": hashlib.sha256(script_body.encode("utf-8")).hexdigest(),
|
|
|
+ "bannedDomains": script_bad_domains,
|
|
|
+ }
|
|
|
+ same_origin_assets.append(asset)
|
|
|
+ if script_bad_domains:
|
|
|
+ violations.append(
|
|
|
+ {
|
|
|
+ "type": "banned-domain-live-script",
|
|
|
+ "site": site["name"],
|
|
|
+ "url": script["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}"})
|
|
|
+ records.append(record)
|
|
|
+ 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(),
|
|
|
+ "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())
|