Re: [PATCH v2] usb: core: reject SG URBs longer than their scatterlist
From: Alan Stern
Date: Wed Dec 02 2026 - 10:40:43 EST
On Tue, Dec 01, 2026 at 11:12:14PM -0500, Artem Dinaburg wrote:
> A bulk or interrupt URB that uses a scatterlist can request more bytes
> than the scatterlist covers. usb_sg_init() copies its caller's length
> into transfer_buffer_length without comparing it to the scatterlist,
> and usb_submit_urb() does not check it either. xhci-hcd queues TRBs
> until the requested length is reached; after the final entry it
> continues from the last DMA address and length, so the controller
> transfers data outside the mapping. A USB device can cause this
> mismatch.
>
> Reject such URBs in usb_submit_urb() so that every HCD is covered. The
> existing scatter-gather check is skipped when the bus has no SG
> constraint, as is the case for xHCI, so sum the entry lengths for every
> SG URB and keep the maxpacket check conditional.
>
> Found and fixed with AI assistance.
>
> Suggested-by: Alan Stern <stern@xxxxxxxxxxxxxxxxxxx>
> Fixes: 86065c2719a5 ("xhci: don't rely on precalculated value of needed trbs in the enqueue loop")
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Artem Dinaburg <artem@xxxxxxxxxxxxxxx>
> ---
> v2: Move the check from xhci-hcd into usb_submit_urb(), as suggested
> by Alan Stern.
> v1: https://lore.kernel.org/r/20261201202438.32470.9674.04-xhci-sg-length-patch@xxxxxxxxxxxxxxx
>
> Tested on mainline 19cc08c1a6a6 in QEMU (q35, KASAN): an emulated
> storage device that makes the driver submit an SG URB longer than its
> scatterlist now gets -EINVAL from usb_submit_urb(). 1 GiB direct I/O
> over usb-storage and UAS on xHCI, usb-storage on EHCI, and xHCI with an
> Intel vIOMMU showed no regressions. Built with W=1 on mainline and
> usb-next.
>
> drivers/usb/core/urb.c | 15 +++++++++++++--
> 1 file changed, 13 insertions(+), 2 deletions(-)
Acked-by: Alan Stern <stern@xxxxxxxxxxxxxxxxxxx>
> diff --git a/drivers/usb/core/urb.c b/drivers/usb/core/urb.c
> index ae0d61b5081f..2a3b317f2de8 100644
> --- a/drivers/usb/core/urb.c
> +++ b/drivers/usb/core/urb.c
> @@ -493,13 +493,24 @@ int usb_submit_urb(struct urb *urb, gfp_t mem_flags)
> urb->iso_frame_desc[n].status = -EXDEV;
> urb->iso_frame_desc[n].actual_length = 0;
> }
> - } else if (urb->num_sgs && !urb->dev->bus->no_sg_constraint) {
> + } else if (urb->num_sgs) {
> struct scatterlist *sg;
> + u64 sg_len = 0;
> int i;
>
> - for_each_sg(urb->sg, sg, urb->num_sgs - 1, i)
> + for_each_sg(urb->sg, sg, urb->num_sgs, i) {
> + sg_len += sg->length;
> +
> + /* Some HCDs need whole packets in every entry but the last */
> + if (urb->dev->bus->no_sg_constraint || i == urb->num_sgs - 1)
> + continue;
> if (sg->length % max)
> return -EINVAL;
> + }
> +
> + /* Don't let the HCD transfer past the end of the scatterlist */
> + if (urb->transfer_buffer_length > sg_len)
> + return -EINVAL;
> }
>
> /* the I/O buffer must be mapped/unmapped, except when length=0 */
> --
> 2.55.0