В ядре Linux устранена следующая уязвимость:
USB: гаджет: f_fs: сериализовать отмену DMABUF при завершении запроса
ffs_epfile_dmabuf_io_complete() вызывает usb_ep_free_request() на
запрос завершен, но остается priv->req, обратный указатель, который
ffs_dmabuf_transfer() устанавливается при отправке и указывает на освобожденный
память. Более поздний FUNCTIONFS_DMABUF_DETACH ioctl или
ffs_epfile_release() на пути закрытия все еще видит priv->req
не NULL в ffs->eps_lock:
if (priv->ep && priv->req)
usb_ep_dequeue(priv->ep, priv->req);
поэтому usb_ep_dequeue() вызывается по освобожденному usb_request. В dummy_hcd путь удаления из очереди проходит только по живой очереди и
указатель-сравнивается, поэтому освобожденный указатель читается без ошибок и
KASAN требует явной проверки на сайте вызова FunctionFS, чтобы
поверхность использования после бесплатного использования.
На внутридеревьевых УДК с поддержкой SG
Путь удаления из очереди немедленно разыменовывает предоставленный запрос:
* ep_dequeue() в Chipidea делает это
Container_of(req, struct ci_hw_req, req) и читает
hwreq->req.status перед получением собственной блокировки.
* cdnsp_gadget_ep_dequeue() cdnsp сначала считывает запрос->статус. Более узкий вариант очистки priv->req через cmpxchg() в
завершение не завершает гонку: завершение проходит без
eps_lock, поэтому путь отмены, содержащий eps_lock, все еще может наблюдаться
priv->req не-NULL, участвуйте в параллельном завершении, которое очищает и
освобождает и передает освобожденный указатель в usb_ep_dequeue(). Немного
необходимо более длинное исправление, которое позволит бесплатно перейти к очистке.
Тот же класс пожизненной гонки, что и недавнее исправление таймера usbip-vudc [1]. Возьмите eps_lock в единственном месте, которое мутирует priv->req из
направление обратного вызова, переместив usb_ep_free_request() из
завершение в ffs_dmabuf_cleanup(), существующем обработчике работ
запланировано ffs_dmabuf_signal_done() на
ffs->io_completion_wq. Очистите priv->req в разделе eps_lock.
перед освобождением и очищается только в том случае, если priv->req по-прежнему называет наши
запрос (последующий ffs_dmabuf_transfer() на том же самом
вложение могло поставить в очередь новое).
Это сохраняет существующий параметр dummy_hcd sync-dequeue неизменным:
обратный вызов завершения по-прежнему вызывается UDC без
eps_lock удерживается (dummy_hcd снимает собственную блокировку перед вызовом
обратный вызов), и обратный вызов теперь вообще не требует блокировки f_fs. Сериализация по пути отмены происходит при очистке, что
запускается из рабочей очереди без блокировки f_fs при входе. Счетчик ссылок priv защищает содержащий ffs_dmabuf_priv:
ffs_dmabuf_transfer() принимает ссылку через ffs_dmabuf_get(), очистка
удаляет его через ffs_dmabuf_put(), поэтому priv остается активным в течение
очистка даже после пути отмены list_del + ffs_dmabuf_put.
Путь ошибки ffs_dmabuf_transfer() больше не освобождает usb_req
встроенный: Fence->req и Fence->ep устанавливаются перед usb_ep_queue(),
поэтому ffs_dmabuf_cleanup() (запланированный по пути к ошибке
ffs_dmabuf_signal_done()) владеет бесплатным независимо от того,
очередь прошла успешно. Воспроизводится под КАСАН как на отрыве, так и на закрытии путей против
dummy_hcd с привязкой к наблюдаемости
(kasan_check_byte(priv->req) непосредственно перед usb_ep_dequeue)
на двух сайтах отмены FunctionFS, чтобы выявить устаревший указатель
доступ; крючок не является частью этого патча. КАСАН
распределитель/свободные стеки в захваченных пятнах идентифицируют
тот же запрос: alloc в dummy_alloc_request, free в
dummy_timer, ошибка произошла из ffs_epfile_release (закрытие) и
из ioctl FUNCTIONFS_DMABUF_DETACH (отсоединить).
С
патч применен, оба пути молчат под одним и тем же хуком. Ошибка достигается из узла устройства FunctionFS, который в
реальные развертывания принадлежат демону привилегированных гаджетов
(adbd, UMS, сервисы составных гаджетов и т. д.); это не так
доступен из непривилегированного пользовательского пространства или с USB-хоста на
кабель. FunctionFS по умолчанию монтирует GLOBAL_ROOT_UID, но
файловая система поддерживает делегирование uid=, gid= и fmode=
демон гаджета без полномочий root, поэтому при реальном развертывании злоумышленник может
быть менее привилегированной службой, а не root.
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: usb: gadget: f_fs: serialize DMABUF cancel against request completion ffs_epfile_dmabuf_io_complete() calls usb_ep_free_request() on the completed request but leaves priv->req, the back-pointer that ffs_dmabuf_transfer() set on submission, pointing at the freed memory. A later FUNCTIONFS_DMABUF_DETACH ioctl or ffs_epfile_release() on the close path still sees priv->req non-NULL under ffs->eps_lock: if (priv->ep && priv->req) usb_ep_dequeue(priv->ep, priv->req); so usb_ep_dequeue() is called on a freed usb_request. On dummy_hcd the dequeue path only walks a live queue and pointer-compares, so the freed pointer reads without faulting and KASAN requires an explicit check at the FunctionFS call site to surface the use-after-free. On SG-capable in-tree UDCs the dequeue path dereferences the supplied request immediately: * chipidea's ep_dequeue() does container_of(req, struct ci_hw_req, req) and reads hwreq->req.status before acquiring its own lock. * cdnsp's cdnsp_gadget_ep_dequeue() reads request->status first. The narrower option of clearing priv->req via cmpxchg() in the completion does not close the race: the completion runs without eps_lock, so a cancel path holding eps_lock can still observe priv->req non-NULL, race a concurrent completion that clears and frees, and pass the freed pointer to usb_ep_dequeue(). A slightly longer fix that moves the free into the cleanup work is needed. Same class of lifetime race as the recent usbip-vudc timer fix [1]. Take eps_lock in the sole place that mutates priv->req from the callback direction by moving usb_ep_free_request() out of the completion into ffs_dmabuf_cleanup(), the existing work handler scheduled by ffs_dmabuf_signal_done() on ffs->io_completion_wq. Clear priv->req there under eps_lock before freeing, and only clear if priv->req still names our request (a subsequent ffs_dmabuf_transfer() on the same attachment may have queued a new one). This keeps the existing dummy_hcd sync-dequeue invariant: the completion callback is still invoked by the UDC without eps_lock held (dummy_hcd drops its own lock before calling the callback), and the callback now takes no f_fs lock at all. Serialization against the cancel path happens in cleanup, which runs from the workqueue with no f_fs lock held on entry. The priv ref count protects the containing ffs_dmabuf_priv: ffs_dmabuf_transfer() takes a ref via ffs_dmabuf_get(), cleanup drops it via ffs_dmabuf_put(), so priv stays live for the cleanup even after the cancel path's list_del + ffs_dmabuf_put. The ffs_dmabuf_transfer() error path no longer frees usb_req inline: fence->req and fence->ep are set before usb_ep_queue(), so ffs_dmabuf_cleanup() (scheduled by the error-path ffs_dmabuf_signal_done()) owns the free regardless of whether the queue succeeded. Reproduced under KASAN on both detach and close paths against dummy_hcd with an observability hook (kasan_check_byte(priv->req) immediately before usb_ep_dequeue) at the two FunctionFS cancel sites to surface the stale-pointer access; the hook is not part of this patch. The KASAN allocator / free stacks in the captured splats identify the same request: alloc in dummy_alloc_request, free in dummy_timer, fault reached from ffs_epfile_release (close) and from the FUNCTIONFS_DMABUF_DETACH ioctl (detach). With the patch applied, both paths are silent under the same hook. The bug is reached from the FunctionFS device node, which in real deployments is owned by the privileged gadget daemon (adbd, UMS, composite gadget services, etc.); it is not reachable from unprivileged userspace or from a USB host on the cable. FunctionFS mounts default to GLOBAL_ROOT_UID, but the filesystem supports uid=, gid=, and fmode= delegation to a non-root gadget daemon, so on real deployments the attacker may be a less-privileged service rather than root.
Характеристики атаки
Последствия
Строка CVSS v3.1
Тип уязвимости (CWE)
Уязвимые продукты 8
| Конфигурация | От (включительно) | До (исключительно) |
|---|---|---|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.9
|
6.12.93
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.13
|
6.18.35
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*
|
6.19
|
7.0.12
|
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:7.1:rc1:*:*:*:*:*:*
|
— | — |
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:7.1:rc2:*:*:*:*:*:*
|
— | — |
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:7.1:rc3:*:*:*:*:*:*
|
— | — |
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:7.1:rc4:*:*:*:*:*:*
|
— | — |
|
Linux Linux_Kernel
cpe:2.3:o:linux:linux_kernel:7.1:rc5:*:*:*:*:*:*
|
— | — |