// For flags

CVE-2024-27080

btrfs: fix race when detecting delalloc ranges during fiemap

Severity Score

"-"
*CVSS v-

Exploit Likelihood

*EPSS

Affected Versions

*CPE

Public Exploits

0
*Multiple Sources

Exploited in Wild

-
*KEV

Decision

Track
*SSVC
Descriptions

In the Linux kernel, the following vulnerability has been resolved:

btrfs: fix race when detecting delalloc ranges during fiemap

For fiemap we recently stopped locking the target extent range for the
whole duration of the fiemap call, in order to avoid a deadlock in a
scenario where the fiemap buffer happens to be a memory mapped range of
the same file. This use case is very unlikely to be useful in practice but
it may be triggered by fuzz testing (syzbot, etc).

This however introduced a race that makes us miss delalloc ranges for
file regions that are currently holes, so the caller of fiemap will not
be aware that there's data for some file regions. This can be quite
serious for some use cases - for example in coreutils versions before 9.0,
the cp program used fiemap to detect holes and data in the source file,
copying only regions with data (extents or delalloc) from the source file
to the destination file in order to preserve holes (see the documentation
for its --sparse command line option). This means that if cp was used
with a source file that had delalloc in a hole, the destination file could
end up without that data, which is effectively a data loss issue, if it
happened to hit the race described below.

The race happens like this:

