key.py 6.7 KB

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