File size: 9,228 Bytes
e921338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a97bc
 
 
 
 
 
 
 
 
 
 
 
 
e921338
 
 
 
 
 
 
 
 
 
 
46a97bc
e921338
 
 
 
 
 
 
46a97bc
 
 
 
e921338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a97bc
 
e921338
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/usr/bin/env python3
# PHOENIX verifier v0.2 — continuite de cle. Autonome, aucune dependance a LEGION. Ne plante jamais.
# python3 phoenix_verify2.py [--pin SHA256_CLE] [--keyring keyring.jsonl] [--head HASH_TETE_ANCREE] [objet.json ...]
# rc: 0 intact + emetteur epingle | 3 preuves manquantes | 4 emetteur non epingle | 1 au moins un INVALID | 2 usage
#     5 keyring fourni mais rejete (troncature, fork, entree invalide) — prioritaire: une revocation a pu etre effacee
# Limite: signed_at n'est pas couvert par la signature 0.1; la preuve de date vient de l'ancrage du registre d'empire.
import sys, os, json, glob, hashlib, base64
F = ("phoenix", "subject", "observation", "claim", "evidence")
def canon(o): return json.dumps({k: o[k] for k in F}, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def ehash(e): return hashlib.sha256(json.dumps({k: v for k, v in e.items() if k != "hash"}, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
def fp(b64): return hashlib.sha256(base64.b64decode(b64)).hexdigest()
def kid(b64): return "k1:" + fp(b64)[:32]
def vsig(b64, sig, msg):
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(base64.b64decode(b64)).verify(base64.b64decode(sig), msg.encode()); return True
    except Exception: return False
def lineage(keys, roots):
    s = set(roots); ch = True
    while ch:
        ch = False
        for x, v in keys.items():
            if x not in s and v["prev"] in s: s.add(x); ch = True
    return s
def tip(path):
    try: return json.loads([l for l in open(path).read().splitlines() if l.strip()][-1]).get("hash")
    except Exception: return None
def load_keyring(path):
    keys, probs, prev = {}, [], "0" * 64
    try: lines = [l for l in open(path).read().splitlines() if l.strip()]
    except Exception as x: return {}, ["keyring illisible: %s" % type(x).__name__]
    for i, l in enumerate(lines):
        try: e = json.loads(l); assert isinstance(e, dict)
        except Exception: probs.append("ligne %d illisible" % i); continue
        if e.get("prev_hash") != prev: probs.append("chaine cassee ligne %d" % i)
        if e.get("hash") != ehash(e): probs.append("hash invalide ligne %d" % i)
        prev = e.get("hash", ""); t = e.get("type")
        try:
            if t == "key_register":
                pk = e.get("public_key_b64", "")
                if e.get("key_id") != kid(pk) or not vsig(pk, e.get("self_sig", ""), "PHOENIX_KEY_REGISTER|%s|%s|%s" % (e.get("key_id"), e.get("issuer_claimed"), e.get("valid_from"))):
                    probs.append("enregistrement invalide ligne %d" % i); continue
                keys[e["key_id"]] = {"pub": pk, "issuer": e.get("issuer_claimed"), "valid_from": e.get("valid_from"), "prev": None, "revoked_at": None, "reason": None}
            elif t == "key_rotate":
                o, n, npk = e.get("old_key_id"), e.get("new_key_id"), e.get("new_public_key_b64", ""); m = "PHOENIX_KEY_ROTATE|%s|%s|%s" % (o, n, e.get("at"))
                if o not in keys or n != kid(npk) or not vsig(keys[o]["pub"], e.get("sig_old", ""), m) or not vsig(npk, e.get("sig_new", ""), m):
                    probs.append("rotation invalide ligne %d" % i); continue
                keys[n] = {"pub": npk, "issuer": keys[o]["issuer"], "valid_from": e.get("at"), "prev": o, "revoked_at": None, "reason": None}
            elif t == "key_revoke":
                k = e.get("key_id"); m = "PHOENIX_KEY_REVOKE|%s|%s|%s" % (k, e.get("at"), e.get("reason"))
                if k not in keys or not any(vsig(keys[x]["pub"], e.get("sig", ""), m) for x in lineage(keys, {k})):
                    probs.append("revocation invalide ligne %d" % i); continue
                keys[k]["revoked_at"], keys[k]["reason"] = e.get("at"), e.get("reason")
            else: probs.append("type inconnu ligne %d" % i)
        except Exception as x: probs.append("ligne %d: %s" % (i, type(x).__name__))
    return keys, probs
def tombstone_ok(p, expected_sha256, pub_b64):
    """Pièce retirée : tombstone phoenix-tombstone/0.1 signé par la clé de l'objet et portant l'empreinte de l'original."""
    try:
        t = json.load(open(p))
        sg = t.get("signature") or {}
        body = {k: v for k, v in t.items() if k != "signature"}
        d = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
        if not (t.get("schema") == "phoenix-tombstone/0.1" and t.get("status") == "RETRACTED" and t.get("original_sha256") == expected_sha256
                and sg.get("public_key_b64") == pub_b64 and sg.get("signed_message") == "PHOENIX_TOMBSTONE_V0.1|" + d): return False
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64)).verify(base64.b64decode(sg.get("sig", "")), sg["signed_message"].encode())
        return True
    except Exception: return False
def check(path, edir, keys, pinset, pin):
    flags, fail = [], []
    try:
        obj = json.load(open(path))
        if not isinstance(obj, dict) or any(k not in obj for k in F + ("attestation",)): return ["INVALID"], ["structure"]
        c, att, ev = obj["claim"], obj["attestation"], obj["evidence"]
        if not (isinstance(c, dict) and isinstance(att, dict) and isinstance(ev, list)): return ["INVALID"], ["structure"]
        print("\n%s | %s" % (os.path.basename(path), str(c.get("text", ""))[:90]))
        d = hashlib.sha256(canon(obj)).hexdigest(); pk = str(att.get("public_key_b64", ""))
        (flags.append("CONTENT_INTACT") if att.get("digest") == d else fail.append("contenu modifie"))
        (flags.append("SIGNATURE_VALID") if vsig(pk, att.get("signature", ""), "PHOENIX_V0.1|" + d) else fail.append("signature invalide"))
        miss = retr = 0
        for e in ev:
            p = None
            if isinstance(e, dict) and edir:
                u = str(e.get("uri", ""))
                for q in (os.path.join(edir, u), os.path.join(edir, os.path.basename(u))):
                    if os.path.isfile(q): p = q; break
            if not p: miss += 1; continue
            if hashlib.sha256(open(p, "rb").read()).hexdigest() != e.get("sha256"):
                if tombstone_ok(p, e.get("sha256"), pk): retr += 1; continue
                fail.append("preuve alteree: " + os.path.basename(p))
        flags.append("EVIDENCE_MISSING" if miss else "EVIDENCE_ALTERED" if any(f.startswith("preuve") for f in fail) else "EVIDENCE_RETRACTED" if retr else "EVIDENCE_INTACT")
        try: k, f = kid(pk), fp(pk)
        except Exception: k = f = None
        flags.append("ISSUER_KEY_PINNED" if k and (k in pinset or (pin and f == pin)) else "ISSUER_NOT_PINNED")
        if k in keys:
            flags.append("KEY_IN_KEYRING"); ra = keys[k]["revoked_at"]
            if ra:
                if str(att.get("signed_at", "")) < ra: flags.append("KEY_REVOKED_AFTER_SIGNING")
                else: flags.append("KEY_REVOKED_BEFORE_SIGNING"); fail.append("signe apres revocation de la cle (%s)" % keys[k]["reason"])
    except Exception as x: return ["INVALID"], ["illisible: %s" % type(x).__name__]
    return flags, fail
def main():
    a, pin, kr, head, objs, i = sys.argv[1:], None, None, None, [], 0
    while i < len(a):
        if a[i] == "--pin" and i + 1 < len(a): pin = a[i + 1].lower(); i += 2
        elif a[i] == "--keyring" and i + 1 < len(a): kr = a[i + 1]; i += 2
        elif a[i] == "--head" and i + 1 < len(a): head = a[i + 1].lower(); i += 2
        else: objs.append(a[i]); i += 1
    objs = objs or sorted(glob.glob("objects/*.json"))
    if not objs: print("usage: phoenix_verify2.py [--pin H] [--keyring F] [--head H] [objet.json ...]"); return 2
    edir = "evidence" if os.path.isdir("evidence") else None
    keys, kr_bad = {}, False
    if kr:
        keys, probs = load_keyring(kr)
        if head and tip(kr) != head: probs.append("tete du keyring differente de la tete ancree (troncature ou fork)")
        print("keyring: %d cle(s) | %s" % (len(keys), "valide" if not probs else "REJETE: " + "; ".join(probs)))
        if probs: keys, kr_bad = {}, True
    elif head: print("--head ignore sans --keyring")
    pinset = lineage(keys, {k for k, v in keys.items() if pin and fp(v["pub"]) == pin}) if keys else set()
    n = {"invalid": 0, "unpinned": 0, "missing": 0}
    for o in objs:
        fl, fa = check(o, edir, keys, pinset, pin)
        print("  ->", " ".join(fl) + ("" if not fa else " | INVALID: " + "; ".join(fa)))
        if fa or "INVALID" in fl: n["invalid"] += 1
        elif "ISSUER_NOT_PINNED" in fl: n["unpinned"] += 1
        elif "EVIDENCE_MISSING" in fl or "EVIDENCE_RETRACTED" in fl: n["missing"] += 1
    print("\nBILAN: %d objet(s) | invalides %d | emetteur non epingle %d | preuves manquantes ou retirees %d%s" % (len(objs), n["invalid"], n["unpinned"], n["missing"], "" if pin else " (aucun --pin)"))
    if kr_bad: print("KEYRING REJETE: une revocation a pu etre effacee; resultat non fiable (rc=5)"); return 5
    return 1 if n["invalid"] else 4 if n["unpinned"] else 3 if n["missing"] else 0
if __name__ == "__main__": sys.exit(main())