Import ECS deployed relay source and historical patches (2026-10-27)
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""Signed ephemeral X25519 envelopes. The router never receives plaintext keys."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
|
||||
|
||||
|
||||
def b64(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).decode()
|
||||
|
||||
|
||||
def unb64(data: str) -> bytes:
|
||||
return base64.b64decode(data.encode(), altchars=b"-_", validate=True)
|
||||
|
||||
|
||||
def canonical(data: dict) -> bytes:
|
||||
return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
|
||||
|
||||
|
||||
def raw_public(key) -> str:
|
||||
return b64(key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw))
|
||||
|
||||
|
||||
def pem_private(key) -> bytes:
|
||||
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption())
|
||||
|
||||
|
||||
def load_private(path):
|
||||
return serialization.load_pem_private_key(path.read_bytes(), password=None)
|
||||
|
||||
|
||||
def load_public(path):
|
||||
return serialization.load_pem_public_key(path.read_bytes())
|
||||
|
||||
|
||||
def fingerprint(pem: str) -> str:
|
||||
return x509.load_pem_x509_certificate(pem.encode()).fingerprint(hashes.SHA256()).hex()
|
||||
|
||||
|
||||
def verify_device(pem: str, ca_pem: bytes, host_id: str):
|
||||
"""v1 deliberately accepts only directly issued Ed25519 device certificates."""
|
||||
cert = x509.load_pem_x509_certificate(pem.encode())
|
||||
ca = x509.load_pem_x509_certificate(ca_pem)
|
||||
now = datetime.now(timezone.utc)
|
||||
if not (ca.not_valid_before_utc <= now <= ca.not_valid_after_utc):
|
||||
raise ValueError("expired CA")
|
||||
if not ca.extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
|
||||
raise ValueError("not a CA")
|
||||
cert.verify_directly_issued_by(ca)
|
||||
if not (cert.not_valid_before_utc <= now <= cert.not_valid_after_utc):
|
||||
raise ValueError("expired certificate")
|
||||
if cert.extensions.get_extension_for_class(x509.BasicConstraints).value.ca:
|
||||
raise ValueError("CA cannot be used as device")
|
||||
if ExtendedKeyUsageOID.CLIENT_AUTH not in cert.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value:
|
||||
raise ValueError("clientAuth missing")
|
||||
names = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
|
||||
if names.get_values_for_type(x509.UniformResourceIdentifier) != [f"urn:hainuo:host:{host_id}"]:
|
||||
raise ValueError("host identity mismatch")
|
||||
public = cert.public_key()
|
||||
if not isinstance(public, ed25519.Ed25519PublicKey):
|
||||
raise ValueError("v1 requires Ed25519 device key")
|
||||
return public
|
||||
|
||||
|
||||
def sign(data: dict, key) -> dict:
|
||||
return {**data, "signature": b64(key.sign(canonical(data)))}
|
||||
|
||||
|
||||
def verified(data: dict, key) -> dict:
|
||||
body = {k: v for k, v in data.items() if k != "signature"}
|
||||
key.verify(unb64(data["signature"]), canonical(body))
|
||||
return body
|
||||
|
||||
|
||||
def seal(payload: dict, recipient_public: str, signer, *, host_id: str, session_id: str) -> dict:
|
||||
ephemeral = x25519.X25519PrivateKey.generate()
|
||||
header = {"v": 1, "host_id": host_id, "session_id": session_id,
|
||||
"ts": int(time.time()), "nonce": b64(secrets.token_bytes(12)),
|
||||
"ephemeral": raw_public(ephemeral.public_key())}
|
||||
shared = ephemeral.exchange(x25519.X25519PublicKey.from_public_bytes(unb64(recipient_public)))
|
||||
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=session_id.encode(),
|
||||
info=b"hainuo-relay-envelope-v1").derive(shared)
|
||||
cipher = AESGCM(key).encrypt(unb64(header["nonce"]), canonical(payload), canonical(header))
|
||||
return sign({**header, "ciphertext": b64(cipher)}, signer)
|
||||
|
||||
|
||||
def open_envelope(envelope: dict, recipient_private, sender_public, *, host_id: str, session_id: str) -> dict:
|
||||
body = verified(envelope, sender_public)
|
||||
if body["v"] != 1 or body["host_id"] != host_id or body["session_id"] != session_id:
|
||||
raise ValueError("wrong destination/session")
|
||||
if abs(time.time() - body["ts"]) > 90:
|
||||
raise ValueError("expired envelope")
|
||||
header = {k: v for k, v in body.items() if k != "ciphertext"}
|
||||
shared = recipient_private.exchange(x25519.X25519PublicKey.from_public_bytes(unb64(body["ephemeral"])))
|
||||
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=session_id.encode(),
|
||||
info=b"hainuo-relay-envelope-v1").derive(shared)
|
||||
plain = AESGCM(key).decrypt(unb64(body["nonce"]), unb64(body["ciphertext"]), canonical(header))
|
||||
return json.loads(plain)
|
||||
|
||||
|
||||
def issue_ca():
|
||||
key = ed25519.Ed25519PrivateKey.generate()
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Hainuo device test CA")])
|
||||
now = datetime.now(timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=3650))
|
||||
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
|
||||
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), critical=True)
|
||||
.sign(key, algorithm=None))
|
||||
return key, cert
|
||||
|
||||
|
||||
def issue_device(ca_key, ca_cert, host_id: str, public_key, days=30):
|
||||
now = datetime.now(timezone.utc)
|
||||
return (x509.CertificateBuilder()
|
||||
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, host_id)]))
|
||||
.issuer_name(ca_cert.subject).public_key(public_key)
|
||||
.serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=days))
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
|
||||
.add_extension(x509.SubjectAlternativeName([x509.UniformResourceIdentifier(f"urn:hainuo:host:{host_id}")]), critical=False)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
|
||||
.sign(ca_key, algorithm=None))
|
||||
Reference in New Issue
Block a user