libbpf: Fix possible use-after-free for externs
authorAdin Scannell <amscanne@meta.com>
Wed, 25 Jun 2025 05:02:15 +0000 (22:02 -0700)
committerAndrii Nakryiko <andrii@kernel.org>
Wed, 25 Jun 2025 19:28:58 +0000 (12:28 -0700)
commitfa6f092cc0a02d0fcee37e9e8172eda372a03d33
treefac5f1d01c3d86466620b8579f8079873750ca21
parent190113989ae01da7f5925877815a3ac75856d9ed
libbpf: Fix possible use-after-free for externs

The `name` field in `obj->externs` points into the BTF data at initial
open time. However, some functions may invalidate this after opening and
before loading (e.g. `bpf_map__set_value_size`), which results in
pointers into freed memory and undefined behavior.

The simplest solution is to simply `strdup` these strings, similar to
the `essent_name`, and free them at the same time.

In order to test this path, the `global_map_resize` BPF selftest is
modified slightly to ensure the presence of an extern, which causes this
test to fail prior to the fix. Given there isn't an obvious API or error
to test against, I opted to add this to the existing test as an aspect
of the resizing feature rather than duplicate the test.

Fixes: 9d0a23313b1a ("libbpf: Add capability for resizing datasec maps")
Signed-off-by: Adin Scannell <amscanne@meta.com>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Link: https://lore.kernel.org/bpf/20250625050215.2777374-1-amscanne@meta.com
tools/lib/bpf/libbpf.c
tools/testing/selftests/bpf/progs/test_global_map_resize.c