models.py 15 KB

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