evidence_seal/sshsig.py

184 lines · 7216 bytes

  1"""SSH signatures (OpenSSH ``PROTOCOL.sshsig``) with Ed25519 keys.
  2
  3Signatures are interchangeable with ``ssh-keygen -Y sign`` / ``-Y verify``, so
  4keys held in an SSH agent or on a hardware token can produce them and anyone
  5with OpenSSH can check them. The namespace binds a signature to one purpose:
  6a signature made for one namespace never verifies under another.
  7
  8Requires the ``cryptography`` package (``evidence-seal[sign]``).
  9"""
 10
 11from __future__ import annotations
 12
 13import base64
 14import hashlib
 15import struct
 16from pathlib import Path
 17
 18MAGIC = b"SSHSIG"
 19VERSION = 1
 20KEY_TYPE = b"ssh-ed25519"
 21_ARMOR_BEGIN = "-----BEGIN SSH SIGNATURE-----"
 22_ARMOR_END = "-----END SSH SIGNATURE-----"
 23_HASHES = {b"sha512": hashlib.sha512, b"sha256": hashlib.sha256}
 24
 25
 26class SignatureError(ValueError):
 27    """The signature is malformed, made for another namespace, or does not verify."""
 28
 29
 30def _ed25519():
 31    try:
 32        from cryptography.hazmat.primitives.asymmetric import ed25519
 33    except ImportError as exc:  # pragma: no cover - exercised via a clear message
 34        raise RuntimeError(
 35            "SSH signatures require the 'cryptography' package — install evidence-seal[sign]"
 36        ) from exc
 37    return ed25519
 38
 39
 40def _string(data: bytes) -> bytes:
 41    return struct.pack(">I", len(data)) + data
 42
 43
 44def _read_string(buf: bytes, offset: int) -> tuple[bytes, int]:
 45    if offset + 4 > len(buf):
 46        raise SignatureError("truncated signature")
 47    (length,) = struct.unpack(">I", buf[offset : offset + 4])
 48    end = offset + 4 + length
 49    if end > len(buf):
 50        raise SignatureError("truncated signature")
 51    return buf[offset + 4 : end], end
 52
 53
 54def public_key_blob(raw_public: bytes) -> bytes:
 55    return _string(KEY_TYPE) + _string(raw_public)
 56
 57
 58def format_public_key(raw_public: bytes, comment: str = "") -> str:
 59    """OpenSSH public key line: ``ssh-ed25519 <base64> [comment]``."""
 60    line = f"ssh-ed25519 {base64.b64encode(public_key_blob(raw_public)).decode('ascii')}"
 61    return f"{line} {comment}".rstrip()
 62
 63
 64def parse_public_key(line: str) -> bytes:
 65    """Return the raw 32-byte Ed25519 key from an OpenSSH public key line."""
 66    parts = str(line or "").split()
 67    if len(parts) < 2 or parts[0] != KEY_TYPE.decode():
 68        raise SignatureError("expected an ssh-ed25519 public key")
 69    try:
 70        blob = base64.b64decode(parts[1], validate=True)
 71    except ValueError as exc:
 72        raise SignatureError("public key is not valid base64") from exc
 73    key_type, offset = _read_string(blob, 0)
 74    raw, offset = _read_string(blob, offset)
 75    if key_type != KEY_TYPE or len(raw) != 32 or offset != len(blob):
 76        raise SignatureError("malformed ssh-ed25519 public key")
 77    return raw
 78
 79
 80def fingerprint(raw_public: bytes) -> str:
 81    """OpenSSH SHA256 fingerprint, as printed by ``ssh-keygen -lf``."""
 82    digest = hashlib.sha256(public_key_blob(raw_public)).digest()
 83    return "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("=")
 84
 85
 86def _signed_data(namespace: str, message: bytes, hash_name: bytes = b"sha512") -> bytes:
 87    return (
 88        MAGIC
 89        + _string(namespace.encode("utf-8"))
 90        + _string(b"")
 91        + _string(hash_name)
 92        + _string(_HASHES[hash_name](message).digest())
 93    )
 94
 95
 96def load_private_key(path: str | Path, passphrase: bytes | None = None):
 97    """Load an Ed25519 private key from PEM (PKCS#8, optionally encrypted) or OpenSSH format."""
 98    ed25519 = _ed25519()
 99    from cryptography.hazmat.primitives import serialization
