key.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. class Key(object):
  15. FILE_ID = 'DARC KEY'
  16. def __init__(self, store=None):
  17. if store:
  18. self.open(self.find_key_file(store))
  19. def find_key_file(self, store):
  20. id = store.meta['id']
  21. keys_dir = get_keys_dir()
  22. for name in os.listdir(keys_dir):
  23. filename = os.path.join(keys_dir, name)
  24. with open(filename, 'rb') as fd:
  25. line = fd.readline().strip()
  26. if line and line.startswith(self.FILE_ID) and line[9:] == id:
  27. return filename
  28. raise Exception('Key file for store with ID %s not found' % id)
  29. def open(self, filename):
  30. with open(filename, 'rb') as fd:
  31. lines = fd.readlines()
  32. if not lines[0].startswith(self.FILE_ID) != self.FILE_ID:
  33. raise ValueError('Not a DARC key file')
  34. self.store_id = lines[0][len(self.FILE_ID):].strip().decode('hex')
  35. cdata = (''.join(lines[1:])).decode('base64')
  36. self.password = ''
  37. data = self.decrypt_key_file(cdata, '')
  38. while not data:
  39. self.password = getpass('Key password: ')
  40. if not self.password:
  41. raise Exception('Key decryption failed')
  42. data = self.decrypt_key_file(cdata, self.password)
  43. if not data:
  44. print 'Incorrect password'
  45. key = msgpack.unpackb(data)
  46. if key['version'] != 1:
  47. raise IntegrityError('Invalid key file header')
  48. self.store_id = key['store_id']
  49. self.enc_key = key['enc_key']
  50. self.enc_hmac_key = key['enc_hmac_key']
  51. self.id_key = key['id_key']
  52. self.chunk_seed = key['chunk_seed']
  53. self.counter = Counter.new(128, initial_value=bytes_to_long(os.urandom(16)), allow_wraparound=True)
  54. def encrypt_key_file(self, data, password):
  55. salt = get_random_bytes(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_key_file(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. key = {
  80. 'version': 1,
  81. 'store_id': self.store_id,
  82. 'enc_key': self.enc_key,
  83. 'enc_hmac_key': self.enc_hmac_key,
  84. 'id_key': self.enc_key,
  85. 'chunk_seed': self.chunk_seed,
  86. }
  87. data = self.encrypt_key_file(msgpack.packb(key), password)
  88. with open(path, 'wb') as fd:
  89. fd.write('%s %s\n' % (self.FILE_ID, self.store_id.encode('hex')))
  90. fd.write(data.encode('base64'))
  91. print 'Key file "%s" created' % path
  92. def chpass(self):
  93. password, password2 = 1, 2
  94. while password != password2:
  95. password = getpass('New password: ')
  96. password2 = getpass('New password again: ')
  97. if password != password2:
  98. print 'Passwords do not match'
  99. self.save(self.path, password)
  100. return 0
  101. @staticmethod
  102. def create(store, filename, password=None):
  103. i = 1
  104. path = filename
  105. while os.path.exists(path):
  106. i += 1
  107. path = filename + '.%d' % i
  108. if password is not None:
  109. password2 = password
  110. else:
  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. key = Key()
  118. key.store_id = store.meta['id'].decode('hex')
  119. # Chunk AES256 encryption key
  120. key.enc_key = get_random_bytes(32)
  121. # Chunk encryption HMAC key
  122. key.enc_hmac_key = get_random_bytes(32)
  123. # Chunk id HMAC key
  124. key.id_key = get_random_bytes(32)
  125. # Chunkifier seed
  126. key.chunk_seed = bytes_to_long(get_random_bytes(4)) & 0x7fffffff
  127. key.save(path, password)
  128. return 0
  129. def id_hash(self, data):
  130. """Return HMAC hash using the "id" HMAC key
  131. """
  132. return HMAC.new(self.id_key, data, SHA256).digest()
  133. def encrypt(self, data):
  134. data = zlib.compress(data)
  135. nonce = long_to_bytes(self.counter.next_value(), 16)
  136. data = ''.join((nonce, AES.new(self.enc_key, AES.MODE_CTR, '',
  137. counter=self.counter).encrypt(data)))
  138. hash = HMAC.new(self.enc_hmac_key, data, SHA256).digest()
  139. return ''.join(('\0', hash, data))
  140. def decrypt(self, id, data):
  141. if data[0] != '\0':
  142. raise IntegrityError('Invalid encryption envelope')
  143. hash = data[1:33]
  144. if HMAC.new(self.enc_hmac_key, data[33:], SHA256).digest() != hash:
  145. raise IntegrityError('Encryption envelope checksum mismatch')
  146. nonce = bytes_to_long(data[33:49])
  147. counter = Counter.new(128, initial_value=nonce, allow_wraparound=True)
  148. data = zlib.decompress(AES.new(self.enc_key, AES.MODE_CTR, counter=counter).decrypt(data[49:]))
  149. if HMAC.new(self.id_key, data, SHA256).digest() != id:
  150. raise IntegrityError('Chunk id verification failed')
  151. return data