Skip to content

Commit 98f153a

Browse files
Jim Lingregkh
authored andcommitted
usb: gadget: configfs: Fix KASAN use-after-free
When gadget is disconnected, running sequence is like this. . composite_disconnect . Call trace: usb_string_copy+0xd0/0x128 gadget_config_name_configuration_store+0x4 gadget_config_name_attr_store+0x40/0x50 configfs_write_file+0x198/0x1f4 vfs_write+0x100/0x220 SyS_write+0x58/0xa8 . configfs_composite_unbind . configfs_composite_bind In configfs_composite_bind, it has "cn->strings.s = cn->configuration;" When usb_string_copy is invoked. it would allocate memory, copy input string, release previous pointed memory space, and use new allocated memory. When gadget is connected, host sends down request to get information. Call trace: usb_gadget_get_string+0xec/0x168 lookup_string+0x64/0x98 composite_setup+0xa34/0x1ee8 If gadget is disconnected and connected quickly, in the failed case, cn->configuration memory has been released by usb_string_copy kfree but configfs_composite_bind hasn't been run in time to assign new allocated "cn->configuration" pointer to "cn->strings.s". When "strlen(s->s) of usb_gadget_get_string is being executed, the dangling memory is accessed, "BUG: KASAN: use-after-free" error occurs. Cc: [email protected] Signed-off-by: Jim Lin <[email protected]> Signed-off-by: Macpaul Lin <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
1 parent 9858af2 commit 98f153a

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

drivers/usb/gadget/configfs.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ struct gadget_config_name {
9797
struct list_head list;
9898
};
9999

100+
#define USB_MAX_STRING_WITH_NULL_LEN (USB_MAX_STRING_LEN+1)
101+
100102
static int usb_string_copy(const char *s, char **s_copy)
101103
{
102104
int ret;
@@ -106,12 +108,16 @@ static int usb_string_copy(const char *s, char **s_copy)
106108
if (ret > USB_MAX_STRING_LEN)
107109
return -EOVERFLOW;
108110

109-
str = kstrdup(s, GFP_KERNEL);
110-
if (!str)
111-
return -ENOMEM;
111+
if (copy) {
112+
str = copy;
113+
} else {
114+
str = kmalloc(USB_MAX_STRING_WITH_NULL_LEN, GFP_KERNEL);
115+
if (!str)
116+
return -ENOMEM;
117+
}
118+
strcpy(str, s);
112119
if (str[ret - 1] == '\n')
113120
str[ret - 1] = '\0';
114-
kfree(copy);
115121
*s_copy = str;
116122
return 0;
117123
}

0 commit comments

Comments
 (0)