В ядре Linux была устранена следующая уязвимость: net: cap skb->queue_mapping при выборе очереди tx skbedit может установить skb->queue_mapping и поднять флаг per-CPU skip_txqueue, чтобы __dev_queue_xmit() выполнил отображение. __dev_queue_xmit() очистил флаг до sch_handle_egress() и прочитал его только после этого, поэтому флаг не ограничивался xmit, который установил его: вложенный xmit (отраженный редирект или зеркало). Пересылаемый пакет по-прежнему несет входной NIC rx_queue + 1 в skb->queue_mapping, поэтому внешнее устройство затем индексирует свое состояние очереди tx с этим устаревшим значением. Дочерний массив Taprio's q->qdiscs[] имеет размер, соответствующий количеству очередей устройства, поэтому taprio_enqueue() индексирует его после распределения и выводит результат в виде структуры Qdisc*.
Мы (ab)используем skb->nf_skip_egress, что означает «выйти из сетевого фильтра для этого пакета», чтобы пометить «я в выходе из TC?». Несмотря на перегрузку, я не рассматриваю это как конфликт, поскольку маркер устанавливается только вокруг одного вызова sch_handle_egress (), а путь входа охраняется tc_at_ingress. Я отправлю последующий патч (net-next), как только он попадет в сеть, чтобы переименовать бит skb->nf_skip_egress / флаг в skb->skip_egress Arm флаг только из классификатора выходов, который может его использовать: поднять skip_txqueue из tcf_skbedit_act () только тогда, когда он работает внутри sch_handle_egress (), благодаря skb->nf_skip_egress.
Классификатор qdisc express запускается в q->enqueue(), после того, как выбрана очередь tx, поэтому отображение, которое он устанавливает, не может повлиять на текущий пакет; вооружение флага там только загрязняет его для более позднего xmit. Затем владейте флагом для кадра xmit, в котором запускается выход: сохраните входящее значение и очистите его непосредственно перед sch_handle_egress (), и восстановите его после крюка - на потребленном (капельном) пути или, в том же вызове, который читает его, на выжившем пути. Сохранение и восстановление остаются внутри статической ветки egress_needed_key, поэтому пакет платит за них только тогда, когда крюки выхода активны (2f1e85b1aee4).
Сохраните значение netdev_cap_txqueue(), выбранное обратно в skb->queue_mapping в netdev_tx_queue_mapping(), как это уже делает netdev_core_pick_tx(), поэтому путь skip_txqueue никогда не передает более позднему читателю путь xmit, который не может служить устройству. Хранилище, сделанное еще позже в том же кадре, программой tc BPF, прикрепленной к qdisc передачи, находится за пределами этого пути и не повторно закрыто; отдельное продолжение решит этот путь. netdev_xmit_skip_txqueue () возвращает предыдущее значение флага, поэтому save-and-clear - это один вызов, а заглушка без операции предоставляется, когда CONFIG_NET_EGRESS отключен. skb->nf_skip_egress скомпилируется под CONFIG_NET_EGRESS, а не CONFIG_NETFILTER_SKIP_EGRESS, так что skb_at_tc_egress() Локальный пользователь в пространстве имен сети может перенаправить пакет с устройства с большим количеством очередей TX на одно с меньшим количеством после установки отображения, действительного только на более крупном устройстве. Это достигает этих считываний, и в KASAN ошибки с «slab-out-of-bounds в taprio_enqueue».
Условия для воссоздания ошибки: собственным триггером отчета является локальный пользователь с CAP_NET_ADMIN в пространстве имен сети, поэтому программа eBPF не требуется. С включенными CONFIG_NET_SCH_TAPRIO=y, CONFIG_NET_ACT_SKBEDIT=y, CONFIG_NET_ACT_MIRRED=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_PRIO=y и KASAN создайте qa (3 очереди), qb (2 очереди) и qc (1 очередь) в качестве фиктивных устройств; поместите корень taprio на qb (num_tc 1, очереди 20) и clsact на всех трех; затем добавьте фильтр ex matchall на каждом устройстве. On qa: "action skbedit queue_mapping 2 pipe action mirred egress redirect dev qb".
On qb: "action mirred egress mirror dev qc". На qc: "action skbedit queue_mapping 0 pipe". Отправить один пакет из qa. qc skbedit устанавливает флаг, в то время как внешний xmit qb находится в полете; без исправления qb потребляет его и читает его двух-входный дочерний массив taprio с пересылаемым пакетом устаревшим отображением. qc, чей skb --- усеченный ---
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: net: cap skb->queue_mapping when the tx queue is picked skbedit can set skb->queue_mapping and raise the per-CPU skip_txqueue flag so __dev_queue_xmit() honours the mapping. __dev_queue_xmit() cleared the flag before sch_handle_egress() and only read it afterwards, so the flag was not confined to the xmit that set it: a nested xmit (mirred redirect or mirror, or a drop after skbedit) could set the flag and the outer xmit would consume it for an skb that never went through skbedit. A forwarded packet still carries the ingress NIC's rx_queue + 1 in skb->queue_mapping, so the outer device then indexes its tx queue state with that stale value. Taprio's child array q->qdiscs[] is sized to the device's queue count, so taprio_enqueue() indexes past its allocation and dereferences the result as a struct Qdisc *. We (ab)use the skb->nf_skip_egress which means "skip netfilter egress for this packet" to tag to "am I in tc egress?". Despite the overload I dont see it as a conflict since the marker is set only around the single sch_handle_egress() call and ingress path is guarded by tc_at_ingress. I will send a followup(net-next) patch once this hits net-next to rename the skb->nf_skip_egress bit/flag to skb->skip_egress Arm the flag only from the egress classifier that can use it: raise skip_txqueue from tcf_skbedit_act() only when it runs inside sch_handle_egress(), thanks to skb->nf_skip_egress. An egress qdisc classifier runs in q->enqueue(), after the tx queue has been picked, so a mapping it sets cannot affect the current packet; arming the flag there only pollutes it for a later xmit. Then own the flag for the xmit frame the egress hook runs in: save the incoming value and clear it just before sch_handle_egress(), and restore it after the hook - on the consumed (drop) path, or, in the same call that reads it, on the surviving path. The save and the restores stay inside the egress_needed_key static branch, so a packet pays for them only when egress hooks are active (2f1e85b1aee4). Store the value netdev_cap_txqueue() selected back into skb->queue_mapping in netdev_tx_queue_mapping(), as netdev_core_pick_tx() already does, so the skip_txqueue path never hands a later reader on the xmit path a mapping the device cannot serve. A store made still later in the same frame, by a tc BPF program attached to a transmit qdisc, is outside this path and is not re-capped; a separate followup will resolve that path. netdev_xmit_skip_txqueue() returns the previous flag value so the save-and-clear is one call, and a no-op stub is provided when CONFIG_NET_EGRESS is disabled. skb->nf_skip_egress is compiled under CONFIG_NET_EGRESS rather than CONFIG_NETFILTER_SKIP_EGRESS, so skb_at_tc_egress() is valid whenever the egress path is built. A local user in a network namespace can redirect a packet from a device with more TX queues to one with fewer after setting a mapping valid only on the larger device. That reaches these reads and, under KASAN, faults with "slab-out-of-bounds in taprio_enqueue". Conditions to recreate the bug: the report's own trigger is a local user with CAP_NET_ADMIN in a network namespace, so no eBPF program is needed. With CONFIG_NET_SCH_TAPRIO=y, CONFIG_NET_ACT_SKBEDIT=y, CONFIG_NET_ACT_MIRRED=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_PRIO=y and KASAN enabled, create qa (3 queues), qb (2 queues) and qc (1 queue) as dummy devices; put a taprio root on qb (num_tc 1, queues 2@0) and clsact on all three; then add an egress matchall filter on every device. On qa: "action skbedit queue_mapping 2 pipe action mirred egress redirect dev qb". On qb: "action mirred egress mirror dev qc". On qc: "action skbedit queue_mapping 0 pipe". Send one packet out qa. qc's skbedit sets the flag while qb's outer xmit is in flight; without the fix qb consumes it and reads its two-entry taprio child array with the forwarded packet's stale mapping. A qc whose skb ---truncated---