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 ffc67b8..6ae8d74 100644 Binary files a/netbox_slm/locale/de/LC_MESSAGES/django.mo and b/netbox_slm/locale/de/LC_MESSAGES/django.mo differ diff --git a/netbox_slm/locale/de/LC_MESSAGES/django.po b/netbox_slm/locale/de/LC_MESSAGES/django.po index 8382b54..9acb8fc 100644 --- a/netbox_slm/locale/de/LC_MESSAGES/django.po +++ b/netbox_slm/locale/de/LC_MESSAGES/django.po @@ -546,3 +546,18 @@ msgstr "Common Name: %(name)s" msgid "Issuer: %(issuer)s" msgstr "Aussteller: %(issuer)s" + +msgid "Taken from the certificate's common name if left empty" +msgstr "Wird aus dem Common Name des Zertifikats übernommen, wenn leer" + +msgid "Enter a name or upload a certificate file." +msgstr "Bitte einen Namen eingeben oder eine Zertifikatsdatei hochladen." + +msgid "PEM or DER file without private key. Common name, SANs, issuer, serial number, fingerprint and validity are filled in automatically." +msgstr "PEM- oder DER-Datei ohne privaten Schlüssel. Common Name, SANs, Aussteller, Seriennummer, Fingerabdruck und Gültigkeit werden automatisch ausgefüllt." + +msgid "The file contains a private key. Please upload only the certificate without its private key." +msgstr "Die Datei enthält einen privaten Schlüssel. Bitte nur das Zertifikat ohne privaten Schlüssel hochladen." + +msgid "The file is not a valid PEM or DER encoded X.509 certificate." +msgstr "Die Datei ist kein gültiges PEM- oder DER-kodiertes X.509-Zertifikat." diff --git a/netbox_slm/tests/test_models.py b/netbox_slm/tests/test_models.py index fc7bc85..132a5d1 100644 --- a/netbox_slm/tests/test_models.py +++ b/netbox_slm/tests/test_models.py @@ -277,6 +277,51 @@ class CertificateTestCase(SlmBaseTestCase): self.assertEqual(1, send_mail.call_count) self.assertIn("expiring.example.com", send_mail.call_args.args[1]) + def test_certificate_form_fills_fields_from_uploaded_file(self): + import datetime + + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.x509.oid import NameOID + from django.core.files.uploadedfile import SimpleUploadedFile + + from netbox_slm.forms import CertificateForm + + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "upload.example.com")]) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(1234) + .not_valid_before(datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)) + .not_valid_after(datetime.datetime(2027, 1, 1, tzinfo=datetime.UTC)) + .add_extension(x509.SubjectAlternativeName([x509.DNSName("upload.example.com")]), critical=False) + .sign(key, hashes.SHA256()) + ) + upload = SimpleUploadedFile("cert.pem", certificate.public_bytes(serialization.Encoding.PEM)) + + form = CertificateForm(data={}, files={"certificate_file": upload}) + form.is_valid() + + self.assertNotIn("name", form.errors) + self.assertNotIn("certificate_file", form.errors) + self.assertEqual("upload.example.com", form.cleaned_data["name"]) + self.assertEqual("upload.example.com", form.cleaned_data["subject_alternative_names"]) + self.assertEqual(datetime.date(2027, 1, 1), form.cleaned_data["expiration_date"]) + + def test_certificate_form_rejects_private_key(self): + from django.core.files.uploadedfile import SimpleUploadedFile + + from netbox_slm.forms import CertificateForm + + upload = SimpleUploadedFile("key.pem", b"-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----\n") + form = CertificateForm(data={"name": "with key"}, files={"certificate_file": upload}) + self.assertFalse(form.is_valid()) + self.assertIn("certificate_file", form.errors) + def test_german_translation(self): with override("de"): self.assertEqual("Zertifikate", gettext("Certificates")) diff --git a/pyproject.toml b/pyproject.toml index ca92a92..816c887 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,6 +32,7 @@ classifiers = [ "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ] dependencies = [ + "cryptography >= 41.0", "license-expression == 30.4.4", ]