key.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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, sha512
  8. import zlib
  9. try:
  10. import lzma # python >= 3.3
  11. except ImportError:
  12. try:
  13. from backports import lzma # backports.lzma from pypi
  14. except ImportError:
  15. lzma = None
  16. from attic.crypto import pbkdf2_sha256, get_random_bytes, AES, bytes_to_long, long_to_bytes, bytes_to_int, num_aes_blocks
  17. from attic.helpers import IntegrityError, get_keys_dir, Error
  18. PREFIX = b'\0' * 8
  19. class UnsupportedPayloadError(Error):
  20. """Unsupported payload type {}. A newer version is required to access this repository.
  21. """
  22. class sha512_256(object): # note: can't subclass sha512
  23. """sha512, but digest truncated to 256bit - faster than sha256 on 64bit platforms"""
  24. digest_size = 32
  25. def __init__(self, data=b''):
  26. self.h = sha512(data)
  27. def digest(self):
  28. return self.h.digest()[:self.digest_size]
  29. def hexdigest(self):
  30. return self.h.hexdigest()[:self.digest_size * 2]
  31. def __getattr__(self, item):
  32. return getattr(self.h, item)
  33. class HMAC(hmac.HMAC):
  34. """Workaround a bug in Python < 3.4 Where HMAC does not accept memoryviews
  35. """
  36. def update(self, msg):
  37. self.inner.update(msg)
  38. class SHA256(object): # note: can't subclass sha256
  39. TYPE = 0x00
  40. def __init__(self, key, data=b''):
  41. # signature is like for a MAC, we ignore the key as this is a simple hash
  42. if key is not None:
  43. raise Exception("use a HMAC if you have a key")
  44. self.h = sha256(data)
  45. def update(self, data):
  46. self.h.update(data)
  47. def digest(self):
  48. return self.h.digest()
  49. def hexdigest(self):
  50. return self.h.hexdigest()
  51. class SHA512_256(sha512_256):
  52. """sha512, but digest truncated to 256bit - faster than sha256 on 64bit platforms"""
  53. TYPE = 0x01
  54. def __init__(self, key, data):
  55. # signature is like for a MAC, we ignore the key as this is a simple hash
  56. if key is not None:
  57. raise Exception("use a HMAC if you have a key")
  58. super().__init__(data)
  59. HASH_DEFAULT = SHA256.TYPE
  60. class HMAC_SHA256(HMAC):
  61. TYPE = 0x02
  62. def __init__(self, key, data):
  63. if key is None:
  64. raise Exception("do not use HMAC if you don't have a key")
  65. super().__init__(key, data, sha256)
  66. class HMAC_SHA512_256(HMAC):
  67. TYPE = 0x03
  68. def __init__(self, key, data):
  69. if key is None:
  70. raise Exception("do not use HMAC if you don't have a key")
  71. super().__init__(key, data, sha512_256)
  72. MAC_DEFAULT = HMAC_SHA256.TYPE
  73. class ZlibCompressor(object): # uses 0..9 in the mapping
  74. TYPE = 0
  75. LEVELS = range(10)
  76. def compress(self, data):
  77. level = self.TYPE - ZlibCompressor.TYPE
  78. return zlib.compress(data, level)
  79. def decompress(self, data):
  80. return zlib.decompress(data)
  81. class LzmaCompressor(object): # uses 10..19 in the mapping
  82. TYPE = 10
  83. PRESETS = range(10)
  84. def __init__(self):
  85. if lzma is None:
  86. raise NotImplemented("lzma compression needs Python >= 3.3 or backports.lzma from PyPi")
  87. def compress(self, data):
  88. preset = self.TYPE - LzmaCompressor.TYPE
  89. return lzma.compress(data, preset=preset)
  90. def decompress(self, data):
  91. return lzma.decompress(data)
  92. COMPR_DEFAULT = ZlibCompressor.TYPE + 6 # zlib level 6
  93. class KeyBase(object):
  94. TYPE = 0x00 # override in derived classes
  95. def __init__(self, compressor, maccer):
  96. self.compressor = compressor()
  97. self.maccer = maccer
  98. def id_hash(self, data):
  99. """Return HMAC hash using the "id" HMAC key
  100. """
  101. def encrypt(self, data):
  102. pass
  103. def decrypt(self, id, data):
  104. pass
  105. class PlaintextKey(KeyBase):
  106. TYPE = 0x02
  107. chunk_seed = 0
  108. @classmethod
  109. def create(cls, repository, args):
  110. print('Encryption NOT enabled.\nUse the "--encryption=passphrase|keyfile" to enable encryption.')
  111. compressor = compressor_creator(args)
  112. maccer = maccer_creator(args, cls)
  113. return cls(compressor, maccer)
  114. @classmethod
  115. def detect(cls, repository, manifest_data):
  116. offset, compressor, crypter, maccer = parser(manifest_data)
  117. return cls(compressor, maccer)
  118. def id_hash(self, data):
  119. return self.maccer(None, data).digest()
  120. def encrypt(self, data):
  121. header = make_header(compr_type=self.compressor.TYPE, crypt_type=self.TYPE, mac_type=self.maccer.TYPE)
  122. return b''.join([header, self.compressor.compress(data)])
  123. def decrypt(self, id, data):
  124. offset, compressor, crypter, maccer = parser(data)
  125. assert isinstance(self, crypter)
  126. assert self.maccer is maccer
  127. data = self.compressor.decompress(memoryview(data)[offset:])
  128. if id and self.id_hash(data) != id:
  129. raise IntegrityError('Chunk id verification failed')
  130. return data
  131. class AESKeyBase(KeyBase):
  132. """Common base class shared by KeyfileKey and PassphraseKey
  133. Chunks are encrypted using 256bit AES in Counter Mode (CTR)
  134. Payload layout: HEADER(4) + HMAC(32) + NONCE(8) + CIPHERTEXT
  135. To reduce payload size only 8 bytes of the 16 bytes nonce is saved
  136. in the payload, the first 8 bytes are always zeros. This does not
  137. affect security but limits the maximum repository capacity to
  138. only 295 exabytes!
  139. """
  140. PAYLOAD_OVERHEAD = 4 + 32 + 8 # HEADER + HMAC + NONCE
  141. def id_hash(self, data):
  142. """Return HMAC hash using the "id" HMAC key
  143. """
  144. return self.maccer(self.id_key, data).digest()
  145. def encrypt(self, data):
  146. data = self.compressor.compress(data)
  147. self.enc_cipher.reset()
  148. data = b''.join((self.enc_cipher.iv[8:], self.enc_cipher.encrypt(data)))
  149. hmac = self.maccer(self.enc_hmac_key, data).digest()
  150. header = make_header(compr_type=self.compressor.TYPE, crypt_type=self.TYPE, mac_type=self.maccer.TYPE)
  151. return b''.join((header, hmac, data))
  152. def decrypt(self, id, data):
  153. offset, compressor, crypter, maccer = parser(data)
  154. assert isinstance(self, crypter)
  155. assert self.maccer is maccer
  156. hmac = memoryview(data)[offset:offset+32]
  157. if memoryview(self.maccer(self.enc_hmac_key, memoryview(data)[offset+32:]).digest()) != hmac:
  158. raise IntegrityError('Encryption envelope checksum mismatch')
  159. self.dec_cipher.reset(iv=PREFIX + data[offset+32:offset+40])
  160. data = self.compressor.decompress(self.dec_cipher.decrypt(data[offset+40:])) # should use memoryview
  161. if id and self.id_hash(data) != id:
  162. raise IntegrityError('Chunk id verification failed')
  163. return data
  164. def extract_nonce(self, payload):
  165. offset, compressor, crypter, maccer = parser(payload)
  166. assert isinstance(self, crypter)
  167. nonce = bytes_to_long(payload[offset+32:offset+40])
  168. return nonce
  169. def init_from_random_data(self, data):
  170. self.enc_key = data[0:32]
  171. self.enc_hmac_key = data[32:64]
  172. self.id_key = data[64:96]
  173. self.chunk_seed = bytes_to_int(data[96:100])
  174. # Convert to signed int32
  175. if self.chunk_seed & 0x80000000:
  176. self.chunk_seed = self.chunk_seed - 0xffffffff - 1
  177. def init_ciphers(self, enc_iv=b''):
  178. self.enc_cipher = AES(self.enc_key, enc_iv)
  179. self.dec_cipher = AES(self.enc_key)
  180. class PassphraseKey(AESKeyBase):
  181. TYPE = 0x01
  182. iterations = 100000
  183. @classmethod
  184. def create(cls, repository, args):
  185. compressor = compressor_creator(args)
  186. maccer = maccer_creator(args, cls)
  187. key = cls(compressor, maccer)
  188. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  189. if passphrase is not None:
  190. passphrase2 = passphrase
  191. else:
  192. passphrase, passphrase2 = 1, 2
  193. while passphrase != passphrase2:
  194. passphrase = getpass('Enter passphrase: ')
  195. if not passphrase:
  196. print('Passphrase must not be blank')
  197. continue
  198. passphrase2 = getpass('Enter same passphrase again: ')
  199. if passphrase != passphrase2:
  200. print('Passphrases do not match')
  201. key.init(repository, passphrase)
  202. if passphrase:
  203. print('Remember your passphrase. Your data will be inaccessible without it.')
  204. return key
  205. @classmethod
  206. def detect(cls, repository, manifest_data):
  207. prompt = 'Enter passphrase for %s: ' % repository._location.orig
  208. offset, compressor, crypter, maccer = parser(manifest_data)
  209. key = cls(compressor, maccer)
  210. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  211. if passphrase is None:
  212. passphrase = getpass(prompt)
  213. while True:
  214. key.init(repository, passphrase)
  215. try:
  216. key.decrypt(None, manifest_data)
  217. num_blocks = num_aes_blocks(len(manifest_data) - offset - 40)
  218. key.init_ciphers(PREFIX + long_to_bytes(key.extract_nonce(manifest_data) + num_blocks))
  219. return key
  220. except IntegrityError:
  221. passphrase = getpass(prompt)
  222. def init(self, repository, passphrase):
  223. self.init_from_random_data(pbkdf2_sha256(passphrase.encode('utf-8'), repository.id, self.iterations, 100))
  224. self.init_ciphers()
  225. class KeyfileKey(AESKeyBase):
  226. FILE_ID = 'ATTIC KEY'
  227. TYPE = 0x00
  228. @classmethod
  229. def detect(cls, repository, manifest_data):
  230. offset, compressor, crypter, maccer = parser(manifest_data)
  231. key = cls(compressor, maccer)
  232. path = cls.find_key_file(repository)
  233. prompt = 'Enter passphrase for key file %s: ' % path
  234. passphrase = os.environ.get('ATTIC_PASSPHRASE', '')
  235. while not key.load(path, passphrase):
  236. passphrase = getpass(prompt)
  237. num_blocks = num_aes_blocks(len(manifest_data) - offset - 40)
  238. key.init_ciphers(PREFIX + long_to_bytes(key.extract_nonce(manifest_data) + num_blocks))
  239. return key
  240. @classmethod
  241. def find_key_file(cls, repository):
  242. id = hexlify(repository.id).decode('ascii')
  243. keys_dir = get_keys_dir()
  244. for name in os.listdir(keys_dir):
  245. filename = os.path.join(keys_dir, name)
  246. with open(filename, 'r') as fd:
  247. line = fd.readline().strip()
  248. if line and line.startswith(cls.FILE_ID) and line[10:] == id:
  249. return filename
  250. raise Exception('Key file for repository with ID %s not found' % id)
  251. def load(self, filename, passphrase):
  252. with open(filename, 'r') as fd:
  253. cdata = a2b_base64(''.join(fd.readlines()[1:]).encode('ascii')) # .encode needed for Python 3.[0-2]
  254. data = self.decrypt_key_file(cdata, passphrase)
  255. if data:
  256. key = msgpack.unpackb(data)
  257. if key[b'version'] != 1:
  258. raise IntegrityError('Invalid key file header')
  259. self.repository_id = key[b'repository_id']
  260. self.enc_key = key[b'enc_key']
  261. self.enc_hmac_key = key[b'enc_hmac_key']
  262. self.id_key = key[b'id_key']
  263. self.chunk_seed = key[b'chunk_seed']
  264. self.path = filename
  265. return True
  266. def decrypt_key_file(self, data, passphrase):
  267. d = msgpack.unpackb(data)
  268. assert d[b'version'] == 1
  269. assert d[b'algorithm'] == b'sha256'
  270. key = pbkdf2_sha256(passphrase.encode('utf-8'), d[b'salt'], d[b'iterations'], 32)
  271. data = AES(key).decrypt(d[b'data'])
  272. if HMAC(key, data, sha256).digest() != d[b'hash']:
  273. return None
  274. return data
  275. def encrypt_key_file(self, data, passphrase):
  276. salt = get_random_bytes(32)
  277. iterations = 100000
  278. key = pbkdf2_sha256(passphrase.encode('utf-8'), salt, iterations, 32)
  279. hash = HMAC(key, data, sha256).digest()
  280. cdata = AES(key).encrypt(data)
  281. d = {
  282. 'version': 1,
  283. 'salt': salt,
  284. 'iterations': iterations,
  285. 'algorithm': 'sha256',
  286. 'hash': hash,
  287. 'data': cdata,
  288. }
  289. return msgpack.packb(d)
  290. def save(self, path, passphrase):
  291. key = {
  292. 'version': 1,
  293. 'repository_id': self.repository_id,
  294. 'enc_key': self.enc_key,
  295. 'enc_hmac_key': self.enc_hmac_key,
  296. 'id_key': self.id_key,
  297. 'chunk_seed': self.chunk_seed,
  298. }
  299. data = self.encrypt_key_file(msgpack.packb(key), passphrase)
  300. with open(path, 'w') as fd:
  301. fd.write('%s %s\n' % (self.FILE_ID, hexlify(self.repository_id).decode('ascii')))
  302. fd.write('\n'.join(textwrap.wrap(b2a_base64(data).decode('ascii'))))
  303. fd.write('\n')
  304. self.path = path
  305. def change_passphrase(self):
  306. passphrase, passphrase2 = 1, 2
  307. while passphrase != passphrase2:
  308. passphrase = getpass('New passphrase: ')
  309. passphrase2 = getpass('Enter same passphrase again: ')
  310. if passphrase != passphrase2:
  311. print('Passphrases do not match')
  312. self.save(self.path, passphrase)
  313. print('Key file "%s" updated' % self.path)
  314. @classmethod
  315. def create(cls, repository, args):
  316. filename = args.repository.to_key_filename()
  317. path = filename
  318. i = 1
  319. while os.path.exists(path):
  320. i += 1
  321. path = filename + '.%d' % i
  322. passphrase = os.environ.get('ATTIC_PASSPHRASE')
  323. if passphrase is not None:
  324. passphrase2 = passphrase
  325. else:
  326. passphrase, passphrase2 = 1, 2
  327. while passphrase != passphrase2:
  328. passphrase = getpass('Enter passphrase (empty for no passphrase):')
  329. passphrase2 = getpass('Enter same passphrase again: ')
  330. if passphrase != passphrase2:
  331. print('Passphrases do not match')
  332. compressor = compressor_creator(args)
  333. maccer = maccer_creator(args, cls)
  334. key = cls(compressor, maccer)
  335. key.repository_id = repository.id
  336. key.init_from_random_data(get_random_bytes(100))
  337. key.init_ciphers()
  338. key.save(path, passphrase)
  339. print('Key file "%s" created.' % key.path)
  340. print('Keep this file safe. Your data will be inaccessible without it.')
  341. return key
  342. # note: key 0 nicely maps to a zlib compressor with level 0 which means "no compression"
  343. compressor_mapping = {}
  344. for level in ZlibCompressor.LEVELS:
  345. compressor_mapping[ZlibCompressor.TYPE + level] = \
  346. type('ZlibCompressorLevel%d' % level, (ZlibCompressor, ), dict(TYPE=ZlibCompressor.TYPE + level))
  347. for preset in LzmaCompressor.PRESETS:
  348. compressor_mapping[LzmaCompressor.TYPE + preset] = \
  349. type('LzmaCompressorPreset%d' % preset, (LzmaCompressor, ), dict(TYPE=LzmaCompressor.TYPE + preset))
  350. crypter_mapping = {
  351. KeyfileKey.TYPE: KeyfileKey,
  352. PassphraseKey.TYPE: PassphraseKey,
  353. PlaintextKey.TYPE: PlaintextKey,
  354. }
  355. maccer_mapping = {
  356. # simple hashes, not MACs (but MAC-like signature):
  357. SHA256.TYPE: SHA256,
  358. SHA512_256.TYPE: SHA512_256,
  359. # MACs:
  360. HMAC_SHA256.TYPE: HMAC_SHA256,
  361. HMAC_SHA512_256.TYPE: HMAC_SHA512_256,
  362. }
  363. def p(offset, compr_type, crypt_type, mac_type):
  364. try:
  365. compressor = compressor_mapping[compr_type]
  366. crypter = crypter_mapping[crypt_type]
  367. maccer = maccer_mapping[mac_type]
  368. except KeyError:
  369. raise UnsupportedPayloadError("compr_type %x crypt_type %x mac_type %x" % (compr_type, crypt_type, mac_type))
  370. return offset, compressor, crypter, maccer
  371. def parser00(data): # legacy, hardcoded
  372. return p(offset=1, compr_type=6, crypt_type=KeyfileKey.TYPE, mac_type=HMAC_SHA256.TYPE)
  373. def parser01(data): # legacy, hardcoded
  374. return p(offset=1, compr_type=6, crypt_type=PassphraseKey.TYPE, mac_type=HMAC_SHA256.TYPE)
  375. def parser02(data): # legacy, hardcoded
  376. return p(offset=1, compr_type=6, crypt_type=PlaintextKey.TYPE, mac_type=SHA256.TYPE)
  377. def parser03(data): # new & flexible
  378. offset = 4
  379. compr_type, crypt_type, mac_type = data[1:offset]
  380. return p(offset=offset, compr_type=compr_type, crypt_type=crypt_type, mac_type=mac_type)
  381. def parser(data):
  382. parser_mapping = {
  383. 0x00: parser00,
  384. 0x01: parser01,
  385. 0x02: parser02,
  386. 0x03: parser03,
  387. }
  388. header_type = data[0]
  389. parser_func = parser_mapping[header_type]
  390. return parser_func(data)
  391. def key_factory(repository, manifest_data):
  392. offset, compressor, crypter, maccer = parser(manifest_data)
  393. return crypter.detect(repository, manifest_data)
  394. def make_header(compr_type, crypt_type, mac_type):
  395. # always create new-style 0x03 headers
  396. return bytes([0x03, compr_type, crypt_type, mac_type])
  397. def compressor_creator(args):
  398. # args == None is used by unit tests
  399. compression = COMPR_DEFAULT if args is None else args.compression
  400. compressor = compressor_mapping.get(compression)
  401. if compressor is None:
  402. raise NotImplementedError("no compression %d" % args.compression)
  403. return compressor
  404. def key_creator(repository, args):
  405. if args.encryption == 'keyfile':
  406. return KeyfileKey.create(repository, args)
  407. if args.encryption == 'passphrase':
  408. return PassphraseKey.create(repository, args)
  409. if args.encryption == 'none':
  410. return PlaintextKey.create(repository, args)
  411. raise NotImplemented("no encryption %s" % args.encryption)
  412. def maccer_creator(args, key_cls):
  413. # args == None is used by unit tests
  414. mac = None if args is None else args.mac
  415. if mac is None:
  416. if key_cls is PlaintextKey:
  417. mac = HASH_DEFAULT
  418. elif key_cls in (KeyfileKey, PassphraseKey):
  419. mac = MAC_DEFAULT
  420. else:
  421. raise NotImplementedError("unknown key class")
  422. maccer = maccer_mapping.get(mac)
  423. if maccer is None:
  424. raise NotImplementedError("no mac %d" % args.mac)
  425. return maccer