Re: [PATCH v6 bpf-next 05/10] libbpf: BTF validation can use kind layout for unknown kinds

bot+bpf-ci
2025-12-10T20:55:53Z

[-- Attachment #1: Type: text/plain, Size: 2081 bytes --]

> diff --git a/tools/lib/bpf/btf.c b/tools/lib/bpf/btf.c
> index 2133e976cb9c..19e37a543e9a 100644
> --- a/tools/lib/bpf/btf.c
> +++ b/tools/lib/bpf/btf.c
> @@ -691,8 +691,12 @@ static int btf_validate_type(const struct btf *btf, const struct btf_type *t, __
> break;
> }
> default:
> - pr_warn("btf: type [%u]: unrecognized kind %u\n", id, kind);
> - return -EINVAL;
> + /* Kind may be represented in kind layout information. */
> + if (btf_type_size_unknown(btf, t) < 0) {
> + pr_warn("btf: type [%u]: unrecognized kind %u\n", id, kind);
> + return -EINVAL;
> + }
> + break;
> }
> return 0;
> }

The btf_type_size_unknown() function is called to validate unknown kinds
by checking the kind_layout array. Can the bounds check in
btf_type_size_unknown() read past the end of the kind_layout array?

In btf_type_size_unknown():

if (btf->kind_layout)
k = &((struct btf_kind_layout *)btf->kind_layout)[kind];

if (!k || (void *)k > ((void *)btf->kind_layout + btf->hdr->kind_layout_len)) {
pr_debug("Unsupported BTF_KIND: %u\n", btf_kind(t));
return -EINVAL;
}

size += k->info_sz;
size += vlen * k->elem_sz;

The check uses '>' to test if k exceeds the array bounds. If kind equals
the number of elements in the array (kind == kind_layout_len /
sizeof(struct btf_kind_layout)), then k points exactly at the array
boundary. The check evaluates k > end as false (since k == end), so the
validation passes and the code proceeds to dereference k, reading
out-of-bounds memory.

For comparison, btf__type_by_id() uses '>=' for its bounds check:

if (type_id >= btf->start_id + btf->nr_types)
return errno = EINVAL, NULL;

Should the bounds check in btf_type_size_unknown() use '>=' instead of
'>' to prevent reading one element past the end of the kind_layout array?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/20112692486