Re: [PATCH] usb: raw_gadget: Fix a KASAN double-free bug in raw_release

Alan Stern
2024-11-03T02:34:48Z

On Sat, Nov 02, 2024 at 03:36:05PM -0700, Chang Yu wrote:
> syzkaller reported a double free bug
> (https://syzkaller.appspot.com/bug?extid=3e563d99e70973c0755c) in
> raw_release.
>
> I suspect this is because a race between raw_release and
> raw_ioctl_run.

This is confusing. raw_ioctl_run is called directly from raw_ioctl,
which is invoked through an open file reference, so while it is running
the file cannot be closed. But raw_release is called when the file is
closed for the last time, so while it runs there cannot be any ioctls in
progress.

Given this, how can the two routines race?

A debugging patch that shows what's going on whenever the kref is
incremented or decremented might help clarify the situation.

Alan Stern

> While kref_get in raw_ioctl_run is protected by
> the spin lock, all kref_put in raw_release are not under the
> lock. This makes it possible that a kref_put might occur during
> kref_get, which is specifically prohibited by the kref
> documentation[1].
>
> The fix is to ensure that all kref_put calls are made under lock
> and that we only call kfree(dev) after releasing the lock.
>
> [1] https://docs.kernel.org/core-api/kref.html