[PATCH] HID: cougar: do not resurrect a zeroed shared object

From: Ziheng Wei

Date: Sun Nov 15 2026 - 03:02:49 EST


cougar_get_shared_data() calls kref_get() on any entry it finds on
cougar_udev_list. The entry itself is removed only from the kref
release callback, which runs after the refcount has already reached
zero:

cougar_remove_shared_data()
kref_put(&shared->kref, cougar_release_shared_data)
/* refcount is now 0, entry still linked */
cougar_release_shared_data()
mutex_lock(&cougar_udev_list_lock)
list_del(&shared->list)
kfree(shared)

A concurrent cougar_get_shared_data() that already holds
cougar_udev_list_lock still finds the entry and increments a zero
refcount. refcount_t reports "addition on 0; use-after-free", the
release callback then frees the object, and the reviving probe's devres
action writes into freed memory.

This was triggered by binding and unbinding two interfaces of the same
emulated (uhid) device concurrently through
/sys/bus/hid/drivers/cougar/{bind,unbind}. hid_bus_type does not set
bus_type.need_parent_lock, so the two sysfs writes run in parallel on
separate CPUs. KASAN on v7.3.1:

refcount_t: addition on 0; use-after-free.
cougar_bind_shared_data+0x53b <- cougar_probe <- __hid_device_probe

BUG: KASAN: slab-use-after-free in cougar_remove_shared_data+0x5e
Write of size 4 at addr ffff888013723550
Allocated by task 534: cougar_bind_shared_data+0x2fb
Freed by task 176: kfree <- cougar_remove_shared_data+0xba

Use kref_get_unless_zero() and skip an entry that is already being
released, as Documentation/core-api/kref.rst describes for lookups,
so the probing interface allocates a fresh shared object instead of
resurrecting the dying one.

Found by LLM-assisted static analysis, then reproduced with uhid as
described above. Not tested with a real Cougar device.

Fixes: b8e759b8f6da ("HID: cougar: Add support for the Cougar 500k Gaming Keyboard")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Ziheng Wei <zihengw03@xxxxxxx>
---

Notes:
The changelog was drafted with an AI assistant from my analysis;
I have reviewed the code, the fix and the text.

drivers/hid/hid-cougar.c | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/drivers/hid/hid-cougar.c b/drivers/hid/hid-cougar.c
index c8ae18f13..fa7bcb34a 100644
--- a/drivers/hid/hid-cougar.c
+++ b/drivers/hid/hid-cougar.c
@@ -122,10 +122,9 @@ static struct cougar_shared *cougar_get_shared_data(struct hid_device *hdev)

/* Try to find an already-probed interface from the same device */
list_for_each_entry(shared, &cougar_udev_list, list) {
- if (hid_compare_device_paths(hdev, shared->dev, '/')) {
- kref_get(&shared->kref);
+ if (hid_compare_device_paths(hdev, shared->dev, '/') &&
+ kref_get_unless_zero(&shared->kref))
return shared;
- }
}
return NULL;
}

base-commit: 97d73c8251226cf27cc6656b4c542869bb8c69fa
--
2.43.0