key.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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.id.encode('hex')
  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.archive_key = key['archive_key']
  53. self.chunk_seed = key['chunk_seed']
  54. self.counter = Counter.new(128, initial_value=bytes_to_long(os.urandom(16)), allow_wraparound=True)
  55. def encrypt_key_file(self, data, password):
  56. salt = get_random_bytes(32)
  57. iterations = 2000
  58. key = pbkdf2(password, salt, 32, iterations, hashlib.sha256)
  59. hash = HMAC.new(key, data, SHA256).digest()
  60. cdata = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(data)
  61. d = {
  62. 'version': 1,
  63. 'salt': salt,
  64. 'iterations': iterations,
  65. 'algorithm': 'SHA256',
  66. 'hash': hash,
  67. 'data': cdata,
  68. }
  69. return msgpack.packb(d)
  70. def decrypt_key_file(self, data, password):
  71. d = msgpack.unpackb(data)
  72. assert d['version'] == 1
  73. assert d['algorithm'] == 'SHA256'
  74. key = pbkdf2(password, d['salt'], 32, d['iterations'], hashlib.sha256)
  75. data = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).decrypt(d['data'])
  76. if HMAC.new(key, data, SHA256).digest() != d['hash']:
  77. return None
  78. return data
  79. def save(self, path, password):
  80. key = {
  81. 'version': 1,
  82. 'store_id': self.store_id,
  83. 'enc_key': self.enc_key,
  84. 'enc_hmac_key': self.enc_hmac_key,
  85. 'id_key': self.enc_key,
  86. 'archive_key': self.enc_key,
  87. 'chunk_seed': self.chunk_seed,
  88. }
  89. data = self.encrypt_key_file(msgpack.packb(key), password)
  90. with open(path, 'wb') as fd:
  91. fd.write('%s %s\n' % (self.FILE_ID, self.store_id.encode('hex')))
  92. fd.write(data.encode('base64'))
  93. print 'Key file "%s" created' % path
  94. def chpass(self):
  95. password, password2 = 1, 2
  96. while password != password2:
  97. password = getpass('New password: ')
  98. password2 = getpass('New password again: ')
  99. if password != password2:
  100. print 'Passwords do not match'
  101. self.save(self.path, password)
  102. return 0
  103. @staticmethod
  104. def create(store, filename, password=None):
  105. i = 1
  106. path = filename
  107. while os.path.exists(path):
  108. i += 1
  109. path = filename + '.%d' % i
  110. if password is not None:
  111. password2 = password
  112. else:
  113. password, password2 = 1, 2
  114. while password != password2:
  115. password = getpass('Keychain password: ')
  116. password2 = getpass('Keychain password again: ')
  117. if password != password2:
  118. print 'Passwords do not match'
  119. key = Key()
  120. key.store_id = store.id
  121. # Chunk AES256 encryption key
  122. key.enc_key = get_random_bytes(32)
  123. # Chunk encryption HMAC key
  124. key.enc_hmac_key = get_random_bytes(32)
  125. # Chunk id HMAC key
  126. key.id_key = get_random_bytes(32)
  127. # Archive name HMAC key
  128. key.archive_key = get_random_bytes(32)
  129. # Chunkifier seed
  130. key.chunk_seed = bytes_to_long(get_random_bytes(4)) & 0x7fffffff
  131. key.save(path, password)
  132. return 0
  133. def id_hash(self, data):
  134. """Return HMAC hash using the "id" HMAC key
  135. """
  136. return HMAC.new(self.id_key, data, SHA256).digest()
  137. def archive_hash(self, data):
  138. """Return HMAC hash using the "archive" HMAC key
  139. """
  140. return HMAC.new(self.archive_key, data, SHA256).digest()
  141. def encrypt(self, data):
  142. data = zlib.compress(data)
  143. nonce = long_to_bytes(self.counter.next_value(), 16)
  144. data = ''.join((nonce, AES.new(self.enc_key, AES.MODE_CTR, '',
  145. counter=self.counter).encrypt(data)))
  146. hash = HMAC.new(self.enc_hmac_key, data, SHA256).digest()
  147. return ''.join(('\0', hash, data)), hash
  148. def decrypt(self, data):
  149. if data[0] != '\0':
  150. raise IntegrityError('Invalid encryption envelope')
  151. hash = data[1:33]
  152. if HMAC.new(self.enc_hmac_key, data[33:], SHA256).digest() != hash:
  153. raise IntegrityError('Encryption envelope checksum mismatch')
  154. nonce = bytes_to_long(data[33:49])
  155. counter = Counter.new(128, initial_value=nonce, allow_wraparound=True)
  156. data = AES.new(self.enc_key, AES.MODE_CTR, counter=counter).decrypt(data[49:])
  157. return zlib.decompress(data), hash