Re: [PATCH bpf v5 1/2] lib/strncpy_from_user.c: Don't overcopy bytes after NUL terminator

From: Linus Torvalds
Date: Fri Nov 13 2020 - 14:30:35 EST


On Fri, Nov 13, 2020 at 11:17 AM Alexei Starovoitov
<alexei.starovoitov@xxxxxxxxx> wrote:
>
> You misunderstood.
> BPF side does not depend on zero padding.
> The destination buffer was already initialized with zeros before the call.
> What BPF didn't expect is strncpy_from_user() copying extra garbage after NUL byte.

BPF made the wrong expectation.

Those bytes are not defined, and it's faster the way it is written.

Nobody else cares.

BPF needs to fix it's usage. It really is that simple.

strncpy_from_user() is one of the hottest functions in the whole
kernel (under certain not very uncommon loads), and it's been
optimized for performance.

You told it that the destination buffer was some amount of bytes, and
strncpy_from_user() will use up to that maximum number of bytes.
That's the only guarantee you have - it won't write _past_ the buffer
you gave it.

The fact that you then use the string not as a string, but as
something else, that's why *you* need to change your code.

Linus