verifier release: verify_tlog.py sha256 23728659
Browse files- verifier/release_statement.json +14 -0
- verifier/verify_tlog.py +1180 -0
- verifier/verify_tlog.py.sha256 +1 -0
verifier/release_statement.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"file": "verify_tlog.py",
|
| 3 |
+
"mirrors_planned": [
|
| 4 |
+
"https://legion33shadow.github.io/legion-tlog-mirror/verify_tlog.py",
|
| 5 |
+
"https://huggingface.co/datasets/gemmozero/phoenix-objects/resolve/main/verifier/verify_tlog.py"
|
| 6 |
+
],
|
| 7 |
+
"note": "UA neutre mcp-tlog-verifier/1.0 depuis le 2026-10-17",
|
| 8 |
+
"prepared_at": "2026-10-17T09:21:10Z",
|
| 9 |
+
"schema": "legion-verifier-release/1",
|
| 10 |
+
"sha256": "23728659f028fcdf97dcf81c66cd652a2d8d1bb3ed5eee44af1fac814e3b2667",
|
| 11 |
+
"size": 57161,
|
| 12 |
+
"source_url": "https://legion-api.com/tlog/verify_tlog.py",
|
| 13 |
+
"test_vectors": "legion-tlog-test-vectors/1 : 336/336"
|
| 14 |
+
}
|
verifier/verify_tlog.py
ADDED
|
@@ -0,0 +1,1180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Vérificateur hors ligne autonome du journal de transparence MCP de LEGION.
|
| 3 |
+
|
| 4 |
+
Dépendances : Python 3 stdlib + `cryptography` (Ed25519, ECDSA). Aucun accès réseau, aucun autre fichier LEGION.
|
| 5 |
+
|
| 6 |
+
Entrées : un enregistrement signé, sa preuve d'inclusion, la tête d'arbre signée (STH), la clé publique LEGION
|
| 7 |
+
(base64 brute 32 octets), et au moins une preuve d'ancrage tiers :
|
| 8 |
+
--ots FICHIER.ots --btc-headers HEADERS.json (OpenTimestamps ; en-têtes tirés de VOTRE nœud Bitcoin)
|
| 9 |
+
--rekor-entry ENTREE.json --rekor-pubkey REKOR.pem (entrée Rekor v1 brute de l'API ; clé Rekor épinglée par vous)
|
| 10 |
+
|
| 11 |
+
Contrôles : 1) intégrité de l'enregistrement 2) signature LEGION 3) inclusion dans la tête signée
|
| 12 |
+
4) horodatage externe de la tête (donc de l'enregistrement inclus).
|
| 13 |
+
Sortie : JSON, code 0 uniquement si tous les contrôles demandés passent.
|
| 14 |
+
|
| 15 |
+
Sous-commandes : receipt (racine legion-receipts ancrée), badge (SVG signé), freeze (gel mensuel), alert (changement signé) ; voir --help.
|
| 16 |
+
|
| 17 |
+
Exemple :
|
| 18 |
+
python3 verify_tlog.py --record rec.json --proof proof.json --sth sth.json --pubkey legion_pub.b64 \
|
| 19 |
+
--ots head.canon.json.ots --btc-headers headers.json --rekor-entry rekor_entry.json --rekor-pubkey rekor_pub.pem
|
| 20 |
+
"""
|
| 21 |
+
import argparse
|
| 22 |
+
import base64
|
| 23 |
+
import hashlib
|
| 24 |
+
import json
|
| 25 |
+
import struct
|
| 26 |
+
import sys
|
| 27 |
+
|
| 28 |
+
# ---------- décodage STRICT (durcissement) : un texte unique accepté par valeur binaire ----------
|
| 29 |
+
import re as _re
|
| 30 |
+
_HEX = _re.compile(r"\A(?:[0-9a-f]{2})*\Z")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _hx(s):
|
| 34 |
+
"""Hexadécimal minuscule, longueur paire, sans espace : sinon refus (pas de malléabilité)."""
|
| 35 |
+
if not isinstance(s, str) or not _HEX.match(s):
|
| 36 |
+
raise ValueError("hexadécimal non canonique")
|
| 37 |
+
return bytes.fromhex(s)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _b64(s):
|
| 41 |
+
"""Base64 RFC 4648 canonique (avec padding, sans caractère parasite) : sinon refus."""
|
| 42 |
+
if not isinstance(s, str):
|
| 43 |
+
raise ValueError("base64 attendu")
|
| 44 |
+
raw = base64.b64decode(s, validate=True)
|
| 45 |
+
if base64.b64encode(raw).decode() != s:
|
| 46 |
+
raise ValueError("base64 non canonique")
|
| 47 |
+
return raw
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
RECORD_SCHEMA = "legion-mcp-tlog-record/0.1"
|
| 51 |
+
CORRECTION_SCHEMA = "legion-mcp-tlog-correction/0.1"
|
| 52 |
+
STH_SCHEMA = "legion-mcp-tlog-sth/0.1"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ---------- primitives (mêmes définitions que legion-receipts / common/legion_proof.py) ----------
|
| 56 |
+
# --- JSON canonique RFC 8785 (JCS), recopié de jcs/jcs.py (le test de synchronisation vérifie l'identité) ---
|
| 57 |
+
import math
|
| 58 |
+
|
| 59 |
+
_ESC = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
|
| 60 |
+
MAX_SAFE = 2 ** 53
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class JCSError(ValueError):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _str(s):
|
| 68 |
+
out = ['"']
|
| 69 |
+
for ch in s:
|
| 70 |
+
o = ord(ch)
|
| 71 |
+
if 0xD800 <= o <= 0xDFFF:
|
| 72 |
+
raise JCSError("moitié de paire de substitution isolée")
|
| 73 |
+
if ch in _ESC:
|
| 74 |
+
out.append(_ESC[ch])
|
| 75 |
+
elif o < 0x20:
|
| 76 |
+
out.append("\\u%04x" % o)
|
| 77 |
+
else:
|
| 78 |
+
out.append(ch)
|
| 79 |
+
out.append('"')
|
| 80 |
+
return "".join(out)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _utf16_key(s):
|
| 84 |
+
return s.encode("utf-16-be")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _num(x, exact_bigint=False):
|
| 88 |
+
if isinstance(x, bool):
|
| 89 |
+
raise JCSError("booléen inattendu")
|
| 90 |
+
if isinstance(x, int):
|
| 91 |
+
if abs(x) > MAX_SAFE and not exact_bigint:
|
| 92 |
+
raise JCSError("entier hors de ±2**53 : non représentable exactement en IEEE 754")
|
| 93 |
+
return str(x) # empreinte v3 seulement (exact_bigint) : décimal exact au-delà de ±2**53
|
| 94 |
+
if not math.isfinite(x):
|
| 95 |
+
raise JCSError("NaN/Infinity interdits")
|
| 96 |
+
if x == 0:
|
| 97 |
+
return "0"
|
| 98 |
+
sign = "-" if x < 0 else ""
|
| 99 |
+
r = repr(abs(x)) # plus court aller-retour (comme ECMAScript), à reformater
|
| 100 |
+
if "e" in r:
|
| 101 |
+
mant, e = r.split("e")
|
| 102 |
+
e = int(e)
|
| 103 |
+
else:
|
| 104 |
+
mant, e = r, 0
|
| 105 |
+
if "." in mant:
|
| 106 |
+
ip, fp = mant.split(".")
|
| 107 |
+
else:
|
| 108 |
+
ip, fp = mant, ""
|
| 109 |
+
digits = (ip + fp).lstrip("0")
|
| 110 |
+
lead_zeros = len(ip + fp) - len((ip + fp).lstrip("0"))
|
| 111 |
+
n = len(ip) + e - lead_zeros # position du point décimal : valeur = 0.d1d2… × 10^n
|
| 112 |
+
digits = digits.rstrip("0") or "0"
|
| 113 |
+
k = len(digits)
|
| 114 |
+
if k <= n <= 21:
|
| 115 |
+
s = digits + "0" * (n - k)
|
| 116 |
+
elif 0 < n <= 21:
|
| 117 |
+
s = digits[:n] + "." + digits[n:]
|
| 118 |
+
elif -6 < n <= 0:
|
| 119 |
+
s = "0." + "0" * (-n) + digits
|
| 120 |
+
else:
|
| 121 |
+
exp = n - 1
|
| 122 |
+
s = digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + ("+" if exp >= 0 else "-") + str(abs(exp))
|
| 123 |
+
return sign + s
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _ser(o, out, xb=False):
|
| 127 |
+
if o is None:
|
| 128 |
+
out.append("null")
|
| 129 |
+
elif o is True:
|
| 130 |
+
out.append("true")
|
| 131 |
+
elif o is False:
|
| 132 |
+
out.append("false")
|
| 133 |
+
elif isinstance(o, str):
|
| 134 |
+
out.append(_str(o))
|
| 135 |
+
elif isinstance(o, (int, float)):
|
| 136 |
+
out.append(_num(o, xb))
|
| 137 |
+
elif isinstance(o, (list, tuple)):
|
| 138 |
+
out.append("[")
|
| 139 |
+
for i, v in enumerate(o):
|
| 140 |
+
if i:
|
| 141 |
+
out.append(",")
|
| 142 |
+
_ser(v, out, xb)
|
| 143 |
+
out.append("]")
|
| 144 |
+
elif isinstance(o, dict):
|
| 145 |
+
if any(not isinstance(k, str) for k in o):
|
| 146 |
+
raise JCSError("nom de membre non textuel")
|
| 147 |
+
out.append("{")
|
| 148 |
+
for i, k in enumerate(sorted(o, key=_utf16_key)):
|
| 149 |
+
if i:
|
| 150 |
+
out.append(",")
|
| 151 |
+
out.append(_str(k))
|
| 152 |
+
out.append(":")
|
| 153 |
+
_ser(o[k], out, xb)
|
| 154 |
+
out.append("}")
|
| 155 |
+
else:
|
| 156 |
+
raise JCSError("type non JSON : %s" % type(o).__name__)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _jcs_canonicalize(obj, exact_bigint=False):
|
| 160 |
+
out = []
|
| 161 |
+
_ser(obj, out, exact_bigint)
|
| 162 |
+
return "".join(out).encode("utf-8")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def canon(o):
|
| 166 |
+
"""RFC 8785 (JCS) : formats du journal de transparence MCP, Rekor SET."""
|
| 167 |
+
return _jcs_canonicalize(o)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def canon_v1(o):
|
| 171 |
+
"""Ancienne canonicalisation : formats tiers signés avec elle (legion-receipts, Phoenix, churn, passeport)."""
|
| 172 |
+
return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# Empreintes tools/list (tools_fingerprint.algo). Feuilles, têtes, alertes et badges restent en JCS strict (canon).
|
| 176 |
+
FP_ALGO_V1 = "sha256(canon(sorted[{name,description,inputSchema}]))/v1"
|
| 177 |
+
FP_ALGO_V2 = "sha256(JCS-RFC8785(sorted[{name,description,inputSchema}]))/v2"
|
| 178 |
+
FP_ALGO_V3 = "sha256(JCS-RFC8785+exact-bigint(sorted[{name,description,inputSchema}]))/v3"
|
| 179 |
+
FP_DIFF_COMPATIBLE = {frozenset((FP_ALGO_V2, FP_ALGO_V3))} # empreintes PAR OUTIL comparables entre ces deux algos
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def canon_fp_v3(o):
|
| 183 |
+
"""Empreinte v3 : JCS RFC 8785, sauf un entier hors ±2**53 écrit en décimal exact (au lieu d'être refusé).
|
| 184 |
+
Identique octet pour octet à v2 sur tout ce que v2 accepte."""
|
| 185 |
+
return _jcs_canonicalize(o, exact_bigint=True)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def canon_fp_for(algo):
|
| 189 |
+
"""Règle de recalcul d'une empreinte depuis les définitions archivées : /v1 -> json.dumps trié ; /v2 et /v3 ->
|
| 190 |
+
canon_fp_v3 (= v2 sur le domaine de v2) ; algo inconnu -> refus explicite."""
|
| 191 |
+
if algo == FP_ALGO_V1:
|
| 192 |
+
return canon_v1
|
| 193 |
+
if algo in (FP_ALGO_V2, FP_ALGO_V3):
|
| 194 |
+
return canon_fp_v3
|
| 195 |
+
raise ValueError("algo d'empreinte inconnu : %r" % (algo,))
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def fp_algos_comparable(a, b):
|
| 199 |
+
return a == b or frozenset((a, b)) in FP_DIFF_COMPATIBLE
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def H(b):
|
| 203 |
+
return hashlib.sha256(b).digest()
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def leaf_hash(b):
|
| 207 |
+
return H(b"\x00" + b)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def node_hash(l, r):
|
| 211 |
+
return H(b"\x01" + l + r)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _hash32(*xs):
|
| 215 |
+
return all(isinstance(x, (bytes, bytearray)) and len(x) == 32 for x in xs)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def verify_inclusion(leaf, index, size, path, root):
|
| 219 |
+
if index < 0 or index >= size:
|
| 220 |
+
return False
|
| 221 |
+
if not _hash32(leaf, root) or not all(_hash32(p) for p in path): # RFC 9162 : hachages de 32 octets exactement
|
| 222 |
+
return False
|
| 223 |
+
fn, sn, r = index, size - 1, leaf
|
| 224 |
+
for p in path:
|
| 225 |
+
if sn == 0:
|
| 226 |
+
return False
|
| 227 |
+
if fn & 1 or fn == sn:
|
| 228 |
+
r = node_hash(p, r)
|
| 229 |
+
if not fn & 1:
|
| 230 |
+
while not fn & 1 and fn != 0:
|
| 231 |
+
fn >>= 1
|
| 232 |
+
sn >>= 1
|
| 233 |
+
else:
|
| 234 |
+
r = node_hash(r, p)
|
| 235 |
+
fn >>= 1
|
| 236 |
+
sn >>= 1
|
| 237 |
+
return sn == 0 and r == root
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def key_pin(pub_b64):
|
| 241 |
+
return hashlib.sha256(_b64(pub_b64)).hexdigest()
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def ed25519_ok(pub_raw, sig, msg):
|
| 245 |
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
| 246 |
+
try:
|
| 247 |
+
Ed25519PublicKey.from_public_bytes(pub_raw).verify(sig, msg)
|
| 248 |
+
return True
|
| 249 |
+
except Exception:
|
| 250 |
+
return False
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def ecdsa_ok(pub, sig_der, msg):
|
| 254 |
+
from cryptography.hazmat.primitives import hashes
|
| 255 |
+
from cryptography.hazmat.primitives.asymmetric import ec
|
| 256 |
+
try:
|
| 257 |
+
pub.verify(sig_der, msg, ec.ECDSA(hashes.SHA256()))
|
| 258 |
+
return True
|
| 259 |
+
except Exception:
|
| 260 |
+
return False
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# ---------- contrôles LEGION ----------
|
| 264 |
+
def _pub(keys, pin):
|
| 265 |
+
"""keys = clé publique base64 (comportement historique) ou dict {pin sha256: clé} issu d'un keyring vérifié."""
|
| 266 |
+
if isinstance(keys, dict):
|
| 267 |
+
return keys.get(pin) or ""
|
| 268 |
+
return keys
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
KEYRING_SIG_FIELDS = ("hash", "self_sig", "endorsement_sig")
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def load_keyring(text, root_pub_b64):
|
| 275 |
+
"""keyring.jsonl du journal -> {pin: clé publique} des clés VALIDES. Ancre : la clé racine épinglée (--pubkey).
|
| 276 |
+
Première entrée = racine (même empreinte que --pubkey). Chaque entrée suivante : chaîne prev_hash/hash, approuvée
|
| 277 |
+
par la racine (endorsement_sig) ; key_register exige en plus la preuve de possession (self_sig). key_revoke retire
|
| 278 |
+
la clé. Toute anomalie lève une exception : le keyring entier est alors refusé."""
|
| 279 |
+
root_pin = key_pin(root_pub_b64)
|
| 280 |
+
keys, revoked, prev, limits, compromised = {}, set(), None, {}, set()
|
| 281 |
+
for n, line in enumerate(l for l in text.splitlines() if l.strip()):
|
| 282 |
+
e = json.loads(line)
|
| 283 |
+
body = {k: v for k, v in e.items() if k not in KEYRING_SIG_FIELDS}
|
| 284 |
+
if n == 0:
|
| 285 |
+
if e.get("type") != "key_register" or key_pin(e.get("public_key_b64", "")) != root_pin:
|
| 286 |
+
raise ValueError("keyring : la première entrée n'est pas la clé racine épinglée")
|
| 287 |
+
keys[root_pin] = root_pub_b64
|
| 288 |
+
prev = e.get("hash") or H(canon(body)).hex()
|
| 289 |
+
continue
|
| 290 |
+
c = canon(body)
|
| 291 |
+
if e.get("prev_hash") != prev or e.get("hash") != H(c).hex():
|
| 292 |
+
raise ValueError("keyring : chaîne rompue à l'entrée %d" % n)
|
| 293 |
+
if not ed25519_ok(_b64(root_pub_b64), _b64(e.get("endorsement_sig", "")), c):
|
| 294 |
+
raise ValueError("keyring : entrée %d non approuvée par la racine" % n)
|
| 295 |
+
if e.get("type") == "key_register":
|
| 296 |
+
pub = e["public_key_b64"]
|
| 297 |
+
if e.get("key_id") != "k1:" + key_pin(pub)[:32] or not ed25519_ok(_b64(pub), _b64(e.get("self_sig", "")), c):
|
| 298 |
+
raise ValueError("keyring : sous-clé invalide à l'entrée %d" % n)
|
| 299 |
+
keys[key_pin(pub)] = pub
|
| 300 |
+
elif e.get("type") == "key_revoke":
|
| 301 |
+
revoked.add(e["key_id"])
|
| 302 |
+
if isinstance(e.get("valid_until_tree_size"), int) and e["key_id"] not in compromised:
|
| 303 |
+
limits[e["key_id"]] = min(e["valid_until_tree_size"], limits.get(e["key_id"], e["valid_until_tree_size"]))
|
| 304 |
+
elif not isinstance(e.get("valid_until_tree_size"), int): # compromission : l'emporte sur toute retraite
|
| 305 |
+
limits.pop(e["key_id"], None)
|
| 306 |
+
compromised.add(e["key_id"])
|
| 307 |
+
else:
|
| 308 |
+
raise ValueError("keyring : type inconnu à l'entrée %d" % n)
|
| 309 |
+
prev = e["hash"]
|
| 310 |
+
out = _Keys({p: k for p, k in keys.items() if "k1:" + p[:32] not in revoked or "k1:" + p[:32] in limits})
|
| 311 |
+
out.limits = {p: limits["k1:" + p[:32]] for p in keys if "k1:" + p[:32] in limits}
|
| 312 |
+
return out
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class _Keys(dict):
|
| 316 |
+
"""{pin: clé publique} + limits {pin: N} pour les sous-clés retirées (valides seulement avant la taille N)."""
|
| 317 |
+
limits = {}
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _within(keys, pin, leaf_index=None, tree_size=None):
|
| 321 |
+
lim = getattr(keys, "limits", {}).get(pin)
|
| 322 |
+
if lim is None:
|
| 323 |
+
return True
|
| 324 |
+
return (leaf_index is not None and leaf_index < lim) or (tree_size is not None and tree_size <= lim)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def check_record(rec, pub_b64):
|
| 328 |
+
"""Intégrité interne + signature. Renvoie (intégrité, signature, détail)."""
|
| 329 |
+
try:
|
| 330 |
+
body = {k: v for k, v in rec.items() if k != "signature_ed25519"}
|
| 331 |
+
if rec.get("schema") == CORRECTION_SCHEMA: # feuille de correction : référence une feuille antérieure
|
| 332 |
+
integ = (rec.get("kind") == "canonicalization_artifact" and isinstance(rec.get("corrects_leaf_index"), int)
|
| 333 |
+
and 0 <= rec["corrects_leaf_index"] < rec["leaf_index"] and isinstance(rec["server_id"], str)
|
| 334 |
+
and isinstance(rec["observed_at"], str) and rec.get("artifact") in ("array_order", "number_format"))
|
| 335 |
+
else:
|
| 336 |
+
fp = rec["tools_fingerprint"]
|
| 337 |
+
names = [n for n, _ in fp["per_tool_sha256"]]
|
| 338 |
+
integ = (rec.get("schema") == RECORD_SCHEMA and fp["tool_count"] == len(names)
|
| 339 |
+
and names == sorted(names) and len(set(names)) == len(names)
|
| 340 |
+
and isinstance(rec["server_id"], str) and isinstance(rec["observed_at"], str))
|
| 341 |
+
keys_ = pub_b64
|
| 342 |
+
pub_b64 = _pub(pub_b64, rec.get("key_id"))
|
| 343 |
+
sig_ok = (bool(pub_b64) and rec.get("key_id") == key_pin(pub_b64)
|
| 344 |
+
and (not isinstance(keys_, dict) or _within(keys_, rec.get("key_id"), leaf_index=rec.get("leaf_index")))
|
| 345 |
+
and ed25519_ok(_b64(pub_b64), _b64(rec["signature_ed25519"]), canon(body)))
|
| 346 |
+
return integ, sig_ok, None
|
| 347 |
+
except Exception as e:
|
| 348 |
+
return False, False, "%s: %s" % (type(e).__name__, e)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def check_sth(sth, pub_b64):
|
| 352 |
+
try:
|
| 353 |
+
head = sth["tree_head"]
|
| 354 |
+
keys_ = pub_b64
|
| 355 |
+
pub_b64 = _pub(pub_b64, head.get("issuer_pin_sha256"))
|
| 356 |
+
if isinstance(keys_, dict) and not _within(keys_, head.get("issuer_pin_sha256"), tree_size=head.get("tree_size")):
|
| 357 |
+
return False
|
| 358 |
+
return (bool(pub_b64) and head.get("schema") == STH_SCHEMA and head.get("issuer_pin_sha256") == key_pin(pub_b64)
|
| 359 |
+
and ed25519_ok(_b64(pub_b64), _b64(sth["signature_ed25519"]), canon(head)))
|
| 360 |
+
except Exception:
|
| 361 |
+
return False
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def check_inclusion(rec, proof, sth):
|
| 365 |
+
try:
|
| 366 |
+
head = sth["tree_head"]
|
| 367 |
+
return (proof["tree_size"] == head["tree_size"] and proof["leaf_index"] == rec["leaf_index"]
|
| 368 |
+
and verify_inclusion(leaf_hash(canon(rec)), proof["leaf_index"], proof["tree_size"],
|
| 369 |
+
[_hx(h) for h in proof["audit_path"]], _hx(head["root_sha256"])))
|
| 370 |
+
except Exception:
|
| 371 |
+
return False
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# ---------- OpenTimestamps (lecteur minimal du format .ots, sans dépendance) ----------
|
| 375 |
+
OTS_MAGIC = b"\x00OpenTimestamps\x00\x00Proof\x00\xbf\x89\xe2\xe8\x84\xe8\x92\x94"
|
| 376 |
+
BTC_TAG = _hx("0588960d73d71901")
|
| 377 |
+
PENDING_TAG = _hx("83dfe30d2ef90c8e")
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
class _R:
|
| 381 |
+
def __init__(self, b):
|
| 382 |
+
self.b, self.i = b, 0
|
| 383 |
+
|
| 384 |
+
def read(self, n):
|
| 385 |
+
if self.i + n > len(self.b):
|
| 386 |
+
raise ValueError("fichier .ots tronqué")
|
| 387 |
+
out = self.b[self.i:self.i + n]
|
| 388 |
+
self.i += n
|
| 389 |
+
return out
|
| 390 |
+
|
| 391 |
+
def varuint(self):
|
| 392 |
+
v, shift = 0, 0
|
| 393 |
+
while True:
|
| 394 |
+
c = self.read(1)[0]
|
| 395 |
+
v |= (c & 0x7f) << shift
|
| 396 |
+
if not c & 0x80:
|
| 397 |
+
return v
|
| 398 |
+
shift += 7
|
| 399 |
+
if shift > 63:
|
| 400 |
+
raise ValueError("varuint trop long")
|
| 401 |
+
|
| 402 |
+
def varbytes(self, maxlen=8192):
|
| 403 |
+
n = self.varuint()
|
| 404 |
+
if n > maxlen:
|
| 405 |
+
raise ValueError("champ trop long")
|
| 406 |
+
return self.read(n)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _apply(tag, arg, msg):
|
| 410 |
+
if tag == 0xf0:
|
| 411 |
+
return msg + arg
|
| 412 |
+
if tag == 0xf1:
|
| 413 |
+
return arg + msg
|
| 414 |
+
if tag == 0x08:
|
| 415 |
+
return hashlib.sha256(msg).digest()
|
| 416 |
+
if tag == 0x02:
|
| 417 |
+
return hashlib.sha1(msg).digest()
|
| 418 |
+
if tag == 0x03:
|
| 419 |
+
return hashlib.new("ripemd160", msg).digest()
|
| 420 |
+
if tag == 0xf2:
|
| 421 |
+
return msg[::-1]
|
| 422 |
+
if tag == 0xf3:
|
| 423 |
+
return msg.hex().encode()
|
| 424 |
+
raise ValueError("opération .ots inconnue 0x%02x" % tag)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def _walk(r, msg, out, depth=0):
|
| 428 |
+
if depth > 256:
|
| 429 |
+
raise ValueError("arbre .ots trop profond")
|
| 430 |
+
|
| 431 |
+
def one(tag):
|
| 432 |
+
if tag == 0x00:
|
| 433 |
+
atag = r.read(8)
|
| 434 |
+
payload = _R(r.varbytes())
|
| 435 |
+
if atag == BTC_TAG:
|
| 436 |
+
out.append(("bitcoin", payload.varuint(), msg))
|
| 437 |
+
elif atag == PENDING_TAG:
|
| 438 |
+
out.append(("pending", payload.varbytes().decode("utf-8", "replace"), msg))
|
| 439 |
+
else:
|
| 440 |
+
out.append(("unknown", atag.hex(), msg))
|
| 441 |
+
else:
|
| 442 |
+
arg = r.varbytes() if tag in (0xf0, 0xf1) else b""
|
| 443 |
+
_walk(r, _apply(tag, arg, msg), out, depth + 1)
|
| 444 |
+
|
| 445 |
+
tag = r.read(1)[0]
|
| 446 |
+
while tag == 0xff:
|
| 447 |
+
one(r.read(1)[0])
|
| 448 |
+
tag = r.read(1)[0]
|
| 449 |
+
one(tag)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def parse_ots(data):
|
| 453 |
+
"""Renvoie (digest_horodaté, [(type, détail, message_final)])."""
|
| 454 |
+
r = _R(data)
|
| 455 |
+
if r.read(len(OTS_MAGIC)) != OTS_MAGIC:
|
| 456 |
+
raise ValueError("ce n'est pas un fichier OpenTimestamps")
|
| 457 |
+
if r.varuint() != 1:
|
| 458 |
+
raise ValueError("version .ots non prise en charge")
|
| 459 |
+
if r.read(1)[0] != 0x08:
|
| 460 |
+
raise ValueError("hachage du fichier : SHA-256 uniquement")
|
| 461 |
+
digest = r.read(32)
|
| 462 |
+
out = []
|
| 463 |
+
_walk(r, digest, out)
|
| 464 |
+
if r.i != len(data):
|
| 465 |
+
raise ValueError("octets en trop après la preuve")
|
| 466 |
+
return digest, out
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _check_ots_impl(ots_bytes, artifact, headers):
|
| 470 |
+
"""headers = {"HAUTEUR": {"merkleroot": hex affiché par bitcoin-cli, "time": unix}} issus de VOTRE nœud."""
|
| 471 |
+
res = {"status": "failed", "detail": None}
|
| 472 |
+
try:
|
| 473 |
+
digest, atts = parse_ots(ots_bytes)
|
| 474 |
+
except Exception as e:
|
| 475 |
+
res["detail"] = "preuve illisible : %s" % e
|
| 476 |
+
return res
|
| 477 |
+
if digest != hashlib.sha256(artifact).digest():
|
| 478 |
+
res["detail"] = "le .ots horodate un autre contenu que cette tête d'arbre"
|
| 479 |
+
return res
|
| 480 |
+
btc = [a for a in atts if a[0] == "bitcoin"]
|
| 481 |
+
if not btc:
|
| 482 |
+
res["status"] = "pending" if any(a[0] == "pending" for a in atts) else "failed"
|
| 483 |
+
res["detail"] = "aucune attestation Bitcoin (lancer `ots upgrade`)"
|
| 484 |
+
return res
|
| 485 |
+
verified = []
|
| 486 |
+
for _, height, msg in btc:
|
| 487 |
+
h = (headers or {}).get(str(height))
|
| 488 |
+
if h is None:
|
| 489 |
+
continue
|
| 490 |
+
if len(msg) == 32 and msg == _hx(h["merkleroot"])[::-1]:
|
| 491 |
+
verified.append({"height": height, "block_time": h.get("time")})
|
| 492 |
+
else:
|
| 493 |
+
res["detail"] = "racine Merkle du bloc %d différente : ancrage falsifié ou mauvais en-tête" % height
|
| 494 |
+
return res
|
| 495 |
+
if not verified:
|
| 496 |
+
res["status"] = "unverified"
|
| 497 |
+
res["detail"] = "en-têtes Bitcoin non fournis pour les hauteurs %s (--btc-headers)" % sorted({a[1] for a in btc})
|
| 498 |
+
return res
|
| 499 |
+
best = min(verified, key=lambda v: v["height"])
|
| 500 |
+
return {"status": "verified", "detail": "existait au plus tard au bloc %d" % best["height"],
|
| 501 |
+
"bitcoin_height": best["height"], "block_time": best["block_time"]}
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
# ---------- Sigstore Rekor v1 (entrée « rekord » brute de /api/v1/log/entries) ----------
|
| 505 |
+
def _parse_checkpoint(text):
|
| 506 |
+
"""Format « signed note » exact : corps (origine, taille, racine b64, lignes éventuelles) + ligne vide
|
| 507 |
+
+ une ou plusieurs lignes « — nom sig », chacune terminée par \\n. Tout écart = refus (pas de texte parasite)."""
|
| 508 |
+
if not isinstance(text, str) or not text.endswith("\n"):
|
| 509 |
+
raise ValueError("checkpoint mal terminé")
|
| 510 |
+
body, sep, sigs = text.partition("\n\n")
|
| 511 |
+
if not sep:
|
| 512 |
+
raise ValueError("checkpoint sans signature")
|
| 513 |
+
lines = body.split("\n")
|
| 514 |
+
if len(lines) < 3 or not lines[1].isdigit() or str(int(lines[1])) != lines[1]:
|
| 515 |
+
raise ValueError("checkpoint : taille non canonique")
|
| 516 |
+
sig_lines = sigs[:-1].split("\n")
|
| 517 |
+
if not sig_lines or any(not l.startswith("\u2014 ") or len(l.split(" ")) != 3 for l in sig_lines):
|
| 518 |
+
raise ValueError("checkpoint : ligne de signature invalide")
|
| 519 |
+
return (body + "\n").encode(), int(lines[1]), _b64(lines[2]), sig_lines
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def check_rekor(entry, artifact, legion_pub_b64, rekor_pub_pem):
|
| 523 |
+
from cryptography.hazmat.primitives import serialization
|
| 524 |
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
| 525 |
+
res = {"status": "failed", "detail": None}
|
| 526 |
+
try:
|
| 527 |
+
if isinstance(entry, dict) and len(entry) == 1 and "body" not in entry:
|
| 528 |
+
entry = next(iter(entry.values()))
|
| 529 |
+
rekor_pub = serialization.load_pem_public_key(rekor_pub_pem)
|
| 530 |
+
rekor_der = rekor_pub.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
| 531 |
+
body_raw = _b64(entry["body"])
|
| 532 |
+
body = json.loads(body_raw)
|
| 533 |
+
spec = body["spec"]
|
| 534 |
+
if body.get("kind") != "rekord":
|
| 535 |
+
res["detail"] = "type d'entrée inattendu : %s" % body.get("kind")
|
| 536 |
+
return res
|
| 537 |
+
if spec["data"]["hash"]["value"] != hashlib.sha256(artifact).hexdigest():
|
| 538 |
+
res["detail"] = "l'entrée Rekor porte sur un autre contenu"
|
| 539 |
+
return res
|
| 540 |
+
pk = serialization.load_pem_public_key(_b64(spec["signature"]["publicKey"]["content"]))
|
| 541 |
+
if not isinstance(pk, Ed25519PublicKey) or base64.b64encode(
|
| 542 |
+
pk.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)).decode() != legion_pub_b64:
|
| 543 |
+
res["detail"] = "l'entrée Rekor est signée par une autre clé que LEGION"
|
| 544 |
+
return res
|
| 545 |
+
if not ed25519_ok(_b64(legion_pub_b64), _b64(spec["signature"]["content"]), artifact):
|
| 546 |
+
res["detail"] = "signature LEGION invalide dans l'entrée Rekor"
|
| 547 |
+
return res
|
| 548 |
+
if entry["logID"] != hashlib.sha256(rekor_der).hexdigest():
|
| 549 |
+
res["detail"] = "logID ne correspond pas à la clé Rekor épinglée"
|
| 550 |
+
return res
|
| 551 |
+
v = entry["verification"]
|
| 552 |
+
set_payload = canon({"body": entry["body"], "integratedTime": entry["integratedTime"],
|
| 553 |
+
"logID": entry["logID"], "logIndex": entry["logIndex"]})
|
| 554 |
+
if not ecdsa_ok(rekor_pub, _b64(v["signedEntryTimestamp"]), set_payload):
|
| 555 |
+
res["detail"] = "horodatage signé (SET) Rekor invalide"
|
| 556 |
+
return res
|
| 557 |
+
ip = v["inclusionProof"]
|
| 558 |
+
root = _hx(ip["rootHash"])
|
| 559 |
+
if not verify_inclusion(leaf_hash(body_raw), ip["logIndex"], ip["treeSize"],
|
| 560 |
+
[_hx(h) for h in ip["hashes"]], root):
|
| 561 |
+
res["detail"] = "preuve d'inclusion Rekor invalide"
|
| 562 |
+
return res
|
| 563 |
+
signed, size, cp_root, sig_lines = _parse_checkpoint(ip["checkpoint"])
|
| 564 |
+
if size != ip["treeSize"] or cp_root != root:
|
| 565 |
+
res["detail"] = "checkpoint Rekor incohérent avec la preuve"
|
| 566 |
+
return res
|
| 567 |
+
if not any(ecdsa_ok(rekor_pub, _b64(l.split(" ")[-1])[4:], signed) for l in sig_lines):
|
| 568 |
+
res["detail"] = "signature du checkpoint Rekor invalide"
|
| 569 |
+
return res
|
| 570 |
+
return {"status": "verified", "detail": "inscrit dans Rekor (index %d)" % entry["logIndex"],
|
| 571 |
+
"integrated_time": entry["integratedTime"], "log_index": entry["logIndex"]}
|
| 572 |
+
except Exception as e:
|
| 573 |
+
res["detail"] = "entrée illisible : %s: %s" % (type(e).__name__, e)
|
| 574 |
+
return res
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
# ---------- orchestration ----------
|
| 578 |
+
def _verify_all_impl(rec, proof, sth, pub_b64, ots=None, headers=None, rekor_entry=None, rekor_pub_pem=None,
|
| 579 |
+
require_anchor=True):
|
| 580 |
+
integ, sig, err = check_record(rec, pub_b64)
|
| 581 |
+
out = {"record_integrity": integ, "record_signature": sig, "head_signature": check_sth(sth, pub_b64),
|
| 582 |
+
"inclusion": check_inclusion(rec, proof, sth), "anchors": {}}
|
| 583 |
+
if err:
|
| 584 |
+
out["error"] = err
|
| 585 |
+
artifact = canon(sth.get("tree_head", {}))
|
| 586 |
+
if ots is not None:
|
| 587 |
+
out["anchors"]["opentimestamps"] = check_ots(ots, artifact, headers)
|
| 588 |
+
if rekor_entry is not None:
|
| 589 |
+
out["anchors"]["rekor"] = check_rekor(rekor_entry, artifact, _pub(pub_b64, sth.get("tree_head", {}).get("issuer_pin_sha256")),
|
| 590 |
+
rekor_pub_pem)
|
| 591 |
+
statuses = [a["status"] for a in out["anchors"].values()]
|
| 592 |
+
anchored = "verified" in statuses and "failed" not in statuses
|
| 593 |
+
if require_anchor and "unverified" in statuses:
|
| 594 |
+
anchored = False # ancrage exigé : une preuve présente mais non vérifiable (en-tête absent) ne passe pas
|
| 595 |
+
base_ok = integ and sig and out["head_signature"] and out["inclusion"]
|
| 596 |
+
out["external_timestamp"] = anchored
|
| 597 |
+
if not base_ok:
|
| 598 |
+
out["claim_state"] = "rejected"
|
| 599 |
+
elif "failed" in statuses:
|
| 600 |
+
out["claim_state"] = "rejected_anchor"
|
| 601 |
+
elif anchored:
|
| 602 |
+
out["claim_state"] = "anchored_observation"
|
| 603 |
+
else:
|
| 604 |
+
out["claim_state"] = "signed_observation_not_anchored"
|
| 605 |
+
out["ok"] = bool(base_ok and (anchored or not require_anchor) and "failed" not in statuses)
|
| 606 |
+
return out
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
# ---------- 5) racine legion-receipts ancrée (non signée) ----------
|
| 610 |
+
RECEIPTS_ANCHOR_SCHEMA = "legion-mcp-receipts-root-anchor/0.1"
|
| 611 |
+
RECEIPTS_ROOT_KEYS = ("schema", "generated_at", "tree_size", "root_sha256", "hash", "canonicalization")
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def receipts_root_artifact(root_doc):
|
| 615 |
+
return canon_v1({"schema": RECEIPTS_ANCHOR_SCHEMA, "source": {k: root_doc[k] for k in RECEIPTS_ROOT_KEYS}})
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def verify_receipt_root(receipt, root_doc, ots=None, headers=None, require_anchor=True):
|
| 619 |
+
"""Un reçu legion-receipts (ligne de receipts.jsonl) + ROOT.json + .ots de root_anchor.canon.json."""
|
| 620 |
+
out = {"anchors": {}}
|
| 621 |
+
try:
|
| 622 |
+
leaf = leaf_hash(canon_v1({k: receipt[k] for k in ("schema", "source", "record")}))
|
| 623 |
+
out["receipt_integrity"] = leaf.hex() == receipt["leaf_hash"]
|
| 624 |
+
out["inclusion"] = (receipt["tree_size"] == root_doc["tree_size"] and verify_inclusion(
|
| 625 |
+
leaf, receipt["index"], receipt["tree_size"], [_hx(h) for h in receipt["proof"]],
|
| 626 |
+
_hx(root_doc["root_sha256"])))
|
| 627 |
+
except Exception as e:
|
| 628 |
+
out.update(receipt_integrity=False, inclusion=False, error="%s: %s" % (type(e).__name__, e))
|
| 629 |
+
if ots is not None:
|
| 630 |
+
out["anchors"]["opentimestamps"] = check_ots(ots, receipts_root_artifact(root_doc), headers)
|
| 631 |
+
st = [a["status"] for a in out["anchors"].values()]
|
| 632 |
+
base = out["receipt_integrity"] and out["inclusion"]
|
| 633 |
+
anchored = "verified" in st and "failed" not in st
|
| 634 |
+
out["claim_state"] = ("rejected" if not base else "rejected_anchor" if "failed" in st
|
| 635 |
+
else "unsigned_root_anchored" if anchored else "unsigned_root_not_anchored")
|
| 636 |
+
out["claim_boundary"] = ("La ligne existait dans la table locale au plus tard à la date du bloc. "
|
| 637 |
+
"Racine non signée par LEGION ; rien n'est affirmé sur le registre MCP source.")
|
| 638 |
+
out["ok"] = bool(base and (anchored or not require_anchor) and "failed" not in st)
|
| 639 |
+
return out
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
# ---------- 6) badge SVG signé ----------
|
| 643 |
+
BADGE_SCHEMA = "legion-mcp-badge/0.1"
|
| 644 |
+
_BADGE_TPL = ('<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="20" role="img" aria-label="{label}: {msg}">'
|
| 645 |
+
'<title>{title}</title>'
|
| 646 |
+
'<metadata id="legion-attestation">{meta}</metadata>'
|
| 647 |
+
'<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>'
|
| 648 |
+
'<stop offset="1" stop-opacity=".1"/></linearGradient>'
|
| 649 |
+
'<clipPath id="r"><rect width="{w}" height="20" rx="3" fill="#fff"/></clipPath>'
|
| 650 |
+
'<g clip-path="url(#r)"><rect width="{lw}" height="20" fill="#555"/>'
|
| 651 |
+
'<rect x="{lw}" width="{rw}" height="20" fill="{color}"/><rect width="{w}" height="20" fill="url(#s)"/></g>'
|
| 652 |
+
'<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">'
|
| 653 |
+
'<text x="{lx}" y="14">{label}</text><text x="{rx}" y="14">{msg}</text></g></svg>\n')
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def _xml(s):
|
| 657 |
+
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def render_badge(statement, signature_b64):
|
| 661 |
+
"""Rendu déterministe : le texte visible est entièrement dérivé de la déclaration signée."""
|
| 662 |
+
label = "MCP tools"
|
| 663 |
+
msg = "no change observed since %s" % statement["last_change_observed_at"][:10]
|
| 664 |
+
title = ("Observed by LEGION. Same tools/list fingerprint for %s from %s to %s. "
|
| 665 |
+
"An observation at those dates, not a guarantee. Verify: %s" % (
|
| 666 |
+
statement["server_id"], statement["last_change_observed_at"], statement["last_checked_at"],
|
| 667 |
+
statement["verify_url"]))
|
| 668 |
+
meta = base64.b64encode(canon({"statement": statement, "signature_ed25519": signature_b64})).decode()
|
| 669 |
+
lw, rw = 10 + 7 * len(label), 10 + 7 * len(msg)
|
| 670 |
+
return _BADGE_TPL.format(w=lw + rw, lw=lw, rw=rw, lx=lw // 2, rx=lw + rw // 2, label=_xml(label), msg=_xml(msg),
|
| 671 |
+
title=_xml(title), meta=meta, color="#2e7d32")
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _verify_badge_impl(svg_text, pub_b64, record=None, proof=None, sth=None, now=None, max_age_days=None):
|
| 675 |
+
import datetime
|
| 676 |
+
import re
|
| 677 |
+
out = {"ok": False}
|
| 678 |
+
m = re.search(r'<metadata id="legion-attestation">([A-Za-z0-9+/=]+)</metadata>', svg_text)
|
| 679 |
+
if not m:
|
| 680 |
+
out["detail"] = "aucune attestation LEGION dans le SVG"
|
| 681 |
+
return out
|
| 682 |
+
try:
|
| 683 |
+
doc = json.loads(_b64(m.group(1)))
|
| 684 |
+
st, sig = doc["statement"], doc["signature_ed25519"]
|
| 685 |
+
except Exception:
|
| 686 |
+
out["detail"] = "attestation illisible"
|
| 687 |
+
return out
|
| 688 |
+
out["statement"] = st
|
| 689 |
+
keys = pub_b64
|
| 690 |
+
pub_b64 = _pub(keys, st.get("key_id"))
|
| 691 |
+
out["signature"] = (bool(pub_b64) and st.get("schema") == BADGE_SCHEMA and st.get("key_id") == key_pin(pub_b64)
|
| 692 |
+
and ed25519_ok(_b64(pub_b64), _b64(sig), canon(st)))
|
| 693 |
+
out["rendering_matches"] = render_badge(st, sig) == svg_text
|
| 694 |
+
ok = out["signature"] and out["rendering_matches"] and st.get("last_change_observed_at", "") <= st.get("last_checked_at", "")
|
| 695 |
+
if record is not None:
|
| 696 |
+
out["record_matches"] = (record.get("server_id") == st["server_id"]
|
| 697 |
+
and record.get("tools_fingerprint", {}).get("sha256") == st["tools_sha256"]
|
| 698 |
+
and record.get("observed_at") == st["last_change_observed_at"]
|
| 699 |
+
and record.get("leaf_index") == st["record_leaf_index"])
|
| 700 |
+
out["record_signature"] = check_record(record, keys)[1]
|
| 701 |
+
out["head_signature"] = check_sth(sth, keys) if sth else False
|
| 702 |
+
out["inclusion"] = check_inclusion(record, proof, sth) if (sth and proof) else False
|
| 703 |
+
out["head_matches"] = bool(sth) and sth["tree_head"]["root_sha256"] == st["root_sha256"] \
|
| 704 |
+
and sth["tree_head"]["tree_size"] == st["tree_size"]
|
| 705 |
+
ok = ok and all(out[k] for k in ("record_matches", "record_signature", "head_signature", "inclusion", "head_matches"))
|
| 706 |
+
if now and max_age_days is not None:
|
| 707 |
+
t = lambda s: datetime.datetime.fromisoformat(s.replace("Z", "+00:00"))
|
| 708 |
+
out["stale"] = (t(now) - t(st["last_checked_at"])).total_seconds() > max_age_days * 86400
|
| 709 |
+
ok = ok and not out["stale"]
|
| 710 |
+
out["claim_state"] = "no_change_observed" if ok else "rejected"
|
| 711 |
+
out["ok"] = bool(ok)
|
| 712 |
+
return out
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
# ---------- 7) gel mensuel ----------
|
| 716 |
+
def _sha_file(p):
|
| 717 |
+
return hashlib.sha256(open(p, "rb").read()).hexdigest()
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def _verify_freeze_impl(d, pub_b64, headers=None, require_anchor=True):
|
| 721 |
+
import os
|
| 722 |
+
j = lambda n: json.load(open(os.path.join(d, n), encoding="utf-8"))
|
| 723 |
+
out = {"anchors": {}}
|
| 724 |
+
man_ok, missing = True, []
|
| 725 |
+
for line in open(os.path.join(d, "MANIFEST.sha256"), encoding="utf-8"):
|
| 726 |
+
h, n = line.rstrip("\n").split(" ", 1)
|
| 727 |
+
p = os.path.join(d, n)
|
| 728 |
+
if not os.path.exists(p):
|
| 729 |
+
missing.append(n)
|
| 730 |
+
man_ok = False
|
| 731 |
+
elif _sha_file(p) != h:
|
| 732 |
+
man_ok = False
|
| 733 |
+
out["manifest"] = man_ok
|
| 734 |
+
if missing:
|
| 735 |
+
out["manifest_missing"] = missing
|
| 736 |
+
try:
|
| 737 |
+
meta, sth = j("FREEZE.json"), j("sth.json")
|
| 738 |
+
recs = [json.loads(l) for l in open(os.path.join(d, "records.jsonl"), encoding="utf-8")]
|
| 739 |
+
sth["tree_head"]["root_sha256"], meta["tree_size"]
|
| 740 |
+
except Exception as e:
|
| 741 |
+
out.update(ok=False, claim_state="rejected", ready_to_deposit=False, error="%s: %s" % (type(e).__name__, e))
|
| 742 |
+
return out
|
| 743 |
+
leaves = [leaf_hash(canon(r)) for r in recs]
|
| 744 |
+
|
| 745 |
+
def mth(h):
|
| 746 |
+
if not h:
|
| 747 |
+
return H(b"")
|
| 748 |
+
if len(h) == 1:
|
| 749 |
+
return h[0]
|
| 750 |
+
k = 1
|
| 751 |
+
while k * 2 < len(h):
|
| 752 |
+
k *= 2
|
| 753 |
+
return node_hash(mth(h[:k]), mth(h[k:]))
|
| 754 |
+
out["records_signed"] = all(check_record(r, pub_b64)[1] and r["leaf_index"] == i for i, r in enumerate(recs))
|
| 755 |
+
out["head_signature"] = check_sth(sth, pub_b64)
|
| 756 |
+
out["root_recomputed"] = (len(recs) == sth["tree_head"]["tree_size"]
|
| 757 |
+
and mth(leaves).hex() == sth["tree_head"]["root_sha256"])
|
| 758 |
+
out["metadata_matches"] = (meta["tree_size"] == sth["tree_head"]["tree_size"]
|
| 759 |
+
and meta["root_sha256"] == sth["tree_head"]["root_sha256"])
|
| 760 |
+
if os.path.exists(os.path.join(d, "previous_sth.json")):
|
| 761 |
+
prev, cp = j("previous_sth.json"), j("consistency.json")
|
| 762 |
+
out["previous_head_signature"] = check_sth(prev, pub_b64)
|
| 763 |
+
out["consistent_with_previous"] = out["previous_head_signature"] and _verify_consistency(
|
| 764 |
+
prev["tree_head"]["tree_size"], sth["tree_head"]["tree_size"], _hx(prev["tree_head"]["root_sha256"]),
|
| 765 |
+
_hx(sth["tree_head"]["root_sha256"]), [_hx(x) for x in cp["proof"]])
|
| 766 |
+
artifact = canon(sth["tree_head"])
|
| 767 |
+
ad = os.path.join(d, "anchor")
|
| 768 |
+
if os.path.exists(os.path.join(ad, "head.canon.json.ots")):
|
| 769 |
+
out["anchors"]["opentimestamps"] = check_ots(open(os.path.join(ad, "head.canon.json.ots"), "rb").read(), artifact, headers)
|
| 770 |
+
if os.path.exists(os.path.join(ad, "rekor_entry.json")):
|
| 771 |
+
out["anchors"]["rekor"] = check_rekor(json.load(open(os.path.join(ad, "rekor_entry.json"))), artifact, pub_b64,
|
| 772 |
+
open(os.path.join(ad, "rekor_pub.pem"), "rb").read())
|
| 773 |
+
rd = lambda n: open(os.path.join(d, n), encoding="utf-8").read() if os.path.exists(os.path.join(d, n)) else ""
|
| 774 |
+
blob = json.dumps(meta) + rd("CITATION.cff") + rd(".zenodo.json")
|
| 775 |
+
out["metadata_placeholders"] = sorted(set(__import__("re").findall(r"A-COMPLETER-[A-Z]+", blob)))
|
| 776 |
+
st = [a["status"] for a in out["anchors"].values()]
|
| 777 |
+
keys = [k for k in ("manifest", "records_signed", "head_signature", "root_recomputed", "metadata_matches",
|
| 778 |
+
"previous_head_signature", "consistent_with_previous") if k in out]
|
| 779 |
+
base = all(out[k] for k in keys)
|
| 780 |
+
anchored = "verified" in st and "failed" not in st
|
| 781 |
+
out["claim_state"] = ("rejected" if not base else "rejected_anchor" if "failed" in st
|
| 782 |
+
else "anchored_freeze" if anchored else "signed_freeze_not_anchored")
|
| 783 |
+
out["ready_to_deposit"] = bool(base and anchored and not out["metadata_placeholders"])
|
| 784 |
+
out["ok"] = bool(base and (anchored or not require_anchor) and "failed" not in st)
|
| 785 |
+
return out
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _verify_consistency(m, n, old_root, new_root, proof):
|
| 789 |
+
if m <= 0: # taille 0 : aucune tête signée possible (comme la référence transparency-dev)
|
| 790 |
+
return False
|
| 791 |
+
if m != n and (not _hash32(old_root, new_root) or not all(_hash32(p) for p in proof)):
|
| 792 |
+
return False
|
| 793 |
+
if m == n:
|
| 794 |
+
return old_root == new_root and not proof
|
| 795 |
+
if m == 0 or m > n:
|
| 796 |
+
return False
|
| 797 |
+
proof = list(proof)
|
| 798 |
+
if m & (m - 1) == 0:
|
| 799 |
+
proof = [old_root] + proof
|
| 800 |
+
if not proof:
|
| 801 |
+
return False
|
| 802 |
+
fn, sn = m - 1, n - 1
|
| 803 |
+
while fn & 1:
|
| 804 |
+
fn >>= 1
|
| 805 |
+
sn >>= 1
|
| 806 |
+
fr = sr = proof[0]
|
| 807 |
+
for c in proof[1:]:
|
| 808 |
+
if sn == 0:
|
| 809 |
+
return False
|
| 810 |
+
if fn & 1 or fn == sn:
|
| 811 |
+
fr, sr = node_hash(c, fr), node_hash(c, sr)
|
| 812 |
+
if not fn & 1:
|
| 813 |
+
while not fn & 1 and fn != 0:
|
| 814 |
+
fn >>= 1
|
| 815 |
+
sn >>= 1
|
| 816 |
+
else:
|
| 817 |
+
sr = node_hash(sr, c)
|
| 818 |
+
fn >>= 1
|
| 819 |
+
sn >>= 1
|
| 820 |
+
return sn == 0 and fr == old_root and sr == new_root
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
# ---------- 8) alerte signée de changement d'outils ----------
|
| 824 |
+
ALERT_SCHEMA = "legion-mcp-tools-alert/1"
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def _diff_fp(before, after):
|
| 828 |
+
b, a = dict(before["per_tool_sha256"]), dict(after["per_tool_sha256"])
|
| 829 |
+
return {"added": sorted(set(a) - set(b)), "removed": sorted(set(b) - set(a)),
|
| 830 |
+
"modified": sorted(k for k in set(a) & set(b) if a[k] != b[k])}
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def verify_alert(alert, pub_b64):
|
| 834 |
+
"""L'alerte embarque : enregistrement précédent, nouvel enregistrement, leurs preuves d'inclusion, la tête signée."""
|
| 835 |
+
out = {"ok": False}
|
| 836 |
+
try:
|
| 837 |
+
body = {k: v for k, v in alert.items() if k != "signature_ed25519"}
|
| 838 |
+
st, prev, new, sth = alert["statement"], alert["previous_record"], alert["new_record"], alert["sth"]
|
| 839 |
+
out["alert_signature"] = (alert.get("schema") == ALERT_SCHEMA and st.get("key_id") == key_pin(pub_b64)
|
| 840 |
+
and ed25519_ok(_b64(pub_b64), _b64(alert["signature_ed25519"]), canon(body)))
|
| 841 |
+
out["records_signed"] = check_record(prev, pub_b64)[1] and check_record(new, pub_b64)[1]
|
| 842 |
+
out["head_signature"] = check_sth(sth, pub_b64)
|
| 843 |
+
out["inclusion"] = check_inclusion(prev, alert["previous_proof"], sth) and check_inclusion(new, alert["new_proof"], sth)
|
| 844 |
+
out["chain"] = (prev["server_id"] == new["server_id"] == st["server_id"] and new["prev_leaf_index"] == prev["leaf_index"]
|
| 845 |
+
and prev["observed_at"] <= new["observed_at"])
|
| 846 |
+
pa, na = prev["tools_fingerprint"].get("algo"), new["tools_fingerprint"].get("algo")
|
| 847 |
+
out["same_fingerprint_algo"] = pa == na
|
| 848 |
+
out["fingerprint_algos_comparable"] = fp_algos_comparable(pa, na) # même algo, ou paire {v2, v3}
|
| 849 |
+
if not out["fingerprint_algos_comparable"]:
|
| 850 |
+
raise ValueError("empreintes de versions différentes : diff non recalculable")
|
| 851 |
+
recomputed = _diff_fp(prev["tools_fingerprint"], new["tools_fingerprint"])
|
| 852 |
+
out["change_matches"] = (recomputed == {k: st["change"][k] for k in ("added", "removed", "modified")}
|
| 853 |
+
== {k: new["change"][k] for k in ("added", "removed", "modified")}
|
| 854 |
+
and st["previous_tools_sha256"] == prev["tools_fingerprint"]["sha256"]
|
| 855 |
+
and st["new_tools_sha256"] == new["tools_fingerprint"]["sha256"]
|
| 856 |
+
and st["previous_tools_sha256"] != st["new_tools_sha256"])
|
| 857 |
+
out["statement"] = st
|
| 858 |
+
out["ok"] = all(out[k] for k in ("alert_signature", "records_signed", "head_signature", "inclusion", "chain", "change_matches"))
|
| 859 |
+
except Exception as e:
|
| 860 |
+
out["detail"] = "%s: %s" % (type(e).__name__, e)
|
| 861 |
+
out["claim_state"] = "change_observed" if out["ok"] else "rejected"
|
| 862 |
+
return out
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
def _emit(res):
|
| 866 |
+
print(json.dumps(res, indent=1, ensure_ascii=False, sort_keys=True))
|
| 867 |
+
print("RESULTAT:", "VALIDE" if res["ok"] else "INVALIDE")
|
| 868 |
+
return 0 if res["ok"] else 1
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
UA = "mcp-tlog-verifier/1.0 (+https://legion-api.com/tlog/)"
|
| 872 |
+
DEFAULT_BASE = "https://tlog.legion-api.com/tlog/v0"
|
| 873 |
+
ROOT_KEY_URL = "https://legion-api.com/passport/legion-ed25519.pub"
|
| 874 |
+
ROOT_PIN = "a7c6a35b1c2c81d589a30c2ad628679bdea9da4139d49aa3c42cdde6e1c65036"
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def _get(url, limit=20 * 1024 * 1024):
|
| 878 |
+
"""Téléchargement avec un User-Agent explicite (l'agent Python par défaut est refusé par Cloudflare : erreur 1010)."""
|
| 879 |
+
import urllib.request
|
| 880 |
+
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json, */*"})
|
| 881 |
+
with urllib.request.urlopen(req, timeout=30) as r:
|
| 882 |
+
b = r.read(limit + 1)
|
| 883 |
+
if len(b) > limit:
|
| 884 |
+
raise ValueError("réponse trop grande : %s" % url)
|
| 885 |
+
return b
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def fetch_and_verify(leaf, pin=ROOT_PIN, base=DEFAULT_BASE, outdir=None, pubkey_file=None):
|
| 889 |
+
"""Télécharge enregistrement, preuve d'inclusion, tête signée, keyring (et .ots s'il existe), puis vérifie HORS LIGNE.
|
| 890 |
+
La confiance repose sur l'empreinte épinglée de la clé racine (--pin), pas sur le serveur."""
|
| 891 |
+
import os
|
| 892 |
+
root = open(pubkey_file).read().strip() if pubkey_file else _get(ROOT_KEY_URL).decode().strip()
|
| 893 |
+
if key_pin(root) != pin:
|
| 894 |
+
return {"ok": False, "claim_state": "rejected", "error": "clé racine : empreinte %s != épinglée %s" % (key_pin(root), pin)}
|
| 895 |
+
head = json.loads(_get(base + "/head"))
|
| 896 |
+
n = head["sth"]["tree_head"]["tree_size"]
|
| 897 |
+
rec = json.loads(_get("%s/records/%d" % (base, leaf)))
|
| 898 |
+
proof = json.loads(_get("%s/proof/inclusion?leaf_index=%d&tree_size=%d" % (base, leaf, n)))
|
| 899 |
+
keys = load_keyring(_get(base + "/keyring").decode("utf-8"), root)
|
| 900 |
+
ots = None
|
| 901 |
+
try:
|
| 902 |
+
ots = _get("%s/anchor/%d/ots" % (base, n))
|
| 903 |
+
except Exception:
|
| 904 |
+
pass
|
| 905 |
+
if outdir:
|
| 906 |
+
os.makedirs(outdir, exist_ok=True)
|
| 907 |
+
for name, obj in (("record.json", rec), ("proof.json", proof), ("sth.json", head["sth"])):
|
| 908 |
+
json.dump(obj, open(os.path.join(outdir, name), "w"), indent=1, sort_keys=True, ensure_ascii=False)
|
| 909 |
+
if ots:
|
| 910 |
+
open(os.path.join(outdir, "head.ots"), "wb").write(ots)
|
| 911 |
+
res = verify_all(rec, proof, head["sth"], keys, ots=ots, headers=None, require_anchor=False)
|
| 912 |
+
res.update(server_id=rec.get("server_id"), leaf_index=leaf, tree_size=n, change=rec.get("change"),
|
| 913 |
+
observed_at=rec.get("observed_at"), root_pin=pin,
|
| 914 |
+
anchor_note="OTS téléchargé : statut indiqué sans en-têtes Bitcoin ; pour une date vérifiée, voir --btc-headers (votre nœud)."
|
| 915 |
+
if ots else "aucun .ots publié pour cette tête")
|
| 916 |
+
return res
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
# ---------- vérifications 100 % hors ligne (aucun appel réseau) ----------
|
| 921 |
+
def verify_consistency_offline(old_sth, new_sth, proof, keys):
|
| 922 |
+
"""Deux têtes signées + preuve RFC 9162 : signatures des deux têtes (keyring) et cohérence append-only."""
|
| 923 |
+
o, n = old_sth["tree_head"], new_sth["tree_head"]
|
| 924 |
+
out = {"old_head_signature": check_sth(old_sth, keys), "new_head_signature": check_sth(new_sth, keys),
|
| 925 |
+
"old_size": o["tree_size"], "new_size": n["tree_size"]}
|
| 926 |
+
p = proof.get("proof", proof) if isinstance(proof, dict) else proof
|
| 927 |
+
out["consistent"] = _verify_consistency(o["tree_size"], n["tree_size"], _hx(o["root_sha256"]), _hx(n["root_sha256"]), [_hx(h) for h in p])
|
| 928 |
+
out["ok"] = out["old_head_signature"] and out["new_head_signature"] and out["consistent"]
|
| 929 |
+
return out
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
def verify_bundle_offline(bundle, keys, anchored_sth=None, anchor_consistency=None, ots=None, headers=None):
|
| 933 |
+
"""Bundle /tlog/v1/servers/{id}/latest : signature de l'enregistrement, inclusion dans la tête, signature de la tête.
|
| 934 |
+
Option ancrage : tête ancrée (sth) + son .ots + en-têtes Bitcoin (votre nœud ou explorateur) + preuve de cohérence
|
| 935 |
+
tête ancrée -> tête du bundle. Sans ces fichiers, l'ancrage est déclaré non vérifié (jamais supposé)."""
|
| 936 |
+
rec, sth = bundle["record"], bundle["sth"]
|
| 937 |
+
integ, sig, err = check_record(rec, keys)
|
| 938 |
+
out = {"server_id": rec.get("server_id"), "leaf_index": rec.get("leaf_index"), "tree_size": sth["tree_head"]["tree_size"],
|
| 939 |
+
"record_integrity": integ, "record_signature": sig, "head_signature": check_sth(sth, keys),
|
| 940 |
+
"inclusion": check_inclusion(rec, bundle["inclusion"], sth), "error": err}
|
| 941 |
+
out["ok"] = bool(integ and sig and out["head_signature"] and out["inclusion"])
|
| 942 |
+
if anchored_sth is not None:
|
| 943 |
+
a = verify_consistency_offline(anchored_sth, sth, anchor_consistency or [], keys) if anchored_sth["tree_head"]["tree_size"] != sth["tree_head"]["tree_size"] \
|
| 944 |
+
else {"ok": anchored_sth == sth, "consistent": anchored_sth == sth}
|
| 945 |
+
out["anchored_head"] = anchored_sth["tree_head"]["tree_size"]
|
| 946 |
+
out["anchored_head_extends_to_bundle_head"] = bool(a.get("ok"))
|
| 947 |
+
if ots is not None:
|
| 948 |
+
st = check_ots(ots, canon(anchored_sth["tree_head"]), headers)
|
| 949 |
+
out["anchor"] = st
|
| 950 |
+
else:
|
| 951 |
+
out["anchor"] = {"status": "not_checked", "reason": "no .ots given"}
|
| 952 |
+
else:
|
| 953 |
+
out["anchor"] = {"status": "not_checked", "reason": "no anchored head given"}
|
| 954 |
+
return out
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
# ---------- tête contresignée par N témoins (C2SP signed-note + tlog-cosignature) ----------
|
| 958 |
+
def _vkey(v):
|
| 959 |
+
name, kid_hex, b64 = v.strip().split("+", 2)
|
| 960 |
+
raw = base64.b64decode(b64)
|
| 961 |
+
return name, bytes.fromhex(kid_hex), raw[0], raw[1:]
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
def verify_witnessed(note_text, log_vkey, witness_vkeys, n_required):
|
| 965 |
+
"""La note est signée par la clé du journal (log_vkey) ET contresignée (cosignature/v1) par au moins n_required clés
|
| 966 |
+
parmi witness_vkeys, la liste des témoins que VOUS jugez indépendants. Clé inconnue : ignorée. Clé connue qui échoue :
|
| 967 |
+
rejet (règle C2SP signed-note). Renvoie le détail."""
|
| 968 |
+
out = {"ok": False, "log_signature": False, "witnesses_valid": [], "required": n_required}
|
| 969 |
+
try:
|
| 970 |
+
body, rest = note_text.split("\n\n", 1)
|
| 971 |
+
body += "\n"
|
| 972 |
+
lines = [l for l in rest.split("\n") if l.strip()]
|
| 973 |
+
lname, lkid, ltype, lpub = _vkey(log_vkey)
|
| 974 |
+
ws = {}
|
| 975 |
+
for v in witness_vkeys:
|
| 976 |
+
n, k, t, p = _vkey(v)
|
| 977 |
+
if t == 0x04:
|
| 978 |
+
ws[n] = (k, p)
|
| 979 |
+
H_ = lambda b: hashlib.sha256(b).digest()
|
| 980 |
+
for l in lines:
|
| 981 |
+
if not l.startswith("\u2014 "):
|
| 982 |
+
return dict(out, error="ligne de signature malformée")
|
| 983 |
+
name, b64 = l[2:].rsplit(" ", 1)
|
| 984 |
+
raw = base64.b64decode(b64, validate=True)
|
| 985 |
+
if name == lname and raw[:4] == lkid and ltype == 0x01:
|
| 986 |
+
out["log_signature"] = ed25519_ok(lpub, raw[4:], body.encode())
|
| 987 |
+
elif name in ws:
|
| 988 |
+
k, p = ws[name]
|
| 989 |
+
if raw[:4] != k or len(raw) != 76 or H_(name.encode() + b"\n" + b"\x04" + p)[:4] != k:
|
| 990 |
+
return dict(out, error="cosignature du témoin connu %s : identifiant de clé incohérent" % name)
|
| 991 |
+
ts = struct.unpack(">Q", raw[4:12])[0]
|
| 992 |
+
if not ed25519_ok(p, raw[12:], ("cosignature/v1\ntime %d\n" % ts).encode() + body.encode()):
|
| 993 |
+
return dict(out, error="cosignature invalide du témoin connu %s" % name)
|
| 994 |
+
out["witnesses_valid"].append(name)
|
| 995 |
+
lines0 = body.split("\n")
|
| 996 |
+
out.update(origin=lines0[0], tree_size=int(lines0[1]), root_sha256=base64.b64decode(lines0[2]).hex())
|
| 997 |
+
out["witnesses_valid"] = sorted(set(out["witnesses_valid"]))
|
| 998 |
+
out["ok"] = out["log_signature"] and len(out["witnesses_valid"]) >= n_required
|
| 999 |
+
except Exception as e:
|
| 1000 |
+
out["error"] = "%s: %s" % (type(e).__name__, e)
|
| 1001 |
+
return out
|
| 1002 |
+
|
| 1003 |
+
def main():
|
| 1004 |
+
ld = lambda p: json.load(open(p, encoding="utf-8")) if p else None
|
| 1005 |
+
if len(sys.argv) > 1 and sys.argv[1] == "fetch":
|
| 1006 |
+
ap = argparse.ArgumentParser(prog="verify_tlog.py fetch",
|
| 1007 |
+
description="Télécharge (User-Agent mcp-tlog-verifier/1.0) puis vérifie hors ligne une feuille du journal.")
|
| 1008 |
+
ap.add_argument("--leaf", type=int, required=True)
|
| 1009 |
+
ap.add_argument("--pin", default=ROOT_PIN, help="empreinte SHA-256 épinglée de la clé racine LEGION")
|
| 1010 |
+
ap.add_argument("--pubkey", help="clé racine locale (base64) au lieu de la télécharger")
|
| 1011 |
+
ap.add_argument("--base", default=DEFAULT_BASE)
|
| 1012 |
+
ap.add_argument("--out", help="dossier où garder les fichiers téléchargés")
|
| 1013 |
+
a = ap.parse_args(sys.argv[2:])
|
| 1014 |
+
import urllib.error
|
| 1015 |
+
try:
|
| 1016 |
+
res = fetch_and_verify(a.leaf, a.pin, a.base, a.out, a.pubkey)
|
| 1017 |
+
except (urllib.error.URLError, OSError, TimeoutError) as e:
|
| 1018 |
+
# Téléchargement impossible (réseau, limite de débit 429, serveur absent) : ce n'est PAS un verdict sur la preuve.
|
| 1019 |
+
code = getattr(e, "code", None)
|
| 1020 |
+
print(json.dumps({"ok": None, "error": "téléchargement impossible : %s%s" % (type(e).__name__, " HTTP %s" % code if code else ""),
|
| 1021 |
+
"hint": "réessayer plus tard (limite 60 requêtes/min/IP) ou vérifier des fichiers locaux sans 'fetch'"},
|
| 1022 |
+
ensure_ascii=False))
|
| 1023 |
+
print("RESULTAT: ERREUR_RESEAU")
|
| 1024 |
+
return 3
|
| 1025 |
+
print(json.dumps(res, indent=1, ensure_ascii=False, sort_keys=True))
|
| 1026 |
+
print("RESULTAT:", "VALIDE" if res.get("ok") else "INVALIDE")
|
| 1027 |
+
return 0 if res.get("ok") else 1
|
| 1028 |
+
if len(sys.argv) > 1 and sys.argv[1] == "witnessed":
|
| 1029 |
+
ap = argparse.ArgumentParser(prog="verify_tlog.py witnessed", description="Tête signée par le journal ET contresignée par >= N témoins de VOTRE liste (hors ligne).")
|
| 1030 |
+
ap.add_argument("note", help="note C2SP (ex. /tlog/v1/checkpoint/<taille>)")
|
| 1031 |
+
ap.add_argument("--log-vkey", required=True, help="clé du journal au format vkey (log_vkey de /tlog/v1/witnesses, à épingler)")
|
| 1032 |
+
ap.add_argument("--witness-vkeys", required=True, help="fichier : une vkey de témoin par ligne, ceux que VOUS jugez indépendants")
|
| 1033 |
+
ap.add_argument("--min", type=int, default=1)
|
| 1034 |
+
a = ap.parse_args(sys.argv[2:])
|
| 1035 |
+
res = verify_witnessed(open(a.note, encoding="utf-8").read(), a.log_vkey,
|
| 1036 |
+
[l for l in open(a.witness_vkeys) if l.strip() and not l.startswith("#")], a.min)
|
| 1037 |
+
print(json.dumps(res, indent=1, ensure_ascii=False, sort_keys=True)); print("RESULTAT:", "VALIDE" if res["ok"] else "INVALIDE")
|
| 1038 |
+
return 0 if res["ok"] else 1
|
| 1039 |
+
if len(sys.argv) > 1 and sys.argv[1] in ("consistency", "bundle"):
|
| 1040 |
+
sub = sys.argv[1]
|
| 1041 |
+
ap = argparse.ArgumentParser(prog="verify_tlog.py " + sub, description="Vérification 100 % hors ligne (aucun appel réseau).")
|
| 1042 |
+
ap.add_argument("--pubkey", required=True, help="clé racine LEGION (base64) ; son empreinte doit valoir --pin")
|
| 1043 |
+
ap.add_argument("--pin", default=ROOT_PIN)
|
| 1044 |
+
ap.add_argument("--keyring", required=True, help="keyring.jsonl (sous-clés approuvées par la racine)")
|
| 1045 |
+
if sub == "consistency":
|
| 1046 |
+
ap.add_argument("--old", required=True); ap.add_argument("--new", required=True); ap.add_argument("--proof", required=True)
|
| 1047 |
+
else:
|
| 1048 |
+
ap.add_argument("bundle"); ap.add_argument("--anchored-sth"); ap.add_argument("--anchor-consistency")
|
| 1049 |
+
ap.add_argument("--ots"); ap.add_argument("--btc-headers")
|
| 1050 |
+
a = ap.parse_args(sys.argv[2:])
|
| 1051 |
+
root = open(a.pubkey).read().strip()
|
| 1052 |
+
if key_pin(root) != a.pin:
|
| 1053 |
+
print(json.dumps({"ok": False, "error": "clé racine : empreinte %s != épinglée %s" % (key_pin(root), a.pin)})); print("RESULTAT: INVALIDE"); return 1
|
| 1054 |
+
keys = load_keyring(open(a.keyring, encoding="utf-8").read(), root)
|
| 1055 |
+
if sub == "consistency":
|
| 1056 |
+
res = verify_consistency_offline(ld(a.old).get("sth", ld(a.old)), ld(a.new).get("sth", ld(a.new)), ld(a.proof), keys)
|
| 1057 |
+
else:
|
| 1058 |
+
an = ld(a.anchored_sth); an = an.get("sth", an) if an else None
|
| 1059 |
+
ac = ld(a.anchor_consistency); ac = ac.get("proof", ac) if isinstance(ac, dict) else ac
|
| 1060 |
+
res = verify_bundle_offline(ld(a.bundle), keys, an, ac, open(a.ots, "rb").read() if a.ots else None, ld(a.btc_headers))
|
| 1061 |
+
print(json.dumps(res, indent=1, ensure_ascii=False, sort_keys=True, default=str))
|
| 1062 |
+
print("RESULTAT:", "VALIDE" if res.get("ok") else "INVALIDE")
|
| 1063 |
+
return 0 if res.get("ok") else 1
|
| 1064 |
+
if len(sys.argv) > 1 and sys.argv[1] == "alert":
|
| 1065 |
+
ap = argparse.ArgumentParser(prog="verify_tlog.py alert")
|
| 1066 |
+
ap.add_argument("alert"); ap.add_argument("--pubkey", required=True)
|
| 1067 |
+
a = ap.parse_args(sys.argv[2:])
|
| 1068 |
+
return _emit(verify_alert(ld(a.alert), open(a.pubkey).read().strip()))
|
| 1069 |
+
if len(sys.argv) > 1 and sys.argv[1] in ("receipt", "badge", "freeze"):
|
| 1070 |
+
sub = sys.argv[1]
|
| 1071 |
+
ap = argparse.ArgumentParser(prog="verify_tlog.py " + sub)
|
| 1072 |
+
if sub == "receipt":
|
| 1073 |
+
ap.add_argument("--receipt", required=True, help="une ligne de receipts.jsonl (fichier JSON)")
|
| 1074 |
+
ap.add_argument("--root", required=True, help="ROOT.json")
|
| 1075 |
+
elif sub == "badge":
|
| 1076 |
+
ap.add_argument("svg")
|
| 1077 |
+
ap.add_argument("--record")
|
| 1078 |
+
ap.add_argument("--proof")
|
| 1079 |
+
ap.add_argument("--sth")
|
| 1080 |
+
ap.add_argument("--now")
|
| 1081 |
+
ap.add_argument("--max-age-days", type=float)
|
| 1082 |
+
ap.add_argument("--keyring", help="keyring.jsonl du journal (sous-clés approuvées par la clé --pubkey)")
|
| 1083 |
+
else:
|
| 1084 |
+
ap.add_argument("dir")
|
| 1085 |
+
ap.add_argument("--keyring", help="keyring.jsonl (sous-clés approuvées par la clé --pubkey)")
|
| 1086 |
+
if sub != "receipt":
|
| 1087 |
+
ap.add_argument("--pubkey", required=True)
|
| 1088 |
+
ap.add_argument("--ots")
|
| 1089 |
+
ap.add_argument("--btc-headers")
|
| 1090 |
+
ap.add_argument("--no-anchor", action="store_true")
|
| 1091 |
+
a = ap.parse_args(sys.argv[2:])
|
| 1092 |
+
if sub == "receipt":
|
| 1093 |
+
return _emit(verify_receipt_root(ld(a.receipt), ld(a.root), open(a.ots, "rb").read() if a.ots else None,
|
| 1094 |
+
ld(a.btc_headers), require_anchor=not a.no_anchor))
|
| 1095 |
+
pub = open(a.pubkey).read().strip()
|
| 1096 |
+
if sub in ("badge", "freeze") and a.keyring:
|
| 1097 |
+
pub = load_keyring(open(a.keyring, encoding="utf-8").read(), pub)
|
| 1098 |
+
if sub == "badge":
|
| 1099 |
+
return _emit(verify_badge(open(a.svg, encoding="utf-8").read(), pub, ld(a.record), ld(a.proof), ld(a.sth),
|
| 1100 |
+
a.now, a.max_age_days))
|
| 1101 |
+
return _emit(verify_freeze(a.dir, pub, ld(a.btc_headers), require_anchor=not a.no_anchor))
|
| 1102 |
+
return _main_record()
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
def _main_record():
|
| 1106 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 1107 |
+
ap.add_argument("--record", required=True)
|
| 1108 |
+
ap.add_argument("--proof", required=True)
|
| 1109 |
+
ap.add_argument("--sth", required=True)
|
| 1110 |
+
ap.add_argument("--pubkey", required=True, help="clé publique LEGION, base64 des 32 octets bruts")
|
| 1111 |
+
ap.add_argument("--ots")
|
| 1112 |
+
ap.add_argument("--btc-headers")
|
| 1113 |
+
ap.add_argument("--rekor-entry")
|
| 1114 |
+
ap.add_argument("--rekor-pubkey")
|
| 1115 |
+
ap.add_argument("--no-anchor", action="store_true", help="vérifier 1-3 seulement (horodatage externe non exigé)")
|
| 1116 |
+
ap.add_argument("--keyring", help="keyring.jsonl du journal : clés résolues par key_id, ancrées sur --pubkey (racine)")
|
| 1117 |
+
a = ap.parse_args()
|
| 1118 |
+
ld = lambda p: json.load(open(p, encoding="utf-8"))
|
| 1119 |
+
pub = open(a.pubkey).read().strip()
|
| 1120 |
+
if a.keyring:
|
| 1121 |
+
pub = load_keyring(open(a.keyring, encoding="utf-8").read(), pub)
|
| 1122 |
+
res = verify_all(ld(a.record), ld(a.proof), ld(a.sth), pub,
|
| 1123 |
+
ots=open(a.ots, "rb").read() if a.ots else None,
|
| 1124 |
+
headers=ld(a.btc_headers) if a.btc_headers else None,
|
| 1125 |
+
rekor_entry=ld(a.rekor_entry) if a.rekor_entry else None,
|
| 1126 |
+
rekor_pub_pem=open(a.rekor_pubkey, "rb").read() if a.rekor_pubkey else None,
|
| 1127 |
+
require_anchor=not a.no_anchor)
|
| 1128 |
+
print(json.dumps(res, indent=1, ensure_ascii=False, sort_keys=True))
|
| 1129 |
+
print("RESULTAT:", "VALIDE" if res["ok"] else "INVALIDE")
|
| 1130 |
+
return 0 if res["ok"] else 1
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
def _safe(fn):
|
| 1134 |
+
"""Point d'entrée : toute entrée illisible (JSON tronqué, fichier absent, structure inattendue) donne un refus propre,
|
| 1135 |
+
code 1, jamais une trace Python ni un succès."""
|
| 1136 |
+
try:
|
| 1137 |
+
return fn()
|
| 1138 |
+
except SystemExit:
|
| 1139 |
+
raise
|
| 1140 |
+
except Exception as e:
|
| 1141 |
+
print(json.dumps({"ok": False, "claim_state": "rejected", "error": "%s: %s" % (type(e).__name__, str(e)[:200])},
|
| 1142 |
+
ensure_ascii=False))
|
| 1143 |
+
print("RESULTAT: INVALIDE")
|
| 1144 |
+
return 1
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
|
| 1149 |
+
# ---------- durcissement (fuzzing 2026-10-09) : une entrée inexploitable donne un refus propre, jamais une exception ----------
|
| 1150 |
+
def verify_all(*a, **k):
|
| 1151 |
+
try:
|
| 1152 |
+
return _verify_all_impl(*a, **k)
|
| 1153 |
+
except Exception as e:
|
| 1154 |
+
return {"ok": False, "claim_state": "rejected", "error": "entrée inexploitable : %s: %s" % (type(e).__name__, str(e)[:160]),
|
| 1155 |
+
"anchors": {}, "external_timestamp": False}
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
def verify_badge(*a, **k):
|
| 1159 |
+
try:
|
| 1160 |
+
return _verify_badge_impl(*a, **k)
|
| 1161 |
+
except Exception as e:
|
| 1162 |
+
return {"ok": False, "claim_state": "rejected", "detail": "badge inexploitable : %s: %s" % (type(e).__name__, str(e)[:160])}
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def verify_freeze(*a, **k):
|
| 1166 |
+
try:
|
| 1167 |
+
return _verify_freeze_impl(*a, **k)
|
| 1168 |
+
except Exception as e:
|
| 1169 |
+
return {"ok": False, "claim_state": "rejected", "ready_to_deposit": False, "anchors": {},
|
| 1170 |
+
"error": "gel inexploitable : %s: %s" % (type(e).__name__, str(e)[:160])}
|
| 1171 |
+
|
| 1172 |
+
|
| 1173 |
+
def check_ots(*a, **k):
|
| 1174 |
+
try:
|
| 1175 |
+
return _check_ots_impl(*a, **k)
|
| 1176 |
+
except Exception as e:
|
| 1177 |
+
return {"status": "failed", "detail": "preuve .ots ou en-têtes inexploitables : %s: %s" % (type(e).__name__, str(e)[:160])}
|
| 1178 |
+
|
| 1179 |
+
if __name__ == "__main__":
|
| 1180 |
+
sys.exit(_safe(main))
|
verifier/verify_tlog.py.sha256
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
23728659f028fcdf97dcf81c66cd652a2d8d1bb3ed5eee44af1fac814e3b2667 verify_tlog.py
|