Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .bumpversion.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "1.20.2+261121"
current_version = "1.21.1+261122"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)\\+(?P<build>\\d+)"
serialize = ["{major}.{minor}.{patch}+{build}"]
search = "{current_version}"
Expand Down
20 changes: 20 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,26 @@ RM_ENVIRONMENT="dev"
You can read more about BaseSettings class here: https://pydantic-docs.helpmanual.io/usage/settings/


Apple ACME enrollment
---------------------

The Apple profile uses ``https://<deployment-dns>/api/v1/acme/directory``,
with the hostname from the existing deployment manifest. Serve the directory
with a publicly trusted HTTPS certificate. Invite enrollment accepts ``"acme": true``
with an OpenDefence callsign and no CSR. After operator approval,
``GET /api/v1/enrollment/status`` reports state ``3`` (awaiting ACME issuance).
Use the enrollment JWT to download the Apple configuration profile at
``GET /api/v1/enrollment/acme-profile``. The profile can be downloaded again
within 15 minutes of approval.

The directory supports the Apple enrollment flow with ``device-attest-01``.
This pilot authorizes the order using the single-use enrollment identifier and
the ACME account key. The profile requests a hardware-bound key with Apple
attestation disabled. RMAPI validates the device CSR, signs it with the
configured client CA, and returns the certificate and chain. Revocation uses
the existing RMAPI user revocation flow.


Backend services manifest
-------------------------
Integration APIs are always https in port 4625.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "rasenmaeher_api"
version = "1.20.2+261121"
version = "1.21.1+261122"
description = "python-rasenmaeher-api"
authors = [
{ name = "Aciid", email = "703382+Aciid@users.noreply.github.com" },
Expand Down
2 changes: 1 addition & 1 deletion src/rasenmaeher_api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""python-rasenmaeher-api"""

__version__ = "1.20.2+261121" # NOTE Use `bump-my-version` to bump versions correctly
__version__ = "1.21.1+261122" # NOTE Use `bump-my-version` to bump versions correctly
72 changes: 72 additions & 0 deletions src/rasenmaeher_api/cert/acme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""Validation shared by the Apple ACME order and its certificate signer."""

import base64
import re

from cryptography import x509
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec

from .usages import csr_usages


class ACMEError(Exception):
"""An ACME problem response."""

def __init__(self, code: str, detail: str, status: int = 400) -> None:
super().__init__(detail)
self.code = code
self.status = status


def b64url(data: bytes) -> str:
"""Encode an unpadded base64url value."""
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def decode_b64url(value: str) -> bytes:
"""Decode a canonical, unpadded base64url value."""
if not re.fullmatch(r"[A-Za-z0-9_-]*", value):
raise ValueError("Invalid base64url")
data = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
if b64url(data) != value:
raise ValueError("Invalid base64url")
return data


def validate_device_csr(der: bytes, callsign: str, identifier: str) -> str:
"""Validate the signed CSR and allow only the identity requested by the profile."""
try:
csr = x509.load_der_x509_csr(der)
key = csr.public_key()
pem = csr.public_bytes(serialization.Encoding.PEM).decode("ascii")
if not (
isinstance(key, ec.EllipticCurvePublicKey)
and isinstance(key.curve, ec.SECP256R1)
and isinstance(csr.signature_hash_algorithm, hashes.SHA256)
and csr.is_signature_valid
and csr.subject == x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, callsign)])
and set(csr_usages(pem)) == {"digital signature", "client auth"}
):
raise ValueError("CSR does not match the approved client certificate policy")
for extension in csr.extensions:
match extension.value:
case x509.KeyUsage() | x509.ExtendedKeyUsage():
pass
case x509.BasicConstraints(ca=False, path_length=None):
pass
case x509.SubjectAlternativeName() as san:
# RFC 4043 permanentIdentifier with just the UTF8String identifierValue.
encoded = identifier.encode("ascii")
other_name = x509.OtherName(
x509.ObjectIdentifier("1.3.6.1.5.5.7.8.3"),
bytes((0x30, len(encoded) + 2, 0x0C, len(encoded))) + encoded,
)
if list(san) != [other_name]:
raise ValueError("CSR SAN does not match the approved identifier")
case _:
raise ValueError("CSR contains an unsupported extension")
except (ValueError, UnsupportedAlgorithm, x509.DuplicateExtension, x509.UnsupportedGeneralNameType) as exc:
raise ACMEError("badCSR", "CSR does not match the approved client certificate policy") from exc
return pem
205 changes: 205 additions & 0 deletions src/rasenmaeher_api/db/acme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
"""Persist ACME accounts, replay nonces, and the single order on each approved enrollment."""

