models.py 15 KB

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