20261112 完成#187真实序列录制回放与七指标评估

This commit is contained in:
2026-11-12 15:14:06 +08:00
parent 05650b23bf
commit dcf3e5b6ae
49 changed files with 6943 additions and 111 deletions

View File

@@ -0,0 +1,142 @@
"""Validate recorded RRDP references and object update semantics without resigning."""
from __future__ import annotations
import base64
import hashlib
import json
from pathlib import Path
import re
import urllib.parse
import xml.etree.ElementTree as ET
from common import origin
NS = "{http://www.ripe.net/rpki/rrdp}"
SHA256 = re.compile(r"^[0-9a-fA-F]{64}$")
def positive(value: str) -> int:
if not value.isascii() or not value.isdecimal() or int(value) < 1:
raise ValueError(f"invalid positive serial: {value}")
return int(value)
def checked_hash(value: str) -> str:
if not SHA256.fullmatch(value):
raise ValueError("invalid reference SHA-256")
return value.lower()
def safe_xml(path: Path) -> None:
"""Reject non-ASCII/DTD before parsing, without loading a large snapshot."""
tail = b""
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
chunk.decode("ascii")
combined = tail + chunk
if b"<!DOCTYPE" in combined or b"<!ENTITY" in combined:
raise ValueError("DTD/entities are forbidden in RRDP")
tail = combined[-16:]
def notification(path: Path, uri: str, max_refs: int = 10000) -> dict:
if path.stat().st_size > 8 * 1024**2:
raise ValueError("notification size limit")
safe_xml(path)
root = ET.parse(path).getroot()
if root.tag != NS + "notification" or root.attrib.get("version") != "1":
raise ValueError("invalid notification root/version")
import uuid
session = str(uuid.UUID(root.attrib["session_id"]))
serial = positive(root.attrib["serial"])
refs, seen, snapshots = [], set(), 0
for child in root:
if child.tag not in (NS + "snapshot", NS + "delta"):
raise ValueError("unknown notification child")
kind = child.tag.removeprefix(NS)
target = child.attrib["uri"]
if origin(target) != origin(uri):
raise ValueError("cross-origin notification reference")
ref = {"kind": kind, "uri": target, "sha256": checked_hash(child.attrib["hash"])}
if kind == "snapshot":
snapshots += 1
ref["serial"] = serial
else:
ref["serial"] = positive(child.attrib["serial"])
if ref["serial"] > serial or ref["serial"] in seen:
raise ValueError("duplicate/future delta serial")
seen.add(ref["serial"])
refs.append(ref)
if len(refs) > max_refs:
raise ValueError("notification reference limit")
if snapshots != 1:
raise ValueError("notification must contain exactly one snapshot")
return {"session": session, "serial": serial, "references": refs}
def object_uri(value: str) -> str:
parsed = urllib.parse.urlsplit(value)
if parsed.scheme != "rsync" or not parsed.hostname or parsed.username or parsed.password or parsed.fragment or parsed.query:
raise ValueError(f"invalid publication URI: {value}")
if not parsed.path or parsed.path.endswith("/"):
raise ValueError("publication URI must name an object")
return value
def payload_view(path: Path, kind: str, session: str, serial: int,
base: dict[str, str] | None = None, max_objects: int = 2_000_000) -> dict[str, str]:
safe_xml(path)
view = {} if kind == "snapshot" else dict(base or {})
iterator = ET.iterparse(path, events=("start", "end"))
_, root = next(iterator)
if (root.tag != NS + kind or root.attrib.get("version") != "1"
or root.attrib.get("session_id", "").lower() != session
or positive(root.attrib["serial"]) != serial):
raise ValueError(f"{kind} session/serial/version mismatch")
seen, depth = set(), 0
for event, element in iterator:
if event == "start":
depth += 1
if depth > 1:
raise ValueError("nested RRDP payload element")
continue
if element is root:
break
uri = object_uri(element.attrib["uri"])
if kind == "snapshot" and uri in seen:
raise ValueError("duplicate URI in RRDP payload")
seen.add(uri)
if len(seen) > max_objects:
raise ValueError("object count limit")
if element.tag == NS + "publish":
previous = element.attrib.get("hash")
if kind == "snapshot" and previous is not None:
raise ValueError("snapshot publish has previous hash")
if kind == "delta":
if previous is None and uri in view:
raise ValueError("delta adds existing object")
if previous is not None and view.get(uri) != checked_hash(previous):
raise ValueError("delta replacement previous hash mismatch")
encoded = "".join((element.text or "").split())
raw = base64.b64decode(encoded, validate=True)
if not raw:
raise ValueError("empty publish")
view[uri] = hashlib.sha256(raw).hexdigest()
elif element.tag == NS + "withdraw" and kind == "delta":
if view.get(uri) != checked_hash(element.attrib["hash"]):
raise ValueError("delta withdrawal previous hash mismatch")
del view[uri]
else:
raise ValueError("invalid RRDP payload element")
depth -= 1
element.clear()
root.clear()
return view
def view_digest(view: dict[str, str]) -> str:
digest = hashlib.sha256()
for uri, hash_value in sorted(view.items()):
digest.update(json.dumps([uri, hash_value], separators=(",", ":")).encode("ascii"))
digest.update(b"\n")
return digest.hexdigest()