100
101    data = Path(path).read_bytes()
102    if b"OPENSSH PRIVATE KEY" in data:
103        key = serialization.load_ssh_private_key(data, password=passphrase)
104    else:
105        key = serialization.load_pem_private_key(data, password=passphrase)
106    if not isinstance(key, ed25519.Ed25519PrivateKey):
107        raise SignatureError("only Ed25519 keys are supported")
108    return key
109
110
111def raw_public_key(private_key) -> bytes:
112    from cryptography.hazmat.primitives import serialization
113
114    return private_key.public_key().public_bytes(
115        encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw
116    )
117
118
119def sign(message: bytes, private_key, namespace: str) -> str:
120    """Return an armored SSH signature of *message* under *namespace*."""
121    _ed25519()
122    signature = private_key.sign(_signed_data(namespace, message))
123    blob = (
124        MAGIC
125        + struct.pack(">I", VERSION)
126        + _string(public_key_blob(raw_public_key(private_key)))
127        + _string(namespace.encode("utf-8"))
128        + _string(b"")
129        + _string(b"sha512")
130        + _string(_string(KEY_TYPE) + _string(signature))
131    )
132    encoded = base64.b64encode(blob).decode("ascii")
133    lines = [encoded[i : i + 70] for i in range(0, len(encoded), 70)]
134    return "\n".join([_ARMOR_BEGIN, *lines, _ARMOR_END]) + "\n"
135
136
137def verify(message: bytes, armored: str, namespace: str) -> bytes:
138    """Verify an armored SSH signature; return the signer's raw public key.
139
140    Raises :class:`SignatureError` if the signature is malformed, was made for
141    another namespace, or does not match *message*. Checking that the signer is
142    someone you trust is the caller's job.
143    """
144    ed25519 = _ed25519()
145    text = str(armored or "").strip()
146    if not (text.startswith(_ARMOR_BEGIN) and text.endswith(_ARMOR_END)):
147        raise SignatureError("not an armored SSH signature")
148    body = "".join(text[len(_ARMOR_BEGIN) : -len(_ARMOR_END)].split())
149    try:
150        blob = base64.b64decode(body, validate=True)
151    except ValueError as exc:
152        raise SignatureError("signature is not valid base64") from exc
153    if not blob.startswith(MAGIC) or len(blob) < len(MAGIC) + 4:
154        raise SignatureError("not an SSHSIG signature")
155    (version,) = struct.unpack(">I", blob[len(MAGIC) : len(MAGIC) + 4])
156    if version != VERSION:
157        raise SignatureError(f"unsupported SSHSIG version {version}")
158    offset = len(MAGIC) + 4
159    key_blob, offset = _read_string(blob, offset)
160    sig_namespace, offset = _read_string(blob, offset)
161    _reserved, offset = _read_string(blob, offset)
162    hash_name, offset = _read_string(blob, offset)
163    sig_blob, offset = _read_string(blob, offset)
164    if offset != len(blob):
165        raise SignatureError("trailing data after signature")
166    if sig_namespace.decode("utf-8", "replace") != namespace:
167        raise SignatureError(
168            f"signature namespace {sig_namespace.decode('utf-8', 'replace')!r} is not {namespace!r}"
169        )
170    if hash_name not in _HASHES:
171        raise SignatureError(f"unsupported hash {hash_name!r}")
172    key_type, k_off = _read_string(key_blob, 0)
173    raw_public, k_off = _read_string(key_blob, k_off)
174    sig_type, s_off = _read_string(sig_blob, 0)
175    raw_sig, s_off = _read_string(sig_blob, s_off)
176    if key_type != KEY_TYPE or sig_type != KEY_TYPE or len(raw_public) != 32:
177        raise SignatureError("only ssh-ed25519 signatures are supported")
178    try:
179        ed25519.Ed25519PublicKey.from_public_bytes(raw_public).verify(
180            raw_sig, _signed_data(namespace, message, hash_name)
181        )
182    except Exception as exc:
183        raise SignatureError("signature does not match the signed data") from exc
184    return raw_public