import datetime
import hashlib
import logging
import secrets
import uuid
from typing import Any

from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.exc import OperationalError
from sqlmodel import Session, col, delete, select
from sqlmodel.sql.expression import SelectOfScalar

from ..cert.acme import ACMEError, b64url, validate_device_csr
from .engine import EngineWrapper
from .enrollments import ACME_CLIENT_IDENTIFIER_KEY, ACME_ORDER_KEY, Enrollment, EnrollmentState
from .errors import BackendError, CallsignReserved
from .nonces import SeenToken
from .people import Person

LOGGER = logging.getLogger(__name__)
NONCE_LIFETIME = datetime.timedelta(minutes=10)
NONCE_PREFIX = "acme-nonce:"
ACCOUNT_PREFIX = "acme-account:"


def issue_nonce() -> str:
"""Mint a canonical nonce and discard expired ACME nonces, including on POST responses."""
nonce = b64url(secrets.token_bytes(32))
cutoff = datetime.datetime.now(datetime.UTC) - NONCE_LIFETIME
with EngineWrapper.get_session() as session:
session.exec(
delete(SeenToken).where(col(SeenToken.token).startswith(NONCE_PREFIX), col(SeenToken.created) <= cutoff)
)
session.add(SeenToken(token=f"{NONCE_PREFIX}{nonce}"))
session.commit()
return nonce


def consume_nonce(nonce: str) -> None:
"""Remove an unexpired nonce atomically, allowing its use just once."""
cutoff = datetime.datetime.now(datetime.UTC) - NONCE_LIFETIME
with EngineWrapper.get_session() as session:
used = session.exec(
delete(SeenToken)
.where(col(SeenToken.token) == f"{NONCE_PREFIX}{nonce}", col(SeenToken.created) > cutoff)
.returning(col(SeenToken.pk))
).first()
session.commit()
if used is None:
raise ACMEError("badNonce", "Unknown, expired, or already used nonce")


def account_exists(account: str) -> bool:
"""Check whether a public account key was registered."""
with EngineWrapper.get_session() as session:
return (
session.exec(select(SeenToken.pk).where(SeenToken.token == f"{ACCOUNT_PREFIX}{account}")).first()
is not None
)


def register_account(account: str) -> bool:
"""Register the public key once across concurrent requests."""
with EngineWrapper.get_session() as session:
created = session.exec(
insert(SeenToken)
.values(pk=uuid.uuid4(), token=f"{ACCOUNT_PREFIX}{account}", auditmeta={})
.on_conflict_do_nothing(index_elements=[col(SeenToken.token)])
.returning(col(SeenToken.pk))
).first()
session.commit()
return created is not None


def order_data(enrollment: Enrollment) -> dict[str, Any]:
"""Read ACME's metadata from the enrollment that owns the order."""
data = enrollment.extra.get(ACME_ORDER_KEY)
return data if isinstance(data, dict) else {}


def _locked(session: Session, query: SelectOfScalar[Enrollment]) -> Enrollment | None:
# A concurrent finalization can hold the row while awaiting the signer.
# NOWAIT keeps a synchronous database call from blocking the event loop.
try:
return session.exec(query.with_for_update(nowait=True)).first()
except OperationalError as exc:
if getattr(exc.orig, "pgcode", None) != "55P03": # lock_not_available
raise
raise ACMEError("serverInternal", "Order is being updated. Retry shortly.", 503) from exc


def _check_approval(enrollment: Enrollment) -> None:
expires_at = enrollment.acme_authorization_expires_at
if enrollment.deleted is not None or expires_at is None or datetime.datetime.now(datetime.UTC) >= expires_at:
raise ACMEError("unauthorized", "Enrollment is no longer authorized for ACME issuance", 403)


