models.py 15 KB

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