Subject: Re: [PATCH v2] bpf: Add length check for SK_DIAG_BPF_STORAGE_REQ_MAP_FD parsing

From: Leon Romanovsky <[email-masked]>
Date: Tue, 25 Jul 2023 07:44:09 +0300

On Tue, Jul 25, 2023 at 10:33:30AM +0800, Lin Ma wrote:
> The nla_for_each_nested parsing in function bpf_sk_storage_diag_alloc
> does not check the length of the nested attribute. This can lead to an
> out-of-attribute read and allow a malformed nlattr (e.g., length 0) to
> be viewed as a 4 byte integer.
> 
> This patch adds an additional check when the nlattr is getting counted.
> This makes sure the latter nla_get_u32 can access the attributes with
> the correct length.
> 
> Fixes: 1ed4d92458a9 ("bpf: INET_DIAG support in bpf_sk_storage")
> Suggested-by: Jakub Kicinski <[email-masked]>
> Signed-off-by: Lin Ma <[email-masked]>
> ---
> V1 -> V2: moves the check to the counting loop as Jakub suggested,
>           alters the commit message accordingly.
> 
>  net/core/bpf_sk_storage.c | 5 ++++-
>  1 file changed, 4 insertions(+), 1 deletion(-)
> 
> diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c
> index d4172534dfa8..cca7594be92e 100644
> --- a/net/core/bpf_sk_storage.c
> +++ b/net/core/bpf_sk_storage.c
> @@ -496,8 +496,11 @@ bpf_sk_storage_diag_alloc(const struct nlattr *nla_stgs)
>  		return ERR_PTR(-EPERM);
>  
>  	nla_for_each_nested(nla, nla_stgs, rem) {
> -		if (nla_type(nla) == SK_DIAG_BPF_STORAGE_REQ_MAP_FD)
> +		if (nla_type(nla) == SK_DIAG_BPF_STORAGE_REQ_MAP_FD) {
> +			if (nla_len(nla) != sizeof(u32))

Jakub, it seems like Lin adds this check to all nla_for_each_nested() loops.
IMHO, the better change will be to change nla_for_each_nested() skip empty/not valid NLAs.

Thanks

> +				return ERR_PTR(-EINVAL);
>  			nr_maps++;
> +		}
>  	}
>  
>  	diag = kzalloc(struct_size(diag, maps, nr_maps), GFP_KERNEL);
> -- 
> 2.17.1
> 
>