В ядре Linux устранена следующая уязвимость: mac802154: fix data race и NULL deref на local->assoc_dev local->assoc_dev разделяется между ассоциативным путём и работником ассоциации-ответа без общей синхронизации. mac802154_perform_association() хранит указатель координатора и ждёт ответа. Его тайм-аут и пути ошибок очищают указатель и возвращаются в mac802154_associate(), который затем может освободить объект-координатор. Между тем, mac802154_rx_mac_cmd_worker() может наблюдать ассоциативный бит и войти в mac802154_process_association_resp(), который отсылает assoc_dev.
Тест бита рабочего и указатель обработчика не являются атомарными в отношении очистки. Очистка может очистить assoc_dev между ними, вызывая удаление NULL, или освободить координатора, пока обработчик ответа все еще использует указатель. Записанный результат отображается в том же окне. assoc_status и assoc_addr записываются обработчиком, но считываются путем ассоциации, пока ассоциативный бит все еще установлен, поэтому второй ответ на тот же запрос - вредоносный, например - может заменить их между этими чтениями и оставить вызывающему абоненту непоследовательную пару состояния и адреса.
Ответчику нужен только расширенный адрес координатора. Замените assoc_dev кэшированным адресом, удалив пожизненную зависимость указателя. Защитите кэшированный адрес и связанный бит выделенным спинлоком.
Пара READ_ONCE()/WRITE_ONCE() не гарантирует атомарный доступ __le64 на всех 32-битных архитектурах. wpan_dev->association_lock не может быть повторно использован здесь: nl802154_associate() удерживает его через rdev_associate(), следовательно, для всего mac802154_perform_association(), включая ожидание ответа. Обработчик ответа, взявший этот замок, получит его только после того, как ассоциация уже сдалась. Сбросьте завершение, опубликуйте кэшированный адрес и установите ассоциативный бит, удерживая замок.
Обработчик ответа берёт блокировку, перепроверяет бит и кэшированный адрес, записывает ответ, очищает бит и только после этого завершает работу официанта. Таким образом, очистка не может пройти обработчик между его проверкой состояния и завершением, и кэшированное 64-битное значение не может разорваться. Обработчик очищает бит перед завершением, а не разбуженный официант: в противном случае complete() выдается под замком, и второй (например, злонамеренный) ответ может повторно получить его перед официантом и заменить результат.
Таким образом, ожидание, которое возвращает успех, подразумевает, что бит уже ясен, и пути успеха и отрицательного ответа возвращаются напрямую. Пути передачи и таймаута по-прежнему очищают его под assoc_lock, который сериализует любой гоночный ответ против очистки, в то время как вызов возвращает ошибку, которую он уже выбрал. assoc_status и assoc_addr под одним и тем же замком. Оба пользователя работают в контексте процесса, поэтому достаточно простого спинлока.
Замок не удерживается в ожидании завершения.
Показать оригинальное описание (EN)
In the Linux kernel, the following vulnerability has been resolved: mac802154: fix data race and NULL deref on local->assoc_dev local->assoc_dev is shared between the association path and the association-response worker without common synchronization. mac802154_perform_association() stores the coordinator pointer and waits for a response. Its timeout and error paths clear the pointer and return to mac802154_associate(), which may then free the coordinator object. Meanwhile, mac802154_rx_mac_cmd_worker() may observe the associating bit and enter mac802154_process_association_resp(), which dereferences assoc_dev. The worker's bit test and the handler's pointer dereference are not atomic with respect to cleanup. Cleanup can clear assoc_dev between them, causing a NULL dereference, or free the coordinator while the response handler still uses the pointer. The recorded result is exposed to the same window. assoc_status and assoc_addr are written by the handler but read by the association path while the associating bit is still set, so a second response for the same request - a malicious one, for instance - can replace them between those reads and leave the caller with an incoherent status and address pair. The response handler only needs the coordinator extended address. Replace assoc_dev with a cached address, removing the pointer lifetime dependency. Protect the cached address and the associating bit with a dedicated spinlock. A READ_ONCE()/WRITE_ONCE() pair would not guarantee an atomic __le64 access on all 32-bit architectures. wpan_dev->association_lock cannot be reused here: nl802154_associate() holds it across rdev_associate(), hence for the whole of mac802154_perform_association() including the wait for the response. A response handler taking that lock would only get it once the association has already given up. Reset the completion, publish the cached address, and set the associating bit while holding the lock. The response handler takes the lock, rechecks the bit and the cached address, records the response, clears the bit, and only then completes the waiter. Thus cleanup cannot pass the handler between its state check and completion, and the cached 64-bit value cannot tear. The handler clears the bit before completing, not the woken waiter: otherwise complete() is issued under the lock and a second (e.g. malicious) response can reacquire it before the waiter and replace the result. So a wait that returns success implies the bit is already clear, and the success and negative-response paths return directly. The transmit-error and timeout paths still clear it under assoc_lock, which serializes any racing response against the cleanup while the call returns the error it already selected. Both paths snapshot assoc_status and assoc_addr under the same lock. Both users run in process context, so a plain spinlock is sufficient. The lock is not held while waiting for the completion.