Skip to content
Open
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.20.3+261123"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)\\+(?P<build>\\d+)"
serialize = ["{major}.{minor}.{patch}+{build}"]
search = "{current_version}"
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.20.3+261123"
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.20.3+261123" # NOTE Use `bump-my-version` to bump versions correctly
5 changes: 4 additions & 1 deletion src/rasenmaeher_api/cert/cfssl/private.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import aiohttp
import cryptography.x509
from cryptography.hazmat.primitives import serialization
from libadvian.tasks import TaskMaster

from ...rmsettings import RMSettings
Expand Down Expand Up @@ -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:
Expand Down
85 changes: 75 additions & 10 deletions src/rasenmaeher_api/web/api/product/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@

import aiohttp
from cryptography import x509
from cryptography.x509.oid import NameOID
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_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
Expand All @@ -16,6 +17,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
Expand All @@ -24,14 +26,35 @@
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"""
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")
Expand Down Expand Up @@ -102,20 +125,62 @@ 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"
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"
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, UnsupportedAlgorithm):
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))])
Expand Down
3 changes: 3 additions & 0 deletions src/rasenmaeher_api/web/api/utils/csr_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down
76 changes: 76 additions & 0 deletions tests/cert/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -123,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")
9 changes: 8 additions & 1 deletion tests/test_csr_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
17 changes: 17 additions & 0 deletions tests/test_enrollment.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Person,
)
from rasenmaeher_api.rmsettings import RMSettings
from tests.cert.helpers import CsrFactory, invalidate_signature

LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -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"""
Expand Down
25 changes: 22 additions & 3 deletions tests/test_product_csr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading
Loading