1) Fiemap is called, without the FIEMAP_FLAG_SYNC flag, for a file that
has delalloc in the file range [64M, 65M[, which is currently a hole;

2) Fiemap locks the inode in shared mode, then starts iterating the
inode's subvolume tree searching for file extent items, without having
the whole fiemap target range locked in the inode's io tree - the
change introduced recently by commit b0ad381fa769 ("btrfs: fix
deadlock with fiemap and extent locking"). It only locks ranges in
the io tree when it finds a hole or prealloc extent since that
commit;

3) Note that fiemap clones each leaf before using it, and this is to
avoid deadlocks when locking a file range in the inode's io tree and
the fiemap buffer is memory mapped to some file, because writing
to the page with btrfs_page_mkwrite() will wait on any ordered extent
for the page's range and the ordered extent needs to lock the range
and may need to modify the same leaf, therefore leading to a deadlock
on the leaf;

4) While iterating the file extent items in the cloned leaf before
finding the hole in the range [64M, 65M[, the delalloc in that range
is flushed and its ordered extent completes - meaning the corresponding
file extent item is in the inode's subvolume tree, but not present in
the cloned leaf that fiemap is iterating over;

5) When fiemap finds the hole in the [64M, 65M[ range by seeing the gap in
the cloned leaf (or a file extent item with disk_bytenr == 0 in case
the NO_HOLES feature is not enabled), it will lock that file range in
the inode's io tree and then search for delalloc by checking for the
EXTENT_DELALLOC bit in the io tree for that range and ordered extents
(with btrfs_find_delalloc_in_range()). But it finds nothing since the
delalloc in that range was already flushed and the ordered extent
completed and is gone - as a result fiemap will not report that there's
delalloc or an extent for the range [64M, 65M[, so user space will be
mislead into thinking that there's a hole in that range.

This could actually be sporadically triggered with test case generic/094
from fstests, which reports a missing extent/delalloc range like this:

generic/094 2s ... - output mismatch (see /home/fdmanana/git/hub/xfstests/results//generic/094.out.bad)
--- tests/generic/094.out 2020-06-10 19:29:03.830519425 +0100
+++ /home/fdmanana/git/hub/xfstests/results//generic/094.out.bad 2024-02-28 11:00:00.381071525 +0000
@@ -1,3 +1,9 @@
QA output created by 094
fiemap run with sync
fiemap run without sync
+ERROR: couldn't find extent at 7
+map is 'HHDDHPPDPHPH'
+logical: [ 5.. 6] phys:
---truncated---

En el kernel de Linux, se resolvió la siguiente vulnerabilidad: btrfs: corrige la ejecución al detectar rangos de delalloc durante fiemap Para fiemap recientemente dejamos de bloquear el rango de extensión objetivo durante toda la duración de la llamada a fiemap, para evitar un punto muerto en un escenario donde el búfer fiemap resulta ser un rango mapeado en memoria del mismo archivo. Es muy poco probable que este caso de uso sea útil en la práctica, pero puede activarse mediante pruebas difusas (syzbot, etc.). Sin embargo, esto introdujo una ejecución que nos hace perder rangos de delalloc para regiones de archivos que actualmente están vacías, por lo que quien llama a fiemap no sabrá que hay datos para algunas regiones de archivos. Esto puede ser bastante grave en algunos casos de uso; por ejemplo, en las versiones de Coreutils anteriores a la 9.0, el programa cp utilizaba fiemap para detectar agujeros y datos en el archivo de origen, copiando solo regiones con datos (extensiones o delalloc) del archivo de origen al destino. archivo para preservar los agujeros (consulte la documentación para conocer su opción de línea de comando --sparse). Esto significa que si se usó cp con un archivo de origen que tenía delalloc en un agujero, el archivo de destino podría terminar sin esos datos, lo que efectivamente es un problema de pérdida de datos, si llegara a la ejecución que se describe a continuación. La ejecución ocurre así: 1) Se llama a Fiemap, sin el indicador FIEMAP_FLAG_SYNC, para un archivo que tiene delalloc en el rango de archivos [64M, 65M[, que actualmente es un agujero; 2) Fiemap bloquea el inodo en modo compartido, luego comienza a iterar el árbol de subvolumen del inodo buscando elementos de extensión de archivo, sin tener todo el rango objetivo de fiemap bloqueado en el árbol io del inodo - el cambio introducido recientemente por el commit b0ad381fa769 ("btrfs: fix deadlock" con fiemap y bloqueo de extensión"). Solo bloquea rangos en el árbol io cuando encuentra un agujero o una extensión de asignación previa desde esa confirmación; 3) Tenga en cuenta que fiemap clona cada hoja antes de usarla, y esto es para evitar interbloqueos al bloquear un rango de archivos en el árbol io del inodo y el búfer de fiemap está asignado en memoria a algún archivo, porque escribir en la página con btrfs_page_mkwrite() esperará en cualquier extensión ordenada para el rango de la página y la extensión ordenada necesita bloquear el rango y puede necesitar modificar la misma hoja, lo que lleva a un punto muerto en la hoja; 4) Mientras se iteran los elementos de extensión del archivo en la hoja clonada antes de encontrar el hueco en el rango [64M, 65M[, la delalloc en ese rango se vacía y su extensión ordenada se completa, lo que significa que el elemento de extensión del archivo correspondiente está en el árbol de subvolumen del inodo. , pero no está presente en la hoja clonada sobre la que fiemap está iterando; 5) Cuando fiemap encuentra el agujero en el rango [64M, 65M[ al ver el espacio en la hoja clonada (o un elemento de extensión de archivo con disk_bytenr == 0 en caso de que la función NO_HOLES no esté habilitada), bloqueará ese rango de archivos. en el árbol io del inodo y luego busque delalloc verificando el bit EXTENT_DELALLOC en el árbol io para ese rango y extensiones ordenadas (con btrfs_find_delalloc_in_range()). Pero no encuentra nada ya que la delalloc en ese rango ya se vació y la extensión ordenada se completó y desapareció; como resultado, fiemap no informará que hay delalloc o una extensión para el rango [64M, 65M[, por lo que el espacio del usuario será engañoso a pensar que hay un agujero en ese rango. En realidad, esto podría activarse esporádicamente con el caso de prueba generic/094 de fstests, que informa que falta un rango de extensión/delalloc como este: generic/094 2s ... - falta de coincidencia de salida (consulte /home/fdmanana/git/hub/xfstests/results //generic/094.out.bad) ---truncado---

*Credits: N/A
CVSS Scores
Attack Vector
-
Attack Complexity
-
Privileges Required
-
User Interaction
-
Scope
-
Confidentiality
-
Integrity
-
Availability
-
* Common Vulnerability Scoring System
SSVC
  • Decision:Track
Exploitation
None
Automatable
No
Tech. Impact
Partial
* Organization's Worst-case Scenario
Timeline
  • 2024-02-19 CVE Reserved
  • 2024-05-01 CVE Published
  • 2024-05-02 EPSS Updated
  • 2024-08-02 CVE Updated
  • ---------- Exploited in Wild
  • ---------- KEV Due Date
  • ---------- First Exploit
CWE
CAPEC
Affected Vendors, Products, and Versions
Vendor Product Version Other Status
Vendor Product Version Other Status <-- --> Vendor Product Version Other Status
Linux
Search vendor "Linux"
Linux Kernel
Search vendor "Linux" for product "Linux Kernel"
>= 6.6.24 < 6.6.26
Search vendor "Linux" for product "Linux Kernel" and version " >= 6.6.24 < 6.6.26"
en
Affected
Linux
Search vendor "Linux"
Linux Kernel
Search vendor "Linux" for product "Linux Kernel"
>= 6.8 < 6.8.2
Search vendor "Linux" for product "Linux Kernel" and version " >= 6.8 < 6.8.2"
en
Affected
Linux
Search vendor "Linux"
Linux Kernel
Search vendor "Linux" for product "Linux Kernel"
>= 6.8 < 6.9
Search vendor "Linux" for product "Linux Kernel" and version " >= 6.8 < 6.9"
en
Affected
Linux
Search vendor "Linux"
Linux Kernel
Search vendor "Linux" for product "Linux Kernel"
6.7.12
Search vendor "Linux" for product "Linux Kernel" and version "6.7.12"
en
Affected