key.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from __future__ import with_statement
  2. from getpass import getpass
  3. import hashlib
  4. import os
  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.Util import Counter
  11. from Crypto.Util.number import bytes_to_long, long_to_bytes
  12. from Crypto.Random import get_random_bytes
  13. from .helpers import IntegrityError, get_keys_dir
  14. PREFIX = '\0' * 8
  15. class Key(object):
  16. FILE_ID = 'DARC KEY'
  17. def __init__(self, store=None):
  18. if store:
  19. self.open(self.find_key_file(store))
  20. def find_key_file(self, store):
  21. id = store.id.encode('hex')
  22. keys_dir = get_keys_dir()
  23. for name in os.listdir(keys_dir):
  24. filename = os.path.join(keys_dir, name)
  25. with open(filename, 'rb') as fd:
  26. line = fd.readline().strip()
  27. if line and line.startswith(self.FILE_ID) and line[9:] == id:
  28. return filename
  29. raise Exception('Key file for store with ID %s not found' % id)
  30. def open(self, filename):
  31. with open(filename, 'rb') as fd:
  32. lines = fd.readlines()
  33. if not lines[0].startswith(self.FILE_ID) != self.FILE_ID:
  34. raise ValueError('Not a DARC key file')
  35. self.store_id = lines[0][len(self.FILE_ID):].strip().decode('hex')
  36. cdata = (''.join(lines[1:])).decode('base64')
  37. self.password = ''
  38. data = self.decrypt_key_file(cdata, '')
  39. while not data:
  40. self.password = getpass('Key password: ')
  41. if not self.password:
  42. raise Exception('Key decryption failed')
  43. data = self.decrypt_key_file(cdata, self.password)
  44. if not data:
  45. print 'Incorrect password'
  46. key = msgpack.unpackb(data)
  47. if key['version'] != 1:
  48. raise IntegrityError('Invalid key file header')
  49. self.store_id = key['store_id']
  50. self.enc_key = key['enc_key']
  51. self.enc_hmac_key = key['enc_hmac_key']
  52. self.id_key = key['id_key']
  53. self.chunk_seed = key['chunk_seed']
  54. self.counter = Counter.new(64, initial_value=1, prefix=PREFIX)
  55. def post_manifest_load(self, config):
  56. iv = bytes_to_long(config['aes_counter'])+100
  57. self.counter = Counter.new(64, initial_value=iv, prefix=PREFIX)
  58. def pre_manifest_write(self, manifest):
  59. manifest.config['aes_counter'] = long_to_bytes(self.counter.next_value(), 8)
  60. def encrypt_key_file(self, data, password):
  61. salt = get_random_bytes(32)
  62. iterations = 2000
  63. key = pbkdf2(password, salt, 32, iterations, hashlib.sha256)
  64. hash = HMAC.new(key, data, SHA256).digest()
  65. cdata = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(data)
  66. d = {
  67. 'version': 1,
  68. 'salt': salt,
  69. 'iterations': iterations,
  70. 'algorithm': 'SHA256',
  71. 'hash': hash,
  72. 'data': cdata,
  73. }
  74. return msgpack.packb(d)
  75. def decrypt_key_file(self, data, password):
  76. d = msgpack.unpackb(data)
  77. assert d['version'] == 1
  78. assert d['algorithm'] == 'SHA256'
  79. key = pbkdf2(password, d['salt'], 32, d['iterations'], hashlib.sha256)
  80. data = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).decrypt(d['data'])
  81. if HMAC.new(key, data, SHA256).digest() != d['hash']:
  82. return None
  83. return data
  84. def save(self, path, password):
  85. key = {
  86. 'version': 1,
  87. 'store_id': self.store_id,
  88. 'enc_key': self.enc_key,
  89. 'enc_hmac_key': self.enc_hmac_key,
  90. 'id_key': self.enc_key,
  91. 'chunk_seed': self.chunk_seed,
  92. }
  93. data = self.encrypt_key_file(msgpack.packb(key), password)
  94. with open(path, 'wb') as fd:
  95. fd.write('%s %s\n' % (self.FILE_ID, self.store_id.encode('hex')))
  96. fd.write(data.encode('base64'))
  97. print 'Key file "%s" created' % path
  98. def chpass(self):
  99. password, password2 = 1, 2
  100. while password != password2:
  101. password = getpass('New password: ')
  102. password2 = getpass('New password again: ')
  103. if password != password2:
  104. print 'Passwords do not match'
  105. self.save(self.path, password)
  106. return 0
  107. @staticmethod
  108. def create(store, filename, password=None):
  109. i = 1
  110. path = filename
  111. while os.path.exists(path):
  112. i += 1
  113. path = filename + '.%d' % i
  114. if password is not None:
  115. password2 = password
  116. else:
  117. password, password2 = 1, 2
  118. while password != password2:
  119. password = getpass('Key password: ')
  120. password2 = getpass('Key password again: ')
  121. if password != password2:
  122. print 'Passwords do not match'
  123. key = Key()
  124. key.store_id = store.id
  125. # Chunk AES256 encryption key
  126. key.enc_key = get_random_bytes(32)
  127. # Chunk encryption HMAC key
  128. key.enc_hmac_key = get_random_bytes(32)
  129. # Chunk id HMAC key
  130. key.id_key = get_random_bytes(32)
  131. # Chunkifier seed
  132. key.chunk_seed = bytes_to_long(get_random_bytes(4))
  133. # Convert to signed int32
  134. if key.chunk_seed & 0x80000000:
  135. key.chunk_seed = key.chunk_seed - 0xffffffff - 1
  136. key.save(path, password)
  137. return 0
  138. def id_hash(self, data):
  139. """Return HMAC hash using the "id" HMAC key
  140. """
  141. return HMAC.new(self.id_key, data, SHA256).digest()
  142. def encrypt(self, data):
  143. data = zlib.compress(data)
  144. nonce = long_to_bytes(self.counter.next_value(), 8)
  145. data = ''.join((nonce, AES.new(self.enc_key, AES.MODE_CTR, '',
  146. counter=self.counter).encrypt(data)))
  147. hash = HMAC.new(self.enc_hmac_key, data, SHA256).digest()
  148. return ''.join(('\0', hash, data))
  149. def decrypt(self, id, data):
  150. if data[0] != '\0':
  151. raise IntegrityError('Invalid encryption envelope')
  152. hash = data[1:33]
  153. if HMAC.new(self.enc_hmac_key, data[33:], SHA256).digest() != hash:
  154. raise IntegrityError('Encryption envelope checksum mismatch')
  155. nonce = bytes_to_long(data[33:41])
  156. counter = Counter.new(64, initial_value=nonce, prefix=PREFIX)
  157. data = zlib.decompress(AES.new(self.enc_key, AES.MODE_CTR, counter=counter).decrypt(data[41:]))
  158. if id and HMAC.new(self.id_key, data, SHA256).digest() != id:
  159. raise IntegrityError('Chunk id verification failed')
  160. return data