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 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-21 14:16:58 +02:00
1 parent f296a576f2
commit 2a41118e8e
9 files changed
+228

No files matched your search

+11
View File
@@ -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:
+121
View File
@@ -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
+27
View File
@@ -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 = (
Binary file not shown.
@@ -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."
+45
View File
@@ -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"))