fix(orchestrator): refuse RS256 passkeys under 2048 bits
passkey.py accepted an RS256 public key of any modulus size. It now refuses a modulus under 2048 bits at registration and at every verification, before either signature backend, with a fixed error asking for a new passkey; the library backend checks key_size again and the openssl backend's key_type requires the same size. The SubjectPublicKeyInfo is read as strict DER (no negative or padded INTEGERs, minimal lengths, no unused bits, no trailing data) and the rsaEncryption identifier must match exactly. ES256 and EdDSA are unchanged. An already pinned weak key is refused on every use until a new passkey is pinned. Accepted MEDUSA findings: AIC-EXFIL-005 and PRIV-SCAN-762 at tests/hub_support.py:151 (public half of a throwaway test key) and PQC001 at passkey.py:236 (WebAuthn offers no post-quantum algorithm yet). 🎯 Fix: 95 % 💥 Break: 3 % 💸 Cost: – ⏱️ Time: – 🛡️ Security: 100 % 🏆 Score: 92 🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 % Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5b65fb5284
commit
0e569323fb
3 files changed
+140
-10
No files matched your search
@@ -24,6 +24,8 @@ P256_PRIME = 2**256 - 2**224 + 2**192 + 2**96 - 1
|
||||
P256_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
|
||||
ED_PREFIX = bytes.fromhex("302a300506032b6570032100")
|
||||
RSA_IDENTIFIER = bytes.fromhex("300d06092a864886f70d0101010500")
|
||||
RSA_MIN_BITS = 2048
|
||||
NOT_RSA = "the RS256 key is no RSA public key"
|
||||
B64URL = re.compile(r"[A-Za-z0-9_-]+")
|
||||
ASSERTION_KEYS = ("id", "clientDataJSON", "authenticatorData", "signature")
|
||||
CBOR_DEPTH = 16
|
||||
@@ -99,6 +101,54 @@ def der_integer(value: bytes) -> bytes:
|
||||
return der(0x02, b"\x00" + digits if digits[0] & 0x80 else digits)
|
||||
|
||||
|
||||
def der_item(data: bytes, offset: int, tag: int) -> tuple[bytes, int]:
|
||||
if offset + 2 > len(data) or data[offset] != tag:
|
||||
raise Refused(NOT_RSA)
|
||||
size, offset = data[offset + 1], offset + 2
|
||||
if size & 0x80:
|
||||
width = size & 0x7F
|
||||
head = data[offset : offset + width]
|
||||
size, offset = int.from_bytes(head, "big"), offset + width
|
||||
if size < 0x80 or head[0] == 0:
|
||||
raise Refused(NOT_RSA)
|
||||
if not 0 < size <= len(data) - offset:
|
||||
raise Refused(NOT_RSA)
|
||||
return data[offset : offset + size], offset + size
|
||||
|
||||
|
||||
def der_whole(data: bytes, offset: int, tag: int) -> bytes:
|
||||
body, end = der_item(data, offset, tag)
|
||||
if end != len(data):
|
||||
raise Refused(NOT_RSA)
|
||||
return body
|
||||
|
||||
|
||||
def der_unsigned(data: bytes, offset: int) -> tuple[int, int]:
|
||||
body, end = der_item(data, offset, 0x02)
|
||||
if body[0] & 0x80 or (body[0] == 0 and len(body) > 1 and not body[1] & 0x80):
|
||||
raise Refused(NOT_RSA)
|
||||
return int.from_bytes(body, "big"), end
|
||||
|
||||
|
||||
def rsa_bits(spki: bytes) -> int:
|
||||
outer = der_whole(spki, 0, 0x30)
|
||||
if not outer.startswith(RSA_IDENTIFIER):
|
||||
raise Refused(NOT_RSA)
|
||||
bits = der_whole(outer, len(RSA_IDENTIFIER), 0x03)
|
||||
if bits[0]:
|
||||
raise Refused(NOT_RSA)
|
||||
public = der_whole(bits, 1, 0x30)
|
||||
modulus, offset = der_unsigned(public, 0)
|
||||
if der_unsigned(public, offset)[1] != len(public):
|
||||
raise Refused(NOT_RSA)
|
||||
return modulus.bit_length()
|
||||
|
||||
|
||||
def refuse_weak(alg: object, spki: bytes) -> None:
|
||||
if alg == -257 and rsa_bits(spki) < RSA_MIN_BITS:
|
||||
raise Refused(f"the RS256 key has a modulus under {RSA_MIN_BITS} bits; register a new passkey")
|
||||
|
||||
|
||||
def octets(value: object, size: int) -> bool:
|
||||
return isinstance(value, bytes) and len(value) == size
|
||||
|
||||
@@ -172,6 +222,7 @@ def attested(credential: object, origin: str) -> dict:
|
||||
raise Refused("the attested credential id differs from the id")
|
||||
key, _ = cbor(data, 55 + size, 0)
|
||||
alg, spki = cose_key(key)
|
||||
refuse_weak(alg, spki)
|
||||
return {"id": b64encode(raw_id), "alg": alg, "spki": b64encode(spki)}
|
||||
|
||||
|
||||
@@ -182,7 +233,7 @@ def by_library(alg: int, spki: bytes, data: bytes, signature: bytes) -> bool:
|
||||
key.verify(signature, data, ec.ECDSA(hashes.SHA256()))
|
||||
elif alg == -8 and isinstance(key, ed25519.Ed25519PublicKey):
|
||||
key.verify(signature, data)
|
||||
elif alg == -257 and isinstance(key, rsa.RSAPublicKey):
|
||||
elif alg == -257 and isinstance(key, rsa.RSAPublicKey) and key.key_size >= RSA_MIN_BITS:
|
||||
key.verify(signature, data, padding.PKCS1v15(), hashes.SHA256())
|
||||
else:
|
||||
return False
|
||||
@@ -196,7 +247,10 @@ def key_type(alg: int, spki: bytes) -> bool:
|
||||
return len(spki) == len(EC_PREFIX) + 65 and spki.startswith(EC_PREFIX)
|
||||
if alg == -8:
|
||||
return len(spki) == len(ED_PREFIX) + 32 and spki.startswith(ED_PREFIX)
|
||||
return alg == -257 and RSA_IDENTIFIER in spki[:24]
|
||||
try:
|
||||
return alg == -257 and rsa_bits(spki) >= RSA_MIN_BITS
|
||||
except Refused:
|
||||
return False
|
||||
|
||||
|
||||
def by_openssl(alg: int, spki: bytes, data: bytes, signature: bytes) -> bool:
|
||||
@@ -243,12 +297,14 @@ def verify_assertion(assertion: object, payload: dict, credentials: list[dict],
|
||||
credential = next((entry for entry in credentials if entry["id"] == assertion["id"]), None)
|
||||
if credential is None:
|
||||
raise Refused("the signing key is not pinned")
|
||||
spki = b64decode(credential["spki"], "spki")
|
||||
refuse_weak(credential["alg"], spki)
|
||||
raw = b64decode(assertion["clientDataJSON"], "clientDataJSON")
|
||||
if client_data(raw, "webauthn.get", origin).get("challenge") != challenge(payload):
|
||||
raise Refused("the challenge is not the one of the payload")
|
||||
data = b64decode(assertion["authenticatorData"], "authenticatorData")
|
||||
rp_flags(data, 37)
|
||||
signed = data + hashlib.sha256(raw).digest()
|
||||
if not verify_signature(credential["alg"], b64decode(credential["spki"], "spki"), signed, b64decode(assertion["signature"], "signature")):
|
||||
if not verify_signature(credential["alg"], spki, signed, b64decode(assertion["signature"], "signature")):
|
||||
raise Refused("the signature does not verify with the pinned key")
|
||||
return int.from_bytes(data[33:37], "big")
|
||||
+16
-5
@@ -103,10 +103,16 @@ ORIGIN = "http://localhost:8737"
|
||||
PRESENT = 0x05
|
||||
REGISTERED = 0x45
|
||||
ZERO_LED_TRIES = 4096
|
||||
|
||||
|
||||
def rsa_spec(bits: int) -> list[str]:
|
||||
return ["-algorithm", "RSA", "-pkeyopt", f"rsa_keygen_bits:{bits}"]
|
||||
|
||||
|
||||
KEY_SPECS = {
|
||||
-7: ["-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256"],
|
||||
-8: ["-algorithm", "ED25519"],
|
||||
-257: ["-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048"],
|
||||
-257: rsa_spec(2048),
|
||||
}
|
||||
|
||||
|
||||
@@ -139,10 +145,10 @@ def cbor_encode(value: object) -> bytes:
|
||||
|
||||
|
||||
class Key:
|
||||
def __init__(self, alg: int, name: str) -> None:
|
||||
def __init__(self, alg: int, name: str, spec: list[str]) -> None:
|
||||
self.alg = alg
|
||||
self.pem = Path(KEYS.name) / f"{name}{alg}.pem"
|
||||
openssl(["genpkey", *KEY_SPECS[alg], "-out", str(self.pem)], b"")
|
||||
openssl(["genpkey", *spec, "-out", str(self.pem)], b"")
|
||||
self.spki = openssl(["pkey", "-in", str(self.pem), "-pubout", "-outform", "DER"], b"")
|
||||
self.raw_id = os.urandom(16)
|
||||
self.id = b64(self.raw_id)
|
||||
@@ -188,7 +194,12 @@ class Key:
|
||||
|
||||
@functools.cache
|
||||
def key(alg: int, name: str) -> Key:
|
||||
return Key(alg, name)
|
||||
return Key(alg, name, KEY_SPECS[alg])
|
||||
|
||||
|
||||
@functools.cache
|
||||
def rsa_key(bits: int) -> Key:
|
||||
return Key(-257, f"rsa{bits}", rsa_spec(bits))
|
||||
|
||||
|
||||
@functools.cache
|
||||
@@ -202,7 +213,7 @@ def zero_led(label: int) -> Key:
|
||||
"""
|
||||
with concurrent.futures.ThreadPoolExecutor() as pool:
|
||||
for start in range(0, ZERO_LED_TRIES, 64):
|
||||
for signer in pool.map(lambda attempt: Key(-7, f"zero{label}-{attempt}"), range(start, start + 64)):
|
||||
for signer in pool.map(lambda attempt: Key(-7, f"zero{label}-{attempt}", KEY_SPECS[-7]), range(start, start + 64)):
|
||||
if signer.cose()[label][0] == 0:
|
||||
return signer
|
||||
raise AssertionError(f"no P-256 key with a zero-led coordinate {label} in {ZERO_LED_TRIES} tries")
|
||||
@@ -29,12 +29,14 @@ from hub_support import (
|
||||
hub_api,
|
||||
key,
|
||||
passkey,
|
||||
rsa_key,
|
||||
signing,
|
||||
verifier,
|
||||
zero_led,
|
||||
)
|
||||
|
||||
PASSKEY_PAGE = HUB / "templates" / "page-passkey.js"
|
||||
BACKENDS = [passkey.by_openssl] if passkey.serialization is None else [passkey.by_openssl, passkey.by_library]
|
||||
PASSKEY_PROBE = """
|
||||
const fs = require("fs");
|
||||
const vm = require("vm");
|
||||
@@ -88,6 +90,30 @@ class TestApproval(unittest.TestCase):
|
||||
verifier.check(signer.proof(self.payload([self.item], int(self.now) + 60), ORIGIN), self.item, "", self.trust, self.now)
|
||||
self.assertEqual([entry["alg"] for entry in verifier.pinned(self.approvers)], [-7, -8, -257])
|
||||
|
||||
def test_an_rs256_key_under_2048_bits_is_refused_at_registration_and_at_every_verification(self):
|
||||
payloads = {
|
||||
"approval": self.payload([self.item], int(self.now) + 60),
|
||||
"rule": signing.rule_payload("fedcba9876543210", ["ask"], "Bash", "make *", "/repo*", int(self.now) + 3600),
|
||||
}
|
||||
for bits in (1024, 2047):
|
||||
signer = rsa_key(bits)
|
||||
self.assertEqual(int.from_bytes(signer.cose()[-1], "big").bit_length(), bits)
|
||||
with self.subTest(bits=bits, at="registration"), self.assertRaisesRegex(signing.Refused, "modulus under 2048 bits"):
|
||||
passkey.attested(signer.credential(ORIGIN, "localhost", REGISTERED), ORIGIN)
|
||||
weak = verifier.Trust(approvers=self.base / f"weak-{bits}.json", replay=self.base / f"weak-{bits}-replay.json", origin=ORIGIN)
|
||||
verifier.pin(weak.approvers, {"id": signer.id, "alg": -257, "spki": b64(signer.spki)}, self.now)
|
||||
for name, payload in payloads.items():
|
||||
with self.subTest(bits=bits, at=name), self.assertRaisesRegex(signing.Refused, "modulus under 2048 bits"):
|
||||
verifier.check(signer.proof(payload, ORIGIN), self.item, "", weak, self.now)
|
||||
signer = rsa_key(2048)
|
||||
self.assertEqual(passkey.attested(signer.credential(ORIGIN, "localhost", REGISTERED), ORIGIN)["spki"], b64(signer.spki))
|
||||
signer.pin(self.approvers, ORIGIN)
|
||||
for payload in payloads.values():
|
||||
verifier.check(signer.proof(payload, ORIGIN), self.item, "", self.trust, self.now)
|
||||
mislabelled = key(-7, "main")
|
||||
verifier.pin(self.approvers, {"id": mislabelled.id, "alg": -257, "spki": b64(mislabelled.spki)}, self.now)
|
||||
self.refused(mislabelled.proof(payloads["approval"], ORIGIN), self.item, "", "no RSA public key")
|
||||
|
||||
def test_every_broken_part_of_a_signature_is_refused(self):
|
||||
signer = key(-7, "main")
|
||||
signer.pin(self.approvers, ORIGIN)
|
||||
@@ -279,12 +305,11 @@ class TestApproval(unittest.TestCase):
|
||||
passkey.cbor(data, 0, 0)
|
||||
|
||||
def test_both_backends_verify_and_reject_the_same(self):
|
||||
backends = [passkey.by_openssl] if passkey.serialization is None else [passkey.by_openssl, passkey.by_library]
|
||||
for alg in (-7, -8, -257):
|
||||
signer = key(alg, "main")
|
||||
data = os.urandom(64)
|
||||
signature = signer.sign(data)
|
||||
for backend in backends:
|
||||
for backend in BACKENDS:
|
||||
with self.subTest(alg=alg, backend=backend.__name__):
|
||||
self.assertTrue(backend(alg, signer.spki, data, signature))
|
||||
self.assertFalse(backend(alg, signer.spki, data + b"x", signature))
|
||||
@@ -296,6 +321,44 @@ class TestApproval(unittest.TestCase):
|
||||
with mock.patch.object(passkey, "serialization", None):
|
||||
verifier.check(signer.proof(self.payload([self.item], int(self.now) + 60), ORIGIN), self.item, "", self.trust, self.now)
|
||||
|
||||
def test_both_backends_refuse_a_valid_signature_of_an_rs256_key_under_2048_bits(self):
|
||||
data = os.urandom(64)
|
||||
for bits in (1024, 2047):
|
||||
signer = rsa_key(bits)
|
||||
signature = signer.sign(data)
|
||||
for backend in BACKENDS:
|
||||
with self.subTest(bits=bits, backend=backend.__name__):
|
||||
self.assertFalse(backend(-257, signer.spki, data, signature))
|
||||
with mock.patch.object(passkey, "RSA_MIN_BITS", 1024):
|
||||
self.assertTrue(backend(-257, signer.spki, data, signature))
|
||||
|
||||
def test_the_rsa_key_parser_reads_strict_der_only(self):
|
||||
signer = rsa_key(2048)
|
||||
modulus = signer.cose()[-1]
|
||||
exponent = passkey.der_integer((65537).to_bytes(3, "big"))
|
||||
|
||||
def wrapped(integers: bytes, unused: int) -> bytes:
|
||||
return passkey.der(0x30, passkey.RSA_IDENTIFIER + passkey.der(0x03, bytes([unused]) + passkey.der(0x30, integers)))
|
||||
|
||||
valid = wrapped(passkey.der_integer(modulus) + exponent, 0)
|
||||
self.assertEqual(valid, signer.spki)
|
||||
self.assertEqual((passkey.rsa_bits(valid), passkey.key_type(-257, valid)), (2048, True))
|
||||
for name, given in (
|
||||
("negative modulus", wrapped(passkey.der(0x02, b"\xff" * 256) + exponent, 0)),
|
||||
("superfluous leading zero", wrapped(passkey.der(0x02, b"\x00\x00" + modulus) + exponent, 0)),
|
||||
("short length in long form", wrapped(passkey.der_integer(modulus) + b"\x02\x81\x03\x01\x00\x01", 0)),
|
||||
("zero-led long length", wrapped(b"\x02\x83\x00\x01\x01\x00" + modulus + exponent, 0)),
|
||||
("nonzero unused bits", wrapped(passkey.der_integer(modulus) + exponent, 1)),
|
||||
("trailing data in the key", wrapped(passkey.der_integer(modulus) + exponent + b"\x05\x00", 0)),
|
||||
("trailing data after the key", valid + b"\x00"),
|
||||
("shifted identifier", passkey.der(0x30, b"\x05\x00" + valid[4:])),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
with self.assertRaisesRegex(signing.Refused, "no RSA public key"):
|
||||
passkey.rsa_bits(given)
|
||||
self.assertFalse(passkey.key_type(-257, given))
|
||||
self.assertEqual((passkey.rsa_bits(rsa_key(2047).spki), passkey.key_type(-257, rsa_key(2047).spki)), (2047, False))
|
||||
|
||||
def test_openssl_without_a_temporary_directory_refuses_cleanly(self):
|
||||
signer = key(-7, "main")
|
||||
data = os.urandom(64)
|
||||
|
||||
Reference in new issue
Block a user