key.py 11 KB

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