key.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. from binascii import hexlify, a2b_base64, b2a_base64
  2. from getpass import getpass
  3. import os
  4. import msgpack
  5. import textwrap
  6. from collections import namedtuple
  7. import hmac
  8. from hashlib import sha256, sha512
  9. import zlib
  10. try:
  11. import lzma # python >= 3.3
  12. except ImportError:
  13. try:
  14. from backports import lzma # backports.lzma from pypi
  15. except ImportError:
  16. lzma = None
  17. from attic.crypto import pbkdf2_sha256, get_random_bytes, AES, bytes_to_long, long_to_bytes, bytes_to_int, num_aes_blocks
  18. from attic.helpers import IntegrityError, get_keys_dir, Error
  19. # we do not store the full IV on disk, as the upper 8 bytes are expected to be
  20. # zero anyway as the full IV is a 128bit counter. PREFIX are the upper 8 bytes,
  21. # stored_iv are the lower 8 Bytes.
  22. PREFIX = b'\0' * 8
  23. Meta = namedtuple('Meta', 'compr_type, crypt_type, mac_type, cipher_type, hmac, stored_iv')
  24. class UnsupportedPayloadError(Error):
  25. """Unsupported payload type {}. A newer version is required to access this repository.
  26. """
  27. class sha512_256(object): # note: can't subclass sha512
  28. """sha512, but digest truncated to 256bit - faster than sha256 on 64bit platforms"""
  29. digestsize = digest_size = 32
  30. block_size = 64
  31. def __init__(self, data=None):
  32. self.name = 'sha512-256'
  33. self._h = sha512()
  34. if data:
  35. self.update(data)
  36. def update(self, data):
  37. self._h.update(data)
  38. def digest(self):
  39. return self._h.digest()[:self.digest_size]
  40. def hexdigest(self):
  41. return self._h.hexdigest()[:self.digest_size * 2]
  42. def copy(self):
  43. new = sha512_256.__new__(sha512_256)
  44. new._h = self._h.copy()
  45. return new
  46. class HMAC(hmac.HMAC):
  47. """Workaround a bug in Python < 3.4 Where HMAC does not accept memoryviews
  48. """
  49. def update(self, msg):
  50. self.inner.update(msg)
  51. class SHA256(object): # note: can't subclass sha256
  52. TYPE = 0
  53. def __init__(self, key, data=b''):
  54. # signature is like for a MAC, we ignore the key as this is a simple hash
  55. if key is not None:
  56. raise Exception("use a HMAC if you have a key")
  57. self.h = sha256(data)
  58. def update(self, data):
  59. self.h.update(data)
  60. def digest(self):
  61. return self.h.digest()
  62. def hexdigest(self):
  63. return self.h.hexdigest()
  64. class SHA512_256(sha512_256):
  65. """sha512, but digest truncated to 256bit - faster than sha256 on 64bit platforms"""
  66. TYPE = 1
  67. def __init__(self, key, data):
  68. # signature is like for a MAC, we ignore the key as this is a simple hash
  69. if key is not None:
  70. raise Exception("use a HMAC if you have a key")
  71. super().__init__(data)
  72. HASH_DEFAULT = SHA256.TYPE
  73. class HMAC_SHA256(HMAC):
  74. TYPE = 10
  75. def __init__(self, key, data):
  76. if key is None:
  77. raise Exception("do not use HMAC if you don't have a key")
  78. super().__init__(key, data, sha256)
  79. class HMAC_SHA512_256(HMAC):
  80. TYPE = 11
  81. def __init__(self, key, data):
  82. if key is None:
  83. raise Exception("do not use HMAC if you don't have a key")
  84. super().__init__(key, data, sha512_256)
  85. class GMAC:
  86. TYPE = 20
  87. def __init__(self, key, data):
  88. if key is None:
  89. raise Exception("do not use GMAC if you don't have a key")
  90. self.key = key
  91. self.data = data
  92. def digest(self):
  93. mac_cipher = AES(is_encrypt=True, key=self.key, iv=b'\0' * 16)
  94. # GMAC = aes-gcm with all data as AAD, no data as to-be-encrypted data
  95. mac_cipher.add(bytes(self.data))
  96. tag, _ = mac_cipher.compute_tag_and_encrypt(b'')
  97. return tag
  98. MAC_DEFAULT = GMAC.TYPE
  99. class ZlibCompressor(object): # uses 0..9 in the mapping
  100. TYPE = 0
  101. LEVELS = range(10)
  102. def compress(self, data):
  103. level = self.TYPE - ZlibCompressor.TYPE
  104. return zlib.compress(data, level)
  105. def decompress(self, data):
  106. return zlib.decompress(data)
  107. class LzmaCompressor(object): # uses 10..19 in the mapping
  108. TYPE = 10
  109. PRESETS = range(10)
  110. def __init__(self):
  111. if lzma is None:
  112. raise NotImplemented("lzma compression needs Python >= 3.3 or backports.lzma from PyPi")
  113. def compress(self, data):
  114. preset = self.TYPE - LzmaCompressor.TYPE
  115. return lzma.compress(data, preset=preset)
  116. def decompress(self, data):
  117. return lzma.decompress(data)
  118. COMPR_DEFAULT = ZlibCompressor.TYPE + 6 # zlib level 6
  119. class PLAIN:
  120. TYPE = 0
  121. def __init__(self, **kw):
  122. pass
  123. def compute_tag_and_encrypt(self, data):
  124. return b'', b'', data
  125. def check_tag_and_decrypt(self, tag, iv_last8, data):
  126. return data
  127. class AES_CTR_HMAC:
  128. TYPE = 1
  129. # TODO
  130. class AES_GCM:
  131. TYPE = 2
  132. def __init__(self, enc_key=b'\0' * 32, enc_iv=b'\0' * 16, **kw):
  133. # note: hmac_key is not used for aes-gcm, it does aes+gmac in 1 pass
  134. self.enc_iv = enc_iv
  135. self.enc_cipher = AES(is_encrypt=True, key=enc_key, iv=enc_iv)
  136. self.dec_cipher = AES(is_encrypt=False, key=enc_key)
  137. def compute_tag_and_encrypt(self, data):
  138. self.enc_cipher.reset(iv=self.enc_iv)
  139. iv_last8 = self.enc_iv[8:]
  140. self.enc_cipher.add(iv_last8)
  141. tag, data = self.enc_cipher.compute_tag_and_encrypt(data)
  142. # increase the IV (counter) value so same value is never used twice
  143. current_iv = bytes_to_long(iv_last8)
  144. self.enc_iv = PREFIX + long_to_bytes(current_iv + num_aes_blocks(len(data)))
  145. return tag, iv_last8, data
  146. def check_tag_and_decrypt(self, tag, iv_last8, data):
  147. iv = PREFIX + iv_last8
  148. self.dec_cipher.reset(iv=iv)
  149. self.dec_cipher.add(iv_last8)
  150. try:
  151. data = self.dec_cipher.check_tag_and_decrypt(tag, data)
  152. except Exception:
  153. raise IntegrityError('Encryption envelope checksum mismatch')
  154. return data
  155. PLAIN_DEFAULT = PLAIN.TYPE
  156. CIPHER_DEFAULT = AES_GCM.TYPE
  157. class KeyBase(object):
  158. TYPE = 0x00 # override in derived classes
  159. def __init__(self, compressor_cls, maccer_cls, cipher_cls):
  160. self.compressor = compressor_cls()
  161. self.maccer_cls = maccer_cls # hasher/maccer used by id_hash
  162. self.cipher_cls = cipher_cls # plaintext dummy or AEAD cipher
  163. self.cipher = cipher_cls()
  164. self.id_key = None
  165. def id_hash(self, data):
  166. """Return a HASH (no id_key) or a MAC (using the "id_key" key)
  167. XXX do we need a cryptographic hash function here or is a keyed hash
  168. function like GMAC / GHASH good enough? See NIST SP 800-38D.
  169. IMPORTANT: in 1 repo, there should be only 1 kind of id_hash, otherwise
  170. data hashed/maced with one id_hash might result in same ID as already
  171. exists in the repo for other data created with another id_hash method.
  172. somehow unlikely considering 128 or 256bits, but still.
  173. """
  174. return self.maccer_cls(self.id_key, data).digest()
  175. def encrypt(self, data):
  176. data = self.compressor.compress(data)
  177. tag, iv_last8, data = self.cipher.compute_tag_and_encrypt(data)
  178. meta = Meta(compr_type=self.compressor.TYPE, crypt_type=self.TYPE,
  179. mac_type=self.maccer_cls.TYPE, cipher_type=self.cipher.TYPE,
  180. hmac=tag, stored_iv=iv_last8)
  181. return generate(meta, data)
  182. def decrypt(self, id, data):
  183. meta, data, compressor, crypter, maccer, cipher = parser(data)
  184. assert isinstance(self, crypter)
  185. assert self.maccer_cls is maccer
  186. assert self.cipher_cls is cipher
  187. data = self.cipher.check_tag_and_decrypt(meta.hmac, meta.stored_iv, data)
  188. data = self.compressor.decompress(data)
  189. if id and self.id_hash(data) != id:
  190. raise IntegrityError('Chunk id verification failed')
  191. return data
  192. class PlaintextKey(KeyBase):
  193. TYPE = 0x02
  194. chunk_seed = 0
  195. @classmethod
  196. def create(cls, repository, args):
  197. print('Encryption NOT enabled.\nUse the "--encryption=passphrase|keyfile" to enable encryption.')
  198. compressor = compressor_creator(args)
  199. maccer = maccer_creator(args, cls)
  200. cipher = cipher_creator(args, cls)
  201. return cls(compressor, maccer, cipher)
  202. @classmethod
  203. def detect(cls, repository, manifest_data):
  204. meta, data, compressor, crypter, maccer, cipher = parser(manifest_data)
  205. return cls(compressor, maccer, cipher)
  206. class AESKeyBase(KeyBase):
  207. """Common base class shared by KeyfileKey and PassphraseKey
  208. Chunks are encrypted using 256bit AES in Galois Counter Mode (GCM)
  209. Payload layout: TYPE(1) + TAG(32) + NONCE(8) + CIPHERTEXT
  210. To reduce payload size only 8 bytes of the 16 bytes nonce is saved
  211. in the payload, the first 8 bytes are always zeros. This does not
  212. affect security but limits the maximum repository capacity to
  213. only 295 exabytes!
  214. """
  215. def extract_nonce(self, payload):
  216. meta, data, compressor, crypter, maccer, cipher = parser(payload)
  217. assert isinstance(self, crypter)
  218. nonce = bytes_to_long(meta.stored_iv)
  219. return nonce
  220. def init_from_random_data(self, data):
  221. self.enc_key = data[0:32]
  222. self.enc_hmac_key = data[32:64]
  223. self.id_key = data[64:96]
  224. self.chunk_seed = bytes_to_int(data[96:100])
  225. # Convert to signed int32
  226. if self.chunk_seed & 0x80000000:
  227. self.chunk_seed = self.chunk_seed - 0xffffffff - 1
  228. def init_ciphers(self, enc_iv=b'\0' * 16):
  229. self.cipher = self.cipher_cls(enc_key=self.enc_key, enc_iv=enc_iv,
  230. enc_hmac_key=self.enc_hmac_key)
  231. @property
  232. def enc_iv(self):
  233. return self.cipher.enc_iv
  234. class PassphraseKey(AESKeyBase):
  235. TYPE = 0x01
  236. iterations = 100000
  237. @classmethod
  238. def create(cls, repository, args):
  239. compressor = compressor_creator(args)
  240. maccer = maccer_creator(args, cls)
  241. cipher = cipher_creator(args, cls)
  242. key = cls(compressor, maccer, cipher)
  243. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  244. if passphrase is not None:
  245. passphrase2 = passphrase
  246. else:
  247. passphrase, passphrase2 = 1, 2
  248. while passphrase != passphrase2:
  249. passphrase = getpass('Enter passphrase: ')
  250. if not passphrase:
  251. print('Passphrase must not be blank')
  252. continue
  253. passphrase2 = getpass('Enter same passphrase again: ')
  254. if passphrase != passphrase2:
  255. print('Passphrases do not match')
  256. key.init(repository, passphrase)
  257. if passphrase:
  258. print('Remember your passphrase. Your data will be inaccessible without it.')
  259. return key
  260. @classmethod
  261. def detect(cls, repository, manifest_data):
  262. prompt = 'Enter passphrase for %s: ' % repository._location.orig
  263. meta, data, compressor, crypter, maccer, cipher = parser(manifest_data)
  264. key = cls(compressor, maccer, cipher)
  265. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  266. if passphrase is None:
  267. passphrase = getpass(prompt)
  268. while True:
  269. key.init(repository, passphrase)
  270. try:
  271. key.decrypt(None, manifest_data)
  272. num_blocks = num_aes_blocks(len(data))
  273. key.init_ciphers(PREFIX + long_to_bytes(key.extract_nonce(manifest_data) + num_blocks))
  274. return key
  275. except IntegrityError:
  276. passphrase = getpass(prompt)
  277. def change_passphrase(self):
  278. class ImmutablePassphraseError(Error):
  279. """The passphrase for this encryption key type can't be changed."""
  280. raise ImmutablePassphraseError
  281. def init(self, repository, passphrase):
  282. self.init_from_random_data(pbkdf2_sha256(passphrase.encode('utf-8'), repository.id, self.iterations, 100))
  283. self.init_ciphers()
  284. class KeyfileKey(AESKeyBase):
  285. FILE_ID = 'ATTIC KEY'
  286. TYPE = 0x00
  287. @classmethod
  288. def detect(cls, repository, manifest_data):
  289. meta, data, compressor, crypter, maccer, cipher = parser(manifest_data)
  290. key = cls(compressor, maccer, cipher)
  291. path = cls.find_key_file(repository)
  292. prompt = 'Enter passphrase for key file %s: ' % path
  293. passphrase = os.environ.get('ATTIC_PASSPHRASE', '')
  294. while not key.load(path, passphrase):
  295. passphrase = getpass(prompt)
  296. num_blocks = num_aes_blocks(len(data))
  297. key.init_ciphers(PREFIX + long_to_bytes(key.extract_nonce(manifest_data) + num_blocks))
  298. return key
  299. @classmethod
  300. def find_key_file(cls, repository):
  301. id = hexlify(repository.id).decode('ascii')
  302. keys_dir = get_keys_dir()
  303. for name in os.listdir(keys_dir):
  304. filename = os.path.join(keys_dir, name)
  305. with open(filename, 'r') as fd:
  306. line = fd.readline().strip()
  307. if line and line.startswith(cls.FILE_ID) and line[10:] == id:
  308. return filename
  309. raise Exception('Key file for repository with ID %s not found' % id)
  310. def load(self, filename, passphrase):
  311. with open(filename, 'r') as fd:
  312. cdata = a2b_base64(''.join(fd.readlines()[1:]).encode('ascii')) # .encode needed for Python 3.[0-2]
  313. data = self.decrypt_key_file(cdata, passphrase)
  314. if data:
  315. key = msgpack.unpackb(data)
  316. if key[b'version'] != 1:
  317. raise IntegrityError('Invalid key file header')
  318. self.repository_id = key[b'repository_id']
  319. self.enc_key = key[b'enc_key']
  320. self.enc_hmac_key = key[b'enc_hmac_key']
  321. self.id_key = key[b'id_key']
  322. self.chunk_seed = key[b'chunk_seed']
  323. self.path = filename
  324. return True
  325. def decrypt_key_file(self, data, passphrase):
  326. d = msgpack.unpackb(data)
  327. assert d[b'version'] == 1
  328. assert d[b'algorithm'] == b'gmac'
  329. key = pbkdf2_sha256(passphrase.encode('utf-8'), d[b'salt'], d[b'iterations'], 32)
  330. try:
  331. data = AES(is_encrypt=False, key=key, iv=b'\0'*16).check_tag_and_decrypt(d[b'hash'], d[b'data'])
  332. return data
  333. except Exception:
  334. return None
  335. def encrypt_key_file(self, data, passphrase):
  336. salt = get_random_bytes(32)
  337. iterations = 100000
  338. key = pbkdf2_sha256(passphrase.encode('utf-8'), salt, iterations, 32)
  339. tag, cdata = AES(is_encrypt=True, key=key, iv=b'\0'*16).compute_tag_and_encrypt(data)
  340. d = {
  341. 'version': 1,
  342. 'salt': salt,
  343. 'iterations': iterations,
  344. 'algorithm': 'gmac',
  345. 'hash': tag,
  346. 'data': cdata,
  347. }
  348. return msgpack.packb(d)
  349. def save(self, path, passphrase):
  350. key = {
  351. 'version': 1,
  352. 'repository_id': self.repository_id,
  353. 'enc_key': self.enc_key,
  354. 'enc_hmac_key': self.enc_hmac_key,
  355. 'id_key': self.id_key,
  356. 'chunk_seed': self.chunk_seed,
  357. }
  358. data = self.encrypt_key_file(msgpack.packb(key), passphrase)
  359. with open(path, 'w') as fd:
  360. fd.write('%s %s\n' % (self.FILE_ID, hexlify(self.repository_id).decode('ascii')))
  361. fd.write('\n'.join(textwrap.wrap(b2a_base64(data).decode('ascii'))))
  362. fd.write('\n')
  363. self.path = path
  364. def change_passphrase(self):
  365. passphrase, passphrase2 = 1, 2
  366. while passphrase != passphrase2:
  367. passphrase = getpass('New passphrase: ')
  368. passphrase2 = getpass('Enter same passphrase again: ')
  369. if passphrase != passphrase2:
  370. print('Passphrases do not match')
  371. self.save(self.path, passphrase)
  372. print('Key file "%s" updated' % self.path)
  373. @classmethod
  374. def create(cls, repository, args):
  375. filename = args.repository.to_key_filename()
  376. path = filename
  377. i = 1
  378. while os.path.exists(path):
  379. i += 1
  380. path = filename + '.%d' % i
  381. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  382. if passphrase is not None:
  383. passphrase2 = passphrase
  384. else:
  385. passphrase, passphrase2 = 1, 2
  386. while passphrase != passphrase2:
  387. passphrase = getpass('Enter passphrase (empty for no passphrase):')
  388. passphrase2 = getpass('Enter same passphrase again: ')
  389. if passphrase != passphrase2:
  390. print('Passphrases do not match')
  391. compressor = compressor_creator(args)
  392. maccer = maccer_creator(args, cls)
  393. cipher = cipher_creator(args, cls)
  394. key = cls(compressor, maccer, cipher)
  395. key.repository_id = repository.id
  396. key.init_from_random_data(get_random_bytes(100))
  397. key.init_ciphers()
  398. key.save(path, passphrase)
  399. print('Key file "%s" created.' % key.path)
  400. print('Keep this file safe. Your data will be inaccessible without it.')
  401. return key
  402. # note: key 0 nicely maps to a zlib compressor with level 0 which means "no compression"
  403. compressor_mapping = {}
  404. for level in ZlibCompressor.LEVELS:
  405. compressor_mapping[ZlibCompressor.TYPE + level] = \
  406. type('ZlibCompressorLevel%d' % level, (ZlibCompressor, ), dict(TYPE=ZlibCompressor.TYPE + level))
  407. for preset in LzmaCompressor.PRESETS:
  408. compressor_mapping[LzmaCompressor.TYPE + preset] = \
  409. type('LzmaCompressorPreset%d' % preset, (LzmaCompressor, ), dict(TYPE=LzmaCompressor.TYPE + preset))
  410. crypter_mapping = {
  411. KeyfileKey.TYPE: KeyfileKey,
  412. PassphraseKey.TYPE: PassphraseKey,
  413. PlaintextKey.TYPE: PlaintextKey,
  414. }
  415. maccer_mapping = {
  416. # simple hashes, not MACs (but MAC-like class __init__ method signature):
  417. SHA256.TYPE: SHA256,
  418. SHA512_256.TYPE: SHA512_256,
  419. # MACs:
  420. HMAC_SHA256.TYPE: HMAC_SHA256,
  421. HMAC_SHA512_256.TYPE: HMAC_SHA512_256,
  422. GMAC.TYPE: GMAC,
  423. }
  424. cipher_mapping = {
  425. # no cipher (but cipher-like class __init__ method signature):
  426. PLAIN.TYPE: PLAIN,
  427. # AEAD cipher implementations
  428. AES_CTR_HMAC.TYPE: AES_CTR_HMAC,
  429. AES_GCM.TYPE: AES_GCM,
  430. }
  431. def get_implementations(meta):
  432. try:
  433. compressor = compressor_mapping[meta.compr_type]
  434. crypter = crypter_mapping[meta.crypt_type]
  435. maccer = maccer_mapping[meta.mac_type]
  436. cipher = cipher_mapping[meta.cipher_type]
  437. except KeyError:
  438. raise UnsupportedPayloadError("compr_type %x crypt_type %x mac_type %x" % (
  439. meta.compr_type, meta.crypt_type, meta.mac_type, meta.cipher_type))
  440. return compressor, crypter, maccer, cipher
  441. def legacy_parser(all_data, crypt_type): # all rather hardcoded
  442. """
  443. Payload layout:
  444. no encryption: TYPE(1) + data
  445. with encryption: TYPE(1) + HMAC(32) + NONCE(8) + data
  446. data is compressed with zlib level 6 and (in the 2nd case) encrypted.
  447. To reduce payload size only 8 bytes of the 16 bytes nonce is saved
  448. in the payload, the first 8 bytes are always zeros. This does not
  449. affect security but limits the maximum repository capacity to
  450. only 295 exabytes!
  451. """
  452. offset = 1
  453. if crypt_type == PlaintextKey.TYPE:
  454. hmac = None
  455. iv = stored_iv = None
  456. data = all_data[offset:]
  457. else:
  458. hmac = all_data[offset:offset+32]
  459. stored_iv = all_data[offset+32:offset+40]
  460. data = all_data[offset+40:]
  461. meta = Meta(compr_type=6, crypt_type=crypt_type,
  462. mac_type=HMAC_SHA256.TYPE, cipher_type=AES_CTR_HMAC.TYPE,
  463. hmac=hmac, stored_iv=stored_iv)
  464. compressor, crypter, maccer, cipher = get_implementations(meta)
  465. return meta, data, compressor, crypter, maccer, cipher
  466. def parser00(all_data):
  467. return legacy_parser(all_data, KeyfileKey.TYPE)
  468. def parser01(all_data):
  469. return legacy_parser(all_data, PassphraseKey.TYPE)
  470. def parser02(all_data):
  471. return legacy_parser(all_data, PlaintextKey.TYPE)
  472. def parser03(all_data): # new & flexible
  473. """
  474. Payload layout:
  475. always: TYPE(1) + MSGPACK((meta, data))
  476. meta is a Meta namedtuple and contains all required information about data.
  477. data is maybe compressed (see meta) and maybe encrypted (see meta).
  478. """
  479. # TODO use Unpacker(..., max_*_len=NOTMORETHANNEEDED) to avoid any memory
  480. # allocation issues on untrusted and potentially tampered input data.
  481. # Problem: we currently must use older msgpack because pure python impl.
  482. # is broken in 0.4.2 < version <= 0.4.5, but this api is only offered by
  483. # more recent ones, not by 0.4.2. So, fix here when 0.4.6 is out. :-(
  484. meta_tuple, data = msgpack.unpackb(all_data[1:])
  485. meta = Meta(*meta_tuple)
  486. compressor, crypter, maccer, cipher = get_implementations(meta)
  487. return meta, data, compressor, crypter, maccer, cipher
  488. def parser(data):
  489. parser_mapping = {
  490. 0x00: parser00,
  491. 0x01: parser01,
  492. 0x02: parser02,
  493. 0x03: parser03,
  494. }
  495. header_type = data[0]
  496. parser_func = parser_mapping[header_type]
  497. return parser_func(data)
  498. def key_factory(repository, manifest_data):
  499. meta, data, compressor, crypter, maccer, cipher = parser(manifest_data)
  500. return crypter.detect(repository, manifest_data)
  501. def generate(meta, data):
  502. # always create new-style 0x03 format
  503. return b'\x03' + msgpack.packb((meta, data))
  504. def compressor_creator(args):
  505. # args == None is used by unit tests
  506. compression = COMPR_DEFAULT if args is None else args.compression
  507. compressor = compressor_mapping.get(compression)
  508. if compressor is None:
  509. raise NotImplementedError("no compression %d" % args.compression)
  510. return compressor
  511. def key_creator(repository, args):
  512. if args.encryption == 'keyfile':
  513. return KeyfileKey.create(repository, args)
  514. if args.encryption == 'passphrase':
  515. return PassphraseKey.create(repository, args)
  516. if args.encryption == 'none':
  517. return PlaintextKey.create(repository, args)
  518. raise NotImplemented("no encryption %s" % args.encryption)
  519. def maccer_creator(args, key_cls):
  520. # args == None is used by unit tests
  521. mac = None if args is None else args.mac
  522. if mac is None:
  523. if key_cls is PlaintextKey:
  524. mac = HASH_DEFAULT
  525. elif key_cls in (KeyfileKey, PassphraseKey):
  526. mac = MAC_DEFAULT
  527. else:
  528. raise NotImplementedError("unknown key class")
  529. maccer = maccer_mapping.get(mac)
  530. if maccer is None:
  531. raise NotImplementedError("no mac %d" % args.mac)
  532. return maccer
  533. def cipher_creator(args, key_cls):
  534. # args == None is used by unit tests
  535. cipher = None if args is None else args.cipher
  536. if cipher is None:
  537. if key_cls is PlaintextKey:
  538. cipher = PLAIN_DEFAULT
  539. elif key_cls in (KeyfileKey, PassphraseKey):
  540. cipher = CIPHER_DEFAULT
  541. else:
  542. raise NotImplementedError("unknown key class")
  543. cipher = cipher_mapping.get(cipher)
  544. if cipher is None:
  545. raise NotImplementedError("no cipher %d" % args.cipher)
  546. return cipher