models.py 15 KB

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