8 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 0a81a04746 docs: state fork, original authors and Apache 2.0 license
Follow the attribution requirements of the Apache License 2.0 for this fork of
ICTU/netbox_slm:

- add a NOTICE file with the original copyright (ICTU) and the fork's notice
- mark every file changed since upstream 1.9.0 as modified (section 4b);
  the original copyright header in __init__.py is kept
- add a visible fork notice and a section on origin, credits, changes and
  license to the README
- point project URLs to this fork (with an Upstream link), list ICTU as
  author and MrBlake as maintainer, and stop showing ICTU's email address
  as the plugin contact
- ship NOTICE in the package and drop the MANIFEST entry for the removed
  SECURITY.md

Bump version to 1.14.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 15:52:13 +01:00
MrBlake 0f72a53d01 Merge branch 'master' of https://git.mrblake.cc/MrBlake/NetBox-SLM 2026-11-04 14:32:28 +01:00
MrBlakeandClaude Opus 5.5 30d748969f fix: shorten email permission codenames to fit NetBox action limit
NetBox ObjectPermission actions are limited to 30 characters, so assigning
manage_softwarelicense_email_notifications or
manage_certificate_email_notifications to a group failed validation.
Rename them to manage_license_emails and manage_certificate_emails and
migrate existing auth permissions in place to keep assignments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 14:32:23 +01:00
MrBlakeandClaude Opus 5.5 9acf685b34 docs: add screenshots and generalise README
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:58:14 +01:00
MrBlakeandClaude Opus 5.5 5dedfc9206 fix: handle None from NetBox form clean() in certificate form
NetBox 4.7 form mixins return None from clean(), which crashed adding a
certificate with AttributeError. Use self.cleaned_data instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 15:02:28 +02:00
MrBlakeandClaude Opus 5.5 2a41118e8e 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]>
2026-10-21 14:16:58 +02:00
MrBlakeandClaude Opus 5.5 f296a576f2 feat: show certificates in a separate sidebar menu
NetBox loads only one menu per plugin, so the certificate menu is
registered explicitly in SLMConfig.ready(). Without top_level_menu the
certificate entry stays in the shared plugin menu items.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 14:11:17 +02:00
MrBlakeandClaude Opus 5.5 c4c93c5709 fix: drop nonexistent squashed migration dependencies from certificate migration
NetBox squashed its app migrations, so ('virtualization', '0001_initial') and
similar nodes no longer exist. The required dcim, extras, tenancy and
virtualization tables are already guaranteed through earlier netbox_slm
migrations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 14:08:26 +02:00
39 changed files with 426 additions and 28 deletions

No files matched your search

