[PATCH] usb: core: Fix crash w/ usb_choose_configuration() if no driver

From: Douglas Anderson
Date: Fri Dec 08 2023 - 15:32:12 EST


It's possible that usb_choose_configuration() can get called when a
USB device has no driver. In this case the recent commit a87b8e3be926
("usb: core: Allow subclassed USB drivers to override
usb_choose_configuration()") can cause a crash since it dereferenced
the driver structure without checking for NULL. Let's add a check.

This was seen in the real world when usbguard got ahold of a r8152
device at the wrong time. It can also be simulated via this on a
computer with one r8152-based USB Ethernet adapter:
cd /sys/bus/usb/drivers/r8152-cfgselector
to_unbind="$(ls -d *-*)"
real_dir="$(readlink -f "${to_unbind}")"
echo "${to_unbind}" > unbind
cd "${real_dir}"
echo 0 > authorized
echo 1 > authorized

Fixes: a87b8e3be926 ("usb: core: Allow subclassed USB drivers to override usb_choose_configuration()")
Signed-off-by: Douglas Anderson <dianders@xxxxxxxxxxxx>
---

drivers/usb/core/generic.c | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/drivers/usb/core/generic.c b/drivers/usb/core/generic.c
index dcb897158228..365482347333 100644
--- a/drivers/usb/core/generic.c
+++ b/drivers/usb/core/generic.c
@@ -59,15 +59,19 @@ int usb_choose_configuration(struct usb_device *udev)
int num_configs;
int insufficient_power = 0;
struct usb_host_config *c, *best;
- struct usb_device_driver *udriver = to_usb_device_driver(udev->dev.driver);
+ struct usb_device_driver *udriver;

if (usb_device_is_owned(udev))
return 0;

- if (udriver->choose_configuration) {
- i = udriver->choose_configuration(udev);
- if (i >= 0)
- return i;
+ if (udev->dev.driver) {
+ udriver = to_usb_device_driver(udev->dev.driver);
+
+ if (udriver->choose_configuration) {
+ i = udriver->choose_configuration(udev);
+ if (i >= 0)
+ return i;
+ }
}

best = NULL;
--
2.43.0.472.g3155946c3a-goog