models.py 15 KB

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