[PATCH] net/9p/usbg: Fix use-after-free in usb9pfs_free_func

Yizhou Zhao <[email protected]> Fri, 29 May 2026 16:18:16 +0800
Newsgroups dev.linux.lists.v9fs,org.kernel.vger.linux-kernel
Message-ID <[email protected]>
In usb9pfs_free_func, kfree(usb9pfs) frees the entire f_usb9pfs
structure which contains the embedded usb_function member that the
parameter 'f' points to. After the kfree, the code accesses f->fi
via container_of(f->fi, struct f_usb9pfs_opts, func_inst) and later
calls usb_free_all_descriptors(f), both of which dereference the
freed memory. Since f is &usb9pfs->function, all post-kfree accesses
through f constitute use-after-free on the already-freed usb9pfs
allocation.

Move kfree(usb9pfs) to the end of the function so that all accesses
through f complete before the memory is freed.

Fixes: a3be076dc174 ("net/9p/usbg: Add new usb gadget function transport")
Reported-by: Yizhou Zhao <[email protected]>
Reported-by: Yuxiang Yang <[email protected]>
Reported-by: Ao Wang <[email protected]>
Reported-by: Xuewei Feng <[email protected]>
Reported-by: Qi Li <[email protected]>
Reported-by: Ke Xu <[email protected]>
Assisted-by: GLM:GLM-5.1
Signed-off-by: Yizhou Zhao <[email protected]>
---
diff --git a/net/9p/trans_usbg.c b/net/9p/trans_usbg.c
index 1ce7033..c30ef5f 100644
--- a/net/9p/trans_usbg.c
+++ b/net/9p/trans_usbg.c
@@ -725,8 +725,6 @@ static void usb9pfs_free_func(struct usb_function *f)
 	struct f_usb9pfs *usb9pfs = func_to_usb9pfs(f);
 	struct f_usb9pfs_opts *opts;
 
-	kfree(usb9pfs);
-
 	opts = container_of(f->fi, struct f_usb9pfs_opts, func_inst);
 
 	mutex_lock(&opts->lock);
@@ -734,6 +732,8 @@ static void usb9pfs_free_func(struct usb_function *f)
 	mutex_unlock(&opts->lock);
 
 	usb_free_all_descriptors(f);
+
+	kfree(usb9pfs);
 }
 
 static int usb9pfs_set_alt(struct usb_function *f,

--
2.43.0