В ядре Linux устранена следующая уязвимость:
tcp: исправлено использование информации AO после освобождения в tcp_ao_connect_init().
tcp_v4_connect() добавляет сокет SYN-SENT в хэш перед вызовом
tcp_connect(). Если TCP-AO настроен, tcp_connect() сначала проверяет, что
ключ соответствует узлу и текущему мастеру L3 связанного устройства.
tcp_ao_connect_init() позже снова разрешает мастер L3 и удаляет ключи.
которые ему не соответствуют. Блокировка сокета не стабилизирует членство привязанного устройства в VRF.
Отсоединение устройства от VRF между первоначальной проверкой и
Таким образом, вычисление L3-master в tcp_ao_connect_init() может сделать
проверка успешна, в то время как инициализация наблюдает за доменом L3 по умолчанию и
удаляет единственный ключ. Последующий поиск AO завершается неудачей, поэтому
path очищает tp->ao_info и освобождает его напрямую. Путь получения может найти сокет в ehash и загрузить tp->ao_info.
под RCU до получения блокировки розетки.
Читалка, которая загружала старую
Таким образом, указатель может перейти в tcp_inbound_ao_hash() после прямого освобождения. Проблема была обнаружена во время статического аудита времени жизни объекта TCP-AO. Ан
непривилегированный воспроизводитель в самостоятельно созданных пространствах имен пользователей и сети
Connect() с отсоединением veth от его VRF при отправке сегментов TCP-AO.
Это вызвало тот же отчет KASAN о двух свежих загрузках:
ОШИБКА: KASAN: slab-use-after-free в tcp_inbound_ao_hash+0x585/0x19f0
Запись размера 8 по адресу ffff88800bf88128 с помощью задачи tcp_ao_vrf_race/232. Отслеживание вызова:
tcp_inbound_ao_hash+0x585/0x19f0
tcp_inbound_hash+0x677/0xa80
tcp_v4_rcv+0x1c3e/0x3ab0
Выделено задачей 235:
tcp_ao_alloc_info+0x43/0xf0
tcp_ao_add_cmd+0xdf7/0x13b0
do_tcp_setsockopt+0x168c/0x2640
Освобожден заданием 235:
kfree+0x1b8/0x550
tcp_connect+0x252/0x4f00
tcp_v4_connect+0x1114/0x1720
Плохой адрес занимает 40 байт внутри освобожденного 128-байтового объекта, что соответствует
Поле tcp_ao_info counters.key_not_found. В двух забегах использовано 1000 попыток.
каждый достиг пути без ключа 366 и 411 раз и произвел один и два
Об этом сообщает KASAN соответственно.
Благодаря этому изменению тот же репродуктор достиг
безключевой путь 366 раз за 1000 попыток без отчета KASAN или упс. Используйте tcp_ao_destroy_sock() для пути без ключа. Он отменяет публикацию информации АО,
обновляет память сокетов и учет статических ключей, а также откладывает бесплатное
до истечения льготного периода RCU.
Также удалите WARN_ON_ONCE() и его устаревший комментарий. Гонка на отрыв VRF
делает состояние без ключа доступным во время нормальной работы, так что это
обрабатываемое условие, а не невозможное утверждение. На панике_on_warn
ядер, WARN превратит эту управляемую гонку в панику ядра.
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: tcp: fix AO info use-after-free in tcp_ao_connect_init() tcp_v4_connect() adds a SYN-SENT socket to the ehash before calling tcp_connect(). If TCP-AO is configured, tcp_connect() first verifies that a key matches the peer and the bound device's current L3 master. tcp_ao_connect_init() later resolves the L3 master again and removes keys which do not match it. The socket lock does not stabilize the bound device's VRF membership. Detaching the device from its VRF between the initial validation and the L3-master calculation in tcp_ao_connect_init() can therefore make the validation succeed while initialization observes the default L3 domain and removes the only key. The subsequent AO lookup then fails, so the no-key path clears tp->ao_info and frees it directly. The receive path can find the socket in the ehash and load tp->ao_info under RCU before acquiring the socket lock. A reader which loaded the old pointer can thus continue into tcp_inbound_ao_hash() after the direct free. The issue was found during a static audit of TCP-AO object lifetime. An unprivileged reproducer in self-created user and network namespaces raced connect() with detaching a veth from its VRF while sending TCP-AO segments. It triggered the same KASAN report on two fresh boots: BUG: KASAN: slab-use-after-free in tcp_inbound_ao_hash+0x585/0x19f0 Write of size 8 at addr ffff88800bf88128 by task tcp_ao_vrf_race/232 Call Trace: tcp_inbound_ao_hash+0x585/0x19f0 tcp_inbound_hash+0x677/0xa80 tcp_v4_rcv+0x1c3e/0x3ab0 Allocated by task 235: tcp_ao_alloc_info+0x43/0xf0 tcp_ao_add_cmd+0xdf7/0x13b0 do_tcp_setsockopt+0x168c/0x2640 Freed by task 235: kfree+0x1b8/0x550 tcp_connect+0x252/0x4f00 tcp_v4_connect+0x1114/0x1720 The bad address is 40 bytes inside the freed 128-byte object, matching the tcp_ao_info counters.key_not_found field. The two runs used 1000 attempts each, reached the no-key path 366 and 411 times, and produced one and two KASAN reports respectively. With this change, the same reproducer reached the no-key path 366 times in 1000 attempts without a KASAN report or oops. Use tcp_ao_destroy_sock() for the no-key path. It unpublishes the AO info, updates the socket memory and static-key accounting, and defers the free until after an RCU grace period. Also drop the WARN_ON_ONCE() and its stale comment. The VRF detach race makes the no-key state reachable during normal operation, so it is a handled condition rather than an impossible assertion. On panic_on_warn kernels the WARN would turn this handled race into a kernel panic.