В ядре Linux устранена следующая уязвимость:
sched/fair: запретить мертвым группам задач восстанавливать cfs_rq. Кевин сообщает о сбоях, которые указывают на использование после освобождения файла cfs_rq.
в update_blocked_averages(). Первоначальная отладка показала, что мы
живые cfs_rq (on_list=1) в группе задач, которая будет запущена kfree() в
free_fair_sched_group().
Однако было неясно, как это может произойти. Его конфигурация ядра привела к макету структуры sched_entity.
это помещает член my_q прямо в середину объекта
из-за чего он случайно перекрывается с указателем свободного списка SLUB. Это в сочетании с указателем свободного списка SLAB_FREELIST_HARDENED
искажение приводит к надежному нарушению доступа в виде #GP, который
заставили ВСУ быстро провалиться.
Михал, похоже, столкнулся с той же проблемой[1]. Он уже правильно
диагностировано, что коммит a7b359fc6a37 («sched/fair: правильно вставьте
cfs_rq's to list on unthrottle") вызывает предварительные условия для
UAF произойдет путем повторного добавления cfs_rq также в группы задач, у которых нет
больше работающих задач, т. е. еще и мертвых. Однако его анализ
упускает реальную первопричину, и ее невозможно увидеть по сбою
только обратная трассировка, поскольку настоящий нарушитель - это tg_unthrottle_up(), получающий
вызывается через sched_cfs_ period_timer() через прерывание таймера в
неудобное время.
Когда unregister_fair_sched_group() отключает все cfs_rq от умирающего
группа задач, она не защищает себя от прерываний. Если
прерывание таймера срабатывает во время итерации по всем процессорам или после
unregister_fair_sched_group() завершился, но до отсоединения
группы задач, sched_cfs_ period_timer() выполнит и пройдёт по списку
группы задач, пытаясь разблокировать cfs_rq, то есть повторно добавить их в
умирающая целевая группа. Позже они будут в функции free_fair_sched_group().
kfree() используется, хотя он все еще связан, что приводит к фейерверку Кевина
и Михал видят.
Чтобы исправить эту гонку, сначала убедитесь, что умирающая группа задач отключена. Однако простое изменение порядка отмены регистрации и отсоединения
группы задач недостаточно, так как одновременные проходчики RCU все равно могут видеть
это, как видно ниже:
ЦП1: ЦП2:
: таймер IRQ:
: do_sched_cfs_ period_timer():
: :
: Distribute_cfs_runtime():
: rcu_read_lock();
: :
: unthrottle_cfs_rq():
sched_offline_group(): :
: walk_tg_tree_from(…,tg_unthrottle_up,…):
list_del_rcu(&tg->list); :
(1) : list_for_each_entry_rcu(ребенок, &parent->дети, братья и сестры)
: :
(2) list_del_rcu(&tg->братья и сестры); :
: tg_unthrottle_up():
unregister_fair_sched_group(): struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
: :
list_del_leaf_cfs_rq(tg->cfs_rq[процессор]); :
: :
: if (!cfs_rq_is_decayed(cfs_rq) || cfs_rq->nr_running)
(3): list_add_leaf_cfs_rq(cfs_rq);
: :
: :
: :
: :
:
---усечено---
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: sched/fair: Prevent dead task groups from regaining cfs_rq's Kevin is reporting crashes which point to a use-after-free of a cfs_rq in update_blocked_averages(). Initial debugging revealed that we've live cfs_rq's (on_list=1) in an about to be kfree()'d task group in free_fair_sched_group(). However, it was unclear how that can happen. His kernel config happened to lead to a layout of struct sched_entity that put the 'my_q' member directly into the middle of the object which makes it incidentally overlap with SLUB's freelist pointer. That, in combination with SLAB_FREELIST_HARDENED's freelist pointer mangling, leads to a reliable access violation in form of a #GP which made the UAF fail fast. Michal seems to have run into the same issue[1]. He already correctly diagnosed that commit a7b359fc6a37 ("sched/fair: Correctly insert cfs_rq's to list on unthrottle") is causing the preconditions for the UAF to happen by re-adding cfs_rq's also to task groups that have no more running tasks, i.e. also to dead ones. His analysis, however, misses the real root cause and it cannot be seen from the crash backtrace only, as the real offender is tg_unthrottle_up() getting called via sched_cfs_period_timer() via the timer interrupt at an inconvenient time. When unregister_fair_sched_group() unlinks all cfs_rq's from the dying task group, it doesn't protect itself from getting interrupted. If the timer interrupt triggers while we iterate over all CPUs or after unregister_fair_sched_group() has finished but prior to unlinking the task group, sched_cfs_period_timer() will execute and walk the list of task groups, trying to unthrottle cfs_rq's, i.e. re-add them to the dying task group. These will later -- in free_fair_sched_group() -- be kfree()'ed while still being linked, leading to the fireworks Kevin and Michal are seeing. To fix this race, ensure the dying task group gets unlinked first. However, simply switching the order of unregistering and unlinking the task group isn't sufficient, as concurrent RCU walkers might still see it, as can be seen below: CPU1: CPU2: : timer IRQ: : do_sched_cfs_period_timer(): : : : distribute_cfs_runtime(): : rcu_read_lock(); : : : unthrottle_cfs_rq(): sched_offline_group(): : : walk_tg_tree_from(…,tg_unthrottle_up,…): list_del_rcu(&tg->list); : (1) : list_for_each_entry_rcu(child, &parent->children, siblings) : : (2) list_del_rcu(&tg->siblings); : : tg_unthrottle_up(): unregister_fair_sched_group(): struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; : : list_del_leaf_cfs_rq(tg->cfs_rq[cpu]); : : : : if (!cfs_rq_is_decayed(cfs_rq) || cfs_rq->nr_running) (3) : list_add_leaf_cfs_rq(cfs_rq); : : : : : : : : : ---truncated---
Характеристики атаки
Последствия
Строка CVSS v3.1
Тип уязвимости (CWE)
Уязвимые продукты 1
| Конфигурация | От (включительно) | До (исключительно) |
|---|---|---|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
5.13
|
5.15.5
|