From 2a41118e8ec7f067cc2d425d993b869b6a8c09eb Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 21 Oct 2026 14:16:58 +0200 Subject: [PATCH] feat: fill certificate fields from uploaded certificate file Parse uploaded PEM or DER certificates with cryptography and fill common name, SANs, issuer, serial number, SHA-256 fingerprint and validity dates. Name and type are only set when left empty; the type is derived from the CA flag and extended key usage. Files containing a private key are rejected. Works in the UI form and the REST API. Adds cryptography as a dependency. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 7 ++ netbox_slm/api/serializers.py | 11 ++ netbox_slm/certificate_parser.py | 121 +++++++++++++++++++++ netbox_slm/forms/certificate.py | 27 +++++ netbox_slm/locale/de/LC_MESSAGES/django.mo | Bin 11097 -> 12023 bytes netbox_slm/locale/de/LC_MESSAGES/django.po | 15 +++ netbox_slm/tests/test_models.py | 45 ++++++++ pyproject.toml | 1 + 9 files changed, 228 insertions(+) create mode 100644 netbox_slm/certificate_parser.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8347ea6..8641c02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ * Certificate management with type, common name, SANs, issuer, serial number, fingerprint and validity period * Optional certificate assignment to software products, installations, devices, virtual machines and tenants * Separate Certificates menu in the sidebar +* Fill certificate fields automatically from an uploaded PEM or DER file and reject files containing private keys * Daily certificate expiration notifications with the same reminder and email options as licenses * Optional tenant group and tenant assignments for software licenses * German translation for navigation, forms, tables, detail views, choices, and validation messages diff --git a/README.md b/README.md index 842e2a9..9432f79 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,13 @@ stores: - Optional assignment to a software product, installation, device, virtual machine, tenant group and tenant +When a certificate file (PEM or DER) is uploaded, the common name, subject +alternative names, issuer, serial number, SHA-256 fingerprint and validity +period are read from the file and overwrite the corresponding fields. Name and +type are only filled in if they were left empty (the type is derived from the +CA flag and extended key usage). For PEM bundles the first certificate is used. +Files that contain a private key are rejected. + > **Note:** Private keys are intentionally not stored. Keep them in a dedicated > secret store and reference that location through the storage location fields. diff --git a/netbox_slm/api/serializers.py b/netbox_slm/api/serializers.py index 6becda4..3a6c5cb 100644 --- a/netbox_slm/api/serializers.py +++ b/netbox_slm/api/serializers.py @@ -1,8 +1,10 @@ +from django.core.files.uploadedfile import UploadedFile from rest_framework import serializers from rest_framework.serializers import SerializerMethodField, HyperlinkedIdentityField from django.utils.translation import gettext_lazy as _ from netbox.api.serializers import NetBoxModelSerializer +from netbox_slm.certificate_parser import CertificateParseError, apply_certificate_file from netbox_slm.models import ( Certificate, SoftwareProduct, @@ -236,6 +238,7 @@ class CertificateSerializer(NetBoxModelSerializer): "last_updated", ) brief_fields = ("id", "display", "url", "name", "description", "expiration_date") + extra_kwargs = {"name": {"required": False, "allow_blank": True}} def get_display(self, obj): return f"{obj}" @@ -257,6 +260,14 @@ class CertificateSerializer(NetBoxModelSerializer): raise serializers.ValidationError( {"tenant": _("The selected tenant does not belong to the selected tenant group.")} ) + uploaded_file = attrs.get("certificate_file") + if isinstance(uploaded_file, UploadedFile): + try: + apply_certificate_file(attrs, uploaded_file) + except CertificateParseError as error: + raise serializers.ValidationError({"certificate_file": str(error)}) from error + if not attrs.get("name", getattr(self.instance, "name", "")): + raise serializers.ValidationError({"name": _("Enter a name or upload a certificate file.")}) start_date = attrs.get("start_date", getattr(self.instance, "start_date", None)) expiration_date = attrs.get("expiration_date", getattr(self.instance, "expiration_date", None)) if start_date and expiration_date and start_date > expiration_date: diff --git a/netbox_slm/certificate_parser.py b/netbox_slm/certificate_parser.py new file mode 100644 index 0000000..e2113e7 --- /dev/null +++ b/netbox_slm/certificate_parser.py @@ -0,0 +1,121 @@ +"""Extract metadata from uploaded X.509 certificate files (PEM or DER).""" + +from dataclasses import dataclass, field +from datetime import date + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID +from django.utils.translation import gettext_lazy as _ + + +class CertificateParseError(ValueError): + pass + + +@dataclass +class CertificateInfo: + common_name: str = "" + subject_alternative_names: list[str] = field(default_factory=list) + issuer: str = "" + serial_number: str = "" + fingerprint: str = "" + start_date: date | None = None + expiration_date: date | None = None + type: str = "" + + +def _common_name(name): + attributes = name.get_attributes_for_oid(NameOID.COMMON_NAME) + return str(attributes[0].value) if attributes else "" + + +def _format_hex(data): + return ":".join(f"{byte:02X}" for byte in data) + + +def _serial_bytes(serial): + return serial.to_bytes((serial.bit_length() + 7) // 8 or 1, "big") + + +def _guess_type(certificate): + # Values match netbox_slm.models.CertificateTypes + try: + if certificate.extensions.get_extension_for_class(x509.BasicConstraints).value.ca: + return "ca" + except x509.ExtensionNotFound: + pass + try: + usages = set(certificate.extensions.get_extension_for_class(x509.ExtendedKeyUsage).value) + except x509.ExtensionNotFound: + return "" + for oid, value in ( + (ExtendedKeyUsageOID.SERVER_AUTH, "server"), + (ExtendedKeyUsageOID.CODE_SIGNING, "code_signing"), + (ExtendedKeyUsageOID.EMAIL_PROTECTION, "email"), + (ExtendedKeyUsageOID.CLIENT_AUTH, "client"), + ): + if oid in usages: + return value + return "" + + +def parse_certificate(data: bytes) -> CertificateInfo: + """Parse the first certificate of a PEM or DER file. Files containing private keys are rejected.""" + if b"PRIVATE KEY" in data: + raise CertificateParseError( + _("The file contains a private key. Please upload only the certificate without its private key.") + ) + try: + if b"-----BEGIN CERTIFICATE-----" in data: + certificate = x509.load_pem_x509_certificates(data)[0] + else: + certificate = x509.load_der_x509_certificate(data) + except ValueError as error: + raise CertificateParseError( + _("The file is not a valid PEM or DER encoded X.509 certificate.") + ) from error + + sans = [] + try: + extension = certificate.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + sans += extension.get_values_for_type(x509.DNSName) + sans += [str(address) for address in extension.get_values_for_type(x509.IPAddress)] + except x509.ExtensionNotFound: + pass + + issuer = _common_name(certificate.issuer) or certificate.issuer.rfc4514_string() + return CertificateInfo( + common_name=_common_name(certificate.subject), + subject_alternative_names=sans, + issuer=issuer[:255], + serial_number=_format_hex(_serial_bytes(certificate.serial_number)), + fingerprint=_format_hex(certificate.fingerprint(hashes.SHA256())), + start_date=certificate.not_valid_before_utc.date(), + expiration_date=certificate.not_valid_after_utc.date(), + type=_guess_type(certificate), + ) + + +def apply_certificate_file(values: dict, uploaded_file) -> None: + """ + Fill certificate fields in ``values`` (form cleaned_data or serializer attrs) from an uploaded file. + + Fields derived from the certificate are overwritten so they always match the uploaded file. Name and type + are only set when they were left empty. + """ + uploaded_file.seek(0) + info = parse_certificate(uploaded_file.read()) + uploaded_file.seek(0) + + values["common_name"] = info.common_name + values["subject_alternative_names"] = "\n".join(info.subject_alternative_names) + values["issuer"] = info.issuer + values["serial_number"] = info.serial_number + values["fingerprint"] = info.fingerprint + values["start_date"] = info.start_date + values["expiration_date"] = info.expiration_date + if not values.get("name"): + values["name"] = info.common_name or info.fingerprint[:23] + if not values.get("type") and info.type: + values["type"] = info.type diff --git a/netbox_slm/forms/certificate.py b/netbox_slm/forms/certificate.py index b7969d2..05ff20f 100644 --- a/netbox_slm/forms/certificate.py +++ b/netbox_slm/forms/certificate.py @@ -1,8 +1,10 @@ +from django.core.files.uploadedfile import UploadedFile from django.forms import CharField, ChoiceField, DateField, IntegerField, MultipleChoiceField, Textarea from django.utils.translation import gettext_lazy as _ from dcim.models import Device from netbox.forms import NetBoxModelForm, NetBoxModelFilterSetForm, NetBoxModelImportForm, NetBoxModelBulkEditForm +from netbox_slm.certificate_parser import CertificateParseError, apply_certificate_file from netbox_slm.models import ( Certificate, CertificateTypes, @@ -27,6 +29,12 @@ from virtualization.models import VirtualMachine class CertificateForm(NetBoxModelForm): comments = CommentField() + name = CharField( + required=False, + max_length=128, + label=_("Name"), + help_text=_("Taken from the certificate's common name if left empty"), + ) fieldsets = ( FieldSet("name", "description", "type", name=_("Certificate")), FieldSet("software_product", "installation", "device", "virtualmachine", name=_("Assignment")), @@ -99,6 +107,25 @@ class CertificateForm(NetBoxModelForm): label=_("Tenant"), ) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["certificate_file"].help_text = _( + "PEM or DER file without private key. Common name, SANs, issuer, serial number, fingerprint and " + "validity are filled in automatically." + ) + + def clean(self): + cleaned_data = super().clean() + uploaded_file = cleaned_data.get("certificate_file") + if isinstance(uploaded_file, UploadedFile): + try: + apply_certificate_file(cleaned_data, uploaded_file) + except CertificateParseError as error: + self.add_error("certificate_file", error) + if not cleaned_data.get("name") and "name" not in self.errors: + self.add_error("name", _("Enter a name or upload a certificate file.")) + return cleaned_data + class Meta: model = Certificate fields = ( diff --git a/netbox_slm/locale/de/LC_MESSAGES/django.mo b/netbox_slm/locale/de/LC_MESSAGES/django.mo index ffc67b809c4794c7b16b213d1f67cca3772669d7..6ae8d7451943b63f2f5f8c6a554561e10e13cf6f 100644 GIT binary patch delta 3913 zcmZ|RdvF!y9mesuBwWKq5F&z2UXW`@(m0rK5i~#|BEd^2Vr}BgA!kpr=A1onb`Lb7 zv$Zn43`}*(AUaq(U|}FrQ8_~|kaj9*Ym0wCr>$11g-$z8M`)|Gofg`m{XTm(5IR#P zw$MM{EVJSY2RT$zd>_wIe&Cj{`6a(+0792Cim`OMdC*lIU0b7t)Ogj$8 z$Kv}OvXBW;^R}ZB*^A5Y2dDtdSYs++DC+$gIE?*G9Ty`QSb&PS5pTv;)PiYLU|&FO z{2cOQUgDQBdIcxruW=lH9N&L}8}>F+Q0vdZVR#!Vk%hQ`{Y^6$dhyBlh3z)|* z+>g`n9BQE$$E5hBjkcgN-iDh0Eb?Ps;8&>9^m3sWUqwaO zhZ^t4A^1~Vi*MomSV@`mJc~DBfVbifoP)37YJ3-UHfEB|Hk^lZ^&A!OnF-Wi8GOiq zN_YjCV{T$l0nLqVK$Ut05`*!u9>e(gQRK&*;FlJD8yDgSxCSdZNUCrKRe`Ojb+%2U z{_JUXG4M$|h}HO$_=Ug5Ls0Pzx?cwd7t@MIJ;2{3tfyrr3kn#{F4bic9E=PXFV$3i~ix zpDeUr8Ae}CITzY!I<{gJszgtsGW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