models.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import os
  2. from Crypto.Cipher import AES
  3. from Crypto.PublicKey import RSA
  4. from Crypto.Util import strxor
  5. from django.conf import settings
  6. from django.contrib.auth.hashers import make_password, check_password
  7. from django.contrib.auth.models import Group, User
  8. from django.contrib.contenttypes.fields import GenericRelation
  9. from django.core.exceptions import ValidationError
  10. from django.db import models
  11. from django.urls import reverse
  12. from django.utils.encoding import force_bytes
  13. from taggit.managers import TaggableManager
  14. from dcim.models import Device
  15. from extras.models import ChangeLoggedModel, CustomFieldModel, TaggedItem
  16. from extras.utils import extras_features
  17. from utilities.querysets import RestrictedQuerySet
  18. from .exceptions import InvalidKey
  19. from .hashers import SecretValidationHasher
  20. from .querysets import UserKeyQuerySet
  21. from .utils import encrypt_master_key, decrypt_master_key, generate_random_key
  22. __all__ = (
  23. 'Secret',
  24. 'SecretRole',
  25. 'SessionKey',
  26. 'UserKey',
  27. )
  28. class UserKey(models.Model):
  29. """
  30. A UserKey stores a user's personal RSA (public) encryption key, which is used to generate their unique encrypted
  31. copy of the master encryption key. The encrypted instance of the master key can be decrypted only with the user's
  32. matching (private) decryption key.
  33. """
  34. created = models.DateField(
  35. auto_now_add=True
  36. )
  37. last_updated = models.DateTimeField(
  38. auto_now=True
  39. )
  40. user = models.OneToOneField(
  41. to=User,
  42. on_delete=models.CASCADE,
  43. related_name='user_key',
  44. editable=False
  45. )
  46. public_key = models.TextField(
  47. verbose_name='RSA public key'
  48. )
  49. master_key_cipher = models.BinaryField(
  50. max_length=512,
  51. blank=True,
  52. null=True,
  53. editable=False
  54. )
  55. objects = UserKeyQuerySet.as_manager()
  56. class Meta:
  57. ordering = ['user__username']
  58. def __init__(self, *args, **kwargs):
  59. super().__init__(*args, **kwargs)
  60. # Store the initial public_key and master_key_cipher to check for changes on save().
  61. self.__initial_public_key = self.public_key
  62. self.__initial_master_key_cipher = self.master_key_cipher
  63. def __str__(self):
  64. return self.user.username
  65. def clean(self, *args, **kwargs):
  66. if self.public_key:
  67. # Validate the public key format
  68. try:
  69. pubkey = RSA.import_key(self.public_key)
  70. except ValueError:
  71. raise ValidationError({
  72. 'public_key': "Invalid RSA key format."
  73. })
  74. except Exception:
  75. raise ValidationError("Something went wrong while trying to save your key. Please ensure that you're "
  76. "uploading a valid RSA public key in PEM format (no SSH/PGP).")
  77. # Validate the public key length
  78. pubkey_length = pubkey.size_in_bits()
  79. if pubkey_length < settings.SECRETS_MIN_PUBKEY_SIZE:
  80. raise ValidationError({
  81. 'public_key': "Insufficient key length. Keys must be at least {} bits long.".format(
  82. settings.SECRETS_MIN_PUBKEY_SIZE
  83. )
  84. })
  85. # We can't use keys bigger than our master_key_cipher field can hold
  86. if pubkey_length > 4096:
  87. raise ValidationError({
  88. 'public_key': "Public key size ({}) is too large. Maximum key size is 4096 bits.".format(
  89. pubkey_length
  90. )
  91. })
  92. super().clean()
  93. def save(self, *args, **kwargs):
  94. # Check whether public_key has been modified. If so, nullify the initial master_key_cipher.
  95. if self.__initial_master_key_cipher and self.public_key != self.__initial_public_key:
  96. self.master_key_cipher = None
  97. # If no other active UserKeys exist, generate a new master key and use it to activate this UserKey.
  98. if self.is_filled() and not self.is_active() and not UserKey.objects.active().count():
  99. master_key = generate_random_key()
  100. self.master_key_cipher = encrypt_master_key(master_key, self.public_key)
  101. super().save(*args, **kwargs)
  102. def delete(self, *args, **kwargs):
  103. # If Secrets exist and this is the last active UserKey, prevent its deletion. Deleting the last UserKey will
  104. # result in the master key being destroyed and rendering all Secrets inaccessible.
  105. if Secret.objects.count() and [uk.pk for uk in UserKey.objects.active()] == [self.pk]:
  106. raise Exception("Cannot delete the last active UserKey when Secrets exist! This would render all secrets "
  107. "inaccessible.")
  108. super().delete(*args, **kwargs)
  109. def is_filled(self):
  110. """
  111. Returns True if the UserKey has been filled with a public RSA key.
  112. """
  113. return bool(self.public_key)
  114. is_filled.boolean = True
  115. def is_active(self):
  116. """
  117. Returns True if the UserKey has been populated with an encrypted copy of the master key.
  118. """
  119. return self.master_key_cipher is not None
  120. is_active.boolean = True
  121. def get_master_key(self, private_key):
  122. """
  123. Given the User's private key, return the encrypted master key.
  124. """
  125. if not self.is_active:
  126. raise ValueError("Unable to retrieve master key: UserKey is inactive.")
  127. try:
  128. return decrypt_master_key(force_bytes(self.master_key_cipher), private_key)
  129. except ValueError:
  130. return None
  131. def activate(self, master_key):
  132. """
  133. Activate the UserKey by saving an encrypted copy of the master key to the database.
  134. """
  135. if not self.public_key:
  136. raise Exception("Cannot activate UserKey: Its public key must be filled first.")
  137. self.master_key_cipher = encrypt_master_key(master_key, self.public_key)
  138. self.save()
  139. class SessionKey(models.Model):
  140. """
  141. A SessionKey stores a User's temporary key to be used for the encryption and decryption of secrets.
  142. """
  143. userkey = models.OneToOneField(
  144. to='secrets.UserKey',
  145. on_delete=models.CASCADE,
  146. related_name='session_key',
  147. editable=False
  148. )
  149. cipher = models.BinaryField(
  150. max_length=512,
  151. editable=False
  152. )
  153. hash = models.CharField(
  154. max_length=128,
  155. editable=False
  156. )
  157. created = models.DateTimeField(
  158. auto_now_add=True
  159. )
  160. key = None
  161. class Meta:
  162. ordering = ['userkey__user__username']
  163. def __str__(self):
  164. return self.userkey.user.username
  165. def save(self, master_key=None, *args, **kwargs):
  166. if master_key is None:
  167. raise Exception("The master key must be provided to save a session key.")
  168. # Generate a random 256-bit session key if one is not already defined
  169. if self.key is None:
  170. self.key = generate_random_key()
  171. # Generate SHA256 hash using Django's built-in password hashing mechanism
  172. self.hash = make_password(self.key)
  173. # Encrypt master key using the session key
  174. self.cipher = strxor.strxor(self.key, master_key)
  175. super().save(*args, **kwargs)
  176. def get_master_key(self, session_key):
  177. # Validate the provided session key
  178. if not check_password(session_key, self.hash):
  179. raise InvalidKey("Invalid session key")
  180. # Decrypt master key using provided session key
  181. master_key = strxor.strxor(session_key, bytes(self.cipher))
  182. return master_key
  183. def get_session_key(self, master_key):
  184. # Recover session key using the master key
  185. session_key = strxor.strxor(master_key, bytes(self.cipher))
  186. # Validate the recovered session key
  187. if not check_password(session_key, self.hash):
  188. raise InvalidKey("Invalid master key")
  189. return session_key
  190. class SecretRole(ChangeLoggedModel):
  191. """
  192. A SecretRole represents an arbitrary functional classification of Secrets. For example, a user might define roles
  193. such as "Login Credentials" or "SNMP Communities."
  194. """
  195. name = models.CharField(
  196. max_length=50,
  197. unique=True
  198. )
  199. slug = models.SlugField(
  200. unique=True
  201. )
  202. description = models.CharField(
  203. max_length=200,
  204. blank=True,
  205. )
  206. objects = RestrictedQuerySet.as_manager()
  207. csv_headers = ['name', 'slug', 'description']
  208. class Meta:
  209. ordering = ['name']
  210. def __str__(self):
  211. return self.name
  212. def get_absolute_url(self):
  213. return "{}?role={}".format(reverse('secrets:secret_list'), self.slug)
  214. def to_csv(self):
  215. return (
  216. self.name,
  217. self.slug,
  218. self.description,
  219. )
  220. @extras_features('custom_fields', 'custom_links', 'export_templates', 'webhooks')
  221. class Secret(ChangeLoggedModel, CustomFieldModel):
  222. """
  223. A Secret stores an AES256-encrypted copy of sensitive data, such as passwords or secret keys. An irreversible
  224. SHA-256 hash is stored along with the ciphertext for validation upon decryption. Each Secret is assigned to a
  225. Device; Devices may have multiple Secrets associated with them. A name can optionally be defined along with the
  226. ciphertext; this string is stored as plain text in the database.
  227. A Secret can be up to 65,535 bytes (64KB - 1B) in length. Each secret string will be padded with random data to
  228. a minimum of 64 bytes during encryption in order to protect short strings from ciphertext analysis.
  229. """
  230. device = models.ForeignKey(
  231. to='dcim.Device',
  232. on_delete=models.CASCADE,
  233. related_name='secrets'
  234. )
  235. role = models.ForeignKey(
  236. to='secrets.SecretRole',
  237. on_delete=models.PROTECT,
  238. related_name='secrets'
  239. )
  240. name = models.CharField(
  241. max_length=100,
  242. blank=True
  243. )
  244. ciphertext = models.BinaryField(
  245. max_length=65568, # 128-bit IV + 16-bit pad length + 65535B secret + 15B padding
  246. editable=False
  247. )
  248. hash = models.CharField(
  249. max_length=128,
  250. editable=False
  251. )
  252. custom_field_values = GenericRelation(
  253. to='extras.CustomFieldValue',
  254. content_type_field='obj_type',
  255. object_id_field='obj_id'
  256. )
  257. tags = TaggableManager(through=TaggedItem)
  258. objects = RestrictedQuerySet.as_manager()
  259. plaintext = None
  260. csv_headers = ['device', 'role', 'name', 'plaintext']
  261. class Meta:
  262. ordering = ['device', 'role', 'name']
  263. unique_together = ['device', 'role', 'name']
  264. def __init__(self, *args, **kwargs):
  265. self.plaintext = kwargs.pop('plaintext', None)
  266. super().__init__(*args, **kwargs)
  267. def __str__(self):
  268. try:
  269. device = self.device
  270. except Device.DoesNotExist:
  271. device = None
  272. if self.role and device and self.name:
  273. return '{} for {} ({})'.format(self.role, self.device, self.name)
  274. # Return role and device if no name is set
  275. if self.role and device:
  276. return '{} for {}'.format(self.role, self.device)
  277. return 'Secret'
  278. def get_absolute_url(self):
  279. return reverse('secrets:secret', args=[self.pk])
  280. def to_csv(self):
  281. return (
  282. self.device,
  283. self.role,
  284. self.name,
  285. self.plaintext or '',
  286. )
  287. def _pad(self, s):
  288. """
  289. Prepend the length of the plaintext (2B) and pad with garbage to a multiple of 16B (minimum of 64B).
  290. +--+--------+-------------------------------------------+
  291. |LL|MySecret|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|
  292. +--+--------+-------------------------------------------+
  293. """
  294. s = s.encode('utf8')
  295. if len(s) > 65535:
  296. raise ValueError("Maximum plaintext size is 65535 bytes.")
  297. # Minimum ciphertext size is 64 bytes to conceal the length of short secrets.
  298. if len(s) <= 62:
  299. pad_length = 62 - len(s)
  300. elif (len(s) + 2) % 16:
  301. pad_length = 16 - ((len(s) + 2) % 16)
  302. else:
  303. pad_length = 0
  304. header = bytes([len(s) >> 8]) + bytes([len(s) % 256])
  305. return header + s + os.urandom(pad_length)
  306. def _unpad(self, s):
  307. """
  308. Consume the first two bytes of s as a plaintext length indicator and return only that many bytes as the
  309. plaintext.
  310. """
  311. if isinstance(s[0], str):
  312. plaintext_length = (ord(s[0]) << 8) + ord(s[1])
  313. else:
  314. plaintext_length = (s[0] << 8) + s[1]
  315. return s[2:plaintext_length + 2].decode('utf8')
  316. def encrypt(self, secret_key):
  317. """
  318. Generate a random initialization vector (IV) for AES. Pad the plaintext to the AES block size (16 bytes) and
  319. encrypt. Prepend the IV for use in decryption. Finally, record the SHA256 hash of the plaintext for validation
  320. upon decryption.
  321. """
  322. if self.plaintext is None:
  323. raise Exception("Must unlock or set plaintext before locking.")
  324. # Pad and encrypt plaintext
  325. iv = os.urandom(16)
  326. aes = AES.new(secret_key, AES.MODE_CFB, iv)
  327. self.ciphertext = iv + aes.encrypt(self._pad(self.plaintext))
  328. # Generate SHA256 using Django's built-in password hashing mechanism
  329. self.hash = make_password(self.plaintext, hasher=SecretValidationHasher())
  330. self.plaintext = None
  331. def decrypt(self, secret_key):
  332. """
  333. Consume the first 16 bytes of self.ciphertext as the AES initialization vector (IV). The remainder is decrypted
  334. using the IV and the provided secret key. Padding is then removed to reveal the plaintext. Finally, validate the
  335. decrypted plaintext value against the stored hash.
  336. """
  337. if self.plaintext is not None:
  338. return
  339. if not self.ciphertext:
  340. raise Exception("Must define ciphertext before unlocking.")
  341. # Decrypt ciphertext and remove padding
  342. iv = bytes(self.ciphertext[0:16])
  343. ciphertext = bytes(self.ciphertext[16:])
  344. aes = AES.new(secret_key, AES.MODE_CFB, iv)
  345. plaintext = self._unpad(aes.decrypt(ciphertext))
  346. # Verify decrypted plaintext against hash
  347. if not self.validate(plaintext):
  348. raise ValueError("Invalid key or ciphertext!")
  349. self.plaintext = plaintext
  350. def validate(self, plaintext):
  351. """
  352. Validate that a given plaintext matches the stored hash.
  353. """
  354. if not self.hash:
  355. raise Exception("Hash has not been generated for this secret.")
  356. return check_password(plaintext, self.hash, preferred=SecretValidationHasher())