key.py 29 KB

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