From c5180af8c7e2958dcf56e86de7adfda3866f4172 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 07:29:04 +0200 Subject: [PATCH 1/6] fix(enrollment): require the CSR to be signed by its own key --- src/rasenmaeher_api/web/api/utils/csr_utils.py | 3 +++ tests/cert/helpers.py | 7 +++++++ tests/test_csr_utils.py | 9 ++++++++- tests/test_enrollment.py | 17 +++++++++++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/rasenmaeher_api/web/api/utils/csr_utils.py b/src/rasenmaeher_api/web/api/utils/csr_utils.py index d9bdea30..f75f3b7d 100644 --- a/src/rasenmaeher_api/web/api/utils/csr_utils.py +++ b/src/rasenmaeher_api/web/api/utils/csr_utils.py @@ -19,6 +19,9 @@ def verify_csr(csrpem: str, callsign: str) -> bool: csr = x509.load_pem_x509_csr(ensure_utf8(csrpem)) dn = csr.subject.rfc4514_string() LOGGER.debug(f"DN={dn} callsign={callsign}") + if not csr.is_signature_valid: + LOGGER.warning(f"CSR signature does not verify with its own key. DN={dn} callsign={callsign}") + return False cns = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME) if len(csr.subject) != 1 or len(cns) != 1 or cns[0].value != callsign: LOGGER.warning(f"Callsign does not match CSR subject. DN={dn} callsign={callsign}") diff --git a/tests/cert/helpers.py b/tests/cert/helpers.py index f3b14d0c..43cf88cc 100644 --- a/tests/cert/helpers.py +++ b/tests/cert/helpers.py @@ -100,6 +100,13 @@ def make_key_usage(**flags: bool) -> cryptography.x509.KeyUsage: return cryptography.x509.KeyUsage(**{**off, **flags}) +def invalidate_signature(csr_pem: str) -> str: + """The same CSR with one bit of its signature flipped, so it no longer verifies""" + der = cryptography.x509.load_pem_x509_csr(csr_pem.encode("utf-8")).public_bytes(serialization.Encoding.DER) + altered = der[:-1] + bytes([der[-1] ^ 0x01]) + return cryptography.x509.load_der_x509_csr(altered).public_bytes(serialization.Encoding.PEM).decode("utf-8") + + def make_csr( common_name: str | None = "test leaf", key_usage: cryptography.x509.KeyUsage | None = None, diff --git a/tests/test_csr_utils.py b/tests/test_csr_utils.py index 9441c1c5..9fa87db9 100644 --- a/tests/test_csr_utils.py +++ b/tests/test_csr_utils.py @@ -7,7 +7,7 @@ from libpvarki.mtlshelp.csr import async_create_client_csr, async_create_keypair, async_create_server_csr from rasenmaeher_api.web.api.utils.csr_utils import verify_csr -from tests.cert.helpers import CsrFactory +from tests.cert.helpers import CsrFactory, invalidate_signature @pytest.mark.asyncio @@ -43,3 +43,10 @@ def test_verify_csr_rejects_unknown_ext_key_usage(mint_csr: CsrFactory) -> None: "csr_test", ext_key_usage=[ExtendedKeyUsageOID.CLIENT_AUTH, ExtendedKeyUsageOID.ANY_EXTENDED_KEY_USAGE] ) assert verify_csr(csrpem, "csr_test") is False + + +def test_verify_csr_requires_valid_signature(mint_csr: CsrFactory) -> None: + """A CSR must be signed by the key it carries""" + csrpem = mint_csr("csr_test") + assert verify_csr(csrpem, "csr_test") is True + assert verify_csr(invalidate_signature(csrpem), "csr_test") is False diff --git a/tests/test_enrollment.py b/tests/test_enrollment.py index f171a2c9..7cb1fe80 100644 --- a/tests/test_enrollment.py +++ b/tests/test_enrollment.py @@ -18,6 +18,7 @@ Person, ) from rasenmaeher_api.rmsettings import RMSettings +from tests.cert.helpers import CsrFactory, invalidate_signature LOGGER = logging.getLogger(__name__) @@ -715,6 +716,22 @@ async def test_enroll_with_csr( # TODO: check extensions +@pytest.mark.asyncio(loop_scope="session") +async def test_enroll_requires_csr_signed_by_its_key( + tilauspalvelu_jwt_admin_client: TestClient, unauth_client_session: TestClient, mint_csr: CsrFactory +) -> None: + """Enrolment refuses a CSR whose signature does not verify with its own key""" + resp = await tilauspalvelu_jwt_admin_client.post("/api/v1/enrollment/invitecode/create") + assert resp.status_code == 200 + callsign = f"csr_signature_{secrets.token_hex(4)}" + csrpem = invalidate_signature(mint_csr(callsign)) + json_dict = {"invite_code": resp.json()["invite_code"], "callsign": callsign, "csr": csrpem} + unauth_client_session.headers.clear() + resp = await unauth_client_session.post("/api/v1/enrollment/invitecode/enroll", json=json_dict) + assert resp.status_code == 400 + assert resp.json()["detail"] == "CSR subject or key usages not allowed for callsign" + + @pytest.mark.asyncio(loop_scope="session") async def test_enrollmentpools_revoked_creator(dbinit_func, tilauspalvelu_jwt_admin_client: TestClient) -> None: """Test that pools list does not die if creator is revoked""" From 70ab8acd84343aba4949afc4ddc794197d3bb1b5 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 07:29:04 +0200 Subject: [PATCH 2/6] fix(product): allow renew_csr only for a product's own name and usages, audit the outcome --- src/rasenmaeher_api/web/api/product/views.py | 76 ++++++- tests/test_product_renew.py | 209 +++++++++++++++++++ 2 files changed, 275 insertions(+), 10 deletions(-) create mode 100644 tests/test_product_renew.py diff --git a/src/rasenmaeher_api/web/api/product/views.py b/src/rasenmaeher_api/web/api/product/views.py index 882ea923..f2852662 100644 --- a/src/rasenmaeher_api/web/api/product/views.py +++ b/src/rasenmaeher_api/web/api/product/views.py @@ -5,9 +5,9 @@ import aiohttp from cryptography import x509 -from cryptography.x509.oid import NameOID +from cryptography.x509.oid import ExtensionOID, NameOID from fastapi import APIRouter, Depends, HTTPException, Request, Response -from libadvian.binpackers import ensure_str, ensure_utf8 +from libadvian.binpackers import ensure_utf8 from libpvarki.middleware.mtlsheader import MTLSHeader from libpvarki.schemas.generic import OperationResultResponse from libpvarki.schemas.product import ReadyRequest, UserCRUDRequest @@ -16,6 +16,7 @@ from rasenmaeher_api.db.issuedcerts import record_issued_cert from ....cert.backend import CertError, get_bundle, get_ca, revoke_pem, sign_csr +from ....cert.usages import KeyUsages, csr_usages from ....db import Person from ....db.errors import NotFound from ....db.nonces import SeenToken @@ -24,11 +25,26 @@ from ....productapihelpers import post_to_product from ....rmsettings import RMSettings from ..middleware.user import ValidUser +from ..utils.auditcontext import build_audit_extra from .schema import CertificatesRequest, CertificatesResponse, KCClientToken, ProductAddRequest, RevokeRequest router = APIRouter() LOGGER = logging.getLogger(__name__) +# What a product's own CSR carries when its certificate is first issued: client and server auth, its name as DNS SAN +RENEW_USAGES: frozenset[KeyUsages] = frozenset( + {"digital signature", "key encipherment", "data encipherment", "client auth", "server auth"} +) +RENEW_EXTENSIONS = frozenset( + { + ExtensionOID.BASIC_CONSTRAINTS, + ExtensionOID.KEY_USAGE, + ExtensionOID.EXTENDED_KEY_USAGE, + ExtensionOID.SUBJECT_ALTERNATIVE_NAME, + } +) +RENEW_REFUSED = "Renewal not allowed" + async def csr_common(certs: CertificatesRequest) -> CertificatesResponse: """Common parts of CSR handling""" @@ -102,20 +118,60 @@ async def revoke_cert( return OperationResultResponse(success=False, error=str(exc)) +def renewal_error(csrpem: str, peer_cn: str | None) -> str | None: + """Why the CSR is not a renewal of the calling product's own certificate, None when it is""" + if peer_cn is None or peer_cn not in RMSettings.singleton().valid_product_cns: + return "NOT_A_PRODUCT" + try: + csr = x509.load_pem_x509_csr(ensure_utf8(csrpem)) + if not csr.is_signature_valid: + return "CSR_SIGNATURE_INVALID" + cns = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME) + if len(csr.subject) != 1 or len(cns) != 1 or cns[0].value != peer_cn: + return "CSR_SUBJECT_MISMATCH" + for ext in csr.extensions: + if ext.oid not in RENEW_EXTENSIONS: + return "CSR_EXTENSION_NOT_ALLOWED" + if isinstance(ext.value, x509.BasicConstraints) and ext.value.ca: + return "CSR_EXTENSION_NOT_ALLOWED" + if isinstance(ext.value, x509.SubjectAlternativeName) and list(ext.value) != [x509.DNSName(peer_cn)]: + return "CSR_SUBJECT_MISMATCH" + if not set(csr_usages(csrpem)) <= RENEW_USAGES: + return "CSR_USAGE_NOT_ALLOWED" + except (ValueError, x509.DuplicateExtension, x509.UnsupportedGeneralNameType): + return "CSR_INVALID" + return None + + @router.post("/renew_csr", dependencies=[Depends(MTLSHeader(auto_error=True))]) async def renew_csr( request: Request, certs: CertificatesRequest, ) -> CertificatesResponse: """Used by product integration API to request renew of their mTLS client cert""" - req = x509.load_pem_x509_csr(ensure_utf8(certs.csr)) - req_cn = req.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value - peer_dn = request.state.mtlsdn - # Make sure the renew is for same name - if ensure_str(req_cn) != ensure_str(peer_dn["CN"]): - raise HTTPException(403, "Renewal must be for same name") - - return await csr_common(certs) + peer_cn = request.state.mtlsdn.get("CN") + error_code = renewal_error(certs.csr, peer_cn) + if error_code is None: + try: + resp = await csr_common(certs) + LOGGER.audit( # type: ignore[attr-defined] + "Product certificate renewed", + extra=build_audit_extra(action="product_cert_renew", outcome="success", actor=peer_cn, request=request), + ) + return resp + except HTTPException: + error_code = "SIGNING_REFUSED" + LOGGER.audit( # type: ignore[attr-defined] + "Product certificate renewal refused", + extra=build_audit_extra( + action="product_cert_renew", + outcome="failure", + actor=peer_cn, + request=request, + error_code=error_code, + ), + ) + raise HTTPException(403, RENEW_REFUSED) @router.post("/ready", dependencies=[Depends(MTLSHeader(auto_error=True))]) diff --git a/tests/test_product_renew.py b/tests/test_product_renew.py new file mode 100644 index 00000000..2c9dd8c7 --- /dev/null +++ b/tests/test_product_renew.py @@ -0,0 +1,209 @@ +"""Test product certificate renewal""" + +import ipaddress +import logging +from collections.abc import Callable + +import pytest +from async_asgi_testclient import TestClient # type: ignore[import-untyped] +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, rsa +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + +from rasenmaeher_api.web.api.product import views +from tests.cert.helpers import invalidate_signature, make_key_usage, make_name + +LOGGER = logging.getLogger(__name__) +PRODUCT = "fake.localmaeher.dev.pvarki.fi" +OTHER_PRODUCT = "interoptest.localmaeher.dev.pvarki.fi" + + +def product_csr( + common_name: str = PRODUCT, + *, + key: ec.EllipticCurvePrivateKey | rsa.RSAPrivateKey | None = None, + subject: x509.Name | None = None, + names: list[x509.GeneralName] | None = None, + ca: bool = False, + key_usage: x509.KeyUsage | None = None, + ext_key_usage: list[x509.ObjectIdentifier] | None = None, + extra: x509.ExtensionType | None = None, +) -> str: + """A CSR shaped like the one a product sends when its certificate is first issued""" + builder = ( + x509.CertificateSigningRequestBuilder() + .subject_name(subject or make_name(common_name)) + .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) + .add_extension( + x509.ExtendedKeyUsage(ext_key_usage or [ExtendedKeyUsageOID.CLIENT_AUTH, ExtendedKeyUsageOID.SERVER_AUTH]), + critical=True, + ) + .add_extension(key_usage or make_key_usage(digital_signature=True), critical=True) + .add_extension( + x509.SubjectAlternativeName(names if names is not None else [x509.DNSName(common_name)]), critical=False + ) + ) + if extra is not None: + builder = builder.add_extension(extra, critical=False) + signer = key or ec.generate_private_key(ec.SECP256R1()) + return builder.sign(signer, hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode("utf-8") + + +async def renew(client: TestClient, csr: str, caller: str = PRODUCT) -> x509.Certificate | None: + """POST the renewal as the given caller, return the issued leaf or None when refused""" + client.headers.update({"X-ClientCert-DN": f"CN={caller},O=N/A"}) + resp = await client.post("/api/v1/product/renew_csr", json={"csr": csr}) + if resp.status_code == 200: + return x509.load_pem_x509_certificates(resp.json()["certificate"].encode("utf-8"))[0] + assert resp.status_code == 403 + assert resp.json()["detail"] == "Renewal not allowed" + return None + + +def renew_records(caplog: pytest.LogCaptureFixture) -> list[logging.LogRecord]: + """The audit records written for renewals""" + return [record for record in caplog.records if record.__dict__.get("event.action") == "product_cert_renew"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "csr_factory", + [ + pytest.param(product_csr, id="ec"), + pytest.param( + lambda: product_csr( + key=rsa.generate_private_key(public_exponent=65537, key_size=2048), + key_usage=make_key_usage(digital_signature=True, key_encipherment=True, data_encipherment=True), + ), + id="rsa", + ), + ], +) +async def test_product_renews_own_certificate( + dbinit_func: None, unauth_client: TestClient, caplog: pytest.LogCaptureFixture, csr_factory: Callable[[], str] +) -> None: + """A product renewing its own certificate gets it signed, and the success is audited""" + _ = dbinit_func + with caplog.at_level("AUDIT"): + cert = await renew(unauth_client, csr_factory()) + assert cert is not None + assert cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value == PRODUCT + records = renew_records(caplog) + assert len(records) == 1 + assert records[0].__dict__["event.outcome"] == "success" + assert records[0].__dict__["user.name"] == PRODUCT + + +REFUSALS: list[tuple[str, Callable[[], str], str]] = [ + ("callsigndude", lambda: product_csr("callsigndude"), "NOT_A_PRODUCT"), + (PRODUCT, lambda: product_csr(OTHER_PRODUCT), "CSR_SUBJECT_MISMATCH"), + ( + PRODUCT, + lambda: product_csr( + subject=x509.Name( + [ + x509.NameAttribute(NameOID.COMMON_NAME, PRODUCT), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, "x"), + ] + ) + ), + "CSR_SUBJECT_MISMATCH", + ), + ( + PRODUCT, + lambda: product_csr( + subject=x509.Name( + [x509.NameAttribute(NameOID.COMMON_NAME, PRODUCT), x509.NameAttribute(NameOID.COMMON_NAME, PRODUCT)] + ) + ), + "CSR_SUBJECT_MISMATCH", + ), + (PRODUCT, lambda: product_csr(names=[x509.DNSName(PRODUCT), x509.DNSName(OTHER_PRODUCT)]), "CSR_SUBJECT_MISMATCH"), + ( + PRODUCT, + lambda: product_csr(names=[x509.DNSName(PRODUCT), x509.IPAddress(ipaddress.ip_address("192.0.2.1"))]), + "CSR_SUBJECT_MISMATCH", + ), + (PRODUCT, lambda: product_csr(ca=True), "CSR_EXTENSION_NOT_ALLOWED"), + ( + PRODUCT, + lambda: product_csr( + extra=x509.UnrecognizedExtension(x509.ObjectIdentifier("1.3.6.1.4.1.99999.1"), b"\x05\x00") + ), + "CSR_EXTENSION_NOT_ALLOWED", + ), + ( + PRODUCT, + lambda: product_csr(ext_key_usage=[ExtendedKeyUsageOID.CLIENT_AUTH, ExtendedKeyUsageOID.CODE_SIGNING]), + "CSR_USAGE_NOT_ALLOWED", + ), + ( + PRODUCT, + lambda: product_csr(key_usage=make_key_usage(digital_signature=True, key_cert_sign=True)), + "CSR_USAGE_NOT_ALLOWED", + ), + ( + PRODUCT, + lambda: product_csr( + ext_key_usage=[ExtendedKeyUsageOID.CLIENT_AUTH, ExtendedKeyUsageOID.ANY_EXTENDED_KEY_USAGE] + ), + "CSR_INVALID", + ), + (PRODUCT, lambda: invalidate_signature(product_csr()), "CSR_SIGNATURE_INVALID"), + (PRODUCT, lambda: "not a CSR", "CSR_INVALID"), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "caller,csr_factory,error_code", + REFUSALS, + ids=[ + "caller-not-a-product", + "other-common-name", + "extra-subject-attribute", + "two-common-names", + "extra-dns-name", + "ip-address-name", + "ca-constraint", + "unknown-extension", + "code-signing-usage", + "cert-sign-usage", + "unknown-extended-usage", + "invalid-signature", + "not-a-csr", + ], +) +async def test_renewal_refused( + unauth_client: TestClient, + caplog: pytest.LogCaptureFixture, + caller: str, + csr_factory: Callable[[], str], + error_code: str, +) -> None: + """Renewal is only for the calling product's own name and usages, and every refusal is audited""" + with caplog.at_level("AUDIT"): + assert await renew(unauth_client, csr_factory(), caller) is None + records = renew_records(caplog) + assert len(records) == 1 + assert records[0].__dict__["event.outcome"] == "failure" + assert records[0].__dict__["error_code"] == error_code + assert records[0].__dict__["user.name"] == caller + + +@pytest.mark.asyncio +async def test_renewal_refused_by_signer( + unauth_client: TestClient, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A CSR the signing backend refuses is a refused renewal""" + + async def refuse(csr: str) -> str: + raise ValueError("refused") + + monkeypatch.setattr(views, "sign_csr", refuse) + with caplog.at_level("AUDIT"): + assert await renew(unauth_client, product_csr()) is None + records = renew_records(caplog) + assert len(records) == 1 + assert records[0].__dict__["error_code"] == "SIGNING_REFUSED" From 5de132c05f282e5a5ade65d6a14580837e190ebd Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 07:34:51 +0200 Subject: [PATCH 3/6] fix(product): require CSRs sent for signing to be signed by their own key --- src/rasenmaeher_api/web/api/product/views.py | 6 +++++ tests/test_product_csr.py | 25 +++++++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/rasenmaeher_api/web/api/product/views.py b/src/rasenmaeher_api/web/api/product/views.py index f2852662..2f14ddf9 100644 --- a/src/rasenmaeher_api/web/api/product/views.py +++ b/src/rasenmaeher_api/web/api/product/views.py @@ -48,6 +48,12 @@ async def csr_common(certs: CertificatesRequest) -> CertificatesResponse: """Common parts of CSR handling""" + try: + signed_by_own_key = x509.load_pem_x509_csr(ensure_utf8(certs.csr)).is_signature_valid + except ValueError: + signed_by_own_key = False + if not signed_by_own_key: + raise HTTPException(status_code=400, detail="CSR is not signed by its own key") cachain = await get_ca() try: certpem = (await sign_csr(certs.csr)).replace("\\n", "\n") diff --git a/tests/test_product_csr.py b/tests/test_product_csr.py index 4b838f19..69663104 100644 --- a/tests/test_product_csr.py +++ b/tests/test_product_csr.py @@ -5,21 +5,40 @@ from rasenmaeher_api.web.api.product import views from rasenmaeher_api.web.api.product.schema import CertificatesRequest +from tests.cert.helpers import CsrFactory, invalidate_signature @pytest.mark.asyncio -async def test_csr_common_rejected_csr_is_400(monkeypatch: pytest.MonkeyPatch) -> None: +async def test_csr_common_rejected_csr_is_400(monkeypatch: pytest.MonkeyPatch, mint_csr: CsrFactory) -> None: """A CSR the signer refuses is the caller's error, not a server error""" async def fake_get_ca() -> str: return "ca" async def refuse(csr: str) -> str: - raise ValueError(f"CSR {csr} requests usages not allowed for it") + raise ValueError("CSR requests usages not allowed for it") monkeypatch.setattr(views, "get_ca", fake_get_ca) monkeypatch.setattr(views, "sign_csr", refuse) with pytest.raises(HTTPException) as excinfo: - await views.csr_common(CertificatesRequest(csr="x")) + await views.csr_common(CertificatesRequest(csr=mint_csr())) assert excinfo.value.status_code == 400 assert "not allowed" in str(excinfo.value.detail) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("broken", ["invalid-signature", "not-a-csr"]) +async def test_csr_common_requires_csr_signed_by_its_key( + monkeypatch: pytest.MonkeyPatch, mint_csr: CsrFactory, broken: str +) -> None: + """A CSR whose signature does not verify with its own key never reaches the signer""" + + async def must_not_sign(csr: str) -> str: + raise AssertionError("signer called") + + monkeypatch.setattr(views, "sign_csr", must_not_sign) + csrpem = invalidate_signature(mint_csr()) if broken == "invalid-signature" else "not a CSR" + with pytest.raises(HTTPException) as excinfo: + await views.csr_common(CertificatesRequest(csr=csrpem)) + assert excinfo.value.status_code == 400 + assert excinfo.value.detail == "CSR is not signed by its own key" From f7e4226ea6f49a0a589ae84c793a534ffa63808b Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 08:01:22 +0200 Subject: [PATCH 4/6] fix(cert): send the signer the parsed form of the CSR --- src/rasenmaeher_api/cert/cfssl/private.py | 5 ++- tests/test_product_renew.py | 45 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/rasenmaeher_api/cert/cfssl/private.py b/src/rasenmaeher_api/cert/cfssl/private.py index e268ee11..69f7ffd2 100644 --- a/src/rasenmaeher_api/cert/cfssl/private.py +++ b/src/rasenmaeher_api/cert/cfssl/private.py @@ -8,6 +8,7 @@ import aiohttp import cryptography.x509 +from cryptography.hazmat.primitives import serialization from libadvian.tasks import TaskMaster from ...rmsettings import RMSettings @@ -53,9 +54,11 @@ async def sign_csr(csr: str, bundle: bool = True) -> str: params: csr, whether to return cert of full bundle returns: certificate as PEM """ + parsed = cryptography.x509.load_pem_x509_csr(csr.encode("utf-8")) + normalized = parsed.public_bytes(encoding=serialization.Encoding.PEM).decode("utf-8") async with await mtls_session() as session: url = f"{ocsprest_base()}/api/v1/csr/sign" - payload = {"certificate_request": csr, "profile": signing_profile(csr), "bundle": bundle} + payload = {"certificate_request": normalized, "profile": signing_profile(normalized), "bundle": bundle} try: LOGGER.debug(f"Calling {url}") async with session.post(url, json=payload, timeout=default_timeout()) as response: diff --git a/tests/test_product_renew.py b/tests/test_product_renew.py index 2c9dd8c7..3af22edb 100644 --- a/tests/test_product_renew.py +++ b/tests/test_product_renew.py @@ -3,7 +3,9 @@ import ipaddress import logging from collections.abc import Callable +from typing import Any, Self +import aiohttp import pytest from async_asgi_testclient import TestClient # type: ignore[import-untyped] from cryptography import x509 @@ -11,6 +13,8 @@ from cryptography.hazmat.primitives.asymmetric import ec, rsa from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from rasenmaeher_api.cert.cfssl import private as cfssl_private +from rasenmaeher_api.cert.cfssl.base import CFSSLError from rasenmaeher_api.web.api.product import views from tests.cert.helpers import invalidate_signature, make_key_usage, make_name @@ -207,3 +211,44 @@ async def refuse(csr: str) -> str: records = renew_records(caplog) assert len(records) == 1 assert records[0].__dict__["error_code"] == "SIGNING_REFUSED" + + +@pytest.mark.asyncio +async def test_signer_receives_the_checked_request(monkeypatch: pytest.MonkeyPatch) -> None: + """The signer is sent the canonical PEM of the parsed request, not the text around it""" + checked = product_csr() + posted: list[dict[str, Any]] = [] + + class Session: + """Records the payload and fails the call""" + + async def __aenter__(self) -> Self: + return self + + async def __aexit__(self, *args: object) -> None: + return None + + def post(self, url: str, json: dict[str, Any], timeout: object) -> None: + _ = url, timeout + posted.append(json) + raise aiohttp.ClientError("recorded") + + async def session() -> Session: + return Session() + + monkeypatch.setattr(cfssl_private, "mtls_session", session) + with pytest.raises(CFSSLError): + await cfssl_private.sign_csr("x" + checked + product_csr(OTHER_PRODUCT)) + canonical = x509.load_pem_x509_csr(checked.encode("utf-8")).public_bytes(serialization.Encoding.PEM).decode("utf-8") + assert [payload["certificate_request"] for payload in posted] == [canonical] + + +@pytest.mark.asyncio +async def test_renewal_signs_the_checked_request(dbinit_func: None, unauth_client: TestClient) -> None: + """The issued certificate carries only the checked request's subject and names""" + _ = dbinit_func + cert = await renew(unauth_client, "x" + product_csr() + product_csr(OTHER_PRODUCT)) + assert cert is not None + assert cert.subject.rfc4514_string() == f"CN={PRODUCT}" + names = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + assert list(names) == [x509.DNSName(PRODUCT)] From e665b314547258396322b423a197fd27e9eff855 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 08:05:29 +0200 Subject: [PATCH 5/6] fix(product): accept a renewal CSR only with a single extension request and a supported key --- src/rasenmaeher_api/web/api/product/views.py | 5 +- tests/cert/helpers.py | 69 ++++++++++++++++++++ tests/test_product_renew.py | 35 +++++++++- 3 files changed, 106 insertions(+), 3 deletions(-) diff --git a/src/rasenmaeher_api/web/api/product/views.py b/src/rasenmaeher_api/web/api/product/views.py index 2f14ddf9..8d0bfcd1 100644 --- a/src/rasenmaeher_api/web/api/product/views.py +++ b/src/rasenmaeher_api/web/api/product/views.py @@ -5,6 +5,7 @@ import aiohttp from cryptography import x509 +from cryptography.exceptions import UnsupportedAlgorithm from cryptography.x509.oid import ExtensionOID, NameOID from fastapi import APIRouter, Depends, HTTPException, Request, Response from libadvian.binpackers import ensure_utf8 @@ -135,6 +136,8 @@ def renewal_error(csrpem: str, peer_cn: str | None) -> str | None: cns = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME) if len(csr.subject) != 1 or len(cns) != 1 or cns[0].value != peer_cn: return "CSR_SUBJECT_MISMATCH" + if [attribute.oid.dotted_string for attribute in csr.attributes] not in ([], ["1.2.840.113549.1.9.14"]): + return "CSR_EXTENSION_NOT_ALLOWED" for ext in csr.extensions: if ext.oid not in RENEW_EXTENSIONS: return "CSR_EXTENSION_NOT_ALLOWED" @@ -144,7 +147,7 @@ def renewal_error(csrpem: str, peer_cn: str | None) -> str | None: return "CSR_SUBJECT_MISMATCH" if not set(csr_usages(csrpem)) <= RENEW_USAGES: return "CSR_USAGE_NOT_ALLOWED" - except (ValueError, x509.DuplicateExtension, x509.UnsupportedGeneralNameType): + except (ValueError, x509.DuplicateExtension, x509.UnsupportedGeneralNameType, UnsupportedAlgorithm): return "CSR_INVALID" return None diff --git a/tests/cert/helpers.py b/tests/cert/helpers.py index 43cf88cc..5c1da16e 100644 --- a/tests/cert/helpers.py +++ b/tests/cert/helpers.py @@ -130,3 +130,72 @@ def make_csr( if ext_key_usage is not None: builder = builder.add_extension(cryptography.x509.ExtendedKeyUsage(ext_key_usage), critical=False) return builder.sign(key, hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode("utf-8") + + +EXTENSION_REQUEST_OID = b"\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x09\x0e" # 1.2.840.113549.1.9.14 +MS_EXTENSION_REQUEST_OID = b"\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x01\x0e" # 1.3.6.1.4.1.311.2.1.14 +EC_PUBLIC_KEY_OID = b"\x06\x07\x2a\x86\x48\xce\x3d\x02\x01" # 1.2.840.10045.2.1 +UNKNOWN_KEY_OID = b"\x06\x07\x2a\x86\x48\xce\x3d\x02\x7f" # 1.2.840.10045.2.127 + + +def _der(tag: int, body: bytes) -> bytes: + """One DER TLV""" + if len(body) < 0x80: + return bytes([tag, len(body)]) + body + size = len(body).to_bytes((len(body).bit_length() + 7) // 8, "big") + return bytes([tag, 0x80 | len(size)]) + size + body + + +def _der_header(data: bytes) -> tuple[int, int]: + """Header and content lengths of the TLV at the start of data""" + if data[1] & 0x80: + header = 2 + (data[1] & 0x7F) + return header, int.from_bytes(data[2:header], "big") + return 2, data[1] + + +def _der_items(body: bytes) -> list[bytes]: + """Split concatenated DER TLVs, each returned whole""" + items = [] + while body: + header, size = _der_header(body) + items.append(body[: header + size]) + body = body[header + size :] + return items + + +def _der_body(item: bytes) -> bytes: + """The contents of one DER TLV""" + return item[_der_header(item)[0] :] + + +def _csr_der(csr_pem: str) -> bytes: + return cryptography.x509.load_pem_x509_csr(csr_pem.encode("utf-8")).public_bytes(serialization.Encoding.DER) + + +def csr_attributes(csr_pem: str) -> list[bytes]: + """The DER attributes of a CSR""" + info = _der_items(_der_body(_csr_der(csr_pem)))[0] + return _der_items(_der_body(_der_items(_der_body(info))[3])) + + +def with_ms_extension_request_oid(attribute: bytes) -> bytes: + """The same extension-request attribute under the Microsoft OID""" + return _der(0x30, MS_EXTENSION_REQUEST_OID + _der_body(attribute)[len(EXTENSION_REQUEST_OID) :]) + + +def with_attributes(csr_pem: str, key: ec.EllipticCurvePrivateKey, extra: list[bytes]) -> str: + """The CSR with extra DER attributes, DER-sorted into its attribute set and signed again by key""" + info, algorithm, _ = _der_items(_der_body(_csr_der(csr_pem))) + version, subject, public_key, attributes = _der_items(_der_body(info)) + attribute_set = _der(0xA0, b"".join(sorted(_der_items(_der_body(attributes)) + extra))) + info = _der(0x30, version + subject + public_key + attribute_set) + signature = _der(0x03, b"\x00" + key.sign(info, ec.ECDSA(hashes.SHA256()))) + der = _der(0x30, info + algorithm + signature) + return cryptography.x509.load_der_x509_csr(der).public_bytes(serialization.Encoding.PEM).decode("utf-8") + + +def with_unknown_key_type(csr_pem: str) -> str: + """The same EC CSR with its public key algorithm replaced by an unknown one""" + der = _csr_der(csr_pem).replace(EC_PUBLIC_KEY_OID, UNKNOWN_KEY_OID, 1) + return cryptography.x509.load_der_x509_csr(der).public_bytes(serialization.Encoding.PEM).decode("utf-8") diff --git a/tests/test_product_renew.py b/tests/test_product_renew.py index 3af22edb..be9fb2d5 100644 --- a/tests/test_product_renew.py +++ b/tests/test_product_renew.py @@ -11,12 +11,20 @@ from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec, rsa -from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from cryptography.x509.oid import AttributeOID, ExtendedKeyUsageOID, NameOID from rasenmaeher_api.cert.cfssl import private as cfssl_private from rasenmaeher_api.cert.cfssl.base import CFSSLError from rasenmaeher_api.web.api.product import views -from tests.cert.helpers import invalidate_signature, make_key_usage, make_name +from tests.cert.helpers import ( + csr_attributes, + invalidate_signature, + make_key_usage, + make_name, + with_attributes, + with_ms_extension_request_oid, + with_unknown_key_type, +) LOGGER = logging.getLogger(__name__) PRODUCT = "fake.localmaeher.dev.pvarki.fi" @@ -33,6 +41,7 @@ def product_csr( key_usage: x509.KeyUsage | None = None, ext_key_usage: list[x509.ObjectIdentifier] | None = None, extra: x509.ExtensionType | None = None, + attribute: tuple[x509.ObjectIdentifier, bytes] | None = None, ) -> str: """A CSR shaped like the one a product sends when its certificate is first issued""" builder = ( @@ -50,6 +59,8 @@ def product_csr( ) if extra is not None: builder = builder.add_extension(extra, critical=False) + if attribute is not None: + builder = builder.add_attribute(*attribute) signer = key or ec.generate_private_key(ec.SECP256R1()) return builder.sign(signer, hashes.SHA256()).public_bytes(serialization.Encoding.PEM).decode("utf-8") @@ -99,6 +110,14 @@ async def test_product_renews_own_certificate( assert records[0].__dict__["user.name"] == PRODUCT +def extra_extension_request(microsoft_oid: bool = False) -> str: + """A product CSR with a second extension request naming another product""" + key = ec.generate_private_key(ec.SECP256R1()) + other = csr_attributes(product_csr(OTHER_PRODUCT)) + extra = [with_ms_extension_request_oid(attribute) for attribute in other] if microsoft_oid else other + return with_attributes(product_csr(key=key), key, extra) + + REFUSALS: list[tuple[str, Callable[[], str], str]] = [ ("callsigndude", lambda: product_csr("callsigndude"), "NOT_A_PRODUCT"), (PRODUCT, lambda: product_csr(OTHER_PRODUCT), "CSR_SUBJECT_MISMATCH"), @@ -156,6 +175,14 @@ async def test_product_renews_own_certificate( ), (PRODUCT, lambda: invalidate_signature(product_csr()), "CSR_SIGNATURE_INVALID"), (PRODUCT, lambda: "not a CSR", "CSR_INVALID"), + (PRODUCT, extra_extension_request, "CSR_EXTENSION_NOT_ALLOWED"), + (PRODUCT, lambda: extra_extension_request(microsoft_oid=True), "CSR_EXTENSION_NOT_ALLOWED"), + ( + PRODUCT, + lambda: product_csr(attribute=(AttributeOID.CHALLENGE_PASSWORD, b"secret")), + "CSR_EXTENSION_NOT_ALLOWED", + ), + (PRODUCT, lambda: with_unknown_key_type(product_csr()), "CSR_INVALID"), ] @@ -177,6 +204,10 @@ async def test_product_renews_own_certificate( "unknown-extended-usage", "invalid-signature", "not-a-csr", + "two-extension-requests", + "other-extension-request-oid", + "other-attribute", + "unsupported-key-type", ], ) async def test_renewal_refused( From f0a83b60569a0d12ab1967790f4f4b1760b77053 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 02:00:43 +0200 Subject: [PATCH 6/6] chore: bump version --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/rasenmaeher_api/__init__.py | 2 +- tests/test_rasenmaeher_api.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index b27017bc..2ad9604e 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.20.2+261121" +current_version = "1.20.3+261123" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index a40b39ed..65c18069 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "rasenmaeher_api" -version = "1.20.2+261121" +version = "1.20.3+261123" description = "python-rasenmaeher-api" authors = [ { name = "Aciid", email = "703382+Aciid@users.noreply.github.com" }, diff --git a/src/rasenmaeher_api/__init__.py b/src/rasenmaeher_api/__init__.py index ad9f2f95..a67b3689 100644 --- a/src/rasenmaeher_api/__init__.py +++ b/src/rasenmaeher_api/__init__.py @@ -1,3 +1,3 @@ """python-rasenmaeher-api""" -__version__ = "1.20.2+261121" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.20.3+261123" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_rasenmaeher_api.py b/tests/test_rasenmaeher_api.py index 850b3bea..b7ba1546 100644 --- a/tests/test_rasenmaeher_api.py +++ b/tests/test_rasenmaeher_api.py @@ -15,7 +15,7 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.20.2+261121" + assert __version__ == "1.20.3+261123" @pytest.mark.asyncio(loop_scope="session") diff --git a/uv.lock b/uv.lock index eaa8c0d1..030410ab 100644 --- a/uv.lock +++ b/uv.lock @@ -2366,7 +2366,7 @@ wheels = [ [[package]] name = "rasenmaeher-api" -version = "1.20.2+261121" +version = "1.20.3+261123" source = { editable = "." } dependencies = [ { name = "aiodns" },