In the Linux kernel, the following vulnerability has been resolved:
usb: dwc3: gadget: Bail from dwc3gadgetexit() if dwc->gadget is NULL
There exists a possible scenario in which dwc3gadgetinit() can fail: during during host -> peripheral mode switch in dwc3setmode(), and a pending gadget driver fails to bind. Then, if the DRD undergoes another mode switch from peripheral->host the resulting dwc3gadgetexit() will attempt to reference an invalid and dangling dwc->gadget pointer as well as call dmafreecoherent() on unmapped DMA pointers.
The exact scenario can be reproduced as follows: - Start DWC3 in peripheral mode - Configure ConfigFS gadget with FunctionFS instance (or use gffs) - Run FunctionFS userspace application (open EPs, write descriptors, etc) - Bind gadget driver to DWC3's UDC - Switch DWC3 to host mode => dwc3gadgetexit() is called. usbdelgadget() will put the ConfigFS driver instance on the gadgetdriverpendinglist - Stop FunctionFS application (closes the ep files) - Switch DWC3 to peripheral mode => dwc3gadgetinit() fails as usbaddgadget() calls checkpendinggadgetdrivers() and attempts to rebind the UDC to the ConfigFS gadget but fails with -19 (-ENODEV) because the FFS instance is not in FFSACTIVE state (userspace has not re-opened and written the descriptors yet, i.e. descready!=0). - Switch DWC3 back to host mode => dwc3gadget_exit() is called again, but this time dwc->gadget is invalid.
Although it can be argued that userspace should take responsibility for ensuring that the FunctionFS application be ready prior to allowing the composite driver bind to the UDC, failure to do so should not result in a panic from the kernel driver.
Fix this by setting dwc->gadget to NULL in the failure path of dwc3gadgetinit() and add a check to dwc3gadgetexit() to bail out unless the gadget pointer is valid.