В ядре Linux устранена следующая уязвимость:
bpf: правильно отслеживать дескрипторы подпрограмм и исправлять использование после освобождения. Подпрограммы вызывают map_poke_track(), но при выпуске программы этого нет.
хук для вызова map_poke_untrack(). Однако в выпуске программы дополнительная память
(и таблица дескрипторов poke) освобождается, хотя у нас все еще есть ссылка на
он находится в списке элементов дополнительных данных карты.
Когда мы запускаем map_poke_run(), мы затем
в конечном итоге получаем доступ к свободной памяти, вызывая KASAN в prog_array_map_poke_run():
[...]
[402.824689] ОШИБКА: KASAN: использование после освобождения в prog_array_map_poke_run+0xc2/0x34e
[ 402.824698] Чтение размера 4 по адресу ffff8881905a7940 с помощью задачи Hubble-fgs/4337.
[ 402.824705] ЦП: 1 PID: 4337 Связь: Hubble-fgs Испорчено: G I 5.12.0+ #399
[ 402.824715] Отслеживание вызовов:
[ 402.824719] dump_stack+0x93/0xc2
[ 402.824727] print_address_description.constprop.0+0x1a/0x140
[402.824736] ? prog_array_map_poke_run+0xc2/0x34e
[402.824740] ? prog_array_map_poke_run+0xc2/0x34e
[ 402.824744] kasan_report.cold+0x7c/0xd8
[402.824752] ? prog_array_map_poke_run+0xc2/0x34e
[ 402.824757] prog_array_map_poke_run+0xc2/0x34e
[ 402.824765] bpf_fd_array_map_update_elem+0x124/0x1a0
[...]
Соответствующие элементы обрабатываются следующим образом:
for (i = 0; i <elem->aux->size_poke_tab; i++) {
тыкать = &elem->aux->poke_tab[i];
[...]
Доступ к size_poke_tab представляет собой чтение 4 байтов, подтвержденное проверкой смещений.
на свалке КАСАН:
[ 402.825004] Адрес ошибки принадлежит объекту по адресу ffff8881905a7800.
который принадлежит кешу kmalloc-1k размером 1024
[ 402.825008] Адрес ошибки находится в 320 байтах внутри
Область размером 1024 байта [ffff8881905a7800, ffff8881905a7c00)
Вывод bpf_prog_aux в pahole:
структура bpf_prog_aux {
[...]
/* --- граница строки кэша 5 (320 байт) --- */
u32 size_poke_tab; /* 320 4 */
[...]
В общем, подпрограммы не обязательно управляют своими собственными структурами данных. Например, BTF func_info и linfo — это просто указатели на основную программу.
структура. Это позволяет выполнять подсчет ссылок и очистку последнего.
что немного упрощает их управление.
Однако структура aux->poke_tab не следовал этой логике. Первоначальное предлагаемое исправление для этого использования после бесплатного использования. ошибка в дальнейшем внедрении отслеживания данных в подпрограмму с правильным подсчет ссылок. Однако Даниэль и Алексей задавались вопросом, почему мы лечим эти предметы особенные; Согласен, это ненужно.
Исправление здесь удаляет
подпрограмма тыкает таблицу распределения и отслеживания карт, а вместо этого просто точки
указатель aux->poke_tab на таблицу poke основной программы. Таким образом, карта
отслеживание упрощено до основной программы и нам не нужно ими управлять
за подпрограмму. Это также означает, что bpf_prog_free_deferred() разворачивает ссылку на программу.
подсчет и освобождение объектов, необходимо гарантировать, что мы не пытаемся удвоить освобождение
poke_tab при освобождении структур подпрограммы.
Это легко решается
Обнуление указателя poke_tab. Вторая деталь – убедиться, что
JIT-логика подпрограммы исправляет только записи poke_tab[], которыми она владеет. Делать
для этого мы добавляем в структуру poke указатель, указывающий на значение подпрограммы
поэтому JIT-компиляторы могут легко проверить, просматривая структуру poke_tab, если текущий
запись принадлежит текущей программе.
Указатель AUX стабилен и, следовательно,
подходит для такого сравнения. В пути к ошибке jit_subprogs() мы опускаем
очистка поля poke->aux, потому что на него всегда ссылаются только
стороне JIT, но в случае ошибки мы никогда не доберемся до JIT, так что это нормально
оставьте их висеть. Удаление этих указателей усложнит путь ошибки.
без причины.
Однако нам нужно отменить отслеживание всех дескрипторов poke из файла основной программы, иначе они могли бы поспешить с освобождением JIT-памяти от подпрограммы. Наконец, a748c6975dea3 ("bpf: распространять poke des ---усечено---
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: bpf: Track subprog poke descriptors correctly and fix use-after-free Subprograms are calling map_poke_track(), but on program release there is no hook to call map_poke_untrack(). However, on program release, the aux memory (and poke descriptor table) is freed even though we still have a reference to it in the element list of the map aux data. When we run map_poke_run(), we then end up accessing free'd memory, triggering KASAN in prog_array_map_poke_run(): [...] [ 402.824689] BUG: KASAN: use-after-free in prog_array_map_poke_run+0xc2/0x34e [ 402.824698] Read of size 4 at addr ffff8881905a7940 by task hubble-fgs/4337 [ 402.824705] CPU: 1 PID: 4337 Comm: hubble-fgs Tainted: G I 5.12.0+ #399 [ 402.824715] Call Trace: [ 402.824719] dump_stack+0x93/0xc2 [ 402.824727] print_address_description.constprop.0+0x1a/0x140 [ 402.824736] ? prog_array_map_poke_run+0xc2/0x34e [ 402.824740] ? prog_array_map_poke_run+0xc2/0x34e [ 402.824744] kasan_report.cold+0x7c/0xd8 [ 402.824752] ? prog_array_map_poke_run+0xc2/0x34e [ 402.824757] prog_array_map_poke_run+0xc2/0x34e [ 402.824765] bpf_fd_array_map_update_elem+0x124/0x1a0 [...] The elements concerned are walked as follows: for (i = 0; i < elem->aux->size_poke_tab; i++) { poke = &elem->aux->poke_tab[i]; [...] The access to size_poke_tab is a 4 byte read, verified by checking offsets in the KASAN dump: [ 402.825004] The buggy address belongs to the object at ffff8881905a7800 which belongs to the cache kmalloc-1k of size 1024 [ 402.825008] The buggy address is located 320 bytes inside of 1024-byte region [ffff8881905a7800, ffff8881905a7c00) The pahole output of bpf_prog_aux: struct bpf_prog_aux { [...] /* --- cacheline 5 boundary (320 bytes) --- */ u32 size_poke_tab; /* 320 4 */ [...] In general, subprograms do not necessarily manage their own data structures. For example, BTF func_info and linfo are just pointers to the main program structure. This allows reference counting and cleanup to be done on the latter which simplifies their management a bit. The aux->poke_tab struct, however, did not follow this logic. The initial proposed fix for this use-after-free bug further embedded poke data tracking into the subprogram with proper reference counting. However, Daniel and Alexei questioned why we were treating these objects special; I agree, its unnecessary. The fix here removes the per subprogram poke table allocation and map tracking and instead simply points the aux->poke_tab pointer at the main programs poke table. This way, map tracking is simplified to the main program and we do not need to manage them per subprogram. This also means, bpf_prog_free_deferred(), which unwinds the program reference counting and kfrees objects, needs to ensure that we don't try to double free the poke_tab when free'ing the subprog structures. This is easily solved by NULL'ing the poke_tab pointer. The second detail is to ensure that per subprogram JIT logic only does fixups on poke_tab[] entries it owns. To do this, we add a pointer in the poke structure to point at the subprogram value so JITs can easily check while walking the poke_tab structure if the current entry belongs to the current program. The aux pointer is stable and therefore suitable for such comparison. On the jit_subprogs() error path, we omit cleaning up the poke->aux field because these are only ever referenced from the JIT side, but on error we will never make it to the JIT, so its fine to leave them dangling. Removing these pointers would complicate the error path for no reason. However, we do need to untrack all poke descriptors from the main program as otherwise they could race with the freeing of JIT memory from the subprograms. Lastly, a748c6975dea3 ("bpf: propagate poke des ---truncated---
Характеристики атаки
Последствия
Строка CVSS v3.1
Тип уязвимости (CWE)
Уязвимые продукты 3
| Конфигурация | От (включительно) | До (исключительно) |
|---|---|---|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
5.10
|
5.10.53
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
5.11
|
5.13.5
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:5.14:rc1:*:*:*:*:*:*
|
— | — |