Re: [PATCH -v2] memdup_user(): introduce

From: Andrew Morton
Date: Sat Mar 07 2009 - 13:29:27 EST


On Sat, 7 Mar 2009 08:48:05 -0800 Arjan van de Ven <arjan@xxxxxxxxxxxxx> wrote:

> On Fri, 6 Mar 2009 15:03:35 -0800
> Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx> wrote:
>
> > >
> > > /**
> > > + * memdup_user - duplicate memory region from user space
> > > + *
> > > + * @src: source address in user space
> > > + * @len: number of bytes to copy
> > > + * @gfp: GFP mask to use
> > > + *
> > > + * Returns an ERR_PTR() on failure.
> > > + */
> > > +void *memdup_user(const void __user *src, size_t len, gfp_t gfp)
> > > +{
> > > + void *p;
> > > +
> > > + p = kmalloc_track_caller(len, gfp);
> > > + if (!p)
> > > + return ERR_PTR(-ENOMEM);
> > > +
> > > + if (copy_from_user(p, src, len)) {
> > > + kfree(p);
> > > + return ERR_PTR(-EFAULT);
> > > + }
> > > +
> > > + return p;
> > > +}
> > > +EXPORT_SYMBOL(memdup_user);
>
> Hi,
>
> I like the general idea of this a lot; it will make things much less
> error prone (and we can add some sanity checks on "len" to catch the
> standard security holes around copy_from_user usage). I'd even also
> want a memdup_array() like thing in the style of calloc().
>
> However, I have two questions/suggestions for improvement:
>
> I would like to question the use of the gfp argument here;
> copy_from_user sleeps, so you can't use GFP_ATOMIC anyway.
> You can't use GFP_NOFS etc, because the pagefault path will happily do
> things that are equivalent, if not identical, to GFP_KERNEL.
>
> So the only value you can pass in correctly, as far as I can see, is
> GFP_KERNEL. Am I wrong?

True.

> A second thing.. I'd like to have this function return NULL on failure;
> error checking a pointer for NULL is so much easier than testing for
> anything else; the only distinction is -ENOMEM versus -EFAULT, and I'm
> not sure that that is worth the complexity on all callers.

This errno will be returned to userspace. If the caller guesses wrong,
that's a kernel bug, of the regression variety.
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/