+10
View File
@@ -1,7 +1,15 @@
<!-- Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. -->
# Changelog # Changelog
## [Unreleased] ## [Unreleased]
### Changed
* State the fork, the original authors and the Apache 2.0 license clearly in the README and a new NOTICE file
* Mark files changed in this fork as modified (Apache License 2.0, section 4b)
* Point project URLs to this fork and list ICTU as original author and MrBlake as maintainer
### Fixed ### Fixed
* Add the missing migration for the platform constraint's error message (verified against NetBox 4.7.2) * Add the missing migration for the platform constraint's error message (verified against NetBox 4.7.2)
@@ -15,6 +23,8 @@
* Certificate management with type, common name, SANs, issuer, serial number, fingerprint and validity period * 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 * 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 * Daily certificate expiration notifications with the same reminder and email options as licenses
* Optional tenant group and tenant assignments for software licenses * Optional tenant group and tenant assignments for software licenses
* German translation for navigation, forms, tables, detail views, choices, and validation messages * German translation for navigation, forms, tables, detail views, choices, and validation messages
+1 -1
View File
@@ -1,6 +1,6 @@
include LICENSE include LICENSE
include NOTICE
include README.md include README.md
include SECURITY.md
graft netbox_slm graft netbox_slm
prune netbox_slm/tests prune netbox_slm/tests
global-exclude *.py[cod] global-exclude *.py[cod]
+16
View File
@@ -0,0 +1,16 @@
NetBox SLM (fork)
Copyright 2022-2025 ICTU
Modifications Copyright 2026 MrBlake
This product is a modified version of NetBox SLM by ICTU
(https://github.com/ICTU/netbox_slm), based on its release 1.9.0.
The original work is licensed under the Apache License, Version 2.0. The
modifications are distributed under the same license; see the LICENSE file.
Files that were changed in this fork carry a notice stating that they were
modified. The complete history, including all original commits, is available at
https://git.mrblake.cc/MrBlake/NetBox-SLM
This fork is maintained independently and is not affiliated with or endorsed
by ICTU.
+49 -10
View File
@@ -4,6 +4,10 @@ Software lifecycle and license management for NetBox: software products,
versions, installations, licenses and certificates — with expiry notifications versions, installations, licenses and certificates — with expiry notifications
and optional tenant assignment. and optional tenant assignment.
> **Fork notice:** This is a modified version of [NetBox SLM](https://github.com/ICTU/netbox_slm)
> by **ICTU**, licensed under the [Apache License 2.0](LICENSE). It is maintained independently
> and is not affiliated with or endorsed by ICTU. See [Origin, license and credits](#origin-license-and-credits).
| | | | | |
|---|---| |---|---|
| **Plugin name** | `netbox_slm` | | **Plugin name** | `netbox_slm` |
@@ -12,6 +16,20 @@ and optional tenant assignment.
| **Python** | `>=3.11` | | **Python** | `>=3.11` |
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-SLM> | | **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-SLM> |
## Screenshots
Software licenses with expiry dates:
![Software licenses with expiry dates](docs/screenshots/licenses.png)
Certificates:
![Certificates](docs/screenshots/certificates.png)
Software installations on devices and virtual machines:
![Software installations on devices and virtual machines](docs/screenshots/installations.png)
## Features ## Features
- Manage software products and manufacturers - Manage software products and manufacturers
@@ -149,8 +167,8 @@ on the license, the plugin also sends an e-mail to the address stored in the
user account; NetBox SMTP must be configured for this. user account; NetBox SMTP must be configured for this.
Enabling e-mail delivery can only be changed by administrators or users with Enabling e-mail delivery can only be changed by administrators or users with
the permission `netbox_slm.manage_softwarelicense_email_notifications` the permission `netbox_slm.manage_license_emails`
(licenses) or `netbox_slm.manage_certificate_email_notifications` (licenses) or `netbox_slm.manage_certificate_emails`
(certificates). SMTP (certificates). SMTP
credentials are maintained only in the NetBox server configuration and are not credentials are maintained only in the NetBox server configuration and are not
visible in the plugin. visible in the plugin.
@@ -175,6 +193,13 @@ stores:
- Optional assignment to a software product, installation, device, virtual - Optional assignment to a software product, installation, device, virtual
machine, tenant group and tenant 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 > **Note:** Private keys are intentionally not stored. Keep them in a dedicated
> secret store and reference that location through the storage location fields. > secret store and reference that location through the storage location fields.
@@ -183,15 +208,29 @@ and can be filtered by e.g. `type`, `common_name`, `issuer`, `device_id`,
`virtualmachine_id`, `tenant_id`, `expiration_date__lte` and `virtualmachine_id`, `tenant_id`, `expiration_date__lte` and
`expiration_date__gte`. `expiration_date__gte`.
## Origin and license ## Origin, license and credits
This repository is based on the original project **Original project:** [NetBox SLM](https://github.com/ICTU/netbox_slm) by **ICTU**
[ICTU/netbox_slm](https://github.com/ICTU/netbox_slm). **ICTU** is the original (Copyright 2022-2025 ICTU). The original plugin was started by Hedde van der Heide
author and publisher; [Mart Visser](https://github.com/MartVisser) is named as and developed by ICTU and its contributors; [Mart Visser](https://github.com/MartVisser)
the contact in the original project. is named as the contact of the original project. This fork is based on release 1.9.0,
and the complete original commit history is retained in this repository.
The changes in this fork are maintained at **This fork:** maintained by MrBlake at
[git.mrblake.cc/MrBlake/NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM). [git.mrblake.cc/MrBlake/NetBox-SLM](https://git.mrblake.cc/MrBlake/NetBox-SLM).
It is not affiliated with or endorsed by ICTU. Please report problems with this fork
[here](https://git.mrblake.cc/MrBlake/NetBox-SLM/issues), not to the original project.
Licensed under the [Apache License 2.0](LICENSE). Notices of the original **Main changes compared to the original** (details in [CHANGELOG.md](CHANGELOG.md)):
authors are retained.
- Certificate management with expiry reminders and import from PEM/DER files
- Tenant group and tenant assignment for licenses
- Renewal intervals, license files, license keys and vendor portal links
- License expiry notifications in NetBox and optionally by email
- German translation
- Support for NetBox 4.6 and 4.7, installation via Git/pip instead of Docker
**License:** The original work and all modifications are licensed under the
[Apache License, Version 2.0](LICENSE). The [NOTICE](NOTICE) file lists the copyright
holders. The original copyright and license notices are retained, and every file
changed in this fork carries a notice stating that it was modified.
Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

+9 -3
View File
@@ -1,5 +1,6 @@
""" """
Copyright 2022-2025 ICTU Copyright 2022-2025 ICTU
Modifications Copyright 2026 MrBlake (NetBox-SLM fork, https://git.mrblake.cc/MrBlake/NetBox-SLM)
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@@ -17,7 +18,7 @@ limitations under the License.
from netbox.plugins import PluginConfig from netbox.plugins import PluginConfig
from django.utils.translation import gettext, gettext_lazy as _ from django.utils.translation import gettext, gettext_lazy as _
__version__ = "1.14.0" __version__ = "1.14.1"
class SLMConfig(PluginConfig): class SLMConfig(PluginConfig):
@@ -25,8 +26,7 @@ class SLMConfig(PluginConfig):
verbose_name = _("Licences") verbose_name = _("Licences")
version = __version__ version = __version__
description = _("Licence Management NetBox Plugin.") description = _("Licence Management NetBox Plugin.")
author = "ICTU" author = "ICTU (original), MrBlake (fork)"
author_email = "[email protected]"
base_url = "slm" base_url = "slm"
required_settings = [] required_settings = []
default_settings = { default_settings = {
@@ -47,5 +47,11 @@ class SLMConfig(PluginConfig):
from netbox_slm import jobs # noqa: F401 from netbox_slm import jobs # noqa: F401
from netbox.plugins.registration import register_menu
from netbox_slm import navigation
if hasattr(navigation, "certificate_menu"):
register_menu(navigation.certificate_menu)
config = SLMConfig config = SLMConfig
+15 -2
View File
@@ -1,8 +1,12 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.core.files.uploadedfile import UploadedFile
from rest_framework import serializers from rest_framework import serializers
from rest_framework.serializers import SerializerMethodField, HyperlinkedIdentityField from rest_framework.serializers import SerializerMethodField, HyperlinkedIdentityField
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from netbox.api.serializers import NetBoxModelSerializer from netbox.api.serializers import NetBoxModelSerializer
from netbox_slm.certificate_parser import CertificateParseError, apply_certificate_file
from netbox_slm.models import ( from netbox_slm.models import (
Certificate, Certificate,
SoftwareProduct, SoftwareProduct,
@@ -64,7 +68,7 @@ class SoftwareLicenseSerializer(NetBoxModelSerializer):
if ( if (
"email_notifications" in attrs "email_notifications" in attrs
and request is not None and request is not None
and not request.user.has_perm("netbox_slm.manage_softwarelicense_email_notifications") and not request.user.has_perm("netbox_slm.manage_license_emails")
): ):
raise serializers.ValidationError( raise serializers.ValidationError(
{"email_notifications": _("You do not have permission to change email notifications.")} {"email_notifications": _("You do not have permission to change email notifications.")}
@@ -236,6 +240,7 @@ class CertificateSerializer(NetBoxModelSerializer):
"last_updated", "last_updated",
) )
brief_fields = ("id", "display", "url", "name", "description", "expiration_date") brief_fields = ("id", "display", "url", "name", "description", "expiration_date")
extra_kwargs = {"name": {"required": False, "allow_blank": True}}
def get_display(self, obj): def get_display(self, obj):
return f"{obj}" return f"{obj}"
@@ -245,7 +250,7 @@ class CertificateSerializer(NetBoxModelSerializer):
if ( if (
"email_notifications" in attrs "email_notifications" in attrs
and request is not None and request is not None
and not request.user.has_perm("netbox_slm.manage_certificate_email_notifications") and not request.user.has_perm("netbox_slm.manage_certificate_emails")
): ):
raise serializers.ValidationError( raise serializers.ValidationError(
{"email_notifications": _("You do not have permission to change email notifications.")} {"email_notifications": _("You do not have permission to change email notifications.")}
@@ -257,6 +262,14 @@ class CertificateSerializer(NetBoxModelSerializer):
raise serializers.ValidationError( raise serializers.ValidationError(
{"tenant": _("The selected tenant does not belong to the selected tenant group.")} {"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)) start_date = attrs.get("start_date", getattr(self.instance, "start_date", None))
expiration_date = attrs.get("expiration_date", getattr(self.instance, "expiration_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: if start_date and expiration_date and start_date > expiration_date:
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from netbox.api.routers import NetBoxRouter from netbox.api.routers import NetBoxRouter
from netbox_slm.api.views import ( from netbox_slm.api.views import (
NetboxSLMRootView, NetboxSLMRootView,
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from rest_framework.routers import APIRootView from rest_framework.routers import APIRootView
from netbox.api.viewsets import NetBoxModelViewSet from netbox.api.viewsets import NetBoxModelViewSet
+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
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.db.models import Q from django.db.models import Q
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django_filters import CharFilter, DateFilter, ModelMultipleChoiceFilter, MultipleChoiceFilter, NumberFilter from django_filters import CharFilter, DateFilter, ModelMultipleChoiceFilter, MultipleChoiceFilter, NumberFilter
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from .software_license import ( from .software_license import (
SoftwareLicenseForm, SoftwareLicenseForm,
SoftwareLicenseFilterForm, SoftwareLicenseFilterForm,
+29
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.forms import CharField, ChoiceField, DateField, IntegerField, MultipleChoiceField, Textarea
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from dcim.models import Device from dcim.models import Device
from netbox.forms import NetBoxModelForm, NetBoxModelFilterSetForm, NetBoxModelImportForm, NetBoxModelBulkEditForm from netbox.forms import NetBoxModelForm, NetBoxModelFilterSetForm, NetBoxModelImportForm, NetBoxModelBulkEditForm
from netbox_slm.certificate_parser import CertificateParseError, apply_certificate_file
from netbox_slm.models import ( from netbox_slm.models import (
Certificate, Certificate,
CertificateTypes, CertificateTypes,
@@ -27,6 +29,12 @@ from virtualization.models import VirtualMachine
class CertificateForm(NetBoxModelForm): class CertificateForm(NetBoxModelForm):
comments = CommentField() comments = CommentField()
name = CharField(
required=False,
max_length=128,
label=_("Name"),
help_text=_("Taken from the certificate's common name if left empty"),
)
fieldsets = ( fieldsets = (
FieldSet("name", "description", "type", name=_("Certificate")), FieldSet("name", "description", "type", name=_("Certificate")),
FieldSet("software_product", "installation", "device", "virtualmachine", name=_("Assignment")), FieldSet("software_product", "installation", "device", "virtualmachine", name=_("Assignment")),
@@ -99,6 +107,27 @@ class CertificateForm(NetBoxModelForm):
label=_("Tenant"), 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):
# NetBox form mixins may return None from clean(), so always use self.cleaned_data
super().clean()
cleaned_data = self.cleaned_data
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: class Meta:
model = Certificate model = Certificate
fields = ( fields = (
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.forms import CharField, DateField, ChoiceField, IntegerField, NullBooleanField, Textarea from django.forms import CharField, DateField, ChoiceField, IntegerField, NullBooleanField, Textarea
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.forms import CharField from django.forms import CharField
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.forms import ValidationError from django.forms import ValidationError
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.forms import DateField, CharField, MultipleChoiceField from django.forms import DateField, CharField, MultipleChoiceField
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
Binary file not shown.
@@ -546,3 +546,18 @@ msgstr "Common Name: %(name)s"
msgid "Issuer: %(issuer)s" msgid "Issuer: %(issuer)s"
msgstr "Aussteller: %(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."
@@ -11,10 +11,6 @@ import utilities.json
class Migration(migrations.Migration): class Migration(migrations.Migration):
dependencies = [ dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL), migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("dcim", "0001_initial"),
("extras", "0001_initial"),
("tenancy", "0001_initial"),
("virtualization", "0001_initial"),
("netbox_slm", "0015_platform_constraint_message"), ("netbox_slm", "0015_platform_constraint_message"),
] ]
@@ -0,0 +1,48 @@
from django.db import migrations
# NetBox ObjectPermission actions are limited to 30 characters.
RENAMES = [
("softwarelicense", "manage_softwarelicense_email_notifications", "manage_license_emails"),
("certificate", "manage_certificate_email_notifications", "manage_certificate_emails"),
]
def rename_permissions(apps, schema_editor, reverse=False):
Permission = apps.get_model("auth", "Permission")
for model, old, new in RENAMES:
if reverse:
old, new = new, old
Permission.objects.filter(content_type__app_label="netbox_slm", content_type__model=model, codename=old).update(
codename=new
)
def reverse_rename_permissions(apps, schema_editor):
rename_permissions(apps, schema_editor, reverse=True)
class Migration(migrations.Migration):
dependencies = [
("auth", "0001_initial"),
("netbox_slm", "0016_certificate"),
]
operations = [
migrations.AlterModelOptions(
name="softwarelicense",
options={
"permissions": [("manage_license_emails", "Can manage license email notifications")],
"verbose_name": "software license",
"verbose_name_plural": "software licenses",
},
),
migrations.AlterModelOptions(
name="certificate",
options={
"permissions": [("manage_certificate_emails", "Can manage certificate email notifications")],
"verbose_name": "certificate",
"verbose_name_plural": "certificates",
},
),
migrations.RunPython(rename_permissions, reverse_rename_permissions),
]
+4 -2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
import calendar import calendar
from datetime import timedelta from datetime import timedelta
@@ -327,7 +329,7 @@ class SoftwareLicense(NetBoxModel, ExpirationNotificationModel):
verbose_name = _("software license") verbose_name = _("software license")
verbose_name_plural = _("software licenses") verbose_name_plural = _("software licenses")
permissions = [ permissions = [
("manage_softwarelicense_email_notifications", _("Can manage license email notifications")), ("manage_license_emails", _("Can manage license email notifications")),
] ]
def __str__(self): def __str__(self):
@@ -459,7 +461,7 @@ class Certificate(NetBoxModel, ExpirationNotificationModel):
verbose_name = _("certificate") verbose_name = _("certificate")
verbose_name_plural = _("certificates") verbose_name_plural = _("certificates")
permissions = [ permissions = [
("manage_certificate_email_notifications", _("Can manage certificate email notifications")), ("manage_certificate_emails", _("Can manage certificate email notifications")),
] ]
def __str__(self): def __str__(self):
+12 -1
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from netbox.plugins import PluginMenuButton, PluginMenuItem, PluginMenu, get_plugin_config from netbox.plugins import PluginMenuButton, PluginMenuItem, PluginMenu, get_plugin_config
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from . import SLMConfig from . import SLMConfig
@@ -79,6 +81,9 @@ slm_items = (
), ),
), ),
), ),
)
certificate_items = (
PluginMenuItem( PluginMenuItem(
link="plugins:netbox_slm:certificate_list", link="plugins:netbox_slm:certificate_list",
link_text=_("Certificates"), link_text=_("Certificates"),
@@ -106,6 +111,12 @@ if get_plugin_config("netbox_slm", "top_level_menu"):
groups=((SLMConfig.verbose_name, slm_items),), groups=((SLMConfig.verbose_name, slm_items),),
icon_class="mdi mdi-content-save", icon_class="mdi mdi-content-save",
) )
# NetBox loads only one menu per plugin; this one is registered in SLMConfig.ready()
certificate_menu = PluginMenu(
label=_("Certificates"),
groups=((_("Certificates"), certificate_items),),
icon_class="mdi mdi-certificate",
)
else: else:
# auto imported by default PluginConfig.menu_items = navigation.menu_items # auto imported by default PluginConfig.menu_items = navigation.menu_items
menu_items = slm_items menu_items = slm_items + certificate_items
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
import django_tables2 as tables import django_tables2 as tables
from django.db.models import Count, F, Value from django.db.models import Count, F, Value
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
@@ -1,3 +1,5 @@
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
{% load helpers %} {% load helpers %}
{% load i18n %} {% load i18n %}
@@ -1,3 +1,5 @@
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load buttons %} {% load buttons %}
{% load static %} {% load static %}
@@ -1,3 +1,5 @@
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load buttons %} {% load buttons %}
{% load static %} {% load static %}
@@ -1,3 +1,5 @@
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load buttons %} {% load buttons %}
{% load static %} {% load static %}
@@ -1,3 +1,5 @@
{# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM #}
{# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files. #}
{% extends 'generic/object.html' %} {% extends 'generic/object.html' %}
{% load buttons %} {% load buttons %}
{% load static %} {% load static %}
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.test import TestCase from django.test import TestCase
from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site from dcim.models import Device, DeviceRole, DeviceType, Manufacturer, Site
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from unittest.mock import patch from unittest.mock import patch
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
+47
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from datetime import date, timedelta from datetime import date, timedelta
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@@ -277,6 +279,51 @@ class CertificateTestCase(SlmBaseTestCase):
self.assertEqual(1, send_mail.call_count) self.assertEqual(1, send_mail.call_count)
self.assertIn("expiring.example.com", send_mail.call_args.args[1]) 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): def test_german_translation(self):
with override("de"): with override("de"):
self.assertEqual("Zertifikate", gettext("Certificates")) self.assertEqual("Zertifikate", gettext("Certificates"))
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from django.urls import path, include from django.urls import path, include
from netbox_slm import views # noqa F401 from netbox_slm import views # noqa F401
+2
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from .software_license import ( from .software_license import (
SoftwareLicenseListView, SoftwareLicenseListView,
SoftwareLicenseView, SoftwareLicenseView,
+1 -1
View File
@@ -6,7 +6,7 @@ from utilities.views import register_model_view
class CertificateEmailNotificationPermissionMixin(EmailNotificationPermissionMixin): class CertificateEmailNotificationPermissionMixin(EmailNotificationPermissionMixin):
email_permission = "netbox_slm.manage_certificate_email_notifications" email_permission = "netbox_slm.manage_certificate_emails"
@register_model_view(Certificate, "list", path="", detail=False) @register_model_view(Certificate, "list", path="", detail=False)
+3 -1
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
from netbox.views import generic from netbox.views import generic
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from netbox_slm import filtersets, forms, tables from netbox_slm import filtersets, forms, tables
@@ -8,7 +10,7 @@ from utilities.views import register_model_view
class EmailNotificationPermissionMixin: class EmailNotificationPermissionMixin:
"""Prevent users without the dedicated permission from changing SMTP delivery.""" """Prevent users without the dedicated permission from changing SMTP delivery."""
email_permission = "netbox_slm.manage_softwarelicense_email_notifications" email_permission = "netbox_slm.manage_license_emails"
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
form_attribute = "model_form" if hasattr(self, "model_form") else "form" form_attribute = "model_form" if hasattr(self, "model_form") else "form"
+10 -3
View File
@@ -1,3 +1,5 @@
# Modified by MrBlake for the NetBox-SLM fork: https://git.mrblake.cc/MrBlake/NetBox-SLM
# Based on ICTU/netbox_slm (Apache License 2.0). See the LICENSE and NOTICE files.
[build-system] [build-system]
requires = ["setuptools"] requires = ["setuptools"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
@@ -12,6 +14,9 @@ license = { text = "Apache-2.0" }
authors = [ authors = [
{name = "ICTU", email = "[email protected]"}, {name = "ICTU", email = "[email protected]"},
] ]
maintainers = [
{name = "MrBlake"},
]
classifiers = [ classifiers = [
"Development Status :: 5 - Production/Stable", "Development Status :: 5 - Production/Stable",
"Environment :: Plugins", "Environment :: Plugins",
@@ -32,6 +37,7 @@ classifiers = [
"Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
] ]
dependencies = [ dependencies = [
"cryptography >= 41.0",
"license-expression == 30.4.4", "license-expression == 30.4.4",
] ]
@@ -47,9 +53,10 @@ ci = [
] ]
[project.urls] [project.urls]
Homepage = "https://github.com/ICTU/netbox_slm/" Homepage = "https://git.mrblake.cc/MrBlake/NetBox-SLM"
Changelog = "https://github.com/ICTU/netbox_slm/blob/master/CHANGELOG.md" Changelog = "https://git.mrblake.cc/MrBlake/NetBox-SLM/src/branch/master/CHANGELOG.md"
Issues = "https://github.com/ICTU/netbox_slm/issues/" Issues = "https://git.mrblake.cc/MrBlake/NetBox-SLM/issues"
Upstream = "https://github.com/ICTU/netbox_slm"
[tool.setuptools.dynamic] [tool.setuptools.dynamic]
version = {attr = "netbox_slm.__version__"} version = {attr = "netbox_slm.__version__"}