security.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. When the above attack model is extended to include multiple clients
  30. independently updating the same repository, then Borg fails to provide
  31. confidentiality (i.e. guarantees 3) and 4) do not apply any more).
  32. .. _security_structural_auth:
  33. Structural Authentication
  34. -------------------------
  35. Borg is fundamentally based on an object graph structure (see :ref:`internals`),
  36. where the root object is called the manifest.
  37. Borg follows the `Horton principle`_, which states that
  38. not only the message must be authenticated, but also its meaning (often
  39. expressed through context), because every object used is referenced by a
  40. parent object through its object ID up to the manifest. The object ID in
  41. Borg is a MAC of the object's plaintext, therefore this ensures that
  42. an attacker cannot change the context of an object without forging the MAC.
  43. In other words, the object ID itself only authenticates the plaintext of the
  44. object and not its context or meaning. The latter is established by a different
  45. object referring to an object ID, thereby assigning a particular meaning to
  46. an object. For example, an archive item contains a list of object IDs that
  47. represent packed file metadata. On their own it's not clear that these objects
  48. would represent what they do, but by the archive item referring to them
  49. in a particular part of its own data structure assigns this meaning.
  50. This results in a directed acyclic graph of authentication from the manifest
  51. to the data chunks of individual files.
  52. .. _tam_description:
  53. .. rubric:: Authenticating the manifest
  54. Since the manifest has a fixed ID (000...000) the aforementioned authentication
  55. does not apply to it, indeed, cannot apply to it; it is impossible to authenticate
  56. the root node of a DAG through its edges, since the root node has no incoming edges.
  57. With the scheme as described so far an attacker could easily replace the manifest,
  58. therefore Borg includes a tertiary authentication mechanism (TAM) that is applied
  59. to the manifest since version 1.0.9 (see :ref:`tam_vuln`).
  60. TAM works by deriving a separate key through HKDF_ from the other encryption and
  61. authentication keys and calculating the HMAC of the metadata to authenticate [#]_::
  62. # RANDOM(n) returns n random bytes
  63. salt = RANDOM(64)
  64. ikm = id_key || enc_key || enc_hmac_key
  65. # *context* depends on the operation, for manifest authentication it is
  66. # the ASCII string "borg-metadata-authentication-manifest".
  67. tam_key = HKDF-SHA-512(ikm, salt, context)
  68. # *data* is a dict-like structure
  69. data[hmac] = zeroes
  70. packed = pack(data)
  71. data[hmac] = HMAC(tam_key, packed)
  72. packed_authenticated = pack(data)
  73. Since an attacker cannot gain access to this key and also cannot make the
  74. client authenticate arbitrary data using this mechanism, the attacker is unable
  75. to forge the authentication.
  76. This effectively 'anchors' the manifest to the key, which is controlled by the
  77. client, thereby anchoring the entire DAG, making it impossible for an attacker
  78. to add, remove or modify any part of the DAG without Borg being able to detect
  79. the tampering.
  80. Note that when using BORG_PASSPHRASE the attacker cannot swap the *entire*
  81. repository against a new repository with e.g. repokey mode and no passphrase,
  82. because Borg will abort access when BORG_PASSPHRASE is incorrect.
  83. However, interactively a user might not notice this kind of attack
  84. immediately, if she assumes that the reason for the absent passphrase
  85. prompt is a set BORG_PASSPHRASE. See issue :issue:`2169` for details.
  86. .. [#] The reason why the authentication tag is stored in the packed
  87. data itself is that older Borg versions can still read the
  88. manifest this way, while a changed layout would have broken
  89. compatibility.
  90. .. _security_encryption:
  91. Encryption
  92. ----------
  93. Encryption is currently based on the Encrypt-then-MAC construction,
  94. which is generally seen as the most robust way to create an authenticated
  95. encryption scheme from encryption and message authentication primitives.
  96. Every operation (encryption, MAC / authentication, chunk ID derivation)
  97. uses independent, random keys generated by `os.urandom`_ [#]_.
  98. Borg does not support unauthenticated encryption -- only authenticated encryption
  99. schemes are supported. No unauthenticated encryption schemes will be added
  100. in the future.
  101. Depending on the chosen mode (see :ref:`borg_init`) different primitives are used:
  102. - The actual encryption is currently always AES-256 in CTR mode. The
  103. counter is added in plaintext, since it is needed for decryption,
  104. and is also tracked locally on the client to avoid counter reuse.
  105. - The authentication primitive is either HMAC-SHA-256 or BLAKE2b-256
  106. in a keyed mode.
  107. Both HMAC-SHA-256 and BLAKE2b have undergone extensive cryptanalysis
  108. and have proven secure against known attacks. The known vulnerability
  109. of SHA-256 against length extension attacks does not apply to HMAC-SHA-256.
  110. The authentication primitive should be chosen based upon SHA hardware support:
  111. all AMD Ryzen, Intel 10th+ generation mobile and Intel 11th+ generation
  112. desktop processors, Apple M1+ and most current ARM64 architectures support
  113. SHA extensions and are likely to perform best with HMAC-SHA-256.
  114. 64-bit CPUs without SHA extensions are likely to perform best with BLAKE2b.
  115. - The primitive used for authentication is always the same primitive
  116. that is used for deriving the chunk ID, but they are always
  117. used with independent keys.
  118. Encryption::
  119. id = AUTHENTICATOR(id_key, data)
  120. compressed = compress(data)
  121. iv = reserve_iv()
  122. encrypted = AES-256-CTR(enc_key, 8-null-bytes || iv, compressed)
  123. authenticated = type-byte || AUTHENTICATOR(enc_hmac_key, encrypted) || iv || encrypted
  124. Decryption::
  125. # Given: input *authenticated* data, possibly a *chunk-id* to assert
  126. type-byte, mac, iv, encrypted = SPLIT(authenticated)
  127. ASSERT(type-byte is correct)
  128. ASSERT( CONSTANT-TIME-COMPARISON( mac, AUTHENTICATOR(enc_hmac_key, encrypted) ) )
  129. decrypted = AES-256-CTR(enc_key, 8-null-bytes || iv, encrypted)
  130. decompressed = decompress(decrypted)
  131. ASSERT( CONSTANT-TIME-COMPARISON( chunk-id, AUTHENTICATOR(id_key, decompressed) ) )
  132. The client needs to track which counter values have been used, since
  133. encrypting a chunk requires a starting counter value and no two chunks
  134. may have overlapping counter ranges (otherwise the bitwise XOR of the
  135. overlapping plaintexts is revealed).
  136. The client does not directly track the counter value, because it
  137. changes often (with each encrypted chunk), instead it commits a
  138. "reservation" to the security database and the repository by taking
  139. the current counter value and adding 4 GiB / 16 bytes (the block size)
  140. to the counter. Thus the client only needs to commit a new reservation
  141. every few gigabytes of encrypted data.
  142. This mechanism also avoids reusing counter values in case the client
  143. crashes or the connection to the repository is severed, since any
  144. reservation would have been committed to both the security database
  145. and the repository before any data is encrypted. Borg uses its
  146. standard mechanism (SaveFile) to ensure that reservations are durable
  147. (on most hardware / storage systems), therefore a crash of the
  148. client's host would not impact tracking of reservations.
  149. However, this design is not infallible, and requires synchronization
  150. between clients, which is handled through the repository. Therefore in
  151. a multiple-client scenario a repository can trick a client into
  152. reusing counter values by ignoring counter reservations and replaying
  153. the manifest (which will fail if the client has seen a more recent
  154. manifest or has a more recent nonce reservation). If the repository is
  155. untrusted, but a trusted synchronization channel exists between
  156. clients, the security database could be synchronized between them over
  157. said trusted channel. This is not part of Borg's functionality.
  158. .. [#] Using the :ref:`borg key migrate-to-repokey <borg_key_migrate-to-repokey>`
  159. command a user can convert repositories created using Attic in "passphrase"
  160. mode to "repokey" mode. In this case the keys were directly derived from
  161. the user's passphrase at some point using PBKDF2.
  162. Borg does not support "passphrase" mode otherwise any more.
  163. .. _key_encryption:
  164. Offline key security
  165. --------------------
  166. Borg cannot secure the key material while it is running, because the keys
  167. are needed in plain to decrypt/encrypt repository objects.
  168. For offline storage of the encryption keys they are encrypted with a
  169. user-chosen passphrase.
  170. A 256 bit key encryption key (KEK) is derived from the passphrase
  171. using PBKDF2-HMAC-SHA256 with a random 256 bit salt which is then used
  172. to Encrypt-*and*-MAC (unlike the Encrypt-*then*-MAC approach used
  173. otherwise) a packed representation of the keys with AES-256-CTR with a
  174. constant initialization vector of 0. A HMAC-SHA256 of the plaintext is
  175. generated using the same KEK and is stored alongside the ciphertext,
  176. which is converted to base64 in its entirety.
  177. This base64 blob (commonly referred to as *keyblob*) is then stored in
  178. the key file or in the repository config (keyfile and repokey modes
  179. respectively).
  180. This scheme, and specifically the use of a constant IV with the CTR
  181. mode, is secure because an identical passphrase will result in a
  182. different derived KEK for every key encryption due to the salt.
  183. The use of Encrypt-and-MAC instead of Encrypt-then-MAC is seen as
  184. uncritical (but not ideal) here, since it is combined with AES-CTR mode,
  185. which is not vulnerable to padding attacks.
  186. .. seealso::
  187. Refer to the :ref:`key_files` section for details on the format.
  188. Refer to issue :issue:`747` for suggested improvements of the encryption
  189. scheme and password-based key derivation.
  190. Implementations used
  191. --------------------
  192. We do not implement cryptographic primitives ourselves, but rely
  193. on widely used libraries providing them:
  194. - AES-CTR and HMAC-SHA-256 from OpenSSL 1.0 / 1.1 are used,
  195. which is also linked into the static binaries we provide.
  196. We think this is not an additional risk, since we don't ever
  197. use OpenSSL's networking, TLS or X.509 code, but only their
  198. primitives implemented in libcrypto.
  199. - SHA-256, SHA-512 and BLAKE2b from Python's hashlib_ standard library module are used.
  200. Borg requires a Python built with OpenSSL support (due to PBKDF2), therefore
  201. these functions are delegated to OpenSSL by Python.
  202. - HMAC, PBKDF2 and a constant-time comparison from Python's hmac_ standard
  203. library module is used. While the HMAC implementation is written in Python,
  204. the PBKDF2 implementation is provided by OpenSSL. The constant-time comparison
  205. (``compare_digest``) is written in C and part of Python.
  206. Implemented cryptographic constructions are:
  207. - Encrypt-then-MAC based on AES-256-CTR and either HMAC-SHA-256
  208. or keyed BLAKE2b256 as described above under Encryption_.
  209. - Encrypt-and-MAC based on AES-256-CTR and HMAC-SHA-256
  210. as described above under `Offline key security`_.
  211. - HKDF_-SHA-512
  212. .. _Horton principle: https://en.wikipedia.org/wiki/Horton_Principle
  213. .. _HKDF: https://tools.ietf.org/html/rfc5869
  214. .. _length extension: https://en.wikipedia.org/wiki/Length_extension_attack
  215. .. _hashlib: https://docs.python.org/3/library/hashlib.html
  216. .. _hmac: https://docs.python.org/3/library/hmac.html
  217. .. _os.urandom: https://docs.python.org/3/library/os.html#os.urandom
  218. Remote RPC protocol security
  219. ============================
  220. .. note:: This section could be further expanded / detailed.
  221. The RPC protocol is fundamentally based on msgpack'd messages exchanged
  222. over an encrypted SSH channel (the system's SSH client is used for this
  223. by piping data from/to it).
  224. This means that the authorization and transport security properties
  225. are inherited from SSH and the configuration of the SSH client and the
  226. SSH server -- Borg RPC does not contain *any* networking
  227. code. Networking is done by the SSH client running in a separate
  228. process, Borg only communicates over the standard pipes (stdout,
  229. stderr and stdin) with this process. This also means that Borg doesn't
  230. have to directly use a SSH client (or SSH at all). For example,
  231. ``sudo`` or ``qrexec`` could be used as an intermediary.
  232. By using the system's SSH client and not implementing a
  233. (cryptographic) network protocol Borg sidesteps many security issues
  234. that would normally impact distributing statically linked / standalone
  235. binaries.
  236. The remainder of this section will focus on the security of the RPC
  237. protocol within Borg.
  238. The assumed worst-case a server can inflict to a client is a
  239. denial of repository service.
  240. The situation where a server can create a general DoS on the client
  241. should be avoided, but might be possible by e.g. forcing the client to
  242. allocate large amounts of memory to decode large messages (or messages
  243. that merely indicate a large amount of data follows). The RPC protocol
  244. code uses a limited msgpack Unpacker to prohibit this.
  245. We believe that other kinds of attacks, especially critical vulnerabilities
  246. like remote code execution are inhibited by the design of the protocol:
  247. 1. The server cannot send requests to the client on its own accord,
  248. it only can send responses. This avoids "unexpected inversion of control"
  249. issues.
  250. 2. msgpack serialization does not allow embedding or referencing code that
  251. is automatically executed. Incoming messages are unpacked by the msgpack
  252. unpacker into native Python data structures (like tuples and dictionaries),
  253. which are then passed to the rest of the program.
  254. Additional verification of the correct form of the responses could be implemented.
  255. 3. Remote errors are presented in two forms:
  256. 1. A simple plain-text *stderr* channel. A prefix string indicates the kind of message
  257. (e.g. WARNING, INFO, ERROR), which is used to suppress it according to the
  258. log level selected in the client.
  259. A server can send arbitrary log messages, which may confuse a user. However,
  260. log messages are only processed when server requests are in progress, therefore
  261. the server cannot interfere / confuse with security critical dialogue like
  262. the password prompt.
  263. 2. Server-side exceptions passed over the main data channel. These follow the
  264. general pattern of server-sent responses and are sent instead of response data
  265. for a request.
  266. The msgpack implementation used (msgpack-python) has a good security track record,
  267. a large test suite and no issues found by fuzzing. It is based on the msgpack-c implementation,
  268. sharing the unpacking engine and some support code. msgpack-c has a good track record as well.
  269. Some issues [#]_ in the past were located in code not included in msgpack-python.
  270. Borg does not use msgpack-c.
  271. .. [#] - `MessagePack fuzzing <https://blog.gypsyengineer.com/fun/msgpack-fuzzing.html>`_
  272. - `Fixed integer overflow and EXT size problem <https://github.com/msgpack/msgpack-c/pull/547>`_
  273. - `Fixed array and map size overflow <https://github.com/msgpack/msgpack-c/pull/550>`_
  274. Using OpenSSL
  275. =============
  276. Borg uses the OpenSSL library for most cryptography (see `Implementations used`_ above).
  277. OpenSSL is bundled with static releases, thus the bundled copy is not updated with system
  278. updates.
  279. OpenSSL is a large and complex piece of software and has had its share of vulnerabilities,
  280. however, it is important to note that Borg links against ``libcrypto`` **not** ``libssl``.
  281. libcrypto is the low-level cryptography part of OpenSSL,
  282. while libssl implements TLS and related protocols.
  283. The latter is not used by Borg (cf. `Remote RPC protocol security`_, Borg itself does not implement
  284. any network access) and historically contained most vulnerabilities, especially critical ones.
  285. The static binaries released by the project contain neither libssl nor the Python ssl/_ssl modules.
  286. Compression and Encryption
  287. ==========================
  288. Combining encryption with compression can be insecure in some contexts (e.g. online protocols).
  289. There was some discussion about this in `github issue #1040`_ and for Borg some developers
  290. concluded this is no problem at all, some concluded this is hard and extremely slow to exploit
  291. and thus no problem in practice.
  292. No matter what, there is always the option not to use compression if you are worried about this.
  293. .. _github issue #1040: https://github.com/borgbackup/borg/issues/1040
  294. Fingerprinting
  295. ==============
  296. Stored chunk sizes
  297. ------------------
  298. A borg repository does not hide the size of the chunks it stores (size
  299. information is needed to operate the repository).
  300. The chunks stored in the repo are the (compressed, encrypted and authenticated)
  301. output of the chunker. The sizes of these stored chunks are influenced by the
  302. compression, encryption and authentication.
  303. buzhash chunker
  304. +++++++++++++++
  305. The buzhash chunker chunks according to the input data, the chunker's
  306. parameters and the secret chunker seed (which all influence the chunk boundary
  307. positions).
  308. Small files below some specific threshold (default: 512 KiB) result in only one
  309. chunk (identical content / size as the original file), bigger files result in
  310. multiple chunks.
  311. fixed chunker
  312. +++++++++++++
  313. This chunker yields fixed sized chunks, with optional support of a differently
  314. sized header chunk. The last chunk is not required to have the full block size
  315. and is determined by the input file size.
  316. Within our attack model, an attacker possessing a specific set of files which
  317. he assumes that the victim also possesses (and backups into the repository)
  318. could try a brute force fingerprinting attack based on the chunk sizes in the
  319. repository to prove his assumption.
  320. To make this more difficult, borg has an ``obfuscate`` pseudo compressor, that
  321. will take the output of the normal compression step and tries to obfuscate
  322. the size of that output. Of course, it can only **add** to the size, not reduce
  323. it. Thus, the optional usage of this mechanism comes at a cost: it will make
  324. your repository larger (ranging from a few percent larger [cheap] to ridiculously
  325. larger [expensive], depending on the algorithm/params you wisely choose).
  326. The output of the compressed-size obfuscation step will then be encrypted and
  327. authenticated, as usual. Of course, using that obfuscation would not make any
  328. sense without encryption. Thus, the additional data added by the obfuscator
  329. are just 0x00 bytes, which is good enough because after encryption it will
  330. look like random anyway.
  331. To summarize, this is making size-based fingerprinting difficult:
  332. - user-selectable chunker algorithm (and parametrization)
  333. - for the buzhash chunker: secret, random per-repo chunker seed
  334. - user-selectable compression algorithm (and level)
  335. - optional ``obfuscate`` pseudo compressor with different choices
  336. of algorithm and parameters
  337. Stored chunk proximity
  338. ----------------------
  339. Borg does not try to obfuscate order / proximity of files it discovers by
  340. recursing through the filesystem. For performance reasons, we sort directory
  341. contents in file inode order (not in file name alphabetical order), so order
  342. fingerprinting is not useful for an attacker.
  343. But, when new files are close to each other (when looking at recursion /
  344. scanning order), the resulting chunks will be also stored close to each other
  345. in the resulting repository segment file(s).
  346. This might leak additional information for the chunk size fingerprinting
  347. attack (see above).