keychain.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. from getpass import getpass
  2. import hashlib
  3. import os
  4. import msgpack
  5. import zlib
  6. from pbkdf2 import pbkdf2
  7. from Crypto.Cipher import AES
  8. from Crypto.Hash import SHA256, HMAC
  9. from Crypto.PublicKey import RSA
  10. from Crypto.Util import Counter
  11. from Crypto.Util.number import bytes_to_long, long_to_bytes
  12. from . import PACKET_ENCRYPT_READ, PACKET_ENCRYPT_CREATE
  13. from .helpers import IntegrityError, zero_pad
  14. from .oaep import OAEP
  15. class Keychain(object):
  16. FILE_ID = 'DARC KEYCHAIN'
  17. CREATE = '\1'
  18. READ = '\2'
  19. def __init__(self, path=None):
  20. self._key_cache = {}
  21. self.read_key = os.urandom(32)
  22. self.create_key = os.urandom(32)
  23. self.counter = Counter.new(64, prefix='\0' * 8)
  24. self.aes_id = self.rsa_read = self.rsa_create = None
  25. self.path = path
  26. if path:
  27. self.open(path)
  28. def get_chunkify_seed(self):
  29. return bytes_to_long(self.aes_id[:4]) & 0x7fffffff
  30. def open(self, path):
  31. print 'Opening keychain "%s"' % path
  32. with open(path, 'rb') as fd:
  33. if fd.read(len(self.FILE_ID)) != self.FILE_ID:
  34. raise ValueError('Not a keychain')
  35. cdata = fd.read()
  36. self.password = ''
  37. data = self.decrypt_keychain(cdata, '')
  38. while not data:
  39. self.password = getpass('Keychain password: ')
  40. if not self.password:
  41. raise Exception('Keychain decryption failed')
  42. data = self.decrypt_keychain(cdata, self.password)
  43. if not data:
  44. print 'Incorrect password'
  45. chain = msgpack.unpackb(data)
  46. assert chain['version'] == 1
  47. self.aes_id = chain['aes_id']
  48. self.rsa_read = RSA.importKey(chain['rsa_read'])
  49. self.rsa_create = RSA.importKey(chain['rsa_create'])
  50. self.read_encrypted = OAEP(256, hash=SHA256).encode(self.read_key, os.urandom(32))
  51. self.read_encrypted = zero_pad(self.rsa_read.encrypt(self.read_encrypted, '')[0], 256)
  52. self.create_encrypted = OAEP(256, hash=SHA256).encode(self.create_key, os.urandom(32))
  53. self.create_encrypted = zero_pad(self.rsa_create.encrypt(self.create_encrypted, '')[0], 256)
  54. def encrypt_keychain(self, data, password):
  55. salt = os.urandom(32)
  56. iterations = 2000
  57. key = pbkdf2(password, salt, 32, iterations, hashlib.sha256)
  58. hash = HMAC.new(key, data, SHA256).digest()
  59. cdata = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(data)
  60. d = {
  61. 'version': 1,
  62. 'salt': salt,
  63. 'iterations': iterations,
  64. 'algorithm': 'SHA256',
  65. 'hash': hash,
  66. 'data': cdata,
  67. }
  68. return msgpack.packb(d)
  69. def decrypt_keychain(self, data, password):
  70. d = msgpack.unpackb(data)
  71. assert d['version'] == 1
  72. assert d['algorithm'] == 'SHA256'
  73. key = pbkdf2(password, d['salt'], 32, d['iterations'], hashlib.sha256)
  74. data = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).decrypt(d['data'])
  75. if HMAC.new(key, data, SHA256).digest() != d['hash']:
  76. return None
  77. return data
  78. def save(self, path, password):
  79. chain = {
  80. 'version': 1,
  81. 'aes_id': self.aes_id,
  82. 'rsa_read': self.rsa_read.exportKey('PEM'),
  83. 'rsa_create': self.rsa_create.exportKey('PEM'),
  84. }
  85. data = self.encrypt_keychain(msgpack.packb(chain), password)
  86. with open(path, 'wb') as fd:
  87. fd.write(self.FILE_ID)
  88. fd.write(data)
  89. print 'Key chain "%s" saved' % path
  90. def restrict(self, path):
  91. if os.path.exists(path):
  92. print '%s already exists' % path
  93. return 1
  94. self.rsa_read = self.rsa_read.publickey()
  95. self.save(path, self.password)
  96. return 0
  97. def chpass(self):
  98. password, password2 = 1, 2
  99. while password != password2:
  100. password = getpass('New password: ')
  101. password2 = getpass('New password again: ')
  102. if password != password2:
  103. print 'Passwords do not match'
  104. self.save(self.path, password)
  105. return 0
  106. @staticmethod
  107. def generate(path):
  108. if os.path.exists(path):
  109. print '%s already exists' % path
  110. return 1
  111. password, password2 = 1, 2
  112. while password != password2:
  113. password = getpass('Keychain password: ')
  114. password2 = getpass('Keychain password again: ')
  115. if password != password2:
  116. print 'Passwords do not match'
  117. chain = Keychain()
  118. print 'Generating keychain'
  119. chain.aes_id = os.urandom(32)
  120. chain.rsa_read = RSA.generate(2048)
  121. chain.rsa_create = RSA.generate(2048)
  122. chain.save(path, password)
  123. return 0
  124. def id_hash(self, data):
  125. """Return HMAC hash using the "id" AES key
  126. """
  127. return HMAC.new(self.aes_id, data, SHA256).digest()
  128. def encrypt(self, magic, data):
  129. """Helper function used by `encrypt_read` and `encrypt_create`
  130. """
  131. data = zlib.compress(data)
  132. nonce = long_to_bytes(self.counter.next_value(), 8)
  133. if magic & PACKET_ENCRYPT_READ:
  134. data = ''.join((nonce, self.read_encrypted,
  135. AES.new(self.read_key, AES.MODE_CTR, '',
  136. counter=self.counter).encrypt(data)))
  137. elif magic & PACKET_ENCRYPT_CREATE:
  138. data = ''.join((nonce, self.create_encrypted,
  139. AES.new(self.create_key, AES.MODE_CTR, '',
  140. counter=self.counter).encrypt(data)))
  141. hash = self.id_hash(data)
  142. return ''.join((chr(magic), hash, data)), hash
  143. def _decrypt_key(self, data, rsa_key):
  144. """Helper function used by `decrypt`
  145. """
  146. try:
  147. return self._key_cache[data]
  148. except KeyError:
  149. self._key_cache[data] = OAEP(256, hash=SHA256).decode(rsa_key.decrypt(data))
  150. return self._key_cache[data]
  151. def decrypt(self, data):
  152. """Decrypt `data` previously encrypted by `encrypt_create` or `encrypt_read`
  153. """
  154. magic = ord(data[0])
  155. hash = data[1:33]
  156. if self.id_hash(data[33:]) != hash:
  157. raise IntegrityError('Encryption integrity error')
  158. nonce = bytes_to_long(data[33:41])
  159. counter = Counter.new(64, prefix='\0' * 8, initial_value=nonce)
  160. if magic & PACKET_ENCRYPT_READ:
  161. key = self._decrypt_key(data[41:297], self.rsa_read)
  162. elif magic & PACKET_ENCRYPT_CREATE:
  163. key = self._decrypt_key(data[41:297], self.rsa_create)
  164. else:
  165. raise Exception('Unknown pack magic %d found' % magic)
  166. data = AES.new(key, AES.MODE_CTR, counter=counter).decrypt(data[297:])
  167. return magic, zlib.decompress(data), hash