Re: BUG: bad usercopy in hidraw_ioctl

From: Kees Cook
Date: Thu Aug 08 2019 - 16:27:12 EST


On Wed, Aug 07, 2019 at 12:58:21PM -0700, Matthew Wilcox wrote:
> On Wed, Aug 07, 2019 at 12:28:06PM -0700, syzbot wrote:
> > usercopy: Kernel memory exposure attempt detected from wrapped address
> > (offset 0, size 0)!
> > ------------[ cut here ]------------
> > kernel BUG at mm/usercopy.c:98!
>
> This report is confusing because the arguments to usercopy_abort() are wrong.
>
> /* Reject if object wraps past end of memory. */
> if (ptr + n < ptr)
> usercopy_abort("wrapped address", NULL, to_user, 0, ptr + n);

This test actually contains an off-by-one which was recently fixed:
https://lore.kernel.org/linux-mm/1564509253-23287-1-git-send-email-isaacm@xxxxxxxxxxxxxx/

So, this is actually a false positive if "ptr + n" yields a 0
(e.g. 0xffffffff + 1 == 0).

> ptr + n is not 'size', it's what wrapped. I don't know what 'offset'
> should be set to, but 'size' should be 'n'. Presumably we don't want to
> report 'ptr' because it'll leak a kernel address ... reporting 'n' will

Right, I left offset 0 (this is normally the offset into a reported area
like a specific kmalloc region, but isn't meaningful here IMO). And I
left the size as "how far we wrapped". (Which is pretty telling: we
wrapped 0 bytes ... *cough*.)

> leak a range for a kernel address, but I think that's OK? Admittedly an
> attacker can pass in various values for 'n', but it'll be quite noisy
> and leave a trace in the kernel logs for forensics to find afterwards.
>
> > Call Trace:
> > check_bogus_address mm/usercopy.c:151 [inline]
> > __check_object_size mm/usercopy.c:260 [inline]
> > __check_object_size.cold+0xb2/0xba mm/usercopy.c:250
> > check_object_size include/linux/thread_info.h:119 [inline]
> > check_copy_size include/linux/thread_info.h:150 [inline]
> > copy_to_user include/linux/uaccess.h:151 [inline]
> > hidraw_ioctl+0x38c/0xae0 drivers/hid/hidraw.c:392
>
> The root problem would appear to be:
>
> else if (copy_to_user(user_arg + offsetof(
> struct hidraw_report_descriptor,
> value[0]),
> dev->hid->rdesc,
> min(dev->hid->rsize, len)))
>
> That 'min' should surely be a 'max'?
>
> Jiri, this looks like it was your code back in 2007.

I think this code is correct and the usercopy reporting fix already in
-mm solves the problem.

--
Kees Cook