# SPDX-License-Identifier: Apache-2.0 """`sealed.v1` on top of review/spec_client.py, written against the text of the specification like that file. What this file adds to the Core client: the base mode of HPKE (RFC 9180) written out here, with X25519 and ChaCha20-Poly1305 from the `cryptography` library; the sealing of §11.4; an `enc` key in the Card; and the rotation of that key (§11.5). It uses nothing from the reference package. python review/spec_client_sealed.py against a Gateway that is already running (its base URL, without /v1) python review/spec_client_sealed.py starts the reference Gateway in this process first and ends with one exchange with the reference client; without the jcs, base58 and pyhpke packages: python review/run_independent.py probe review/spec_client_sealed.py python review/spec_client_sealed.py vectors opens and reproduces the sealed Envelope of vectors/, no Gateway Two agents register with an `enc` key each and exchange one sealed message. The recipient then rotates its `enc` key and reads what was sealed to the old key and to the new one. Exit status 0 when every check passes. """ import hashlib import hmac import json import os import sys import time from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import spec_client as core # noqa: E402 from spec_client import (Agent, attempt, b64u, b64u_decode, check, check_delivered, content_digest, # noqa: E402 http, jcs, raw, sign_envelope, sign_record, ts, ulid, verify_envelope, verify_record) # ---- HPKE, base mode (RFC 9180; §11.2 names the suite) ------------------------------------------------------------- ENC_ALG = "hpke-x25519-sha256-chacha20" # DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20-Poly1305 _KEM = b"KEM" + (0x0020).to_bytes(2, "big") # RFC 9180 §4.1: the suite id of the KEM _HPKE = b"HPKE" + (0x0020).to_bytes(2, "big") + (0x0001).to_bytes(2, "big") + (0x0003).to_bytes(2, "big") def _extract(salt: bytes, ikm: bytes) -> bytes: return hmac.new(salt or bytes(32), ikm, hashlib.sha256).digest() def _expand(prk: bytes, info: bytes, length: int) -> bytes: out, block, i = b"", b"", 1 while len(out) < length: block = hmac.new(prk, block + info + bytes([i]), hashlib.sha256).digest() out, i = out + block, i + 1 return out[:length] def _labeled_extract(suite: bytes, salt: bytes, label: bytes, ikm: bytes) -> bytes: return _extract(salt, b"HPKE-v1" + suite + label + ikm) def _labeled_expand(suite: bytes, prk: bytes, label: bytes, info: bytes, length: int) -> bytes: return _expand(prk, length.to_bytes(2, "big") + b"HPKE-v1" + suite + label + info, length) def _hpke_key(dh: bytes, ek: bytes, pk_r: bytes, info: bytes) -> tuple: """RFC 9180 §4.1 (ExtractAndExpand) and §5.1 (KeySchedule) in base mode: mode 0, no PSK. Returns key, nonce.""" shared = _labeled_expand(_KEM, _labeled_extract(_KEM, b"", b"eae_prk", dh), b"shared_secret", ek + pk_r, 32) context = (b"\x00" + _labeled_extract(_HPKE, b"", b"psk_id_hash", b"") + _labeled_extract(_HPKE, b"", b"info_hash", info)) secret = _labeled_extract(_HPKE, shared, b"secret", b"") return (_labeled_expand(_HPKE, secret, b"key", context, 32), _labeled_expand(_HPKE, secret, b"base_nonce", context, 12)) def hpke_seal(pk_r: bytes, info: bytes, plaintext: bytes, eph: bytes = b"") -> tuple: """§11.4: HPKE.Seal in base mode, one message, empty associated data. Returns the encapsulated key and the ciphertext. `eph` fixes the ephemeral key and exists only to reproduce a vector.""" sk_e = X25519PrivateKey.from_private_bytes(eph) if eph else X25519PrivateKey.generate() ek = raw(sk_e.public_key()) key, nonce = _hpke_key(sk_e.exchange(X25519PublicKey.from_public_bytes(pk_r)), ek, pk_r, info) return ek, ChaCha20Poly1305(key).encrypt(nonce, plaintext, b"") def hpke_open(sk_r: X25519PrivateKey, ek: bytes, info: bytes, ciphertext: bytes) -> bytes: key, nonce = _hpke_key(sk_r.exchange(X25519PublicKey.from_public_bytes(ek)), ek, raw(sk_r.public_key()), info) return ChaCha20Poly1305(key).decrypt(nonce, ciphertext, b"") # ---- sealing (§11.4) ----------------------------------------------------------------------------------------------- def seal(record: dict, env_id: str, sender: str, to: str, kid: str, pk: bytes, content_key: bytes = b"", nonce: bytes = b"", eph: bytes = b"") -> tuple: """Explicit recipients: a fresh 32-byte content key K and a 12-byte nonce per Envelope; body = base64url(nonce ‖ ChaCha20-Poly1305(K, nonce, JCS(Record), aad)) with aad = utf8(id) ‖ 0x00 ‖ utf8(from); K wrapped by HPKE.Seal(pk, info, K) with info = utf8(id) ‖ 0x00 ‖ utf8(from) ‖ 0x00 ‖ utf8(to). Returns the Envelope's `enc` and `body` (§5). The last three arguments exist only to reproduce a vector.""" content_key, nonce = content_key or os.urandom(32), nonce or os.urandom(12) aad = env_id.encode() + b"\x00" + sender.encode() body = b64u(nonce + ChaCha20Poly1305(content_key).encrypt(nonce, jcs(record), aad)) ek, ct = hpke_seal(pk, aad + b"\x00" + to.encode(), content_key, eph) return {"alg": ENC_ALG, "recipients": [{"to": to, "kid": kid, "ek": b64u(ek), "ct": b64u(ct)}]}, body def unseal(env: dict, me: str, enc_keys: dict) -> dict: """The receiving side: the wrap addressed to this Actor, opened with the `enc` key its `kid` names.""" assert env["enc"]["alg"] == ENC_ALG, "unsupported (§5)" wrap = next(w for w in env["enc"]["recipients"] if w["to"] == me) aad = env["id"].encode() + b"\x00" + env["from"].encode() content_key = hpke_open(enc_keys[wrap["kid"]], b64u_decode(wrap["ek"]), aad + b"\x00" + me.encode(), b64u_decode(wrap["ct"])) sealed = b64u_decode(env["body"]) return json.loads(ChaCha20Poly1305(content_key).decrypt(sealed[:12], sealed[12:], aad)) def enc_key_of(card: dict): """Among the recipient's `enc` keys the one with the latest `valid_from` that is unexpired; with one key nothing is compared. None when the Card lists no `enc` key this file can seal to: such a recipient gets plaintext or no message, by the sender's own policy.""" now = ts() keys = [k for k in card["body"]["keys"] if k["purpose"] == "enc" and k["alg"] == ENC_ALG and k.get("valid_until", "9999") > now] return max(keys, key=lambda k: k.get("valid_from", "")) if keys else None # ---- an agent with an `enc` key ------------------------------------------------------------------------------------ class SealedAgent(Agent): def __init__(self, base: str, name: str): super().__init__(base, name) self.card = None # this agent's own current Card self.enc = {} # kid -> (X25519 private key, valid_from) self.new_enc_key() def new_enc_key(self) -> None: """§11.5: a new `enc` key. The previous one is kept, so that what was sealed to it still opens.""" self.enc[f"enc-{len(self.enc) + 1}"] = (X25519PrivateKey.generate(), ts()) def register(self) -> dict: """The Card of §20.1 with the `enc` keys, the suite and the Profiles this agent has (§7, §11.2, §21). A later version keeps the Record's id, counts `v` up and names its predecessor by content digest (§4.1, §6.2). keys[] is sorted by kid (§6.2); several `enc` keys carry `valid_from` each, one alone needs none (§11.4).""" keys = [dict({"kid": kid, "purpose": "enc", "alg": ENC_ALG, "pub": b64u(raw(sk.public_key()))}, **({"valid_from": since} if len(self.enc) > 1 else {})) for kid, (sk, since) in sorted(self.enc.items())] keys.append({"kid": "sig-1", "purpose": "sig", "alg": "ed25519", "pub": b64u(self.pub)}) card = {"id": self.card["id"] if self.card else ulid(), "type": "agent_card", "v": self.card["v"] + 1 if self.card else 1, "issuer": self.id, "iat": ts(), "exp": ts(30 * 86400), "body": {"actor_type": "agent", "handles": [self.handle], "keys": keys, "endpoints": [{"kind": "relay", "gateway": self.gw, "url": self.base + "/v1"}], "supported": {"v": [1], "suites": ["ed25519", ENC_ALG], "content_types": ["application/aep.message+json"], "profiles": ["discovery.v1", "sealed.v1"]}, "policy": {"visibility": "direct", "contact": "open"}}} if self.card: card["body"]["prev"] = content_digest(self.card) self.card = sign_record(card, self.id, "sig-1", self.key) status, res = http("POST", f"{self.base}/v1/send", self.envelope(self.gw, self.card)) return {"status": status, **res} def send_sealed(self, to: str, text: str, enc_key: dict) -> dict: """§5, §11.4: the Record sealed to `enc_key`, an entry of the recipient's keys[]. The body is ciphertext, and the Envelope's signature covers that string as the string it is (§11.3).""" rec = self.text_record(text) env = {"v": 1, "id": ulid(), "from": self.id, "to": to, "iat": ts(), "exp": ts(3600)} env["enc"], env["body"] = seal(rec, env["id"], self.id, to, enc_key["kid"], b64u_decode(enc_key["pub"])) return dict(self.post(sign_envelope(env, "sig-1", self.key)), record=rec) def open(self, env: dict) -> dict: """What a receiver does with an Envelope (§11.3, §11.4): the Envelope's signature, decryption when `enc` is present, the Record's signatures, and the sender check: `from` is among the Record's signers.""" verify_envelope(env, self.pub_of) rec = unseal(env, self.id, {kid: sk for kid, (sk, _) in self.enc.items()}) if "enc" in env else env["body"] assert verify_record(rec, self.pub_of) and env["from"] in [s["actor"] for s in rec["sigs"]] return rec def run(base: str) -> None: tag = ulid()[-6:].lower() carol, dave = SealedAgent(base, f"sc-carol-{tag}"), SealedAgent(base, f"sc-dave-{tag}") for who in (carol, dave): res = who.register() check(f"a Card that lists an `enc` key registers (§7, §11.2): {who.handle}", len(res.get("accepted", [])) == 1 and not res.get("rejected"), json.dumps(res)[:300]) plain = Agent(base, f"sc-erin-{tag}") plain.register() check("a Card without an `enc` key gives a sender nothing to seal to (§11.4)", enc_key_of(carol.resolve_handle(plain.handle)) is None) key = enc_key_of(carol.resolve_handle(dave.handle)) check("the recipient's one `enc` key is the one to seal to; nothing is compared (§11.4)", key is not None and key["kid"] == "enc-1" and "valid_from" not in key) sent = carol.send_sealed(dave.id, "Thursday at seven?", key) env = sent["envelope"] check("a sealed Envelope is accepted: one wrap, for `to`, and a ciphertext string as body (§5)", sent.get("accepted") == [env["id"]] and isinstance(env["body"], str) and [w["to"] for w in env["enc"]["recipients"]] == [dave.id], json.dumps({k: v for k, v in sent.items() if k not in ("envelope", "record")})[:300]) entries = dave.sync()["envelopes"] inbound = entries[0]["envelope"] if entries else {} check("the mailbox returns the Envelope with the values it was sent with (§5)", jcs(inbound) == jcs(env)) dave.resolve(f"actors/{carol.id}") rec = attempt(lambda: dave.open(inbound)) check("the recipient opens the wrap with its `enc` key and the body with the content key; the Record verifies " "and its sender signed it (§11.3, §11.4)", isinstance(rec, dict) and jcs(rec) == jcs(sent["record"]), repr(rec)[:200]) moved = attempt(lambda: unseal(dict(inbound, id=ulid()), dave.id, {k: sk for k, (sk, _) in dave.enc.items()})) check("the same wrap and body under another Envelope id do not open: id and from are bound into both (§11.4)", isinstance(moved, Exception)) check("ack is answered ok (§10.1)", dave.ack(entries[0]["cursor"]).get("ok") is True) check_delivered(carol, env) time.sleep(1.1) # `valid_from` counts whole seconds, and the new key's has to be later dave.new_enc_key() res = dave.register() check("an encryption-key rotation is an ordinary Card version, `v`+1 over `prev`, signed by the same key (§11.5)", len(res.get("accepted", [])) == 1 and not res.get("rejected") and dave.card["v"] == 2, json.dumps(res)[:300]) late = carol.send_sealed(dave.id, "Sealed to the key I still hold", key) # carol has not resolved again new_key = enc_key_of(carol.resolve(f"actors/{dave.id}")) check("after resolving again the sender takes the key with the latest `valid_from` (§11.4)", carol.cards[dave.id]["v"] == 2 and new_key is not None and new_key["kid"] == "enc-2") fresh = carol.send_sealed(dave.id, "Sealed to the new key", new_key) entries = dave.sync(cursor=entries[0]["cursor"])["envelopes"] got = {e["envelope"]["id"]: attempt(lambda e=e: dave.open(e["envelope"])) for e in entries} text = lambda r: r["body"]["data"]["text"] if isinstance(r, dict) else repr(r)[:200] check("an Envelope sealed to the previous key still opens after the rotation: the recipient kept the key (§11.5)", text(got.get(late["envelope"]["id"])) == "Sealed to the key I still hold", text(got.get(late["envelope"]["id"]))) check("an Envelope sealed to the new key opens (§11.4)", text(got.get(fresh["envelope"]["id"])) == "Sealed to the new key", text(got.get(fresh["envelope"]["id"]))) bad = {"v": 1, "id": ulid(), "from": carol.id, "to": dave.id, "iat": ts(), "exp": ts(3600)} bad["enc"], bad["body"] = seal(sent["record"], bad["id"], carol.id, carol.id, "enc-1", raw(carol.enc["enc-1"][0].public_key())) status, rep = http("POST", f"{base}/v1/send", sign_envelope(bad, "sig-1", carol.key)) code = (rep.get("rejected") or [{}])[0].get("error", {}).get("code") check("an Envelope whose one wrap is for somebody other than `to` is rejected as invalid_request (§5)", code == "invalid_request", json.dumps(rep)[:200]) def run_with_reference(base: str) -> None: """Run only when this file started the Gateway itself, so that the reference package is at hand: the reference client is the other end, and each of the two opens what the other sealed. The code above uses none of it.""" from aep.client import Agent as Reference tag = ulid()[-6:].lower() mine, theirs = SealedAgent(base, f"sc-heidi-{tag}"), Reference(base, handle=f"ref-ivan-{tag}.agent") mine.register() theirs.register() theirs.resolve(mine.id) env = theirs.send_text(mine.id, "Sealed by the reference client") entries = mine.sync()["envelopes"] def read() -> str: mine.resolve(f"actors/{theirs.id}") return mine.open(entries[0]["envelope"])["body"]["data"]["text"] check("a message sealed by the reference client opens and verifies here (§11.4)", "enc" in env and attempt(read) == "Sealed by the reference client", repr(attempt(read))[:200]) sent = attempt(lambda: mine.send_sealed(theirs.id, "Sealed by the client written against the text", enc_key_of(mine.cards[theirs.id]))) texts = attempt(lambda: [rec["body"]["data"]["text"] for _, rec in theirs.sync(wait=2) if rec["type"] == "payload"]) check("and the reference client opens and verifies what this file sealed", texts == ["Sealed by the client written against the text"], repr(texts)[:200] + " " + repr(sent)[:200]) def run_vectors(vdir: str) -> None: """The sealed Envelope of the reference vectors: opened with the recipient's key, reproduced byte for byte from the fixed values, and its wrap opened once more by the HPKE of the `cryptography` library where it has one.""" load = lambda name: json.load(open(os.path.join(vdir, name), encoding="utf-8")) re_, cards = load("records_envelopes.json"), load("cards.json") pubs = {(c["issuer"], k["kid"]): b64u_decode(k["pub"]) for c in cards["alice_chain"] for k in c["body"]["keys"]} l1 = re_["envelope_l1"] wrap = l1["enc"]["recipients"][0] bob = next(a for a in load("keys.json")["actors"] if a["name"] == "bob") bob_key = X25519PrivateKey.from_private_bytes(bytes.fromhex(bob["enc_seed"])) aad = l1["id"].encode() + b"\x00" + l1["from"].encode() info = aad + b"\x00" + l1["to"].encode() check("an `enc` key in a Card is the raw X25519 public key, base64url (§11.4)", b64u(raw(bob_key.public_key())) == bob["enc_pub"]) check("the associated data of the body and the HPKE info of the wrap (§11.4)", aad.hex() == re_["l1_aad_hex"] and info.hex() == re_["l1_hpke_info_hex"]) opened = attempt(lambda: unseal(l1, l1["to"], {wrap["kid"]: bob_key})) check("the recipient's key opens the wrap and the content key opens the body (§11.4, RFC 9180)", isinstance(opened, dict), repr(opened)[:200]) check("what comes out is a Record its sender signed (§11.3)", isinstance(opened, dict) and attempt(lambda: verify_record(opened, lambda actor, kid: pubs[(actor, kid)])) is True and l1["from"] in [s["actor"] for s in opened["sigs"]]) again = attempt(lambda: seal(opened, l1["id"], l1["from"], l1["to"], wrap["kid"], b64u_decode(bob["enc_pub"]), bytes.fromhex(re_["l1_content_key_hex"]), bytes.fromhex(re_["l1_nonce_hex"]), bytes.fromhex(re_["l1_ephemeral_scalar_hex"]))) check("`enc` and `body` come out byte for byte from the fixed content key, nonce and ephemeral key (§11.4)", again == (l1["enc"], l1["body"]), repr(again)[:200]) try: from cryptography.hazmat.primitives import hpke as lib # a third implementation of RFC 9180, when present except ImportError: print(" (this version of `cryptography` has no HPKE of its own to compare with)") return suite = lib.Suite(lib.KEM.X25519, lib.KDF.HKDF_SHA256, lib.AEAD.CHACHA20_POLY1305) key = attempt(lambda: suite.decrypt(b64u_decode(wrap["ek"]) + b64u_decode(wrap["ct"]), bob_key, info=info)) check("the HPKE of the `cryptography` library opens the same wrap to the same content key", key == bytes.fromhex(re_["l1_content_key_hex"]), repr(key)[:120]) ek, ct = hpke_seal(raw(bob_key.public_key()), info, b"k" * 32) check("and it opens a wrap this file made", attempt(lambda: suite.decrypt(ek + ct, bob_key, info=info)) == b"k" * 32) if __name__ == "__main__": core.main(run, run_vectors, run_with_reference)