key.py 11 KB

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