key.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. try:
  18. import blosc
  19. except ImportError:
  20. blosc = None
  21. from attic.crypto import pbkdf2_sha256, get_random_bytes, AES, AES_CTR_MODE, AES_GCM_MODE, \
  22. bytes_to_int, increment_iv
  23. from attic.helpers import IntegrityError, get_keys_dir, Error
  24. # we do not store the full IV on disk, as the upper 8 bytes are expected to be
  25. # zero anyway as the full IV is a 128bit counter. PREFIX are the upper 8 bytes,
  26. # stored_iv are the lower 8 Bytes.
  27. PREFIX = b'\0' * 8
  28. Meta = namedtuple('Meta', 'compr_type, key_type, mac_type, cipher_type, iv, legacy')
  29. class UnsupportedPayloadError(Error):
  30. """Unsupported payload type {}. A newer version is required to access this repository.
  31. """
  32. class sha512_256(object): # note: can't subclass sha512
  33. """sha512, but digest truncated to 256bit - faster than sha256 on 64bit platforms"""
  34. digestsize = digest_size = 32
  35. block_size = 64
  36. def __init__(self, data=None):
  37. self.name = 'sha512-256'
  38. self._h = sha512()
  39. if data:
  40. self.update(data)
  41. def update(self, data):
  42. self._h.update(data)
  43. def digest(self):
  44. return self._h.digest()[:self.digest_size]
  45. def hexdigest(self):
  46. return self._h.hexdigest()[:self.digest_size * 2]
  47. def copy(self):
  48. new = sha512_256.__new__(sha512_256)
  49. new._h = self._h.copy()
  50. return new
  51. class HMAC(hmac.HMAC):
  52. """Workaround a bug in Python < 3.4 Where HMAC does not accept memoryviews
  53. """
  54. def update(self, msg):
  55. self.inner.update(msg)
  56. # HASH / MAC stuff below all has a mac-like interface, so it can be used in the same way.
  57. # special case: hashes do not use keys (and thus, do not sign/authenticate)
  58. class SHA256(object): # note: can't subclass sha256
  59. TYPE = 0
  60. digest_size = 32
  61. def __init__(self, key, data=b''):
  62. # signature is like for a MAC, we ignore the key as this is a simple hash
  63. if key is not None:
  64. raise Exception("use a HMAC if you have a key")
  65. self.h = sha256(data)
  66. def update(self, data):
  67. self.h.update(data)
  68. def digest(self):
  69. return self.h.digest()
  70. def hexdigest(self):
  71. return self.h.hexdigest()
  72. class SHA512_256(sha512_256):
  73. """sha512, but digest truncated to 256bit - faster than sha256 on 64bit platforms"""
  74. TYPE = 1
  75. digest_size = 32
  76. def __init__(self, key, data):
  77. # signature is like for a MAC, we ignore the key as this is a simple hash
  78. if key is not None:
  79. raise Exception("use a HMAC if you have a key")
  80. super().__init__(data)
  81. class GHASH:
  82. TYPE = 2
  83. digest_size = 16
  84. def __init__(self, key, data):
  85. # signature is like for a MAC, we ignore the key as this is a simple hash
  86. if key is not None:
  87. raise Exception("use a MAC if you have a key")
  88. self.key = b'\0' * 32
  89. self.data = data
  90. def digest(self):
  91. mac_cipher = AES(mode=AES_GCM_MODE, is_encrypt=True, key=self.key, iv=b'\0' * 16)
  92. # GMAC = aes-gcm with all data as AAD, no data as to-be-encrypted data
  93. mac_cipher.add(bytes(self.data))
  94. hash, _ = mac_cipher.compute_mac_and_encrypt(b'')
  95. return hash
  96. class HMAC_SHA256(HMAC):
  97. TYPE = 10
  98. digest_size = 32
  99. def __init__(self, key, data):
  100. if key is None:
  101. raise Exception("do not use HMAC if you don't have a key")
  102. super().__init__(key, data, sha256)
  103. class HMAC_SHA512_256(HMAC):
  104. TYPE = 11
  105. digest_size = 32
  106. def __init__(self, key, data):
  107. if key is None:
  108. raise Exception("do not use HMAC if you don't have a key")
  109. super().__init__(key, data, sha512_256)
  110. class GMAC(GHASH):
  111. TYPE = 20
  112. digest_size = 16
  113. def __init__(self, key, data):
  114. super().__init__(None, data)
  115. if key is None:
  116. raise Exception("do not use GMAC if you don't have a key")
  117. self.key = key
  118. # defaults are optimized for speed on modern CPUs with AES hw support
  119. HASH_DEFAULT = GHASH.TYPE
  120. MAC_DEFAULT = GMAC.TYPE
  121. # compressor classes, all same interface
  122. # special case: zlib level 0 is "no compression"
  123. class NullCompressor(object): # uses 0 in the mapping
  124. TYPE = 0
  125. def compress(self, data):
  126. return bytes(data)
  127. def decompress(self, data):
  128. return bytes(data)
  129. class ZlibCompressor(object): # uses 1..9 in the mapping
  130. TYPE = 0
  131. LEVELS = range(10)
  132. def compress(self, data):
  133. level = self.TYPE - ZlibCompressor.TYPE
  134. return zlib.compress(data, level)
  135. def decompress(self, data):
  136. return zlib.decompress(data)
  137. class LzmaCompressor(object): # uses 10..19 in the mapping
  138. TYPE = 10
  139. PRESETS = range(10)
  140. def __init__(self):
  141. if lzma is None:
  142. raise NotImplemented("lzma compression needs Python >= 3.3 or backports.lzma from PyPi")
  143. def compress(self, data):
  144. preset = self.TYPE - LzmaCompressor.TYPE
  145. return lzma.compress(data, preset=preset)
  146. def decompress(self, data):
  147. return lzma.decompress(data)
  148. class BLOSCCompressor(object):
  149. TYPE = 0 # override in subclass
  150. LEVELS = range(10)
  151. CNAME = '' # override in subclass
  152. def __init__(self):
  153. if blosc is None:
  154. raise NotImplemented("%s compression needs blosc from PyPi" % self.CNAME)
  155. if self.CNAME not in blosc.compressor_list():
  156. raise NotImplemented("%s compression is not supported by blosc" % self.CNAME)
  157. blosc.set_blocksize(16384) # 16kiB is the minimum, so 64kiB are enough for 4 threads
  158. def _get_level(self):
  159. raise NotImplemented
  160. def compress(self, data):
  161. return blosc.compress(bytes(data), 1, cname=self.CNAME, clevel=self._get_level())
  162. def decompress(self, data):
  163. return blosc.decompress(data)
  164. class LZ4Compressor(BLOSCCompressor):
  165. TYPE = 20
  166. CNAME = 'lz4'
  167. def _get_level(self):
  168. return self.TYPE - LZ4Compressor.TYPE
  169. class LZ4HCCompressor(BLOSCCompressor):
  170. TYPE = 30
  171. CNAME = 'lz4hc'
  172. def _get_level(self):
  173. return self.TYPE - LZ4HCCompressor.TYPE
  174. class BLOSCLZCompressor(BLOSCCompressor):
  175. TYPE = 40
  176. CNAME = 'blosclz'
  177. def _get_level(self):
  178. return self.TYPE - BLOSCLZCompressor.TYPE
  179. class SnappyCompressor(BLOSCCompressor):
  180. TYPE = 50
  181. CNAME = 'snappy'
  182. def _get_level(self):
  183. return self.TYPE - SnappyCompressor.TYPE
  184. class BLOSCZlibCompressor(BLOSCCompressor):
  185. TYPE = 60
  186. CNAME = 'zlib'
  187. def _get_level(self):
  188. return self.TYPE - BLOSCZlibCompressor.TYPE
  189. # default is optimized for speed
  190. COMPR_DEFAULT = NullCompressor.TYPE # no compression
  191. # ciphers - AEAD (authenticated encryption with assoc. data) style interface
  192. # special case: PLAIN dummy does not encrypt / authenticate
  193. class PLAIN:
  194. TYPE = 0
  195. enc_iv = None # dummy
  196. def __init__(self, **kw):
  197. pass
  198. def compute_mac_and_encrypt(self, meta, data):
  199. return None, data
  200. def check_mac_and_decrypt(self, mac, meta, data):
  201. return data
  202. def get_aad(meta):
  203. """get additional authenticated data for AEAD ciphers"""
  204. if meta.legacy:
  205. # legacy format computed the mac over (iv_last8 + data)
  206. return meta.iv[8:]
  207. else:
  208. return msgpack.packb(meta)
  209. class AES_CTR_HMAC:
  210. TYPE = 1
  211. def __init__(self, enc_key=b'\0' * 32, enc_iv=b'\0' * 16, enc_hmac_key=b'\0' * 32, **kw):
  212. self.hmac_key = enc_hmac_key
  213. self.enc_iv = enc_iv
  214. self.enc_cipher = AES(mode=AES_CTR_MODE, is_encrypt=True, key=enc_key, iv=enc_iv)
  215. self.dec_cipher = AES(mode=AES_CTR_MODE, is_encrypt=False, key=enc_key)
  216. def compute_mac_and_encrypt(self, meta, data):
  217. self.enc_cipher.reset(iv=meta.iv)
  218. _, data = self.enc_cipher.compute_mac_and_encrypt(data)
  219. self.enc_iv = increment_iv(meta.iv, len(data))
  220. aad = get_aad(meta)
  221. mac = HMAC(self.hmac_key, aad + data, sha256).digest() # XXX mac / hash flexibility
  222. return mac, data
  223. def check_mac_and_decrypt(self, mac, meta, data):
  224. aad = get_aad(meta)
  225. if HMAC(self.hmac_key, aad + data, sha256).digest() != mac:
  226. raise IntegrityError('Encryption envelope checksum mismatch')
  227. self.dec_cipher.reset(iv=meta.iv)
  228. data = self.dec_cipher.check_mac_and_decrypt(None, data)
  229. return data
  230. class AES_GCM:
  231. TYPE = 2
  232. def __init__(self, enc_key=b'\0' * 32, enc_iv=b'\0' * 16, **kw):
  233. # note: hmac_key is not used for aes-gcm, it does aes+gmac in 1 pass
  234. self.enc_iv = enc_iv
  235. self.enc_cipher = AES(mode=AES_GCM_MODE, is_encrypt=True, key=enc_key, iv=enc_iv)
  236. self.dec_cipher = AES(mode=AES_GCM_MODE, is_encrypt=False, key=enc_key)
  237. def compute_mac_and_encrypt(self, meta, data):
  238. self.enc_cipher.reset(iv=meta.iv)
  239. aad = get_aad(meta)
  240. self.enc_cipher.add(aad)
  241. mac, data = self.enc_cipher.compute_mac_and_encrypt(data)
  242. self.enc_iv = increment_iv(meta.iv, len(data))
  243. return mac, data
  244. def check_mac_and_decrypt(self, mac, meta, data):
  245. self.dec_cipher.reset(iv=meta.iv)
  246. aad = get_aad(meta)
  247. self.dec_cipher.add(aad)
  248. try:
  249. data = self.dec_cipher.check_mac_and_decrypt(mac, data)
  250. except Exception:
  251. raise IntegrityError('Encryption envelope checksum mismatch')
  252. return data
  253. # cipher default is optimized for speed on modern CPUs with AES hw support
  254. PLAIN_DEFAULT = PLAIN.TYPE
  255. CIPHER_DEFAULT = AES_GCM.TYPE
  256. # misc. types of keys
  257. # special case: no keys (thus: no encryption, no signing/authentication)
  258. class KeyBase(object):
  259. TYPE = 0x00 # override in derived classes
  260. def __init__(self, compressor_cls, maccer_cls, cipher_cls):
  261. self.compressor = compressor_cls()
  262. self.maccer_cls = maccer_cls # hasher/maccer used by id_hash
  263. self.cipher_cls = cipher_cls # plaintext dummy or AEAD cipher
  264. self.cipher = cipher_cls()
  265. self.id_key = None
  266. def id_hash(self, data):
  267. """Return a HASH (no id_key) or a MAC (using the "id_key" key)
  268. XXX do we need a cryptographic hash function here or is a keyed hash
  269. function like GMAC / GHASH good enough? See NIST SP 800-38D.
  270. IMPORTANT: in 1 repo, there should be only 1 kind of id_hash, otherwise
  271. data hashed/maced with one id_hash might result in same ID as already
  272. exists in the repo for other data created with another id_hash method.
  273. somehow unlikely considering 128 or 256bits, but still.
  274. """
  275. return self.maccer_cls(self.id_key, data).digest()
  276. def encrypt(self, data):
  277. data = self.compressor.compress(data)
  278. meta = Meta(compr_type=self.compressor.TYPE, key_type=self.TYPE,
  279. mac_type=self.maccer_cls.TYPE, cipher_type=self.cipher.TYPE,
  280. iv=self.cipher.enc_iv, legacy=False)
  281. mac, data = self.cipher.compute_mac_and_encrypt(meta, data)
  282. return generate(mac, meta, data)
  283. def decrypt(self, id, data):
  284. mac, meta, data = parser(data)
  285. compressor, keyer, maccer, cipher = get_implementations(meta)
  286. assert isinstance(self, keyer)
  287. assert self.maccer_cls is maccer
  288. assert self.cipher_cls is cipher
  289. data = self.cipher.check_mac_and_decrypt(mac, meta, data)
  290. data = self.compressor.decompress(data)
  291. if id and self.id_hash(data) != id:
  292. raise IntegrityError('Chunk id verification failed')
  293. return data
  294. class PlaintextKey(KeyBase):
  295. TYPE = 0x02
  296. chunk_seed = 0
  297. @classmethod
  298. def create(cls, repository, args):
  299. print('Encryption NOT enabled.\nUse the "--encryption=passphrase|keyfile" to enable encryption.')
  300. compressor = compressor_creator(args)
  301. maccer = maccer_creator(args, cls)
  302. cipher = cipher_creator(args, cls)
  303. return cls(compressor, maccer, cipher)
  304. @classmethod
  305. def detect(cls, repository, manifest_data):
  306. mac, meta, data = parser(manifest_data)
  307. compressor, keyer, maccer, cipher = get_implementations(meta)
  308. return cls(compressor, maccer, cipher)
  309. class AESKeyBase(KeyBase):
  310. """Common base class shared by KeyfileKey and PassphraseKey
  311. Chunks are encrypted using 256bit AES in CTR or GCM mode.
  312. Chunks are authenticated by a GCM GMAC or a HMAC.
  313. Payload layout: TYPE(1) + MAC(32) + NONCE(8) + CIPHERTEXT
  314. To reduce payload size only 8 bytes of the 16 bytes nonce is saved
  315. in the payload, the first 8 bytes are always zeros. This does not
  316. affect security but limits the maximum repository capacity to
  317. only 295 exabytes!
  318. """
  319. def extract_iv(self, payload):
  320. _, meta, _ = parser(payload)
  321. return meta.iv
  322. def init_from_random_data(self, data):
  323. self.enc_key = data[0:32]
  324. self.enc_hmac_key = data[32:64]
  325. self.id_key = data[64:96]
  326. self.chunk_seed = bytes_to_int(data[96:100])
  327. # Convert to signed int32
  328. if self.chunk_seed & 0x80000000:
  329. self.chunk_seed = self.chunk_seed - 0xffffffff - 1
  330. def init_ciphers(self, enc_iv=b'\0' * 16):
  331. self.cipher = self.cipher_cls(enc_key=self.enc_key, enc_iv=enc_iv,
  332. enc_hmac_key=self.enc_hmac_key)
  333. @property
  334. def enc_iv(self):
  335. return self.cipher.enc_iv
  336. class PassphraseKey(AESKeyBase):
  337. TYPE = 0x01
  338. iterations = 100000
  339. @classmethod
  340. def create(cls, repository, args):
  341. compressor = compressor_creator(args)
  342. maccer = maccer_creator(args, cls)
  343. cipher = cipher_creator(args, cls)
  344. key = cls(compressor, maccer, cipher)
  345. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  346. if passphrase is not None:
  347. passphrase2 = passphrase
  348. else:
  349. passphrase, passphrase2 = 1, 2
  350. while passphrase != passphrase2:
  351. passphrase = getpass('Enter passphrase: ')
  352. if not passphrase:
  353. print('Passphrase must not be blank')
  354. continue
  355. passphrase2 = getpass('Enter same passphrase again: ')
  356. if passphrase != passphrase2:
  357. print('Passphrases do not match')
  358. key.init(repository, passphrase)
  359. if passphrase:
  360. print('Remember your passphrase. Your data will be inaccessible without it.')
  361. return key
  362. @classmethod
  363. def detect(cls, repository, manifest_data):
  364. prompt = 'Enter passphrase for %s: ' % repository._location.orig
  365. mac, meta, data = parser(manifest_data)
  366. compressor, keyer, maccer, cipher = get_implementations(meta)
  367. key = cls(compressor, maccer, cipher)
  368. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  369. if passphrase is None:
  370. passphrase = getpass(prompt)
  371. while True:
  372. key.init(repository, passphrase)
  373. try:
  374. key.decrypt(None, manifest_data)
  375. key.init_ciphers(increment_iv(key.extract_iv(manifest_data), len(data)))
  376. return key
  377. except IntegrityError:
  378. passphrase = getpass(prompt)
  379. def change_passphrase(self):
  380. class ImmutablePassphraseError(Error):
  381. """The passphrase for this encryption key type can't be changed."""
  382. raise ImmutablePassphraseError
  383. def init(self, repository, passphrase):
  384. self.init_from_random_data(pbkdf2_sha256(passphrase.encode('utf-8'), repository.id, self.iterations, 100))
  385. self.init_ciphers()
  386. class KeyfileKey(AESKeyBase):
  387. FILE_ID = 'ATTIC KEY'
  388. TYPE = 0x00
  389. @classmethod
  390. def detect(cls, repository, manifest_data):
  391. mac, meta, data = parser(manifest_data)
  392. compressor, keyer, maccer, cipher = get_implementations(meta)
  393. key = cls(compressor, maccer, cipher)
  394. path = cls.find_key_file(repository)
  395. prompt = 'Enter passphrase for key file %s: ' % path
  396. passphrase = os.environ.get('ATTIC_PASSPHRASE', '')
  397. while not key.load(path, passphrase):
  398. passphrase = getpass(prompt)
  399. key.init_ciphers(increment_iv(key.extract_iv(manifest_data), len(data)))
  400. return key
  401. @classmethod
  402. def find_key_file(cls, repository):
  403. id = hexlify(repository.id).decode('ascii')
  404. keys_dir = get_keys_dir()
  405. for name in os.listdir(keys_dir):
  406. filename = os.path.join(keys_dir, name)
  407. with open(filename, 'r') as fd:
  408. line = fd.readline().strip()
  409. if line and line.startswith(cls.FILE_ID) and line[10:] == id:
  410. return filename
  411. raise Exception('Key file for repository with ID %s not found' % id)
  412. def load(self, filename, passphrase):
  413. with open(filename, 'r') as fd:
  414. cdata = a2b_base64(''.join(fd.readlines()[1:]).encode('ascii')) # .encode needed for Python 3.[0-2]
  415. data = self.decrypt_key_file(cdata, passphrase)
  416. if data:
  417. key = msgpack.unpackb(data)
  418. if key[b'version'] != 1:
  419. raise IntegrityError('Invalid key file header')
  420. self.repository_id = key[b'repository_id']
  421. self.enc_key = key[b'enc_key']
  422. self.enc_hmac_key = key[b'enc_hmac_key']
  423. self.id_key = key[b'id_key']
  424. self.chunk_seed = key[b'chunk_seed']
  425. self.path = filename
  426. return True
  427. def decrypt_key_file(self, data, passphrase):
  428. d = msgpack.unpackb(data)
  429. assert d[b'version'] == 1
  430. assert d[b'algorithm'] == b'gmac'
  431. key = pbkdf2_sha256(passphrase.encode('utf-8'), d[b'salt'], d[b'iterations'], 32)
  432. try:
  433. cipher = AES(mode=AES_GCM_MODE, is_encrypt=False, key=key, iv=b'\0'*16)
  434. data = cipher.check_mac_and_decrypt(d[b'hash'], d[b'data'])
  435. return data
  436. except Exception:
  437. return None
  438. def encrypt_key_file(self, data, passphrase):
  439. salt = get_random_bytes(32)
  440. iterations = 100000
  441. key = pbkdf2_sha256(passphrase.encode('utf-8'), salt, iterations, 32)
  442. cipher = AES(mode=AES_GCM_MODE, is_encrypt=True, key=key, iv=b'\0'*16)
  443. mac, cdata = cipher.compute_mac_and_encrypt(data)
  444. d = {
  445. 'version': 1,
  446. 'salt': salt,
  447. 'iterations': iterations,
  448. 'algorithm': 'gmac',
  449. 'hash': mac,
  450. 'data': cdata,
  451. }
  452. return msgpack.packb(d)
  453. def save(self, path, passphrase):
  454. key = {
  455. 'version': 1,
  456. 'repository_id': self.repository_id,
  457. 'enc_key': self.enc_key,
  458. 'enc_hmac_key': self.enc_hmac_key,
  459. 'id_key': self.id_key,
  460. 'chunk_seed': self.chunk_seed,
  461. }
  462. data = self.encrypt_key_file(msgpack.packb(key), passphrase)
  463. with open(path, 'w') as fd:
  464. fd.write('%s %s\n' % (self.FILE_ID, hexlify(self.repository_id).decode('ascii')))
  465. fd.write('\n'.join(textwrap.wrap(b2a_base64(data).decode('ascii'))))
  466. fd.write('\n')
  467. self.path = path
  468. def change_passphrase(self):
  469. passphrase, passphrase2 = 1, 2
  470. while passphrase != passphrase2:
  471. passphrase = getpass('New passphrase: ')
  472. passphrase2 = getpass('Enter same passphrase again: ')
  473. if passphrase != passphrase2:
  474. print('Passphrases do not match')
  475. self.save(self.path, passphrase)
  476. print('Key file "%s" updated' % self.path)
  477. @classmethod
  478. def create(cls, repository, args):
  479. filename = args.repository.to_key_filename()
  480. path = filename
  481. i = 1
  482. while os.path.exists(path):
  483. i += 1
  484. path = filename + '.%d' % i
  485. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  486. if passphrase is not None:
  487. passphrase2 = passphrase
  488. else:
  489. passphrase, passphrase2 = 1, 2
  490. while passphrase != passphrase2:
  491. passphrase = getpass('Enter passphrase (empty for no passphrase):')
  492. passphrase2 = getpass('Enter same passphrase again: ')
  493. if passphrase != passphrase2:
  494. print('Passphrases do not match')
  495. compressor = compressor_creator(args)
  496. maccer = maccer_creator(args, cls)
  497. cipher = cipher_creator(args, cls)
  498. key = cls(compressor, maccer, cipher)
  499. key.repository_id = repository.id
  500. key.init_from_random_data(get_random_bytes(100))
  501. key.init_ciphers()
  502. key.save(path, passphrase)
  503. print('Key file "%s" created.' % key.path)
  504. print('Keep this file safe. Your data will be inaccessible without it.')
  505. return key
  506. # note: key 0 nicely maps to a zlib compressor with level 0 which means "no compression"
  507. compressor_mapping = {}
  508. for level in ZlibCompressor.LEVELS:
  509. compressor_mapping[ZlibCompressor.TYPE + level] = \
  510. type('ZlibCompressorLevel%d' % level, (ZlibCompressor, ), dict(TYPE=ZlibCompressor.TYPE + level))
  511. for preset in LzmaCompressor.PRESETS:
  512. compressor_mapping[LzmaCompressor.TYPE + preset] = \
  513. type('LzmaCompressorPreset%d' % preset, (LzmaCompressor, ), dict(TYPE=LzmaCompressor.TYPE + preset))
  514. for level in LZ4Compressor.LEVELS:
  515. compressor_mapping[LZ4Compressor.TYPE + level] = \
  516. type('LZ4CompressorLevel%d' % level, (LZ4Compressor, ), dict(TYPE=LZ4Compressor.TYPE + level))
  517. for level in LZ4HCCompressor.LEVELS:
  518. compressor_mapping[LZ4HCCompressor.TYPE + level] = \
  519. type('LZ4HCCompressorLevel%d' % level, (LZ4HCCompressor, ), dict(TYPE=LZ4HCCompressor.TYPE + level))
  520. for level in BLOSCLZCompressor.LEVELS:
  521. compressor_mapping[BLOSCLZCompressor.TYPE + level] = \
  522. type('BLOSCLZCompressorLevel%d' % level, (BLOSCLZCompressor, ), dict(TYPE=BLOSCLZCompressor.TYPE + level))
  523. for level in SnappyCompressor.LEVELS:
  524. compressor_mapping[SnappyCompressor.TYPE + level] = \
  525. type('SnappyCompressorLevel%d' % level, (SnappyCompressor, ), dict(TYPE=SnappyCompressor.TYPE + level))
  526. for level in BLOSCZlibCompressor.LEVELS:
  527. compressor_mapping[BLOSCZlibCompressor.TYPE + level] = \
  528. type('BLOSCZlibCompressorLevel%d' % level, (BLOSCZlibCompressor, ), dict(TYPE=BLOSCZlibCompressor.TYPE + level))
  529. # overwrite 0 with NullCompressor
  530. compressor_mapping[NullCompressor.TYPE] = NullCompressor
  531. keyer_mapping = {
  532. KeyfileKey.TYPE: KeyfileKey,
  533. PassphraseKey.TYPE: PassphraseKey,
  534. PlaintextKey.TYPE: PlaintextKey,
  535. }
  536. maccer_mapping = {
  537. # simple hashes, not MACs (but MAC-like class __init__ method signature):
  538. SHA256.TYPE: SHA256,
  539. SHA512_256.TYPE: SHA512_256,
  540. GHASH.TYPE: GHASH,
  541. # MACs:
  542. HMAC_SHA256.TYPE: HMAC_SHA256,
  543. HMAC_SHA512_256.TYPE: HMAC_SHA512_256,
  544. GMAC.TYPE: GMAC,
  545. }
  546. cipher_mapping = {
  547. # no cipher (but cipher-like class __init__ method signature):
  548. PLAIN.TYPE: PLAIN,
  549. # AEAD cipher implementations
  550. AES_CTR_HMAC.TYPE: AES_CTR_HMAC,
  551. AES_GCM.TYPE: AES_GCM,
  552. }
  553. def get_implementations(meta):
  554. try:
  555. compressor = compressor_mapping[meta.compr_type]
  556. keyer = keyer_mapping[meta.key_type]
  557. maccer = maccer_mapping[meta.mac_type]
  558. cipher = cipher_mapping[meta.cipher_type]
  559. except KeyError:
  560. raise UnsupportedPayloadError("compr_type %x key_type %x mac_type %x cipher_type %x" % (
  561. meta.compr_type, meta.key_type, meta.mac_type, meta.cipher_type))
  562. return compressor, keyer, maccer, cipher
  563. def legacy_parser(all_data, key_type): # all rather hardcoded
  564. """
  565. Payload layout:
  566. no encryption: TYPE(1) + data
  567. with encryption: TYPE(1) + HMAC(32) + NONCE(8) + data
  568. data is compressed with zlib level 6 and (in the 2nd case) encrypted.
  569. To reduce payload size only 8 bytes of the 16 bytes nonce is saved
  570. in the payload, the first 8 bytes are always zeros. This does not
  571. affect security but limits the maximum repository capacity to
  572. only 295 exabytes!
  573. """
  574. offset = 1
  575. if key_type == PlaintextKey.TYPE:
  576. mac_type = SHA256.TYPE
  577. mac = None
  578. cipher_type = PLAIN.TYPE
  579. iv = None
  580. data = all_data[offset:]
  581. else:
  582. mac_type = HMAC_SHA256.TYPE
  583. mac = all_data[offset:offset+32]
  584. cipher_type = AES_CTR_HMAC.TYPE
  585. iv = PREFIX + all_data[offset+32:offset+40]
  586. data = all_data[offset+40:]
  587. meta = Meta(compr_type=6, key_type=key_type, mac_type=mac_type,
  588. cipher_type=cipher_type, iv=iv, legacy=True)
  589. return mac, meta, data
  590. def parser00(all_data):
  591. return legacy_parser(all_data, KeyfileKey.TYPE)
  592. def parser01(all_data):
  593. return legacy_parser(all_data, PassphraseKey.TYPE)
  594. def parser02(all_data):
  595. return legacy_parser(all_data, PlaintextKey.TYPE)
  596. def parser03(all_data): # new & flexible
  597. """
  598. Payload layout:
  599. always: TYPE(1) + MSGPACK((mac, meta, data))
  600. meta is a Meta namedtuple and contains all required information about data.
  601. data is maybe compressed (see meta) and maybe encrypted (see meta).
  602. """
  603. max_len = 10000000 # XXX formula?
  604. unpacker = msgpack.Unpacker(
  605. use_list=False,
  606. # avoid memory allocation issues causes by tampered input data.
  607. max_buffer_size=max_len, # does not work in 0.4.6 unpackb C implementation
  608. max_array_len=10, # meta_tuple
  609. max_bin_len=max_len, # data
  610. max_str_len=0, # not used yet
  611. max_map_len=0, # not used yet
  612. max_ext_len=0, # not used yet
  613. )
  614. unpacker.feed(all_data[1:])
  615. mac, meta_tuple, data = unpacker.unpack()
  616. meta = Meta(*meta_tuple)
  617. return mac, meta, data
  618. def parser(data):
  619. parser_mapping = {
  620. 0x00: parser00,
  621. 0x01: parser01,
  622. 0x02: parser02,
  623. 0x03: parser03,
  624. }
  625. header_type = data[0]
  626. parser_func = parser_mapping[header_type]
  627. return parser_func(data)
  628. def key_factory(repository, manifest_data):
  629. mac, meta, data = parser(manifest_data)
  630. compressor, keyer, maccer, cipher = get_implementations(meta)
  631. return keyer.detect(repository, manifest_data)
  632. def generate(mac, meta, data):
  633. # always create new-style 0x03 format
  634. return b'\x03' + msgpack.packb((mac, meta, data), use_bin_type=True)
  635. def compressor_creator(args):
  636. # args == None is used by unit tests
  637. compression = COMPR_DEFAULT if args is None else args.compression
  638. compressor = compressor_mapping.get(compression)
  639. if compressor is None:
  640. raise NotImplementedError("no compression %d" % args.compression)
  641. return compressor
  642. def key_creator(args):
  643. if args.encryption == 'keyfile':
  644. return KeyfileKey
  645. if args.encryption == 'passphrase':
  646. return PassphraseKey
  647. if args.encryption == 'none':
  648. return PlaintextKey
  649. raise NotImplemented("no encryption %s" % args.encryption)
  650. def maccer_creator(args, key_cls):
  651. # args == None is used by unit tests
  652. mac = None if args is None else args.mac
  653. if mac is None:
  654. if key_cls is PlaintextKey:
  655. mac = HASH_DEFAULT
  656. elif key_cls in (KeyfileKey, PassphraseKey):
  657. mac = MAC_DEFAULT
  658. else:
  659. raise NotImplementedError("unknown key class")
  660. maccer = maccer_mapping.get(mac)
  661. if maccer is None:
  662. raise NotImplementedError("no mac %d" % args.mac)
  663. return maccer
  664. def cipher_creator(args, key_cls):
  665. # args == None is used by unit tests
  666. cipher = None if args is None else args.cipher
  667. if cipher is None:
  668. if key_cls is PlaintextKey:
  669. cipher = PLAIN_DEFAULT
  670. elif key_cls in (KeyfileKey, PassphraseKey):
  671. cipher = CIPHER_DEFAULT
  672. else:
  673. raise NotImplementedError("unknown key class")
  674. cipher = cipher_mapping.get(cipher)
  675. if cipher is None:
  676. raise NotImplementedError("no cipher %d" % args.cipher)
  677. return cipher