Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(iot): refuse inactive CAs in RegisterCertificate and use AWS's CA errors (#2143)
iot-rocket97588b190ad2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7a6a53e2..977af966 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Fixed+- **IoT — `RegisterCertificate` under an inactive CA** — a certificate issued by a CA that is not `ACTIVE` registered anyway; it is now refused with `CertificateStateException`, with or without `caCertificatePem`. An unregistered CA and a CA that did not issue the certificate are refused with AWS's codes and messages. Contributed by @iot-rocket.- **IoT — rule SQL `principal()` and `traceid()`** — both resolved to Undefined; `principal()` now returns the client certificate id for mTLS, the caller's `GetCallerIdentity` `UserId` for HTTP Publish and SigV4 WebSocket sessions (also their lifecycle events' `principalIdentifier`) and the rule role's session for a republish, and `traceid()` returns a per-message id that the errorAction document carries as `cloudwatchTraceId`. Contributed by @iot-rocket.### Addeddiff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex f911217b..e6bd8625 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -2140,14 +2140,36 @@ def _certificate_already_exists(cert_id: str, arn: str | None = None) -> tuple:def _registered_issuer_id(cert_pem: str) -> str | None:- """The id of the ACTIVE CA registered in this account/region that signed- ``cert_pem``, or None. Several CAs may share a subject, so the signature- decides, not the issuer name."""+ """The id of the registered CA that signed ``cert_pem``, an ACTIVE one first, or None."""+ issuer_id = Nonefor ca in _ca_certificates.values():- if ca.get("status") == "ACTIVE" and certificate_is_signed_by(- cert_pem, ca.get("certificatePem") or ""- ):- return ca["certificateId"]+ if certificate_is_signed_by(cert_pem, ca.get("certificatePem") or ""):+ if ca.get("status") == "ACTIVE":+ return ca["certificateId"]+ issuer_id = issuer_id or ca["certificateId"]+ return issuer_id+++def _not_issued_by_error(cert_pem: str, ca_pem: str) -> tuple | None:+ """400 when ``ca_pem`` did not issue ``cert_pem``, checking the issuer name before the signature."""+ from cryptography import x509++ cert = x509.load_pem_x509_certificate(cert_pem.encode("utf-8"))+ ca = x509.load_pem_x509_certificate(ca_pem.encode("utf-8"))+ if cert.issuer != ca.subject:+ return error_response_json(+ "CertificateValidationException",+ "The issuer of the certificate did not match the subject of the "+ "provided CA certificate.",+ 400,+ )+ if not certificate_is_signed_by(cert_pem, ca_pem):+ return error_response_json(+ "CertificateValidationException",+ "The signature of the certificate failed verification against the "+ "provided CA certificate.",+ 400,+ )return None@@ -2164,12 +2186,12 @@ async def _register_certificate(CA reference and takes its status from the plain ``status`` body fieldonly — it has no deprecated ``setAsActive``.- ``caCertificatePem`` must name a CA registered via+ ``caCertificatePem`` must name an ACTIVE CA registered via``RegisterCACertificate`` in this account/region that really signed the- leaf; anything else is a ``CertificateValidationException``. Without it,- ``RegisterCertificate`` links the certificate to the registered ACTIVE CA- that signed it, as AWS does, so DescribeCertificate names that CA and- ListCertificatesByCA lists the certificate. Registering+ leaf; anything else is refused. Without it, ``RegisterCertificate`` links+ the certificate to the registered CA that signed it, as AWS does, so+ DescribeCertificate names that CA and ListCertificatesByCA lists the+ certificate, and refuses it while that CA is not ACTIVE. Registeringpublishes no JITR event, whatever the CA's ``autoRegistrationStatus``: AWSsends that event only from a device connect (see ``_mtls_auto_register``),and refuses a registration with status PENDING_ACTIVATION.@@ -2207,33 +2229,25 @@ async def _register_certificate(# fleet, so the claim is verified the way AWS does before anything is# stored — the CA has to be registered in this account/region, and it has to# be the certificate that actually signed the leaf.- ca = Noneif ca_id is not None:- ca = _ca_certificates.get(ca_id)- if ca is None:+ if ca_id not in _ca_certificates:return error_response_json(- "CertificateValidationException",- (- f"The CA certificate {ca_id} is not registered in this "- "account and region. Register it with RegisterCACertificate, "- "or use RegisterCertificateWithoutCA."- ),- 400,- )- if not certificate_is_signed_by(cert_pem, ca_pem):- return error_response_json(- "CertificateValidationException",- (- f"The certificate was not signed by CA {ca_id}. "- "caCertificatePem must be the CA certificate that issued "- "certificatePem."- ),- 400,+ "CertificateStateException",+ "No CA certificate exists for the given certificate",+ 406,)+ refused = _not_issued_by_error(cert_pem, ca_pem)+ if refused is not None:+ return refused+ elif not without_ca:+ ca_id = _registered_issuer_id(cert_pem)+ # A CA that is not ACTIVE refuses the leaf, ahead of the duplicate check.+ if ca_id is not None and _ca_certificates[ca_id]["status"] != "ACTIVE":+ return error_response_json(+ "CertificateStateException", "The CA certificate is not active", 406+ )if cert_id in _certificates:return _certificate_already_exists(cert_id)- if ca_id is None and not without_ca:- ca_id = _registered_issuer_id(cert_pem)record = _certificate_record(cert_id, cert_pem, status or ("ACTIVE" if set_active else "INACTIVE"), ca_id)@@ -2489,27 +2503,15 @@ def _verification_certificate_error()try:cert = x509.load_pem_x509_certificate(verification_pem.encode("utf-8"))- ca = x509.load_pem_x509_certificate(ca_pem.encode("utf-8"))except Exception:return error_response_json("InvalidRequestException","Contents of the Verification Certificate are not correct",400,)- if cert.issuer != ca.subject:- return error_response_json(- "CertificateValidationException",- "The issuer of the certificate did not match the subject of the "- "provided CA certificate.",- 400,- )- if not certificate_is_signed_by(verification_pem, ca_pem):- return error_response_json(- "CertificateValidationException",- "The signature of the certificate failed verification against the "- "provided CA certificate.",- 400,- )+ refused = _not_issued_by_error(verification_pem, ca_pem)+ if refused is not None:+ return refusedcommon_names = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)if [a.value for a in common_names] != [_registration_code()]:return error_response_json(diff --git a/tests/test_iot.py b/tests/test_iot.pyindex f33fff55..718e0b2e 100644--- a/tests/test_iot.py+++ b/tests/test_iot.py@@ -7444,24 +7444,36 @@ def test_iot_register_certificate_without_ca_pem_links_the_signing_ca(iot_client_delete_certificates_and_cas(iot_client, cert_ids, ca_ids)+def _assert_register_refused(iot_client, http_status, code, message, **kwargs):+ with pytest.raises(ClientError) as ei:+ iot_client.register_certificate(**kwargs)+ assert ei.value.response["Error"]["Code"] == code+ assert ei.value.response["Error"]["Message"] == message+ assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == http_status++def test_iot_register_certificate_rejects_an_unregistered_ca(iot_client):- """``caCertificatePem`` naming a CA that was never registered is a- ``CertificateValidationException``, and nothing is stored — otherwise the- CA id is whatever the caller sent and DescribeCertificate points at a CA- that does not exist."""+ """``caCertificatePem`` naming a CA that was never registered, or was+ deleted, is a ``CertificateStateException``, and nothing is stored —+ otherwise the CA id is whatever the caller sent and DescribeCertificate+ points at a CA that does not exist."""from ministack.core.x509_utils import get_certificate_idca_pem, _verification, leaf_pem = _generate_ca_and_leaf("never-registered")- with pytest.raises(ClientError) as ei:- iot_client.register_certificate(- certificatePem=leaf_pem, caCertificatePem=ca_pem+ deleted_pem, _verification, deleted_leaf_pem = _generate_ca_and_leaf("deleted")+ deleted_id = iot_client.register_ca_certificate(+ caCertificate=deleted_pem, certificateMode="SNI_ONLY"+ )["certificateId"]+ iot_client.delete_ca_certificate(certificateId=deleted_id)+ for ca, leaf in ((ca_pem, leaf_pem), (deleted_pem, deleted_leaf_pem)):+ _assert_register_refused(+ iot_client, 406, "CertificateStateException",+ "No CA certificate exists for the given certificate",+ certificatePem=leaf, caCertificatePem=ca,)- assert ei.value.response["Error"]["Code"] == "CertificateValidationException"- assert ei.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400-- with pytest.raises(ClientError) as ei:- iot_client.describe_certificate(certificateId=get_certificate_id(leaf_pem))- assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ with pytest.raises(ClientError) as ei:+ iot_client.describe_certificate(certificateId=get_certificate_id(leaf))+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"def test_iot_register_certificate_rejects_a_leaf_from_another_ca(iot_client):@@ -7508,6 +7520,110 @@ def test_iot_register_certificate_rejects_a_leaf_from_another_ca(iot_client):iot_client.delete_ca_certificate(certificateId=ca_id)+def test_iot_register_certificate_refuses_a_ca_that_is_not_active(iot_client):+ """A CA set INACTIVE refuses its leaves with or without+ ``caCertificatePem``, whatever status they ask for and ahead of the+ duplicate check. A leaf registered before keeps its status,+ RegisterCertificateWithoutCA still takes the CA's leaves, and the CA set+ ACTIVE again accepts them."""+ from ministack.core.x509_utils import get_certificate_id++ ca_pem, verification_pem, leaves = _generate_ca_and_leaves(+ _registration_code(iot_client), count=4+ )+ ca_id = iot_client.register_ca_certificate(+ caCertificate=ca_pem, verificationCertificate=verification_pem, setAsActive=True,+ )["certificateId"]+ cert_ids = [iot_client.register_certificate(+ certificatePem=leaves[0], caCertificatePem=ca_pem, setAsActive=True+ )["certificateId"]]+ try:+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="INACTIVE")+ flags = [{}, {"setAsActive": True}, {"status": "ACTIVE"}, {"status": "INACTIVE"},+ {"status": "REVOKED"}]+ for leaf in leaves[:2]:+ for kwargs in [{"caCertificatePem": ca_pem, **f} for f in flags] + [{"status": "ACTIVE"}]:+ _assert_register_refused(+ iot_client, 406, "CertificateStateException", "The CA certificate is not active",+ certificatePem=leaf, **kwargs,+ )+ _assert_register_refused(+ iot_client, 406, "CertificateStateException",+ "Not allowed to register certificate with PENDING_ACTIVATION status",+ certificatePem=leaves[1], caCertificatePem=ca_pem, status="PENDING_ACTIVATION",+ )+ with pytest.raises(ClientError) as ei:+ iot_client.describe_certificate(certificateId=get_certificate_id(leaves[1]))+ assert ei.value.response["Error"]["Code"] == "ResourceNotFoundException"+ desc = iot_client.describe_certificate(certificateId=cert_ids[0])["certificateDescription"]+ assert (desc["status"], desc["caCertificateId"]) == ("ACTIVE", ca_id)++ cert_ids.append(iot_client.register_certificate_without_ca(+ certificatePem=leaves[2], status="ACTIVE"+ )["certificateId"])+ iot_client.update_ca_certificate(certificateId=ca_id, newStatus="ACTIVE")+ cert_ids.append(iot_client.register_certificate(+ certificatePem=leaves[3], caCertificatePem=ca_pem+ )["certificateId"])+ desc = iot_client.describe_certificate(certificateId=cert_ids[-1])["certificateDescription"]+ assert (desc["status"], desc["caCertificateId"]) == ("INACTIVE", ca_id)+ finally:+ _delete_certificates_and_cas(iot_client, cert_ids, [ca_id])+++def test_iot_register_certificate_checks_the_issuer_before_the_ca_status(iot_client):+ """An unregistered CA is refused first, then a CA that did not issue the+ leaf (issuer name, then signature), then a CA that is not ACTIVE. Without+ ``caCertificatePem`` the signature picks the CA, so of two CAs with one+ subject only the INACTIVE one's leaf is refused."""+ pytest.importorskip("cryptography")+ from ministack.core.x509_utils import generate_ca, sign_leaf_certificate++ subject = _unique("twin-ca")+ (a_pem, a_key), (b_pem, b_key) = twins = [generate_ca(common_name=subject) for _ in range(2)]+ other_pem, other_key = generate_ca(common_name=_unique("other-ca"))+ unregistered_pem, _key = generate_ca(common_name=_unique("unregistered-ca"))++ def leaf(ca_pem, ca_key):+ return sign_leaf_certificate(+ ca_cert_pem=ca_pem, ca_key_pem=ca_key, common_name=_unique("device")+ )[0]++ ca_ids, cert_ids = [], []+ try:+ for ca_pem in (*(pem for pem, _key in twins), other_pem):+ ca_ids.append(iot_client.register_ca_certificate(+ caCertificate=ca_pem, certificateMode="SNI_ONLY", setAsActive=True,+ )["certificateId"])+ iot_client.update_ca_certificate(certificateId=ca_ids[1], newStatus="INACTIVE")+ _assert_register_refused(+ iot_client, 406, "CertificateStateException",+ "No CA certificate exists for the given certificate",+ certificatePem=leaf(other_pem, other_key), caCertificatePem=unregistered_pem,+ )+ _assert_register_refused(+ iot_client, 400, "CertificateValidationException",+ "The issuer of the certificate did not match the subject of the provided CA certificate.",+ certificatePem=leaf(other_pem, other_key), caCertificatePem=b_pem,+ )+ _assert_register_refused(+ iot_client, 400, "CertificateValidationException",+ "The signature of the certificate failed verification against the provided CA certificate.",+ certificatePem=leaf(a_pem, a_key), caCertificatePem=b_pem,+ )+ _assert_register_refused(+ iot_client, 406, "CertificateStateException", "The CA certificate is not active",+ certificatePem=leaf(b_pem, b_key), status="ACTIVE",+ )+ cert_ids.append(iot_client.register_certificate(+ certificatePem=leaf(a_pem, a_key), status="ACTIVE"+ )["certificateId"])+ desc = iot_client.describe_certificate(certificateId=cert_ids[0])["certificateDescription"]+ assert desc["caCertificateId"] == ca_ids[0]+ finally:+ _delete_certificates_and_cas(iot_client, cert_ids, ca_ids)++def _delete_certificates_and_cas(iot_client, cert_ids, ca_ids):for cert_id in cert_ids:iot_client.update_certificate(certificateId=cert_id, newStatus="INACTIVE")