security.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. .. somewhat surprisingly the "bash" highlighter gives nice results with
  2. the pseudo-code notation used in the "Encryption" section.
  3. .. highlight:: bash
  4. ========
  5. Security
  6. ========
  7. .. _borgcrypto:
  8. Cryptography in Borg
  9. ====================
  10. .. _attack_model:
  11. Attack model
  12. ------------
  13. The attack model of Borg is that the environment of the client process
  14. (e.g. ``borg create``) is trusted and the repository (server) is not. The
  15. attacker has any and all access to the repository, including interactive
  16. manipulation (man-in-the-middle) for remote repositories.
  17. Furthermore the client environment is assumed to be persistent across
  18. attacks (practically this means that the security database cannot be
  19. deleted between attacks).
  20. Under these circumstances Borg guarantees that the attacker cannot
  21. 1. modify the data of any archive without the client detecting the change
  22. 2. rename, remove or add an archive without the client detecting the change
  23. 3. recover plain-text data
  24. 4. recover definite (heuristics based on access patterns are possible)
  25. structural information such as the object graph (which archives
  26. refer to what chunks)
  27. The attacker can always impose a denial of service per definition (he could
  28. forbid connections to the repository, or delete it entirely).
  29. .. _security_structural_auth:
  30. Structural Authentication
  31. -------------------------
  32. Borg is fundamentally based on an object graph structure (see :ref:`internals`),
  33. where the root object is called the manifest.
  34. Borg follows the `Horton principle`_, which states that
  35. not only the message must be authenticated, but also its meaning (often
  36. expressed through context), because every object used is referenced by a
  37. parent object through its object ID up to the manifest. The object ID in
  38. Borg is a MAC of the object's plaintext, therefore this ensures that
  39. an attacker cannot change the context of an object without forging the MAC.
  40. In other words, the object ID itself only authenticates the plaintext of the
  41. object and not its context or meaning. The latter is established by a different
  42. object referring to an object ID, thereby assigning a particular meaning to
  43. an object. For example, an archive item contains a list of object IDs that
  44. represent packed file metadata. On their own it's not clear that these objects
  45. would represent what they do, but by the archive item referring to them
  46. in a particular part of its own data structure assigns this meaning.
  47. This results in a directed acyclic graph of authentication from the manifest
  48. to the data chunks of individual files.
  49. .. _tam_description:
  50. .. rubric:: Authenticating the manifest
  51. Since the manifest has a fixed ID (000...000) the aforementioned authentication
  52. does not apply to it, indeed, cannot apply to it; it is impossible to authenticate
  53. the root node of a DAG through its edges, since the root node has no incoming edges.
  54. With the scheme as described so far an attacker could easily replace the manifest,
  55. therefore Borg includes a tertiary authentication mechanism (TAM) that is applied
  56. to the manifest (see :ref:`tam_vuln`).
  57. TAM works by deriving a separate key through HKDF_ from the other encryption and
  58. authentication keys and calculating the HMAC of the metadata to authenticate [#]_::
  59. # RANDOM(n) returns n random bytes
  60. salt = RANDOM(64)
  61. ikm = id_key || enc_key || enc_hmac_key
  62. # *context* depends on the operation, for manifest authentication it is
  63. # the ASCII string "borg-metadata-authentication-manifest".
  64. tam_key = HKDF-SHA-512(ikm, salt, context)
  65. # *data* is a dict-like structure
  66. data[hmac] = zeroes
  67. packed = pack(data)
  68. data[hmac] = HMAC(tam_key, packed)
  69. packed_authenticated = pack(data)
  70. Since an attacker cannot gain access to this key and also cannot make the
  71. client authenticate arbitrary data using this mechanism, the attacker is unable
  72. to forge the authentication.
  73. This effectively 'anchors' the manifest to the key, which is controlled by the
  74. client, thereby anchoring the entire DAG, making it impossible for an attacker
  75. to add, remove or modify any part of the DAG without Borg being able to detect
  76. the tampering.
  77. Note that when using BORG_PASSPHRASE the attacker cannot swap the *entire*
  78. repository against a new repository with e.g. repokey mode and no passphrase,
  79. because Borg will abort access when BORG_PASSPHRASE is incorrect.
  80. However, interactively a user might not notice this kind of attack
  81. immediately, if she assumes that the reason for the absent passphrase
  82. prompt is a set BORG_PASSPHRASE. See issue :issue:`2169` for details.
  83. .. [#] The reason why the authentication tag is stored in the packed
  84. data itself is that older Borg versions can still read the
  85. manifest this way, while a changed layout would have broken
  86. compatibility.
  87. .. _security_encryption:
  88. Encryption
  89. ----------
  90. AEAD modes
  91. ~~~~~~~~~~
  92. Modes: --encryption (repokey|keyfile)-[blake2-](aes-ocb|chacha20-poly1305)
  93. Supported: borg 2.0+
  94. Encryption with these modes is based on AEAD ciphers (authenticated encryption
  95. with associated data) and session keys.
  96. Depending on the chosen mode (see :ref:`borg_rcreate`) different AEAD ciphers are used:
  97. - AES-256-OCB - super fast, single-pass algorithm IF you have hw accelerated AES.
  98. - chacha20-poly1305 - very fast, purely software based AEAD cipher.
  99. The chunk ID is derived via a MAC over the plaintext (mac key taken from borg key):
  100. - HMAC-SHA256 - super fast IF you have hw accelerated SHA256 (see section "Encryption" below).
  101. - Blake2b - very fast, purely software based algorithm.
  102. For each borg invocation, a new session id is generated by `os.urandom`_.
  103. From that session id, the initial key material (ikm, taken from the borg key)
  104. and an application and cipher specific salt, borg derives a session key via HKDF.
  105. For each session key, IVs (nonces) are generated by a counter which increments for
  106. each encrypted message.
  107. Session::
  108. sessionid = os.urandom(24)
  109. ikm = enc_key || enc_hmac_key
  110. salt = "borg-session-key-CIPHERNAME"
  111. sessionkey = HKDF(ikm, sessionid, salt)
  112. message_iv = 0
  113. Encryption::
  114. id = MAC(id_key, data)
  115. compressed = compress(data)
  116. header = type-byte || 00h || message_iv || sessionid
  117. aad = id || header
  118. message_iv++
  119. encrypted, auth_tag = AEAD_encrypt(session_key, message_iv, compressed, aad)
  120. authenticated = header || auth_tag || encrypted
  121. Decryption::
  122. # Given: input *authenticated* data and a *chunk-id* to assert
  123. type-byte, past_message_iv, past_sessionid, auth_tag, encrypted = SPLIT(authenticated)
  124. ASSERT(type-byte is correct)
  125. past_key = HKDF(ikm, past_sessionid, salt)
  126. decrypted = AEAD_decrypt(past_key, past_message_iv, authenticated)
  127. decompressed = decompress(decrypted)
  128. ASSERT( CONSTANT-TIME-COMPARISON( chunk-id, MAC(id_key, decompressed) ) )
  129. Notable:
  130. - More modern and often faster AEAD ciphers instead of self-assembled stuff.
  131. - Due to the usage of session keys, IVs (nonces) do not need special care here as
  132. they did for the legacy encryption modes.
  133. - The id is now also input into the authentication tag computation.
  134. This strongly associates the id with the written data (== associates the key with
  135. the value). When later reading the data for some id, authentication will only
  136. succeed if what we get was really written by us for that id.
  137. Legacy modes
  138. ~~~~~~~~~~~~
  139. Modes: --encryption (repokey|keyfile)-[blake2]
  140. Supported: borg < 2.0
  141. These were the AES-CTR based modes in previous borg versions.
  142. borg 2.0 does not support creating new repos using these modes,
  143. but ``borg transfer`` can still read such existing repos.
  144. .. _key_encryption:
  145. Offline key security
  146. --------------------
  147. Borg cannot secure the key material while it is running, because the keys
  148. are needed in plain to decrypt/encrypt repository objects.
  149. For offline storage of the encryption keys they are encrypted with a
  150. user-chosen passphrase.
  151. A 256 bit key encryption key (KEK) is derived from the passphrase
  152. using PBKDF2-HMAC-SHA256 with a random 256 bit salt which is then used
  153. to Encrypt-*and*-MAC (unlike the Encrypt-*then*-MAC approach used
  154. otherwise) a packed representation of the keys with AES-256-CTR with a
  155. constant initialization vector of 0. A HMAC-SHA256 of the plaintext is
  156. generated using the same KEK and is stored alongside the ciphertext,
  157. which is converted to base64 in its entirety.
  158. This base64 blob (commonly referred to as *keyblob*) is then stored in
  159. the key file or in the repository config (keyfile and repokey modes
  160. respectively).
  161. This scheme, and specifically the use of a constant IV with the CTR
  162. mode, is secure because an identical passphrase will result in a
  163. different derived KEK for every key encryption due to the salt.
  164. The use of Encrypt-and-MAC instead of Encrypt-then-MAC is seen as
  165. uncritical (but not ideal) here, since it is combined with AES-CTR mode,
  166. which is not vulnerable to padding attacks.
  167. .. seealso::
  168. Refer to the :ref:`key_files` section for details on the format.
  169. Refer to issue :issue:`747` for suggested improvements of the encryption
  170. scheme and password-based key derivation.
  171. Implementations used
  172. --------------------
  173. We do not implement cryptographic primitives ourselves, but rely
  174. on widely used libraries providing them:
  175. - AES-CTR, AES-OCB, CHACHA20-POLY1305 and HMAC-SHA-256 from OpenSSL 1.1 are used,
  176. which is also linked into the static binaries we provide.
  177. We think this is not an additional risk, since we don't ever
  178. use OpenSSL's networking, TLS or X.509 code, but only their
  179. primitives implemented in libcrypto.
  180. - SHA-256, SHA-512 and BLAKE2b from Python's hashlib_ standard library module are used.
  181. Borg requires a Python built with OpenSSL support (due to PBKDF2), therefore
  182. these functions are delegated to OpenSSL by Python.
  183. - HMAC, PBKDF2 and a constant-time comparison from Python's hmac_ standard
  184. library module is used. While the HMAC implementation is written in Python,
  185. the PBKDF2 implementation is provided by OpenSSL. The constant-time comparison
  186. (``compare_digest``) is written in C and part of Python.
  187. Implemented cryptographic constructions are:
  188. - AEAD modes: AES-OCB and CHACHA20-POLY1305 are straight from OpenSSL.
  189. - Legacy modes: Encrypt-then-MAC based on AES-256-CTR and either HMAC-SHA-256
  190. or keyed BLAKE2b256 as described above under Encryption_.
  191. - Encrypt-and-MAC based on AES-256-CTR and HMAC-SHA-256
  192. as described above under `Offline key security`_.
  193. - HKDF_-SHA-512
  194. .. _Horton principle: https://en.wikipedia.org/wiki/Horton_Principle
  195. .. _HKDF: https://tools.ietf.org/html/rfc5869
  196. .. _length extension: https://en.wikipedia.org/wiki/Length_extension_attack
  197. .. _hashlib: https://docs.python.org/3/library/hashlib.html
  198. .. _hmac: https://docs.python.org/3/library/hmac.html
  199. .. _os.urandom: https://docs.python.org/3/library/os.html#os.urandom
  200. Remote RPC protocol security
  201. ============================
  202. .. note:: This section could be further expanded / detailed.
  203. The RPC protocol is fundamentally based on msgpack'd messages exchanged
  204. over an encrypted SSH channel (the system's SSH client is used for this
  205. by piping data from/to it).
  206. This means that the authorization and transport security properties
  207. are inherited from SSH and the configuration of the SSH client and the
  208. SSH server -- Borg RPC does not contain *any* networking
  209. code. Networking is done by the SSH client running in a separate
  210. process, Borg only communicates over the standard pipes (stdout,
  211. stderr and stdin) with this process. This also means that Borg doesn't
  212. have to directly use a SSH client (or SSH at all). For example,
  213. ``sudo`` or ``qrexec`` could be used as an intermediary.
  214. By using the system's SSH client and not implementing a
  215. (cryptographic) network protocol Borg sidesteps many security issues
  216. that would normally impact distributing statically linked / standalone
  217. binaries.
  218. The remainder of this section will focus on the security of the RPC
  219. protocol within Borg.
  220. The assumed worst-case a server can inflict to a client is a
  221. denial of repository service.
  222. The situation where a server can create a general DoS on the client
  223. should be avoided, but might be possible by e.g. forcing the client to
  224. allocate large amounts of memory to decode large messages (or messages
  225. that merely indicate a large amount of data follows). The RPC protocol
  226. code uses a limited msgpack Unpacker to prohibit this.
  227. We believe that other kinds of attacks, especially critical vulnerabilities
  228. like remote code execution are inhibited by the design of the protocol:
  229. 1. The server cannot send requests to the client on its own accord,
  230. it only can send responses. This avoids "unexpected inversion of control"
  231. issues.
  232. 2. msgpack serialization does not allow embedding or referencing code that
  233. is automatically executed. Incoming messages are unpacked by the msgpack
  234. unpacker into native Python data structures (like tuples and dictionaries),
  235. which are then passed to the rest of the program.
  236. Additional verification of the correct form of the responses could be implemented.
  237. 3. Remote errors are presented in two forms:
  238. 1. A simple plain-text *stderr* channel. A prefix string indicates the kind of message
  239. (e.g. WARNING, INFO, ERROR), which is used to suppress it according to the
  240. log level selected in the client.
  241. A server can send arbitrary log messages, which may confuse a user. However,
  242. log messages are only processed when server requests are in progress, therefore
  243. the server cannot interfere / confuse with security critical dialogue like
  244. the password prompt.
  245. 2. Server-side exceptions passed over the main data channel. These follow the
  246. general pattern of server-sent responses and are sent instead of response data
  247. for a request.
  248. The msgpack implementation used (msgpack-python) has a good security track record,
  249. a large test suite and no issues found by fuzzing. It is based on the msgpack-c implementation,
  250. sharing the unpacking engine and some support code. msgpack-c has a good track record as well.
  251. Some issues [#]_ in the past were located in code not included in msgpack-python.
  252. Borg does not use msgpack-c.
  253. .. [#] - `MessagePack fuzzing <https://blog.gypsyengineer.com/fun/msgpack-fuzzing.html>`_
  254. - `Fixed integer overflow and EXT size problem <https://github.com/msgpack/msgpack-c/pull/547>`_
  255. - `Fixed array and map size overflow <https://github.com/msgpack/msgpack-c/pull/550>`_
  256. Using OpenSSL
  257. =============
  258. Borg uses the OpenSSL library for most cryptography (see `Implementations used`_ above).
  259. OpenSSL is bundled with static releases, thus the bundled copy is not updated with system
  260. updates.
  261. OpenSSL is a large and complex piece of software and has had its share of vulnerabilities,
  262. however, it is important to note that Borg links against ``libcrypto`` **not** ``libssl``.
  263. libcrypto is the low-level cryptography part of OpenSSL,
  264. while libssl implements TLS and related protocols.
  265. The latter is not used by Borg (cf. `Remote RPC protocol security`_, Borg itself does not implement
  266. any network access) and historically contained most vulnerabilities, especially critical ones.
  267. The static binaries released by the project contain neither libssl nor the Python ssl/_ssl modules.
  268. Compression and Encryption
  269. ==========================
  270. Combining encryption with compression can be insecure in some contexts (e.g. online protocols).
  271. There was some discussion about this in :issue:`1040` and for Borg some developers
  272. concluded this is no problem at all, some concluded this is hard and extremely slow to exploit
  273. and thus no problem in practice.
  274. No matter what, there is always the option not to use compression if you are worried about this.
  275. Fingerprinting
  276. ==============
  277. Stored chunk sizes
  278. ------------------
  279. A borg repository does not hide the size of the chunks it stores (size
  280. information is needed to operate the repository).
  281. The chunks stored in the repo are the (compressed, encrypted and authenticated)
  282. output of the chunker. The sizes of these stored chunks are influenced by the
  283. compression, encryption and authentication.
  284. buzhash chunker
  285. ~~~~~~~~~~~~~~~
  286. The buzhash chunker chunks according to the input data, the chunker's
  287. parameters and the secret chunker seed (which all influence the chunk boundary
  288. positions).
  289. Small files below some specific threshold (default: 512 KiB) result in only one
  290. chunk (identical content / size as the original file), bigger files result in
  291. multiple chunks.
  292. fixed chunker
  293. ~~~~~~~~~~~~~
  294. This chunker yields fixed sized chunks, with optional support of a differently
  295. sized header chunk. The last chunk is not required to have the full block size
  296. and is determined by the input file size.
  297. Within our attack model, an attacker possessing a specific set of files which
  298. he assumes that the victim also possesses (and backups into the repository)
  299. could try a brute force fingerprinting attack based on the chunk sizes in the
  300. repository to prove his assumption.
  301. To make this more difficult, borg has an ``obfuscate`` pseudo compressor, that
  302. will take the output of the normal compression step and tries to obfuscate
  303. the size of that output. Of course, it can only **add** to the size, not reduce
  304. it. Thus, the optional usage of this mechanism comes at a cost: it will make
  305. your repository larger (ranging from a few percent larger [cheap] to ridiculously
  306. larger [expensive], depending on the algorithm/params you wisely choose).
  307. The output of the compressed-size obfuscation step will then be encrypted and
  308. authenticated, as usual. Of course, using that obfuscation would not make any
  309. sense without encryption. Thus, the additional data added by the obfuscator
  310. are just 0x00 bytes, which is good enough because after encryption it will
  311. look like random anyway.
  312. To summarize, this is making size-based fingerprinting difficult:
  313. - user-selectable chunker algorithm (and parametrization)
  314. - for the buzhash chunker: secret, random per-repo chunker seed
  315. - user-selectable compression algorithm (and level)
  316. - optional ``obfuscate`` pseudo compressor with different choices
  317. of algorithm and parameters
  318. Secret key usage against fingerprinting
  319. ---------------------------------------
  320. Borg uses the borg key also for chunking and chunk ID generation to protect against fingerprinting.
  321. As usual for borg's attack model, the attacker is assumed to have access to a borg repository.
  322. The borg key includes a secret random chunk_seed which (together with the chunking algorithm)
  323. determines the cutting places and thereby the length of the chunks cut. Because the attacker trying
  324. a chunk length fingerprinting attack would use a different chunker secret than the borg setup being
  325. attacked, they would not be able to determine the set of chunk lengths for a known set of files.
  326. The borg key also includes a secret random id_key. The chunk ID generation is not just using a simple
  327. cryptographic hash like sha256 (because that would be insecure as an attacker could see the hashes of
  328. small files that result only in 1 chunk in the repository). Instead, borg uses keyed hash (a MAC,
  329. e.g. HMAC-SHA256) to compute the chunk ID from the content and the secret id_key. Thus, an attacker
  330. can't compute the same chunk IDs for a known set of small files to determine whether these are stored
  331. in the attacked repository.
  332. Stored chunk proximity
  333. ----------------------
  334. Borg does not try to obfuscate order / proximity of files it discovers by
  335. recursing through the filesystem. For performance reasons, we sort directory
  336. contents in file inode order (not in file name alphabetical order), so order
  337. fingerprinting is not useful for an attacker.
  338. But, when new files are close to each other (when looking at recursion /
  339. scanning order), the resulting chunks will be also stored close to each other
  340. in the resulting repository segment file(s).
  341. This might leak additional information for the chunk size fingerprinting
  342. attack (see above).