key.py 13 KB

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