crypto.py 6.8 KB

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