Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

bpf: correctly handle malformed BPF_CORE_TYPE_ID_LOCAL relos

In case of malformed relocation record of kind BPF_CORE_TYPE_ID_LOCAL
referencing a non-existing BTF type, function bpf_core_calc_relo_insn
would cause a null pointer deference.

Fix this by adding a proper check upper in call stack, as malformed
relocation records could be passed from user space.

Simplest reproducer is a program:

r0 = 0
exit

With a single relocation record:

.insn_off = 0, /* patch first instruction */
.type_id = 100500, /* this type id does not exist */
.access_str_off = 6, /* offset of string "0" */
.kind = BPF_CORE_TYPE_ID_LOCAL,

See the link for original reproducer or next commit for a test case.

Fixes: 74753e1462e7 ("libbpf: Replace btf__type_by_id() with btf_type_by_id().")
Reported-by: Liu RuiTong <cnitlrt@gmail.com>
Closes: https://lore.kernel.org/bpf/CAK55_s6do7C+DVwbwY_7nKfUz0YLDoiA1v6X3Y9+p0sWzipFSA@mail.gmail.com/
Acked-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Eduard Zingerman <eddyz87@gmail.com>
Link: https://lore.kernel.org/r/20240822080124.2995724-2-eddyz87@gmail.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Eduard Zingerman and committed by
Alexei Starovoitov
3d2786d6 b6ab5090

+8
+8
kernel/bpf/btf.c
··· 8910 8910 struct bpf_core_cand_list cands = {}; 8911 8911 struct bpf_core_relo_res targ_res; 8912 8912 struct bpf_core_spec *specs; 8913 + const struct btf_type *type; 8913 8914 int err; 8914 8915 8915 8916 /* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5" ··· 8919 8918 specs = kcalloc(3, sizeof(*specs), GFP_KERNEL); 8920 8919 if (!specs) 8921 8920 return -ENOMEM; 8921 + 8922 + type = btf_type_by_id(ctx->btf, relo->type_id); 8923 + if (!type) { 8924 + bpf_log(ctx->log, "relo #%u: bad type id %u\n", 8925 + relo_idx, relo->type_id); 8926 + return -EINVAL; 8927 + } 8922 8928 8923 8929 if (need_cands) { 8924 8930 struct bpf_cand_cache *cc;