key.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. from binascii import hexlify, a2b_base64, b2a_base64
  2. from getpass import getpass
  3. import os
  4. import msgpack
  5. import textwrap
  6. import hmac
  7. from hashlib import sha256
  8. import zlib
  9. from .crypto import pbkdf2_sha256, get_random_bytes, AES, bytes_to_long, long_to_bytes, bytes_to_int
  10. from .helpers import IntegrityError, get_keys_dir
  11. PREFIX = b'\0' * 8
  12. KEYFILE = b'\0'
  13. PASSPHRASE = b'\1'
  14. PLAINTEXT = b'\2'
  15. class HMAC(hmac.HMAC):
  16. def update(self, msg):
  17. self.inner.update(msg)
  18. def key_creator(repository, args):
  19. if args.keyfile:
  20. return KeyfileKey.create(repository, args)
  21. elif args.passphrase:
  22. return PassphraseKey.create(repository, args)
  23. else:
  24. return PlaintextKey.create(repository, args)
  25. def key_factory(repository, manifest_data):
  26. if manifest_data[:1] == KEYFILE:
  27. return KeyfileKey.detect(repository, manifest_data)
  28. elif manifest_data[:1] == PASSPHRASE:
  29. return PassphraseKey.detect(repository, manifest_data)
  30. elif manifest_data[:1] == PLAINTEXT:
  31. return PlaintextKey.detect(repository, manifest_data)
  32. else:
  33. raise Exception('Unkown Key type %d' % ord(manifest_data[0]))
  34. class KeyBase(object):
  35. def id_hash(self, data):
  36. """Return HMAC hash using the "id" HMAC key
  37. """
  38. def encrypt(self, data):
  39. pass
  40. def decrypt(self, id, data):
  41. pass
  42. class PlaintextKey(KeyBase):
  43. TYPE = PLAINTEXT
  44. chunk_seed = 0
  45. @classmethod
  46. def create(cls, repository, args):
  47. print('Encryption NOT enabled.\nUse the --key-file or --passphrase options to enable encryption.')
  48. return cls()
  49. @classmethod
  50. def detect(cls, repository, manifest_data):
  51. return cls()
  52. def id_hash(self, data):
  53. return sha256(data).digest()
  54. def encrypt(self, data):
  55. return b''.join([self.TYPE, zlib.compress(data)])
  56. def decrypt(self, id, data):
  57. if data[:1] != self.TYPE:
  58. raise IntegrityError('Invalid encryption envelope')
  59. data = zlib.decompress(memoryview(data)[1:])
  60. if id and sha256(data).digest() != id:
  61. raise IntegrityError('Chunk id verification failed')
  62. return data
  63. class AESKeyBase(KeyBase):
  64. def id_hash(self, data):
  65. """Return HMAC hash using the "id" HMAC key
  66. """
  67. return HMAC(self.id_key, data, sha256).digest()
  68. def encrypt(self, data):
  69. data = zlib.compress(data)
  70. self.enc_cipher.reset()
  71. data = b''.join((self.enc_cipher.iv[8:], self.enc_cipher.encrypt(data)))
  72. hash = HMAC(self.enc_hmac_key, data, sha256).digest()
  73. return b''.join((self.TYPE, hash, data))
  74. def decrypt(self, id, data):
  75. if data[:1] != self.TYPE:
  76. raise IntegrityError('Invalid encryption envelope')
  77. hash = memoryview(data)[1:33]
  78. if memoryview(HMAC(self.enc_hmac_key, memoryview(data)[33:], sha256).digest()) != hash:
  79. raise IntegrityError('Encryption envelope checksum mismatch')
  80. self.dec_cipher.reset(iv=PREFIX + data[33:41])
  81. data = zlib.decompress(self.dec_cipher.decrypt(data[41:])) # should use memoryview
  82. if id and HMAC(self.id_key, data, sha256).digest() != id:
  83. raise IntegrityError('Chunk id verification failed')
  84. return data
  85. def extract_iv(self, payload):
  86. if payload[:1] != self.TYPE:
  87. raise IntegrityError('Invalid encryption envelope')
  88. nonce = bytes_to_long(payload[33:41])
  89. return nonce
  90. def init_from_random_data(self, data):
  91. self.enc_key = data[0:32]
  92. self.enc_hmac_key = data[32:64]
  93. self.id_key = data[64:96]
  94. self.chunk_seed = bytes_to_int(data[96:100])
  95. # Convert to signed int32
  96. if self.chunk_seed & 0x80000000:
  97. self.chunk_seed = self.chunk_seed - 0xffffffff - 1
  98. def init_ciphers(self, enc_iv=b''):
  99. self.enc_cipher = AES(self.enc_key, enc_iv)
  100. self.dec_cipher = AES(self.enc_key)
  101. class PassphraseKey(AESKeyBase):
  102. TYPE = PASSPHRASE
  103. iterations = 100000
  104. @classmethod
  105. def create(cls, repository, args):
  106. key = cls()
  107. passphrase = os.environ.get('DARC_PASSPHRASE')
  108. if passphrase is not None:
  109. passphrase2 = passphrase
  110. else:
  111. passphrase, passphrase2 = 1, 2
  112. while passphrase != passphrase2:
  113. passphrase = getpass('Enter passphrase: ')
  114. if not passphrase:
  115. print('Passphrase must not be blank')
  116. continue
  117. passphrase2 = getpass('Enter same passphrase again: ')
  118. if passphrase != passphrase2:
  119. print('Passphrases do not match')
  120. key.init(repository, passphrase)
  121. if passphrase:
  122. print('Remember your passphrase. Your data will be inaccessible without it.')
  123. return key
  124. @classmethod
  125. def detect(cls, repository, manifest_data):
  126. prompt = 'Enter passphrase for %s: ' % repository._location.orig
  127. key = cls()
  128. passphrase = os.environ.get('DARC_PASSPHRASE')
  129. if passphrase is None:
  130. passphrase = getpass(prompt)
  131. while True:
  132. key.init(repository, passphrase)
  133. try:
  134. key.decrypt(None, manifest_data)
  135. key.init_ciphers(PREFIX + long_to_bytes(key.extract_iv(manifest_data) + 1000))
  136. return key
  137. except IntegrityError:
  138. passphrase = getpass(prompt)
  139. def init(self, repository, passphrase):
  140. self.init_from_random_data(pbkdf2_sha256(passphrase.encode('utf-8'), repository.id, self.iterations, 100))
  141. self.init_ciphers()
  142. class KeyfileKey(AESKeyBase):
  143. FILE_ID = 'DARC KEY'
  144. TYPE = KEYFILE
  145. @classmethod
  146. def detect(cls, repository, manifest_data):
  147. key = cls()
  148. path = cls.find_key_file(repository)
  149. prompt = 'Enter passphrase for key file %s: ' % path
  150. passphrase = os.environ.get('DARC_PASSPHRASE', '')
  151. while not key.load(path, passphrase):
  152. passphrase = getpass(prompt)
  153. key.init_ciphers(PREFIX + long_to_bytes(key.extract_iv(manifest_data) + 1000))
  154. return key
  155. @classmethod
  156. def find_key_file(cls, repository):
  157. id = hexlify(repository.id).decode('ascii')
  158. keys_dir = get_keys_dir()
  159. for name in os.listdir(keys_dir):
  160. filename = os.path.join(keys_dir, name)
  161. with open(filename, 'r') as fd:
  162. line = fd.readline().strip()
  163. if line and line.startswith(cls.FILE_ID) and line[9:] == id:
  164. return filename
  165. raise Exception('Key file for repository with ID %s not found' % id)
  166. def load(self, filename, passphrase):
  167. with open(filename, 'r') as fd:
  168. cdata = a2b_base64(''.join(fd.readlines()[1:]).encode('ascii')) # .encode needed for Python 3.[0-2]
  169. data = self.decrypt_key_file(cdata, passphrase)
  170. if data:
  171. key = msgpack.unpackb(data)
  172. if key[b'version'] != 1:
  173. raise IntegrityError('Invalid key file header')
  174. self.repository_id = key[b'repository_id']
  175. self.enc_key = key[b'enc_key']
  176. self.enc_hmac_key = key[b'enc_hmac_key']
  177. self.id_key = key[b'id_key']
  178. self.chunk_seed = key[b'chunk_seed']
  179. self.path = filename
  180. return True
  181. def decrypt_key_file(self, data, passphrase):
  182. d = msgpack.unpackb(data)
  183. assert d[b'version'] == 1
  184. assert d[b'algorithm'] == b'sha256'
  185. key = pbkdf2_sha256(passphrase.encode('utf-8'), d[b'salt'], d[b'iterations'], 32)
  186. data = AES(key).decrypt(d[b'data'])
  187. if HMAC(key, data, sha256).digest() != d[b'hash']:
  188. return None
  189. return data
  190. def encrypt_key_file(self, data, passphrase):
  191. salt = get_random_bytes(32)
  192. iterations = 100000
  193. key = pbkdf2_sha256(passphrase.encode('utf-8'), salt, iterations, 32)
  194. hash = HMAC(key, data, sha256).digest()
  195. cdata = AES(key).encrypt(data)
  196. d = {
  197. 'version': 1,
  198. 'salt': salt,
  199. 'iterations': iterations,
  200. 'algorithm': 'sha256',
  201. 'hash': hash,
  202. 'data': cdata,
  203. }
  204. return msgpack.packb(d)
  205. def save(self, path, passphrase):
  206. key = {
  207. 'version': 1,
  208. 'repository_id': self.repository_id,
  209. 'enc_key': self.enc_key,
  210. 'enc_hmac_key': self.enc_hmac_key,
  211. 'id_key': self.id_key,
  212. 'chunk_seed': self.chunk_seed,
  213. }
  214. data = self.encrypt_key_file(msgpack.packb(key), passphrase)
  215. with open(path, 'w') as fd:
  216. fd.write('%s %s\n' % (self.FILE_ID, hexlify(self.repository_id).decode('ascii')))
  217. fd.write('\n'.join(textwrap.wrap(b2a_base64(data).decode('ascii'))))
  218. self.path = path
  219. def change_passphrase(self):
  220. passphrase, passphrase2 = 1, 2
  221. while passphrase != passphrase2:
  222. passphrase = getpass('New passphrase: ')
  223. passphrase2 = getpass('Enter same passphrase again: ')
  224. if passphrase != passphrase2:
  225. print('Passphrases do not match')
  226. self.save(self.path, passphrase)
  227. print('Key file "%s" updated' % self.path)
  228. @classmethod
  229. def create(cls, repository, args):
  230. filename = args.repository.to_key_filename()
  231. path = filename
  232. i = 1
  233. while os.path.exists(path):
  234. i += 1
  235. path = filename + '.%d' % i
  236. passphrase = os.environ.get('DARC_PASSPHRASE')
  237. if passphrase is not None:
  238. passphrase2 = passphrase
  239. else:
  240. passphrase, passphrase2 = 1, 2
  241. while passphrase != passphrase2:
  242. passphrase = getpass('Enter passphrase (empty for no passphrase):')
  243. passphrase2 = getpass('Enter same passphrase again: ')
  244. if passphrase != passphrase2:
  245. print('Passphrases do not match')
  246. key = cls()
  247. key.repository_id = repository.id
  248. key.init_from_random_data(get_random_bytes(100))
  249. key.init_ciphers()
  250. key.save(path, passphrase)
  251. print('Key file "%s" created.' % key.path)
  252. print('Keep this file safe. Your data will be inaccessible without it.')
  253. return key