Re: [PATCH] bpf, test_run: Track allocation size of data

From: Alexei Starovoitov
Date: Tue Oct 18 2022 - 12:29:44 EST


On Tue, Oct 18, 2022 at 2:02 AM Kees Cook <keescook@xxxxxxxxxxxx> wrote:
>
> In preparation for requiring that build_skb() have a non-zero size
> argument, track the data allocation size explicitly and pass it into
> build_skb(). To retain the original result of using the ksize()
> side-effect on the skb size, explicitly round up the size during
> allocation.
>
> Cc: Alexei Starovoitov <ast@xxxxxxxxxx>
> Cc: Daniel Borkmann <daniel@xxxxxxxxxxxxx>
> Cc: Andrii Nakryiko <andrii@xxxxxxxxxx>
> Cc: Martin KaFai Lau <martin.lau@xxxxxxxxx>
> Cc: Song Liu <song@xxxxxxxxxx>
> Cc: Yonghong Song <yhs@xxxxxx>
> Cc: John Fastabend <john.fastabend@xxxxxxxxx>
> Cc: KP Singh <kpsingh@xxxxxxxxxx>
> Cc: Stanislav Fomichev <sdf@xxxxxxxxxx>
> Cc: Hao Luo <haoluo@xxxxxxxxxx>
> Cc: Jiri Olsa <jolsa@xxxxxxxxxx>
> Cc: "David S. Miller" <davem@xxxxxxxxxxxxx>
> Cc: Eric Dumazet <edumazet@xxxxxxxxxx>
> Cc: Jakub Kicinski <kuba@xxxxxxxxxx>
> Cc: Paolo Abeni <pabeni@xxxxxxxxxx>
> Cc: Jesper Dangaard Brouer <hawk@xxxxxxxxxx>
> Cc: bpf@xxxxxxxxxxxxxxx
> Cc: netdev@xxxxxxxxxxxxxxx
> Signed-off-by: Kees Cook <keescook@xxxxxxxxxxxx>
> ---
> net/bpf/test_run.c | 84 +++++++++++++++++++++++++---------------------
> 1 file changed, 46 insertions(+), 38 deletions(-)
>
> diff --git a/net/bpf/test_run.c b/net/bpf/test_run.c
> index 13d578ce2a09..299ff102f516 100644
> --- a/net/bpf/test_run.c
> +++ b/net/bpf/test_run.c
> @@ -762,28 +762,38 @@ BTF_ID_FLAGS(func, bpf_kfunc_call_test_ref, KF_TRUSTED_ARGS)
> BTF_ID_FLAGS(func, bpf_kfunc_call_test_destructive, KF_DESTRUCTIVE)
> BTF_SET8_END(test_sk_check_kfunc_ids)
>
> -static void *bpf_test_init(const union bpf_attr *kattr, u32 user_size,
> - u32 size, u32 headroom, u32 tailroom)
> +struct bpfalloc {
> + size_t len;
> + void *data;
> +};
> +
> +static int bpf_test_init(struct bpfalloc *alloc,
> + const union bpf_attr *kattr, u32 user_size,
> + u32 size, u32 headroom, u32 tailroom)
> {
> void __user *data_in = u64_to_user_ptr(kattr->test.data_in);
> - void *data;
>
> if (size < ETH_HLEN || size > PAGE_SIZE - headroom - tailroom)
> - return ERR_PTR(-EINVAL);
> + return -EINVAL;
>
> if (user_size > size)
> - return ERR_PTR(-EMSGSIZE);
> + return -EMSGSIZE;
>
> - data = kzalloc(size + headroom + tailroom, GFP_USER);
> - if (!data)
> - return ERR_PTR(-ENOMEM);
> + alloc->len = kmalloc_size_roundup(size + headroom + tailroom);
> + alloc->data = kzalloc(alloc->len, GFP_USER);

Don't you need to do this generalically in many places in the kernel?