netbox-secrets 3.1.2__tar.gz → 3.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. {netbox_secrets-3.1.2/netbox_secrets.egg-info → netbox_secrets-3.2.0}/PKG-INFO +2 -1
  2. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/README.md +1 -0
  3. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/__init__.py +2 -2
  4. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/serializers_/secrets.py +20 -2
  5. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/forms/model_forms.py +11 -1
  6. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/graphql/filters.py +3 -2
  7. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/graphql/types.py +8 -4
  8. netbox_secrets-3.2.0/netbox_secrets/hashers.py +97 -0
  9. netbox_secrets-3.2.0/netbox_secrets/migrations/0012_ltree_paths.py +142 -0
  10. netbox_secrets-3.2.0/netbox_secrets/migrations/0013_alter_owner_related_name.py +37 -0
  11. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/models/keys.py +4 -4
  12. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/models/secrets.py +19 -12
  13. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/template_content.py +3 -1
  14. netbox_secrets-3.2.0/netbox_secrets/templates/netbox_secrets/secret_data.html +16 -0
  15. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_api.py +190 -1
  16. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_forms.py +115 -0
  17. netbox_secrets-3.2.0/netbox_secrets/tests/test_hashers.py +94 -0
  18. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_models.py +53 -3
  19. netbox_secrets-3.2.0/netbox_secrets/tests/test_template_content.py +66 -0
  20. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_utils.py +5 -1
  21. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_views.py +110 -13
  22. netbox_secrets-3.2.0/netbox_secrets/ui/__init__.py +0 -0
  23. netbox_secrets-3.2.0/netbox_secrets/ui/panels.py +17 -0
  24. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/views.py +57 -9
  25. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0/netbox_secrets.egg-info}/PKG-INFO +2 -1
  26. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets.egg-info/SOURCES.txt +7 -2
  27. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/setup.py +1 -1
  28. netbox_secrets-3.1.2/netbox_secrets/templates/netbox_secrets/secret.html +0 -85
  29. netbox_secrets-3.1.2/netbox_secrets/templates/netbox_secrets/secretrole.html +0 -11
  30. netbox_secrets-3.1.2/netbox_secrets/utils/hashers.py +0 -10
  31. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/LICENSE.md +0 -0
  32. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/MANIFEST.in +0 -0
  33. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/__init__.py +0 -0
  34. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/serializers.py +0 -0
  35. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/serializers_/__init__.py +0 -0
  36. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/serializers_/keys.py +0 -0
  37. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/serializers_/nested.py +0 -0
  38. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/urls.py +0 -0
  39. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/api/views.py +0 -0
  40. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/constants.py +0 -0
  41. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/exceptions.py +0 -0
  42. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/filtersets.py +0 -0
  43. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/forms/__init__.py +0 -0
  44. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/forms/bulk_edit.py +0 -0
  45. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/forms/bulk_import.py +0 -0
  46. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/forms/filterset.py +0 -0
  47. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/graphql/__init__.py +0 -0
  48. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/graphql/schema.py +0 -0
  49. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0001_initial.py +0 -0
  50. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0002_populate_userkeys.py +0 -0
  51. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0003_populate_secretroles.py +0 -0
  52. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0004_populate_secrets.py +0 -0
  53. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0005_alter_secret_custom_field_data_and_more.py +0 -0
  54. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0006_alter_userkey_created_alter_userkey_last_updated.py +0 -0
  55. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0007_secret__object_repr_secret_comments_and_more.py +0 -0
  56. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0008_userkey_custom_field_data_userkey_tags.py +0 -0
  57. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0009_secret_owner_secretrole_level_secretrole_lft_and_more.py +0 -0
  58. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0010_secret_role_rebuild.py +0 -0
  59. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/0011_remove_redundant_indexes.py +0 -0
  60. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/migrations/__init__.py +0 -0
  61. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/models/__init__.py +0 -0
  62. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/navigation.py +0 -0
  63. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/querysets.py +0 -0
  64. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/signals.py +0 -0
  65. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tables.py +0 -0
  66. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/activate_keys.html +0 -0
  67. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/inc/private_key_modal.html +0 -0
  68. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/inc/secret_actions.html +0 -0
  69. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/inc/secret_add_button.html +0 -0
  70. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/inc/secrets_inline_js.html +0 -0
  71. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/inc/secrets_panel.html +0 -0
  72. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/secret_edit.html +0 -0
  73. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/userkey.html +0 -0
  74. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/userkey_edit.html +0 -0
  75. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/templates/netbox_secrets/userkey_list.html +0 -0
  76. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/__init__.py +0 -0
  77. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/constants.py +0 -0
  78. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_filters.py +0 -0
  79. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/tests/test_signals.py +0 -0
  80. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/urls.py +0 -0
  81. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/utils/__init__.py +0 -0
  82. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/utils/crypto.py +0 -0
  83. {netbox_secrets-3.1.2/netbox_secrets → netbox_secrets-3.2.0/netbox_secrets/utils}/hashers.py +0 -0
  84. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets/utils/helpers.py +0 -0
  85. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets.egg-info/dependency_links.txt +0 -0
  86. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets.egg-info/not-zip-safe +0 -0
  87. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets.egg-info/requires.txt +0 -0
  88. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/netbox_secrets.egg-info/top_level.txt +0 -0
  89. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/pyproject.toml +0 -0
  90. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/requirements.txt +0 -0
  91. {netbox_secrets-3.1.2 → netbox_secrets-3.2.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: netbox-secrets
3
- Version: 3.1.2
3
+ Version: 3.2.0
4
4
  Summary: Enhance your secret management with encrypted storage and flexible, user-friendly features.
5
5
  Home-page: https://github.com/Onemind-Services-LLC/netbox-secrets/
6
6
  Author: Abhimanyu Saharan
@@ -58,6 +58,7 @@ with end-to-end encryption. Secrets are encrypted at rest and can be assigned to
58
58
  | 4.4.x | 2.4.x |
59
59
  | 4.5.x | 3.0.x |
60
60
  | 4.6.x | 3.1.x |
61
+ | 4.7.1 | 3.2.x |
61
62
 
62
63
  ## Quickstart
63
64
  - Setup (installation + configuration): [docs/installation.md](docs/installation.md)
@@ -27,6 +27,7 @@ with end-to-end encryption. Secrets are encrypted at rest and can be assigned to
27
27
  | 4.4.x | 2.4.x |
28
28
  | 4.5.x | 3.0.x |
29
29
  | 4.6.x | 3.1.x |
30
+ | 4.7.1 | 3.2.x |
30
31
 
31
32
  ## Quickstart
32
33
  - Setup (installation + configuration): [docs/installation.md](docs/installation.md)
@@ -13,8 +13,8 @@ class NetBoxSecrets(PluginConfig):
13
13
  author = metadata.get('Author')
14
14
  author_email = metadata.get('Author-email')
15
15
  base_url = 'secrets'
16
- min_version = '4.6.0'
17
- max_version = '4.6.99'
16
+ min_version = '4.7.1'
17
+ max_version = '4.7.99'
18
18
  required_settings = []
19
19
  default_settings = {
20
20
  'apps': ['dcim.device', 'virtualization.virtualmachine'],
@@ -48,7 +48,6 @@ class SecretSerializer(PrimaryModelSerializer):
48
48
  assigned_object_type = ContentTypeField(queryset=ObjectType.objects.filter(SECRET_ASSIGNABLE_MODELS))
49
49
  assigned_object = GFKSerializerField(read_only=True)
50
50
  plaintext = serializers.CharField(required=False, help_text="Plaintext secret value (encrypted at rest)")
51
- hash = serializers.CharField(read_only=True, help_text="SHA-256 hash for validation (read-only)")
52
51
 
53
52
  class Meta:
54
53
  model = Secret
@@ -62,7 +61,6 @@ class SecretSerializer(PrimaryModelSerializer):
62
61
  'role',
63
62
  'name',
64
63
  'plaintext',
65
- 'hash',
66
64
  'description',
67
65
  'comments',
68
66
  'tags',
@@ -104,6 +102,26 @@ class SecretSerializer(PrimaryModelSerializer):
104
102
  Raises:
105
103
  ValidationError: If plaintext provided but no master key in context
106
104
  """
105
+ instance = self.instance
106
+ object_type = data.get(
107
+ "assigned_object_type",
108
+ getattr(instance, "assigned_object_type", None),
109
+ )
110
+ object_id = data.get(
111
+ "assigned_object_id",
112
+ getattr(instance, "assigned_object_id", None),
113
+ )
114
+ name = data.get("name", getattr(instance, "name", "")) or ""
115
+ role = data.get("role", getattr(instance, "role", None))
116
+
117
+ duplicates = Secret.objects.filter(
118
+ assigned_object_type_id=object_type.pk,
119
+ assigned_object_id=object_id,
120
+ role=role,
121
+ name=name,
122
+ ).exclude(pk=getattr(instance, "pk", None))
123
+ if duplicates.exists():
124
+ raise serializers.ValidationError({'name': 'A secret with this name already exists for this object.'})
107
125
  plaintext = data.get('plaintext')
108
126
 
109
127
  if plaintext:
@@ -168,7 +168,7 @@ class SecretForm(PrimaryModelForm):
168
168
  return plaintext
169
169
 
170
170
  def clean(self):
171
- """Validate that plaintext values match."""
171
+ """Validate that plaintext values match and the name is unique per assigned object."""
172
172
  super().clean()
173
173
 
174
174
  plaintext = self.cleaned_data.get('plaintext', '')
@@ -178,6 +178,16 @@ class SecretForm(PrimaryModelForm):
178
178
  if plaintext != plaintext2:
179
179
  raise ValidationError({'plaintext2': _("The two secret values do not match. Please check your input.")})
180
180
 
181
+ if self.cleaned_data.get("role") is not None:
182
+ duplicates = Secret.objects.filter(
183
+ assigned_object_type_id=self.instance.assigned_object_type_id,
184
+ assigned_object_id=self.instance.assigned_object_id,
185
+ role=self.cleaned_data.get("role"),
186
+ name=self.cleaned_data.get("name") or "",
187
+ ).exclude(pk=self.instance.pk)
188
+ if duplicates.exists():
189
+ raise ValidationError({'name': _("A secret with this name already exists for this object.")})
190
+
181
191
  return self.cleaned_data
182
192
 
183
193
 
@@ -8,6 +8,7 @@ from strawberry_django import StrFilterLookup
8
8
  from netbox.graphql.filters import (
9
9
  OrganizationalModelFilter,
10
10
  PrimaryModelFilter,
11
+ register_filter,
11
12
  )
12
13
  from tenancy.graphql.filter_mixins import ContactFilterMixin
13
14
  from ..models import *
@@ -21,7 +22,7 @@ __all__ = [
21
22
  ]
22
23
 
23
24
 
24
- @strawberry_django.filter_type(SecretRole, lookups=True)
25
+ @register_filter(SecretRole, lookups=True)
25
26
  class SecretRoleFilter(OrganizationalModelFilter):
26
27
  parent: Annotated[
27
28
  'SecretRoleFilter', strawberry.lazy('netbox_secrets.graphql.filters')
@@ -35,7 +36,7 @@ class SecretRoleFilter(OrganizationalModelFilter):
35
36
  ] | None = strawberry_django.filter_field()
36
37
 
37
38
 
38
- @strawberry_django.filter_type(Secret, lookups=True)
39
+ @register_filter(Secret, lookups=True)
39
40
  class SecretFilter(PrimaryModelFilter, ContactFilterMixin):
40
41
  name: StrFilterLookup[str] | None = strawberry_django.filter_field()
41
42
  role: Annotated[
@@ -5,7 +5,11 @@ import strawberry_django
5
5
  from strawberry.scalars import ID
6
6
 
7
7
  from extras.graphql.mixins import ContactsMixin
8
- from netbox.graphql.types import NestedGroupObjectType, PrimaryObjectType
8
+ from netbox.graphql.types import (
9
+ NestedLtreeGroupObjectType,
10
+ PrimaryObjectType,
11
+ register_type,
12
+ )
9
13
  from netbox_secrets.models import Secret, SecretRole
10
14
  from .filters import *
11
15
 
@@ -18,7 +22,7 @@ __all__ = [
18
22
  ]
19
23
 
20
24
 
21
- @strawberry_django.type(Secret, exclude=['ciphertext', 'hash', 'plaintext'], filters=SecretFilter, pagination=True)
25
+ @register_type(Secret, exclude=['ciphertext', 'hash', 'plaintext'], filters=SecretFilter, pagination=True)
22
26
  class SecretType(ContactsMixin, PrimaryObjectType):
23
27
  role: Annotated['SecretRoleType', strawberry.lazy('netbox_secrets.graphql.types')]
24
28
  assigned_object_type: Annotated[
@@ -28,8 +32,8 @@ class SecretType(ContactsMixin, PrimaryObjectType):
28
32
  assigned_object_id: ID | None = strawberry_django.filter_field()
29
33
 
30
34
 
31
- @strawberry_django.type(SecretRole, fields="__all__", filters=SecretRoleFilter, pagination=True)
32
- class SecretRoleType(NestedGroupObjectType):
35
+ @register_type(SecretRole, exclude=['path', 'sort_path'], filters=SecretRoleFilter, pagination=True)
36
+ class SecretRoleType(NestedLtreeGroupObjectType):
33
37
  parent: Annotated['SecretRoleType', strawberry.lazy('netbox_secrets.graphql.types')] | None
34
38
 
35
39
  secrets: List[SecretType]
@@ -0,0 +1,97 @@
1
+ import hashlib
2
+ import hmac
3
+ import secrets as secrets_module
4
+ import warnings
5
+
6
+ from django.contrib.auth.hashers import PBKDF2PasswordHasher, check_password
7
+
8
+ __all__ = [
9
+ 'SecretValidationHasher',
10
+ 'make_session_key_hash',
11
+ 'check_session_key_hash',
12
+ 'make_secret_hash',
13
+ 'check_secret_hash',
14
+ ]
15
+
16
+ SESSION_KEY_HASH_PREFIX = 'sha256$'
17
+ SECRET_HASH_PREFIX = 'hmac_sha256$'
18
+ SECRET_HASH_SALT_BYTES = 16
19
+
20
+
21
+ # TODO: Remove the legacy (PBKDF2) secret hash support in NetBox v4.8: ``SecretValidationHasher`` and the legacy branch
22
+ # of ``check_secret_hash``.
23
+ LEGACY_HASH_WARNING = (
24
+ "Legacy (PBKDF2) secret hashes are deprecated and support for them will be removed in NetBox v4.8."
25
+ )
26
+
27
+
28
+ class SecretValidationHasher(PBKDF2PasswordHasher):
29
+ """
30
+ We're using Django's stock SHA256 hasher with a low iteration count to avoid introducing excessive delay when
31
+ retrieving a large number of Secrets (the plaintext of each Secret is validated against its hash upon decryption).
32
+
33
+ Kept for backward compatibility: hashes created by older releases are still verified (see
34
+ ``check_secret_hash``), new hashes use ``make_secret_hash``.
35
+
36
+ Deprecated: this class (and legacy secret hash support) will be removed in NetBox v4.8.
37
+ """
38
+
39
+ iterations = 1000
40
+
41
+
42
+ def make_session_key_hash(session_key: bytes) -> str:
43
+ """
44
+ Hash a session key for later validation.
45
+
46
+ A session key is 256 bits of random data, so it cannot be guessed or brute forced. A deliberately slow password
47
+ hasher (PBKDF2) adds nothing here but costs CPU on every authenticated request, so a plain SHA-256 is used.
48
+ """
49
+ return SESSION_KEY_HASH_PREFIX + hashlib.sha256(session_key).hexdigest()
50
+
51
+
52
+ def check_session_key_hash(session_key: bytes, encoded: str) -> bool:
53
+ """
54
+ Verify a session key against a stored hash.
55
+
56
+ Session keys created by older releases (PBKDF2 hash) are no longer supported, they have to be deleted and created
57
+ again.
58
+ """
59
+ if not encoded.startswith(SESSION_KEY_HASH_PREFIX):
60
+ return False
61
+
62
+ return hmac.compare_digest(make_session_key_hash(session_key), encoded)
63
+
64
+
65
+ def _secret_digest(plaintext: str, secret_key: bytes, salt: str) -> str:
66
+ return hmac.new(secret_key, salt.encode('utf-8') + plaintext.encode('utf-8'), hashlib.sha256).hexdigest()
67
+
68
+
69
+ def make_secret_hash(plaintext: str, secret_key: bytes) -> str:
70
+ """
71
+ Create the validation hash stored next to a secret's ciphertext, in the format ``hmac_sha256$<salt>$<digest>``.
72
+
73
+ The digest is an HMAC-SHA256 of ``salt + plaintext`` keyed with the master key. It is only a "did we decrypt with
74
+ the right key" check, so it can be cheap. Because it is keyed, someone who only has the database cannot use it to
75
+ guess low-entropy plaintexts offline, and because of the fresh random salt, encrypting the same value twice gives
76
+ different hashes, so equal secrets cannot be spotted by comparing hashes.
77
+ """
78
+ salt = secrets_module.token_hex(SECRET_HASH_SALT_BYTES)
79
+ return f"{SECRET_HASH_PREFIX}{salt}${_secret_digest(plaintext, secret_key, salt)}"
80
+
81
+
82
+ def check_secret_hash(plaintext: str, secret_key: bytes, encoded: str) -> bool:
83
+ """
84
+ Verify decrypted plaintext against a stored secret hash.
85
+
86
+ Hashes created by older releases (PBKDF2) are still accepted, but they are deprecated. Unlike session keys,
87
+ secrets cannot simply be recreated by users.
88
+ """
89
+ if encoded.startswith(SECRET_HASH_PREFIX):
90
+ salt, separator, digest = encoded[len(SECRET_HASH_PREFIX) :].partition('$')
91
+ if not separator:
92
+ return False
93
+ return hmac.compare_digest(_secret_digest(plaintext, secret_key, salt), digest)
94
+
95
+ # TODO: Remove in NetBox v4.8 (legacy secret hash support)
96
+ warnings.warn(LEGACY_HASH_WARNING, DeprecationWarning, stacklevel=2)
97
+ return check_password(plaintext, encoded)
@@ -0,0 +1,142 @@
1
+ """Migrate SecretRole's hierarchy from django-mptt to PostgreSQL ltree.
2
+
3
+ The supported migration direction is forward. Reversing this migration restores
4
+ the legacy MPTT columns but does not repopulate their values from the parent
5
+ relationships, so it does not reconstruct a valid MPTT tree. Take a database
6
+ backup before applying this migration; do not treat reversing it as a
7
+ data-preserving rollback.
8
+ """
9
+ from django.contrib.postgres.indexes import GistIndex
10
+ from django.contrib.postgres.operations import CreateExtension
11
+ from django.db import migrations, models
12
+
13
+ import netbox.models.ltree
14
+ from utilities.ltree import InstallLtreeTriggers
15
+ from utilities.mptt_to_ltree import assert_paths_populated_sql, populate_paths_sql
16
+
17
+
18
+ class Migration(migrations.Migration):
19
+
20
+ dependencies = [
21
+ ('netbox_secrets', '0011_remove_redundant_indexes'),
22
+ ]
23
+
24
+ operations = [
25
+ # Create the PostgreSQL ltree extension before adding ltree columns and triggers.
26
+ CreateExtension('ltree'),
27
+
28
+ # Switch parent from mptt.fields.TreeForeignKey to django.db.models.ForeignKey.
29
+ migrations.AlterField(
30
+ model_name='secretrole',
31
+ name='parent',
32
+ field=models.ForeignKey(
33
+ blank=True,
34
+ null=True,
35
+ on_delete=models.CASCADE,
36
+ related_name='children',
37
+ to='netbox_secrets.secretrole',
38
+ ),
39
+ ),
40
+
41
+ # Add path (nullable initially).
42
+ migrations.AddField(
43
+ model_name='secretrole',
44
+ name='path',
45
+ field=netbox.models.ltree.LtreeField(
46
+ blank=True,
47
+ editable=False,
48
+ null=True,
49
+ ),
50
+ ),
51
+
52
+ # Add sort_path with natural_sort collation to match name.
53
+ migrations.AddField(
54
+ model_name='secretrole',
55
+ name='sort_path',
56
+ field=models.TextField(
57
+ blank=True,
58
+ default='',
59
+ editable=False,
60
+ db_collation='natural_sort',
61
+ ),
62
+ ),
63
+
64
+ # Install triggers maintaining both path and sort_path.
65
+ InstallLtreeTriggers(
66
+ 'netbox_secrets_secretrole',
67
+ name_column='name',
68
+ ),
69
+
70
+ # Populate path and sort_path for existing rows.
71
+ migrations.RunSQL(
72
+ sql=populate_paths_sql(
73
+ 'netbox_secrets_secretrole',
74
+ sort_path=True,
75
+ ),
76
+ reverse_sql=migrations.RunSQL.noop,
77
+ ),
78
+
79
+ # Fail if any row has a NULL path.
80
+ migrations.RunSQL(
81
+ sql=assert_paths_populated_sql(
82
+ 'netbox_secrets_secretrole',
83
+ ),
84
+ reverse_sql=migrations.RunSQL.noop,
85
+ ),
86
+
87
+ # Make path non-null after successful population.
88
+ migrations.AlterField(
89
+ model_name='secretrole',
90
+ name='path',
91
+ field=netbox.models.ltree.LtreeField(
92
+ blank=True,
93
+ default='',
94
+ editable=False,
95
+ ),
96
+ ),
97
+
98
+ # Use hierarchical ordering.
99
+ migrations.AlterModelOptions(
100
+ name='secretrole',
101
+ options={'ordering': ['sort_path']},
102
+ ),
103
+
104
+ # Drop legacy MPTT columns.
105
+ migrations.RemoveField(
106
+ model_name='secretrole',
107
+ name='lft',
108
+ ),
109
+
110
+ migrations.RemoveField(
111
+ model_name='secretrole',
112
+ name='rght',
113
+ ),
114
+
115
+ migrations.RemoveField(
116
+ model_name='secretrole',
117
+ name='tree_id',
118
+ ),
119
+
120
+ migrations.RemoveField(
121
+ model_name='secretrole',
122
+ name='level',
123
+ ),
124
+
125
+ # GiST index for ltree path queries.
126
+ migrations.AddIndex(
127
+ model_name='secretrole',
128
+ index=GistIndex(
129
+ fields=['path'],
130
+ name='secrets_secretrole_path_gist',
131
+ ),
132
+ ),
133
+
134
+ # B-tree index for sort_path ordering.
135
+ migrations.AddIndex(
136
+ model_name='secretrole',
137
+ index=models.Index(
138
+ fields=['sort_path'],
139
+ name='secrets_sr_sort_path_idx',
140
+ ),
141
+ ),
142
+ ]
@@ -0,0 +1,37 @@
1
+ # Generated by Django 6.1 on 2026-10-13 06:50
2
+
3
+ from django.db import migrations, models
4
+ import django.db.models.deletion
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ dependencies = [
10
+ ('netbox_secrets', '0012_ltree_paths'),
11
+ ('users', '0016_default_ordering_indexes'),
12
+ ]
13
+
14
+ operations = [
15
+ migrations.AlterField(
16
+ model_name='secret',
17
+ name='owner',
18
+ field=models.ForeignKey(
19
+ blank=True,
20
+ null=True,
21
+ on_delete=django.db.models.deletion.PROTECT,
22
+ related_name='+',
23
+ to='users.owner',
24
+ ),
25
+ ),
26
+ migrations.AlterField(
27
+ model_name='secretrole',
28
+ name='owner',
29
+ field=models.ForeignKey(
30
+ blank=True,
31
+ null=True,
32
+ on_delete=django.db.models.deletion.PROTECT,
33
+ related_name='+',
34
+ to='users.owner',
35
+ ),
36
+ ),
37
+ ]
@@ -11,7 +11,6 @@ from typing import Optional
11
11
  from Crypto.PublicKey import RSA
12
12
  from Crypto.Util import strxor
13
13
  from django.conf import settings
14
- from django.contrib.auth.hashers import check_password, make_password
15
14
  from django.core.exceptions import ValidationError
16
15
  from django.db import models, transaction
17
16
  from django.db.models import ProtectedError
@@ -22,6 +21,7 @@ from netbox.models import NetBoxModel
22
21
  from utilities.querysets import RestrictedQuerySet
23
22
  from ..constants import CENSOR_MASTER_KEY, CENSOR_MASTER_KEY_CHANGED, get_public_key_size
24
23
  from ..exceptions import InvalidKey
24
+ from ..hashers import check_session_key_hash, make_session_key_hash
25
25
  from ..querysets import UserKeyQuerySet
26
26
  from ..utils import decrypt_master_key, encrypt_master_key, generate_random_key
27
27
 
@@ -324,7 +324,7 @@ class SessionKey(models.Model):
324
324
  self.key = generate_random_key()
325
325
 
326
326
  # Hash session key for validation
327
- self.hash = make_password(self.key.hex())
327
+ self.hash = make_session_key_hash(self.key)
328
328
 
329
329
  # Encrypt master key with session key using XOR
330
330
  self.cipher = strxor.strxor(self.key, master_key)
@@ -344,7 +344,7 @@ class SessionKey(models.Model):
344
344
  Raises:
345
345
  InvalidKey: If session key is invalid
346
346
  """
347
- if not check_password(session_key.hex(), self.hash):
347
+ if not check_session_key_hash(session_key, self.hash):
348
348
  raise InvalidKey(_("Invalid session key"))
349
349
 
350
350
  return strxor.strxor(session_key, bytes(self.cipher))
@@ -367,7 +367,7 @@ class SessionKey(models.Model):
367
367
  """
368
368
  session_key = strxor.strxor(master_key, bytes(self.cipher))
369
369
 
370
- if not check_password(session_key.hex(), self.hash):
370
+ if not check_session_key_hash(session_key, self.hash):
371
371
  raise InvalidKey(_("Invalid master key"))
372
372
 
373
373
  return session_key
@@ -10,15 +10,15 @@ import secrets as secrets_module
10
10
  from typing import Optional
11
11
 
12
12
  from Crypto.Cipher import AES
13
- from django.contrib.auth.hashers import check_password, make_password
14
13
  from django.contrib.contenttypes.fields import GenericForeignKey
14
+ from django.contrib.postgres.indexes import GistIndex
15
15
  from django.db import models, transaction
16
16
  from django.utils.translation import gettext_lazy as _
17
17
 
18
- from netbox.models import NestedGroupModel, PrimaryModel
18
+ from netbox.models import NestedLtreeGroupModel, PrimaryModel
19
19
  from netbox.models.features import ContactsMixin
20
20
  from utilities.querysets import RestrictedQuerySet
21
- from ..hashers import SecretValidationHasher
21
+ from ..hashers import check_secret_hash, make_secret_hash
22
22
 
23
23
  __all__ = [
24
24
  'SecretRole',
@@ -26,7 +26,7 @@ __all__ = [
26
26
  ]
27
27
 
28
28
 
29
- class SecretRole(NestedGroupModel):
29
+ class SecretRole(NestedLtreeGroupModel):
30
30
  """
31
31
  Functional classification for secrets (e.g., "Login Credentials", "API Keys").
32
32
 
@@ -49,7 +49,13 @@ class SecretRole(NestedGroupModel):
49
49
  slug = models.SlugField(verbose_name=_('slug'), max_length=100, unique=True)
50
50
 
51
51
  class Meta:
52
- ordering = ['name']
52
+ ordering = [
53
+ 'sort_path',
54
+ ]
55
+ indexes = [
56
+ GistIndex(fields=['path'], name='secrets_secretrole_path_gist'),
57
+ models.Index(fields=['sort_path'], name='secrets_sr_sort_path_idx'),
58
+ ]
53
59
  verbose_name = _('Secret Role')
54
60
  verbose_name_plural = _('Secret Roles')
55
61
 
@@ -239,7 +245,7 @@ class Secret(PrimaryModel, ContactsMixin):
239
245
  2. Pad plaintext with length header and random bytes
240
246
  3. Encrypt padded plaintext using AES-256-CFB
241
247
  4. Prepend IV to ciphertext for use in decryption
242
- 5. Generate SHA-256 hash of plaintext for validation
248
+ 5. Generate a keyed HMAC-SHA256 of the plaintext for validation
243
249
  6. Clear plaintext from memory
244
250
 
245
251
  The ciphertext format is:
@@ -262,8 +268,8 @@ class Secret(PrimaryModel, ContactsMixin):
262
268
  padded_plaintext = self._pad(self.plaintext)
263
269
  self.ciphertext = iv + cipher.encrypt(padded_plaintext)
264
270
 
265
- # Generate validation hash using custom hasher
266
- self.hash = make_password(self.plaintext, hasher=SecretValidationHasher())
271
+ # Generate the (keyed) validation hash
272
+ self.hash = make_secret_hash(self.plaintext, secret_key)
267
273
 
268
274
  # Clear plaintext from memory for security
269
275
  self.plaintext = None
@@ -300,20 +306,21 @@ class Secret(PrimaryModel, ContactsMixin):
300
306
  plaintext = self._unpad(cipher.decrypt(encrypted_data))
301
307
 
302
308
  # Validate decrypted plaintext against hash
303
- if not self.validate(plaintext):
309
+ if not self.validate(plaintext, secret_key):
304
310
  raise ValueError(_("Decryption failed: invalid key or corrupted ciphertext"))
305
311
 
306
312
  self.plaintext = plaintext
307
313
 
308
- def validate(self, plaintext: str) -> bool:
314
+ def validate(self, plaintext: str, secret_key: bytes) -> bool:
309
315
  """
310
- Verify plaintext matches the stored SHA-256 hash.
316
+ Verify plaintext matches the stored validation hash.
311
317
 
312
318
  This ensures the decrypted plaintext is correct and hasn't been
313
319
  corrupted or tampered with.
314
320
 
315
321
  Args:
316
322
  plaintext: Plaintext to validate
323
+ secret_key: Key the plaintext was decrypted with (the hash is keyed with it)
317
324
 
318
325
  Returns:
319
326
  True if plaintext matches stored hash, False otherwise
@@ -324,4 +331,4 @@ class Secret(PrimaryModel, ContactsMixin):
324
331
  if not self.hash:
325
332
  raise ValueError(_("Cannot validate: hash not generated for this secret."))
326
333
 
327
- return check_password(plaintext, self.hash, preferred=SecretValidationHasher())
334
+ return check_secret_hash(plaintext, secret_key, self.hash)
@@ -26,7 +26,9 @@ def secrets_panel(self):
26
26
  return self.render(
27
27
  'netbox_secrets/inc/secrets_panel.html',
28
28
  extra_context={
29
- 'secrets': Secret.objects.filter(assigned_object_type=assigned_object_type, assigned_object_id=obj.id),
29
+ 'secrets': Secret.objects.restrict(self.context['request'].user, 'view').filter(
30
+ assigned_object_type=assigned_object_type, assigned_object_id=obj.id
31
+ ),
30
32
  },
31
33
  )
32
34
  return None
@@ -0,0 +1,16 @@
1
+ {% extends 'ui/panels/_base.html' %}
2
+ {% block panel_content %}
3
+ <div class="card-body">
4
+ <form id="secret_form">
5
+ {% csrf_token %}
6
+ </form>
7
+ <div class="row">
8
+ <div class="col col-md-2">Secret</div>
9
+ <div class="col col-md-6"><code id="secret_{{ object.pk }}">********</code></div>
10
+ <div class="col col-md-4 text-end noprint">
11
+ {% include 'netbox_secrets/inc/secret_actions.html' %}
12
+ </div>
13
+ </div>
14
+ </div>
15
+ {% include 'netbox_secrets/inc/private_key_modal.html' %}
16
+ {% endblock %}