def _check_order(enrollment: Enrollment | None, account: str) -> Enrollment:
if enrollment is None or order_data(enrollment).get("account") != account:
raise ACMEError("unauthorized", "Order is unavailable to this account", 403)
if enrollment.state != EnrollmentState.APPROVED or enrollment.person is None or enrollment.deleted is not None:
_check_approval(enrollment)
return enrollment


def new_order(identifier: str, account: str) -> Enrollment:
"""Consume the enrollment identifier by binding it to exactly one account and order."""
with EngineWrapper.get_session() as session:
enrollment = _locked(
session,
select(Enrollment).where(col(Enrollment.extra)[ACME_CLIENT_IDENTIFIER_KEY].as_string() == identifier),
)
if enrollment is None:
raise ACMEError("rejectedIdentifier", "Identifier does not belong to an approved enrollment")
if order_data(enrollment):
return _check_order(enrollment, account)
_check_approval(enrollment)
enrollment.extra = {
**enrollment.extra,
ACME_ORDER_KEY: {"account": account, "token": secrets.token_urlsafe(32)},
}
session.add(enrollment)
session.commit()
session.refresh(enrollment)
return enrollment


def list_orders(account: str) -> list[uuid.UUID]:
"""List order IDs bound to this account."""
with EngineWrapper.get_session() as session:
return list(
session.exec(
select(Enrollment.pk).where(col(Enrollment.extra)[ACME_ORDER_KEY]["account"].as_string() == account)
)
)


def get_order(order_id: uuid.UUID, account: str) -> Enrollment:
"""Read an order for its owning account."""
with EngineWrapper.get_session() as session:
return _check_order(session.get(Enrollment, order_id), account)


def accept_challenge(order_id: uuid.UUID, account: str) -> Enrollment:
"""Record the bound account's acknowledgment in the enrollment-token pilot."""
with EngineWrapper.get_session() as session:
enrollment = _check_order(_locked(session, select(Enrollment).where(Enrollment.pk == order_id)), account)
data = order_data(enrollment)
if "validated" not in data:
data = {**data, "validated": datetime.datetime.now(datetime.UTC).isoformat()}
enrollment.extra = {**enrollment.extra, ACME_ORDER_KEY: data}
session.add(enrollment)
session.commit()
session.refresh(enrollment)
return enrollment


async def finalize_order(order_id: uuid.UUID, account: str, csr_der: bytes) -> Enrollment:
"""Pin the CSR before calling the signer and commit the certificate with its enrollment."""
digest = hashlib.sha256(csr_der).hexdigest()
query = select(Enrollment).where(Enrollment.pk == order_id)
with EngineWrapper.get_session() as session:
enrollment = _check_order(_locked(session, query), account)
data = order_data(enrollment)
if "validated" not in data:
raise ACMEError("orderNotReady", "Complete the challenge before finalizing", 403)
if data.get("csr_digest", digest) != digest:
raise ACMEError("badCSR", "A different CSR was already submitted to this order")
if enrollment.person is not None:
return enrollment
csr_pem = validate_device_csr(csr_der, enrollment.callsign, enrollment.acme_client_identifier or "")
if "csr_digest" not in data:
enrollment.extra = {**enrollment.extra, ACME_ORDER_KEY: {**data, "csr_digest": digest}}
session.add(enrollment)
session.commit()

with EngineWrapper.get_session() as session:
enrollment = _check_order(_locked(session, query), account)
if enrollment.person is not None:
return enrollment
person_extra = {
key: value
for key, value in enrollment.extra.items()
if key not in (ACME_ORDER_KEY, ACME_CLIENT_IDENTIFIER_KEY)
}
try:
async with Person.issue_cert(session, enrollment.callsign, person_extra, csr_pem) as person:
enrollment.csr = csr_pem
enrollment.person = person.pk
enrollment.state = EnrollmentState.APPROVED
session.add(enrollment)
session.commit()
except CallsignReserved as exc:
raise ACMEError("unauthorized", "Callsign is already in use", 403) from exc
except BackendError as exc:
raise ACMEError("serverInternal", "The certificate signer could not complete issuance", 503) from exc
session.refresh(enrollment)
session.refresh(person)
try:
await person.complete_provisioning()
except Exception:
LOGGER.exception("Post-issuance provisioning failed for ACME enrollment %s", order_id)
return enrollment
Loading
Loading