key.py 11 KB

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