Sfoglia il codice sorgente

改为流式生成防篡改哈希清单

GNU sort 对 31 万路径占用约 16GB 内存。改用 Python 按目录排序、逐文件流式计算 SHA-256,并限制 manifest 服务内存为 2GB。

Validation:\n- Python 生成器通过 py_compile\n- shell 包装脚本通过 bash -n\n- 临时目录验证仅输出目标文件并正确排除 .DS_Store
非繁 2 settimane fa
parent
commit
a0cd98a96a

+ 64 - 0
local-run/anti-tamper/zq-artifact-manifest.py

@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+import hashlib
+import os
+import sys
+from pathlib import Path
+
+INTERNAL_ROOT = Path(os.environ.get("ZQ_INTERNAL_WEBAPP", "/home/hxxy/zq/apps/internal/webapp"))
+ROOTS = ("web/upload", "web/subassembly/website")
+EXCLUDED_NAMES = {".DS_Store", ".AppleDouble", "Thumbs.db"}
+EXCLUDED_PREFIXES = ("._", ".zq-stage-")
+EXCLUDED_DIRS = {".zq-quarantine"}
+
+
+def excluded_file(name: str) -> bool:
+    return name in EXCLUDED_NAMES or name.startswith(EXCLUDED_PREFIXES) or name.endswith(".tmp")
+
+
+def sha256_file(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as handle:
+        while True:
+            chunk = handle.read(1024 * 1024)
+            if not chunk:
+                break
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def main() -> int:
+    output = Path(sys.argv[1]) if len(sys.argv) > 1 else None
+    if output is None:
+        print("usage: zq-artifact-manifest.py <output>", file=sys.stderr)
+        return 2
+
+    sys.stdout.reconfigure(errors="surrogateescape")
+    count = 0
+    total_bytes = 0
+    with output.open("w", encoding="utf-8", errors="surrogateescape", newline="\n") as manifest:
+        for root_rel in ROOTS:
+            base = INTERNAL_ROOT / root_rel
+            if not base.is_dir():
+                continue
+            for current, dirs, files in os.walk(base, topdown=True, followlinks=False):
+                dirs[:] = sorted(
+                    name for name in dirs
+                    if name not in EXCLUDED_DIRS and not name.startswith(EXCLUDED_PREFIXES)
+                )
+                for name in sorted(files):
+                    if excluded_file(name):
+                        continue
+                    full = Path(current) / name
+                    if full.is_symlink() or not full.is_file():
+                        continue
+                    rel = full.relative_to(INTERNAL_ROOT).as_posix()
+                    digest = sha256_file(full)
+                    manifest.write(f"{digest}  {rel}\n")
+                    count += 1
+                    total_bytes += full.stat().st_size
+    print(f"files={count} bytes={total_bytes}", file=sys.stderr)
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1 - 0
local-run/anti-tamper/zq-artifact-manifest.service

@@ -8,6 +8,7 @@ Type=oneshot
 User=root
 Group=root
 ExecStart=/usr/local/sbin/zq-artifact-manifest.sh generate
+MemoryMax=2G
 Nice=10
 IOSchedulingClass=best-effort
 IOSchedulingPriority=7

+ 4 - 10
local-run/anti-tamper/zq-artifact-manifest.sh

@@ -7,6 +7,7 @@ INTERNAL_ROOT="${ZQ_INTERNAL_WEBAPP:-/home/hxxy/zq/apps/internal/webapp}"
 STATE_DIR="${ZQ_ANTITAMPER_STATE_DIR:-/var/lib/zq-antitamper}"
 KEY="${ZQ_MANIFEST_SIGNING_KEY:-/etc/zq-antitamper/manifest-signing-key.pem}"
 PUB="${ZQ_MANIFEST_PUBLIC_KEY:-/etc/zq-antitamper/manifest-signing-key.pub.pem}"
+GENERATOR="${ZQ_MANIFEST_GENERATOR:-/usr/local/sbin/zq-artifact-manifest.py}"
 OUT_DIR="${STATE_DIR}/manifests"
 RETENTION_DAYS="${ZQ_MANIFEST_RETENTION_DAYS:-14}"
 mkdir -p "${OUT_DIR}" "$(dirname "${KEY}")"
@@ -29,16 +30,8 @@ txn="$(date '+%Y%m%dT%H%M%S%z')"
 manifest="${OUT_DIR}/manifest-${txn}.sha256"
 signature="${OUT_DIR}/manifest-${txn}.sig"
 tmp="${manifest}.tmp"
-: > "${tmp}"
-for root in web/upload web/subassembly/website; do
-    (
-        cd "${INTERNAL_ROOT}"
-        find "${root}" -type f \
-            ! -name '.DS_Store' ! -name '._*' ! -name 'Thumbs.db' \
-            ! -name '*.tmp' ! -path '*/.zq-quarantine/*' -print0 \
-            | sort -z | xargs -0 -r sha256sum
-    ) >> "${tmp}"
-done
+trap 'rm -f "${tmp}" 2>/dev/null || true' EXIT
+ZQ_INTERNAL_WEBAPP="${INTERNAL_ROOT}" python3 "${GENERATOR}" "${tmp}"
 mv "${tmp}" "${manifest}"
 openssl pkeyutl -sign -inkey "${KEY}" -rawin -in "${manifest}" -out "${signature}"
 sha256sum "${manifest}" > "${manifest}.sha256"
@@ -53,4 +46,5 @@ sha256sum "${manifest}" > "${manifest}.sha256"
 ln -sfn "$(basename "${manifest}")" "${OUT_DIR}/current.sha256"
 ln -sfn "$(basename "${signature}")" "${OUT_DIR}/current.sig"
 find "${OUT_DIR}" -type f -mtime "+${RETENTION_DAYS}" -delete
+find "${OUT_DIR}" -name '*.tmp' -mmin +60 -delete 2>/dev/null || true
 printf 'manifest=%s files=%s sha256=%s\n' "${manifest}" "$(wc -l < "${manifest}")" "$(cut -d' ' -f1 "${manifest}.sha256")"