В ядре Linux устранена следующая уязвимость:
Вернуть «wireguard: устройство: включить потоковый NAPI»
Это возвращает коммит 933466fc50a8e4eb167acbd0d8ec96a078462e9c, который
зафиксируйте db9ae3b6b43c79b1ba87eea849fd65efa05b4b2e в восходящем направлении. У нас было три независимых производственных отчета пользователей в совокупности.
с Cilium, использующим WireGuard в качестве шифрования под этим модулем k8s
E/W-трафик к некоторым одноранговым узлам полностью остановлен. Ситуация появляется
следующим образом:
- Происходит очень редко, но в случайное время при большой нагрузке на сеть.
- Как только проблема возникает, сторона расшифровки полностью перестает работать.
для этого узла WireGuard другие узлы продолжают работать нормально.
Ларек
происходит также для вновь инициированных связей с этим конкретным
Одноранговый узел WireGuard.
- Затрагивается только сторона дешифрования, а не сторона шифрования.
- Однажды сработав, он уже никогда не восстанавливается и остается в этом состоянии,
ЦП/память на этом узле выглядит нормально, нет утечек, циклов занятости или сбоев.
- bpftrace в затронутой системе показывает, что wg_prev_queue_enqueue
происходит сбой, поэтому MAX_QUEUED_PACKETS (1024 skbs!) для узла
rx_queue достигнут.
- Кроме того, bpftrace показывает, что wg_packet_rx_poll для этого узла никогда не
вызывается снова после достижения этого состояния для этого узла. Для других
одноранговые узлы wg_packet_rx_poll вызываются нормально.
— Зафиксируйте db9ae3b («wireguard: устройство: включить потоковый NAPI»)
по умолчанию переключил WireGuard на многопоточный NAPI. По умолчанию есть
не было изменено для возникновения проблемы, как и процессор
происходит горячее подключение (т.е. 5bd8de2 ("wireguard: очередь: всегда
вернуть действительный сетевой процессор в wg_cpumask_choose_online()")).
- Проблема наблюдалась со стабильными ядрами версии 5.15, а также
v6.1.
Нам сообщили, что стабильная версия 5.10 работает нормально, и
также нет отчета о стабильной версии 6.6 (несколько связанное обсуждение в [0]
хотя).
- В драйвере WireGuard единственная существенная разница между v5.10
стабильная версия и стабильная версия 5.15 — это переключение на потоковый NAPI по умолчанию.
[0] https://lore.kernel.org/netdev/CA+wXwBTT74RErDGAnj98PqS=wvdh8eM1pi4q6tTdExtjnokKqA@mail.gmail.com/
Детализация проблемы:
1) skbs, поступающие на расшифровку, ставятся в очередь Peer->rx_queue в
wg_packet_consume_data через wg_queue_enqueue_per_device_and_peer.
2) Последний только перемещает skb в очередь однорангового узла MPSC, если это так.
не превышать MAX_QUEUED_PACKETS (1024), который отслеживается в
атомарный счетчик через wg_prev_queue_enqueue.
3) Если постановка в очередь прошла успешно, skb также ставится в очередь.
в очереди устройств циклический перебор выбирает следующий процессор, находящийся в сети, и
планирует работу дешифратора.
4) wg_packet_decrypt_worker по расписанию подхватывает их.
из очереди, расшифровывает пакеты и после завершения вызывает
wg_queue_enqueue_per_peer_rx.
5) Последний обновляет состояние до PACKET_STATE_CRYPTED в случае успеха.
и вызывает napi_schedule для каждого экземпляра однорангового узла->napi.
6) Затем NAPI опрашивает через wg_packet_rx_poll. wg_prev_queue_peek проверяет
на одноранговом узле->rx_queue. Это будет wg_prev_queue_dequeue, если
очередь->просмотренный скб еще не был в кэше, или просто верните последний
иначе. (wg_prev_queue_drop_peeked позже очищает кеш.)
7) С точки зрения упорядочения одноранговый узел->rx_queue имеет skbs в порядке.
в то время как очередь устройств с рабочими потоками каждого процессора из
PoV глобального заказа может завершить расшифровку и подать сигнал skb
PACKET_STATE_CRYPTED вышел из строя.
8) Можно наблюдать ситуацию, что первый пришедший пакет будет
застрять в ожидании назначения специалиста по расшифровке
более длительное время, когда система находится под давлением.
9) Пока это так, остальные процессоры тем временем завершают работу.
расшифровку и вызов napi_schedule.
10) Теперь в wg_packet_rx_poll подхватывается первый по порядку скб
из однорангового узла->rx_queue и видит, что его состояние все еще
PACKET_STATE_UNCRYPTED. Затем процедура опроса NAPI завершает работу.
---усечено---
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: Revert "wireguard: device: enable threaded NAPI" This reverts commit 933466fc50a8e4eb167acbd0d8ec96a078462e9c which is commit db9ae3b6b43c79b1ba87eea849fd65efa05b4b2e upstream. We have had three independent production user reports in combination with Cilium utilizing WireGuard as encryption underneath that k8s Pod E/W traffic to certain peer nodes fully stalled. The situation appears as follows: - Occurs very rarely but at random times under heavy networking load. - Once the issue triggers the decryption side stops working completely for that WireGuard peer, other peers keep working fine. The stall happens also for newly initiated connections towards that particular WireGuard peer. - Only the decryption side is affected, never the encryption side. - Once it triggers, it never recovers and remains in this state, the CPU/mem on that node looks normal, no leak, busy loop or crash. - bpftrace on the affected system shows that wg_prev_queue_enqueue fails, thus the MAX_QUEUED_PACKETS (1024 skbs!) for the peer's rx_queue is reached. - Also, bpftrace shows that wg_packet_rx_poll for that peer is never called again after reaching this state for that peer. For other peers wg_packet_rx_poll does get called normally. - Commit db9ae3b ("wireguard: device: enable threaded NAPI") switched WireGuard to threaded NAPI by default. The default has not been changed for triggering the issue, neither did CPU hotplugging occur (i.e. 5bd8de2 ("wireguard: queueing: always return valid online CPU in wg_cpumask_choose_online()")). - The issue has been observed with stable kernels of v5.15 as well as v6.1. It was reported to us that v5.10 stable is working fine, and no report on v6.6 stable either (somewhat related discussion in [0] though). - In the WireGuard driver the only material difference between v5.10 stable and v5.15 stable is the switch to threaded NAPI by default. [0] https://lore.kernel.org/netdev/CA+wXwBTT74RErDGAnj98PqS=wvdh8eM1pi4q6tTdExtjnokKqA@mail.gmail.com/ Breakdown of the problem: 1) skbs arriving for decryption are enqueued to the peer->rx_queue in wg_packet_consume_data via wg_queue_enqueue_per_device_and_peer. 2) The latter only moves the skb into the MPSC peer queue if it does not surpass MAX_QUEUED_PACKETS (1024) which is kept track in an atomic counter via wg_prev_queue_enqueue. 3) In case enqueueing was successful, the skb is also queued up in the device queue, round-robin picks a next online CPU, and schedules the decryption worker. 4) The wg_packet_decrypt_worker, once scheduled, picks these up from the queue, decrypts the packets and once done calls into wg_queue_enqueue_per_peer_rx. 5) The latter updates the state to PACKET_STATE_CRYPTED on success and calls napi_schedule on the per peer->napi instance. 6) NAPI then polls via wg_packet_rx_poll. wg_prev_queue_peek checks on the peer->rx_queue. It will wg_prev_queue_dequeue if the queue->peeked skb was not cached yet, or just return the latter otherwise. (wg_prev_queue_drop_peeked later clears the cache.) 7) From an ordering perspective, the peer->rx_queue has skbs in order while the device queue with the per-CPU worker threads from a global ordering PoV can finish the decryption and signal the skb PACKET_STATE_CRYPTED out of order. 8) A situation can be observed that the first packet coming in will be stuck waiting for the decryption worker to be scheduled for a longer time when the system is under pressure. 9) While this is the case, the other CPUs in the meantime finish decryption and call into napi_schedule. 10) Now in wg_packet_rx_poll it picks up the first in-order skb from the peer->rx_queue and sees that its state is still PACKET_STATE_UNCRYPTED. The NAPI poll routine then exits e ---truncated---
Характеристики атаки
Последствия
Строка CVSS v3.1
Тип уязвимости (CWE)
Уязвимые продукты 5
| Конфигурация | От (включительно) | До (исключительно) |
|---|---|---|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
5.15.186
|
5.15.201
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.1.142
|
6.1.164
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.6.94
|
6.6.127
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.12.34
|
6.12.74
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.15.3
|
6.16
|