bpf: Fixes for hooks, tail calls, CAP_BPF, JITs and sockmap
Subsystems (20)
cover bpf: Fixes for hooks, tail calls, CAP_BPF, JITs and sockmap
From: Alexei Starovoitov <[email protected]>
These patches fix bugs in BPF:
patches area ------- ---------------------------------------------------------------- 01-04 what the verifier trusts: pointers, attach types, ranges, ids 05-08 extensions and tail calls: they run in the hook of another prog 09 struct_ops: the struct of a prog 10 bpffs: delegate options 11-12 NULL in tracepoints and helpers 13-15 bpf_throw(): tracers, KASAN, symbols, line info 16 XDP redirect in async callbacks 17-18 checks at attach and load: cgroup links, signed programs 19-20 bpf_lock, dumps of the stack 21-22 arena: the length of mmap(), TLB 23-24 prints of BTF enums, the result of bpf_res_spin_lock() 25-33 kernel addresses and tasks: CAP_BPF is not enough 34-37 x86 and arm64 JIT 38-43 skb, XDP, sk_msg and sockaddr helpers 44-45 sockmap 46 libbpf 47 struct_ops: the type of r0 at exit
Some fixes refuse what was allowed:
patch refused now
----- ------------------------------------------------------------------
01 pointers from a flexible array as arguments of helpers and kfuncs
05 freplace of tp_btf, fmod_ret, LSM and struct_ops progs
07 one prog array for two LSM hooks, two types of struct_ops, or
tracepoints with other NULL args
11 tp_btf/neigh_create: the neighbour as a trusted argument
13 tracers of bpf_throw()
17 BPF_LINK_UPDATE of a cgroup link to another attach type
18 metadata maps of signed progs that can be mapped writable
21 mmap() of a part of an arena
35 misaligned atomics in arenas on x86: skipped at run time patch needs CAP_PERFMON now
----- ------------------------------------------------------------------
25 all but the base helpers in syscall progs
26 kfuncs of arena and task work, bpf_send_signal_task(),
bpf_wakeup_sources_get_head()
27 streams
28 variables of the kernel
29 dumps of xlated insns
31 open() of the bpffs file of a map with special fields but locks
32 values of insn_array as memory
33 inet_diag dump of all sk_storage mapsAlexei Starovoitov (47):
bpf: Do not trust pointers in flexible arrays
bpf: Look at the type of a program next to expected_attach_type
bpf: Do not take bpf_get_retval() of struct bpf_tcp_ops for an errno
bpf: Do not allow bpf_d_path() by an id of another BTF
bpf: Check that an extension fits the hook of its target
bpf: Take the attach type of the target for tail calls of an extension
bpf: Compare what a hook tells next to its prototype at tail calls
bpf: Reserve cookie and ip in the trampoline for tail calls
bpf: Check that a program and a struct_ops map are for the same struct
bpf: Keep the names in front of a number in delegate options
bpf: Do not trust the neighbour of tp_btf/neigh_create
bpf: Check for NULL in helpers that take a kernel pointer
bpf: Leave nothing behind in the frame of bpf_throw()
bpf: Add the symbol of a prog before its id
bpf: Do not fill jited line info for a hidden subprog
bpf: Fix NULL dereference in XDP redirect from async callbacks
bpf: Check the attach type when a cgroup link gets another program
bpf: Refuse metadata maps of signed programs that can be mapped
writable
bpf: Take bpf_lock with interrupts disabled
bpf: Bound the time that dumps of the stack take
bpf: Refuse mmap() of a part of an arena
bpf: Flush TLB when a page of arena replaces the scratch page
bpf: Fix reads past an enum in prints of BTF data
bpf: Give the error of bpf_res_spin_lock() a 32-bit range
bpf: Give syscall programs without CAP_PERFMON the base helpers only
bpf: Require CAP_PERFMON for kfuncs that leak pointers or touch tasks
bpf: Require CAP_PERFMON to read streams
bpf: Limit reads of variables of the kernel
bpf: Require CAP_PERFMON for dumps of xlated insns
bpf: Zero bpf_list_head in copies of map values
bpf: Require CAP_PERFMON to read pinned maps with special fields
bpf: Require CAP_PERFMON to pass values of insn_array as memory
bpf: Require CAP_PERFMON for the dump of all storages of sockets bpf, x86: Do not use the paranoid ITS thunk
bpf, x86: Enforce alignment of atomics in arenas
bpf, x86: Fix the range of BPF code that has a frame pointer bpf, arm64: Restore the shadow call stack pointer after an exception
bpf: Clear the data that bpf_msg_push_data() adds
bpf: Fail loads from a network header that was not set
bpf: Fix slices behind the end of an XDP packet
bpf: Clear family and port of a short address for cgroup sockaddr
hooks
bpf: Take a neighbour of the L3 master in bpf_redirect_neigh()
bpf: Keep the MAC header in bpf_skb_change_tail()
bpf, sockmap: Keep the parser and sk_data_ready in sync bpf, sockmap: Hold the psock of the work in sk_psock_backlog()
libbpf: Fix struct_ops members 59-61 and optional struct_ops maps
bpf: Check the type of R0 at the exit of a struct_ops program
Documentation/bpf/kfuncs.rst | 3 +- Documentation/bpf/signing.rst | 3 +- arch/arm64/net/bpf_jit_comp.c | 7 ++ arch/x86/net/bpf_jit_comp.c | 53 ++++++++--- include/linux/bpf.h | 31 +++++-- include/linux/btf.h | 1 + include/linux/filter.h | 15 +++- include/uapi/linux/bpf.h | 3 +- kernel/bpf/arena.c | 40 +++++---- kernel/bpf/bpf_struct_ops.c | 20 +++-- kernel/bpf/btf.c | 49 +++++++++-- kernel/bpf/cgroup.c | 29 +++++- kernel/bpf/core.c | 50 ++++++++--- kernel/bpf/fixups.c | 7 ++ kernel/bpf/helpers.c | 34 ++++--- kernel/bpf/inode.c | 10 ++- kernel/bpf/stackmap.c | 2 +- kernel/bpf/stream.c | 25 +++++- kernel/bpf/syscall.c | 35 ++++++-- kernel/bpf/verifier.c | 88 +++++++++++++++---- kernel/sched/ext/internal.h | 5 +- kernel/trace/bpf_trace.c | 8 +- net/bpf/bpf_dummy_struct_ops.c | 2 +- net/core/bpf_sk_storage.c | 4 + net/core/filter.c | 40 ++++++--- net/core/skmsg.c | 14 ++- net/core/sock_map.c | 3 +- tools/include/uapi/linux/bpf.h | 3 +- tools/lib/bpf/libbpf.c | 19 ++-- .../selftests/bpf/test_kmods/bpf_testmod.c | 6 +- 30 files changed, 469 insertions(+), 140 deletions(-)
base-commit: 81c6c8c608b6075846d3bd5b6f57958300a56eda
Signature · 1 line
2.55.0
PATCH 1/47 bpf: Do not trust pointers in flexible arrays
From: Alexei Starovoitov <[email protected]>
The verifier does not know how many elements a flexible array of a kernel object has.
Mark pointers that are loaded from one as untrusted. Ignore the __rcu tag of such pointers.
--- kernel/bpf/btf.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/bpf/btf.c +4 -0
@@ -8127,6 +8127,10 @@ int btf_struct_access(struct bpf_verifier_log *log,*/ *next_btf_id = id; *flag = tmp_flag; +/* nothing tells where a flexible array ends */ + t =btf_type_skip_modifiers (btf, reg->btf_id,NULL ); +if (min_off + size > t->size) + *flag = (tmp_flag & ~MEM_RCU ) |PTR_UNTRUSTED ; ret =PTR_TO_BTF_ID ; goto check_variable_offset;case WALK_PTR_UNTRUSTED :
Signature · 1 line
2.55.0
PATCH 2/47 bpf: Look at the type of a program next to expected_attach_type
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
expected_attach_type of a struct_ops program is the index of the member. sock_ops, cgroup_device and cgroup_sysctl programs load with almost any value. The kernel compares it with attach types of other programs:
- Members 25, 26, 27, 43 and 58 can read ctx[nr_args], as fexit does. The slot has stale stack.
- The trampoline of members 58 and 61 clears that slot, as for fsession. It is the last argument when the member returns void.
- Pointer arguments of member 23 get the rules of raw tracepoints.
- Members 59, 60 and 61 cannot be loaded.
- The release of a cgroup looks for the LSM shim of a program that says BPF_LSM_CGROUP and has no attach_btf.
Look at the type of the program too.
--- include/linux/bpf.h | 3 +++ kernel/bpf/btf.c | 5 +++-- kernel/bpf/cgroup.c | 4 ++-- kernel/bpf/syscall.c | 3 ++- 4 files changed, 10 insertions(+), 5 deletions(-)
include/linux/bpf.h +3 -0
@@ -2517,6 +2517,9 @@ static inline int bpf_fsession_cnt(struct bpf_tramp_nodes *nodes)struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY ];int cnt =0 ; +if (is_struct_ops_tramp (&fentries)) +return 0 ; +for (int i =0 ; i < nodes[BPF_TRAMP_FENTRY ].nr_nodes; i++) {if (fentries.nodes[i]->link->prog->expected_attach_type ==BPF_TRACE_FSESSION ) cnt++;
kernel/bpf/btf.c +3 -2
@@ -7485,7 +7485,8 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type, nr_args--; } -if (arg > nr_args) { +/* expected_attach_type of struct_ops is the index of the member */ +if (arg > nr_args || (arg == nr_args && prog->type ==BPF_PROG_TYPE_STRUCT_OPS )) {bpf_log (log,"func '%s' doesn't have %d-th argument\n" , tname, arg +1 );return false;
@@ -7622,7 +7623,7 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,if (btf_param_match_suffix (btf, &args[arg],"__nullable" )) info->reg_type |=PTR_MAYBE_NULL ; -if (prog->expected_attach_type ==BPF_TRACE_RAW_TP ) { +if (prog->aux->attach_btf_trace) {struct btf *btf = prog->aux->attach_btf;const struct btf_type *t;const char *tname;
kernel/bpf/cgroup.c +2 -2
@@ -399,7 +399,7 @@ static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link)return ; } -if (link->link.prog->expected_attach_type ==BPF_LSM_CGROUP ) +if (link->link.prog->type ==BPF_PROG_TYPE_LSM )bpf_trampoline_unlink_cgroup_shim (link->link.prog);cgroup_put (link->cgroup); link->cgroup =NULL ;
@@ -509,7 +509,7 @@ static void cgroup_bpf_release(struct work_struct *work)hlist_for_each_entry_safe (pl, pltmp, progs, node) {hlist_del (&pl->node);if (pl->prog) { -if (pl->prog->expected_attach_type ==BPF_LSM_CGROUP ) +if (pl->prog->type ==BPF_PROG_TYPE_LSM )bpf_trampoline_unlink_cgroup_shim (pl->prog);bpf_prog_put (pl->prog); }
kernel/bpf/syscall.c +2 -1
@@ -3025,7 +3025,8 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_atif (is_perfmon_prog_type (type) && !bpf_token_capable (token,CAP_PERFMON )) goto put_token; - multi_func =is_tracing_multi (attr->expected_attach_type); + multi_func = type !=BPF_PROG_TYPE_STRUCT_OPS && +is_tracing_multi (attr->expected_attach_type);/* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog * or btf, we need to check which one it is
Signature · 1 line
2.55.0
PATCH 3/47 bpf: Do not take bpf_get_retval() of struct bpf_tcp_ops for an errno
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The verifier gives the result of bpf_get_retval() the range [-4095, 0]. In timeout_init and rwnd_init of struct bpf_tcp_ops it is what the previous program returned, any int.
Do not refine the range for struct_ops programs.
--- kernel/bpf/verifier.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/bpf/verifier.c +4 -0
@@ -12305,6 +12305,10 @@ static int do_refine_retval_range(struct bpf_verifier_env *env, env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT)break ; +/* It is what the previous struct bpf_tcp_ops returned, any int */ +if (prog_type ==BPF_PROG_TYPE_STRUCT_OPS ) +break ; +if (prog_type ==BPF_PROG_TYPE_LSM && env->prog->expected_attach_type ==BPF_LSM_CGROUP ) {if (!env->prog->aux->attach_func_proto->type)
Signature · 1 line
2.55.0
PATCH 4/47 bpf: Do not allow bpf_d_path() by an id of another BTF
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
For a program that is attached to a program attach_btf_id is an id in the BTF of the target. bpf_d_path_allowed() looks for it in a list of kernel functions, it can match by chance. Do not look at the list when there is a target program.
--- kernel/trace/bpf_trace.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/trace/bpf_trace.c +4 -0
@@ -980,6 +980,10 @@ BTF_SET_END(btf_allowlist_d_path_fentry)static bool bpf_d_path_allowed (const struct bpf_prog *prog) { +/* attach_btf_id is a function of the target program */ +if (prog->aux->dst_prog) +return false; +if (prog->type ==BPF_PROG_TYPE_TRACING && prog->expected_attach_type ==BPF_TRACE_ITER )return true;
Signature · 1 line
2.55.0
PATCH 5/47 bpf: Check that an extension fits the hook of its target
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
An extension runs in the hook of its target, and the checks for the hook do not see it.
Tracing, LSM and struct_ops programs are checked against the BTF of their hook. An extension takes the type of its target, but it has no attach_btf and no st_ops, and attach_btf_id and the prototype are those of the function that it replaces:
- tp_btf: it can read more arguments than the tracepoint has.
- LSM: the range of bpf_get_retval() and bpf_set_retval(), and the helpers that only some hooks have, are looked up by a wrong id.
- tp_btf and struct_ops: the load can oops.
fentry, fexit, fsession and iterators cannot be extended already. Refuse the rest. freplace of global functions of tp_btf, fmod_ret and LSM programs goes away. Targets of other types load with any expected_attach_type. Do not take their extension for tp_btf or for an iterator.
Some properties of a program are looked at when it is attached or run. Nobody looks at those of an extension:
- bpf_get_local_storage() returns the storage of the attached program, the extension is verified against its own map.
- bpf_override_return() needs a function that allows error injection.
- skb->cb is saved, cleared and restored only for programs that access it.
Ask for the storage map of the target, at load and at attach. Refuse the attach when the target does not call bpf_override_return() itself, or does not access skb->cb. A tail call counts as an access to skb->cb.
--- kernel/bpf/syscall.c | 18 ++++++++++++++++++ kernel/bpf/verifier.c | 38 +++++++++++++++++++++++++------------- 2 files changed, 43 insertions(+), 13 deletions(-)
kernel/bpf/syscall.c +18 -0
@@ -3847,6 +3847,24 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog, err = -EINVAL ; goto out_unlock; } +/* Where the return can be overridden is checked for the target only */ +if (prog->type ==BPF_PROG_TYPE_EXT && + prog->kprobe_override && !tgt_prog->kprobe_override) { + err = -EINVAL ; + goto out_unlock; + } +/* bpf_prog_run_save_cb() and bpf_prog_run_clear_cb() look at the target only */ +if (prog->type ==BPF_PROG_TYPE_EXT && + (tgt_prog->type ==BPF_PROG_TYPE_SOCKET_FILTER || + tgt_prog->type ==BPF_PROG_TYPE_CGROUP_SKB || + tgt_prog->type ==BPF_PROG_TYPE_LWT_IN || + tgt_prog->type ==BPF_PROG_TYPE_LWT_OUT || + tgt_prog->type ==BPF_PROG_TYPE_LWT_XMIT || + tgt_prog->type ==BPF_PROG_TYPE_LWT_SEG6LOCAL ) && + prog->cb_access && !tgt_prog->cb_access) { + err = -EINVAL ; + goto out_unlock; + }/* * The size of these contexts depends on what the program is attached * to, or run with. That is compared with max_ctx_offset of the program,
kernel/bpf/verifier.c +25 -13
@@ -22675,6 +22675,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, }if (tgt_prog) {struct bpf_prog_aux *aux = tgt_prog->aux; +enum bpf_cgroup_storage_type stype;bool tgt_changes_pkt_data;bool tgt_might_sleep;bool tgt_can_unwind;
@@ -22729,6 +22730,16 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, "Extension programs should be JITed\n");return -EINVAL ; } +/* bpf_get_local_storage() returns the storage of the target */ +for_each_cgroup_storage_type (stype) { +struct bpf_map *storage = prog->aux->cgroup_storage[stype]; + +if (storage && storage != aux->cgroup_storage[stype]) { +bpf_log (log, +"Extension program has another cgroup storage than original\n" ); +return -EINVAL ; + } + }/* * How much of the buffer of the tracepoint is used * is checked for the program that is attached to it.
@@ -22793,16 +22804,14 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,bpf_log (log,"Cannot recursively attach\n" );return -EINVAL ; } -if (tgt_prog->type ==BPF_PROG_TYPE_TRACING && - prog_extension && - (tgt_prog->expected_attach_type ==BPF_TRACE_FENTRY || - tgt_prog->expected_attach_type ==BPF_TRACE_FEXIT || - tgt_prog->expected_attach_type ==BPF_TRACE_FENTRY_MULTI || - tgt_prog->expected_attach_type ==BPF_TRACE_FEXIT_MULTI || - tgt_prog->expected_attach_type ==BPF_TRACE_FSESSION || - tgt_prog->expected_attach_type ==BPF_TRACE_FSESSION_MULTI )) { -/* Program extensions can extend all program types -* except fentry/fexit. The reason is the following. +if (prog_extension && + (tgt_prog->type ==BPF_PROG_TYPE_TRACING || + tgt_prog->type ==BPF_PROG_TYPE_LSM || + tgt_prog->type ==BPF_PROG_TYPE_STRUCT_OPS )) { +/* +* These types are checked against the BTF of their hook, +* and an extension has the BTF of its target instead. +* There is one more reason for fentry/fexit. * The fentry/fexit programs are used for performance * analysis, stats and can be attached to any program * type. When extension program is replacing XDP function
@@ -22815,7 +22824,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,* beyond reasonable stack size. Hence extending fentry * is not allowed. */ -bpf_log (log,"Cannot extend fentry/fexit/fsession\n" ); +bpf_log (log,"Cannot extend tracing, LSM and struct_ops programs\n" );return -EINVAL ; } }else {
@@ -23163,10 +23172,13 @@ static int check_attach_btf_id(struct bpf_verifier_env *env) prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; } -if (prog->expected_attach_type ==BPF_TRACE_RAW_TP ) { +/* An extension has expected_attach_type of its target, it can be any value */ +if (prog->type !=BPF_PROG_TYPE_EXT && + prog->expected_attach_type ==BPF_TRACE_RAW_TP ) { prog->aux->attach_btf_trace = true;return 0 ; - }else if (prog->expected_attach_type ==BPF_TRACE_ITER ) { + }else if (prog->type !=BPF_PROG_TYPE_EXT && + prog->expected_attach_type ==BPF_TRACE_ITER ) {return bpf_iter_prog_supported (prog); }
Signature · 1 line
2.55.0
Re: [PATCH bpf 05/47] bpf: Check that an extension fits the hook of its target
Quoted 151 lines · Alexei Starovoitov
From: Alexei Starovoitov <[email protected]>
An extension runs in the hook of its target, and the checks for the hook do not see it.
Tracing, LSM and
struct_opsprograms are checked against the BTF of their hook. An extension takes the type of its target, but it has noattach_btfand nost_ops, andattach_btf_idand the prototype are those of the function that it replaces:-
tp_btf: it can read more arguments than the tracepoint has.
- LSM: the range ofbpf_get_retval()andbpf_set_retval(), and the helpers that only some hooks have, are looked up by a wrong id.
-tp_btfandstruct_ops: the load can oops.fentry, fexit, fsession and iterators cannot be extended already. Refuse the rest. freplace of global functions of
tp_btf,fmod_retand LSM programs goes away. Targets of other types load with anyexpected_attach_type. Do not take their extension fortp_btfor for an iterator.Some properties of a program are looked at when it is attached or run. Nobody looks at those of an extension:
-
bpf_get_local_storage()returns the storage of the attached program, the extension is verified against its own map.
-bpf_override_return()needs a function that allows error injection.
-skb->cbis saved, cleared and restored only for programs that access it.Ask for the storage map of the target, at load and at attach. Refuse the attach when the target does not call
bpf_override_return()itself, or does not accessskb->cb. A tail call counts as an access toskb->cb.Fixes be8704ff07d2 ("bpf: Introduce dynamic program extensions")Signed-off-by Alexei Starovoitov <[email protected]>--- kernel/bpf/syscall.c | 18 ++++++++++++++++++ kernel/bpf/verifier.c | 38 +++++++++++++++++++++++++------------- 2 files changed, 43 insertions(+), 13 deletions(-)kernel/bpf/syscall.c +18
-0@@ -3847,6 +3847,24 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog, err = -EINVAL ; goto out_unlock; } +/* Where the return can be overridden is checked for the target only */ +if (prog->type ==BPF_PROG_TYPE_EXT && + prog->kprobe_override && !tgt_prog->kprobe_override) { + err = -EINVAL ; + goto out_unlock; + } +/* bpf_prog_run_save_cb() and bpf_prog_run_clear_cb() look at the target only */ +if (prog->type ==BPF_PROG_TYPE_EXT && + (tgt_prog->type ==BPF_PROG_TYPE_SOCKET_FILTER || + tgt_prog->type ==BPF_PROG_TYPE_CGROUP_SKB || + tgt_prog->type ==BPF_PROG_TYPE_LWT_IN || + tgt_prog->type ==BPF_PROG_TYPE_LWT_OUT || + tgt_prog->type ==BPF_PROG_TYPE_LWT_XMIT || + tgt_prog->type ==BPF_PROG_TYPE_LWT_SEG6LOCAL ) && + prog->cb_access && !tgt_prog->cb_access) { + err = -EINVAL ; + goto out_unlock; + }/* * The size of these contexts depends on what the program is attached * to, or run with. That is compared with max_ctx_offset of the program, kernel/bpf/verifier.c +25
-14@@ -22675,6 +22675,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, }if (tgt_prog) {struct bpf_prog_aux *aux = tgt_prog->aux; +enum bpf_cgroup_storage_type stype;bool tgt_changes_pkt_data;bool tgt_might_sleep;bool tgt_can_unwind;@@ -22729,6 +22730,16 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, "Extension programs should be JITed\n");return -EINVAL ; } +/* bpf_get_local_storage() returns the storage of the target */ +for_each_cgroup_storage_type (stype) { +struct bpf_map *storage = prog->aux->cgroup_storage[stype]; + +if (storage && storage != aux->cgroup_storage[stype]) { +bpf_log (log, +"Extension program has another cgroup storage than original\n" ); +return -EINVAL ; + } + }/* * How much of the buffer of the tracepoint is used * is checked for the program that is attached to it. @@ -22793,16 +22804,14 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,bpf_log (log,"Cannot recursively attach\n" );return -EINVAL ; } -if (tgt_prog->type ==BPF_PROG_TYPE_TRACING && - prog_extension && - (tgt_prog->expected_attach_type ==BPF_TRACE_FENTRY || - tgt_prog->expected_attach_type ==BPF_TRACE_FEXIT || - tgt_prog->expected_attach_type ==BPF_TRACE_FENTRY_MULTI || - tgt_prog->expected_attach_type ==BPF_TRACE_FEXIT_MULTI || - tgt_prog->expected_attach_type ==BPF_TRACE_FSESSION || - tgt_prog->expected_attach_type ==BPF_TRACE_FSESSION_MULTI )) { -/* Program extensions can extend all program types -* except fentry/fexit. The reason is the following. +if (prog_extension && + (tgt_prog->type ==BPF_PROG_TYPE_TRACING || + tgt_prog->type ==BPF_PROG_TYPE_LSM || + tgt_prog->type ==BPF_PROG_TYPE_STRUCT_OPS )) { +/* +* These types are checked against the BTF of their hook, +* and an extension has the BTF of its target instead. +* There is one more reason for fentry/fexit. * The fentry/fexit programs are used for performance * analysis, stats and can be attached to any program * type. When extension program is replacing XDP function @@ -22815,7 +22824,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,* beyond reasonable stack size. Hence extending fentry * is not allowed. */ -bpf_log (log,"Cannot extend fentry/fexit/fsession\n" ); +bpf_log (log,"Cannot extend tracing, LSM and struct_ops programs\n" );return -EINVAL ; } }else {@@ -23163,10 +23172,13 @@ static int check_attach_btf_id(struct bpf_verifier_env *env) prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; } -if (prog->expected_attach_type ==BPF_TRACE_RAW_TP ) { +/* An extension has expected_attach_type of its target, it can be any value */ +if (prog->type !=BPF_PROG_TYPE_EXT && + prog->expected_attach_type ==BPF_TRACE_RAW_TP ) { prog->aux->attach_btf_trace = true;return 0 ; - }else if (prog->expected_attach_type ==BPF_TRACE_ITER ) { + }else if (prog->type !=BPF_PROG_TYPE_EXT && + prog->expected_attach_type ==BPF_TRACE_ITER ) {return bpf_iter_prog_supported (prog); } --
Quoted 2 lines
2.55.0
This came right in time to reply to bot's complain in my series
PATCH 6/47 bpf: Take the attach type of the target for tail calls of an extension
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A prog array compares expected_attach_type. It is 0 for an extension at the time of the check, so the extension can call programs that were checked for another attach type, and cannot share an array with its target. Take the attach type of the target.
--- kernel/bpf/core.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/core.c +6 -2
@@ -2518,6 +2518,7 @@ static unsigned int __bpf_prog_ret0_warn(const void *ctx,static bool __bpf_prog_map_compatible (struct bpf_map *map,const struct bpf_prog *fp) { +enum bpf_attach_type attach_type = fp->expected_attach_type;enum bpf_prog_type prog_type =resolve_prog_type (fp);struct bpf_prog_aux *aux = fp->aux;enum bpf_cgroup_storage_type i;
@@ -2527,6 +2528,9 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map,if (fp->kprobe_override)return ret; +if (fp->type ==BPF_PROG_TYPE_EXT ) + attach_type = aux->saved_dst_attach_type; +spin_lock (&map->owner_lock);/* There's no owner yet where we could check for compatibility. */ if (!map->owner) {
@@ -2537,7 +2541,7 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->jited = fp->jited; map->owner->xdp_has_frags = aux->xdp_has_frags; map->owner->sleepable = fp->sleepable; - map->owner->expected_attach_type = fp->expected_attach_type; + map->owner->expected_attach_type = attach_type; map->owner->attach_func_proto = aux->attach_func_proto;for_each_cgroup_storage_type (i) { map->owner->storage_cookie[i] =
@@ -2552,7 +2556,7 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->sleepable == fp->sleepable;if (ret && map->map_type ==BPF_MAP_TYPE_PROG_ARRAY && - map->owner->expected_attach_type != fp->expected_attach_type) + map->owner->expected_attach_type != attach_type) ret = false;for_each_cgroup_storage_type (i) {if (!ret)
Signature · 1 line
2.55.0
PATCH 7/47 bpf: Compare what a hook tells next to its prototype at tail calls
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Hooks of one prototype differ in what the verifier assumes:
- struct_ops: two structs can have the same index and prototype of a member. Nullable and referenced arguments, filters of kfuncs and the prologue belong to the struct.
- tp_btf: which arguments can be NULL.
- LSM and iterators: what is trusted, helpers, kfuncs, return values.
- A tracer of a program: the context of the target.
Compare that. Tracepoints that agree, and tracers of kernel functions, share a prog array as before. Two LSM hooks cannot.
--- include/linux/bpf.h | 3 +++ include/linux/btf.h | 1 + kernel/bpf/btf.c | 10 ++++++++++ kernel/bpf/core.c | 20 ++++++++++++++++++-- kernel/bpf/syscall.c | 1 + 5 files changed, 33 insertions(+), 2 deletions(-)
include/linux/bpf.h +3 -0
@@ -300,7 +300,9 @@ struct bpf_map_owner {bool sleepable;u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE ];const struct btf_type *attach_func_proto; +const struct bpf_struct_ops *st_ops;enum bpf_attach_type expected_attach_type; +u64 hook_key; };struct bpf_map {
@@ -1889,6 +1891,7 @@ struct bpf_prog_aux {struct mutex dst_mutex;/* protects dst_* pointers below, *after* prog becomes visible */ struct bpf_prog *dst_prog;struct bpf_trampoline *dst_trampoline; +enum bpf_prog_type saved_dst_ctx_type;enum bpf_prog_type saved_dst_prog_type;enum bpf_attach_type saved_dst_attach_type;bool verifier_zext;/* Zero extensions has been inserted by verifier. */
include/linux/btf.h +1 -0
@@ -159,6 +159,7 @@ struct btf_struct_metas {extern const struct file_operations btf_fops;const char *btf_get_name (const struct btf *btf); +u64 btf_raw_tp_null_mask (const struct bpf_prog *prog);void btf_get (struct btf *btf);void btf_put (struct btf *btf);const struct btf_header *btf_header (const struct btf *btf);
kernel/bpf/btf.c +10 -0
@@ -7449,6 +7449,16 @@ static const struct bpf_raw_tp_null_args raw_tp_null_args[] = { { "amdtp_packet", 0x100 }, }; +u64 btf_raw_tp_null_mask (const struct bpf_prog *prog) +{ +int i; + +for (i =0 ; i <ARRAY_SIZE (raw_tp_null_args); i++) +if (!strcmp (prog->aux->attach_func_name, raw_tp_null_args[i].func)) +return raw_tp_null_args[i].mask; +return btf_is_module (prog->aux->attach_btf) ?U64_MAX :0 ; +} +bool btf_ctx_access (int off,int size,enum bpf_access_type type,const struct bpf_prog *prog,struct bpf_insn_access_aux *info)
kernel/bpf/core.c +18 -2
@@ -2515,6 +2515,18 @@ static unsigned int __bpf_prog_ret0_warn(const void *ctx,return 0 ; } +/* What the verifier took from the hook, next to its prototype */ +static u64 bpf_prog_hook_key (const struct bpf_prog *fp) +{ +if (IS_ENABLED (CONFIG_BPF_SYSCALL ) && fp->aux->attach_btf_trace) +return btf_raw_tp_null_mask (fp); +if (fp->type ==BPF_PROG_TYPE_TRACING && fp->expected_attach_type !=BPF_TRACE_ITER ) +return fp->aux->saved_dst_ctx_type; +if (fp->type ==BPF_PROG_TYPE_TRACING || fp->type ==BPF_PROG_TYPE_LSM ) +return fp->aux->attach_btf_id; +return 0 ; +} +static bool __bpf_prog_map_compatible (struct bpf_map *map,const struct bpf_prog *fp) {
@@ -2522,8 +2534,8 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map,enum bpf_prog_type prog_type =resolve_prog_type (fp);struct bpf_prog_aux *aux = fp->aux;enum bpf_cgroup_storage_type i; +u64 cookie, hook_key =bpf_prog_hook_key (fp);bool ret = false; -u64 cookie;if (fp->kprobe_override)return ret;
@@ -2543,6 +2555,8 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, map->owner->sleepable = fp->sleepable; map->owner->expected_attach_type = attach_type; map->owner->attach_func_proto = aux->attach_func_proto; + map->owner->st_ops = aux->st_ops; + map->owner->hook_key = hook_key;for_each_cgroup_storage_type (i) { map->owner->storage_cookie[i] = aux->cgroup_storage[i] ?
@@ -2553,7 +2567,9 @@ static bool __bpf_prog_map_compatible(struct bpf_map *map, ret = map->owner->type == prog_type && map->owner->jited == fp->jited && map->owner->xdp_has_frags == aux->xdp_has_frags && - map->owner->sleepable == fp->sleepable; + map->owner->sleepable == fp->sleepable && + map->owner->st_ops == aux->st_ops && + map->owner->hook_key == hook_key;if (ret && map->map_type ==BPF_MAP_TYPE_PROG_ARRAY && map->owner->expected_attach_type != attach_type)
kernel/bpf/syscall.c +1 -0
@@ -3091,6 +3091,7 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at prog->aux->attach_btf_id = multi_func ? bpf_multi_func_btf_id[0 ] : attr->attach_btf_id; prog->aux->dst_prog = dst_prog;if (dst_prog) { + prog->aux->saved_dst_ctx_type =resolve_prog_type (dst_prog); prog->aux->saved_dst_prog_type = dst_prog->type; prog->aux->saved_dst_attach_type = dst_prog->expected_attach_type; }
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 07/47] bpf: Compare what a hook tells next to its prototype at tail calls
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] bpf: helper restrictions bypassed via bpf_prog_hook_key() on tail calls --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] bpf: helper restrictions bypassed via bpf_prog_hook_key() on tail calls
--
commit 641147c8dfcc1727cd4d5af22656fb851b62f335
Author: Alexei Starovoitov <[email protected]>
bpf: Compare what a hook tells next to its prototype at tail calls
This commit compares hook-specific properties alongside function prototypes when checking program compatibility for tail call maps.
Quoted 5 lines
kernel/bpf/core.c +0
-0
kernel/bpf/core.c static unsigned int __bpf_prog_ret0_warn(const void *ctx, · line 2524
Quoted 10 lines
kernel/bpf/core.c +7
-0@@ -2515,6 +2515,18 @@ static unsigned int __bpf_prog_ret0_warn(const void *ctx,return 0 ; } +/* What the verifier took from the hook, next to its prototype */ +static u64 bpf_prog_hook_key (const struct bpf_prog *fp) +{ +if (IS_ENABLED (CONFIG_BPF_SYSCALL ) && fp->aux->attach_btf_trace) +return btf_raw_tp_null_mask (fp); +if (fp->type ==BPF_PROG_TYPE_TRACING && fp->expected_attach_type !=BPF_TRACE_ITER ) +return fp->aux->saved_dst_ctx_type;
[Severity: High]
Can a kernel-function tracing program bypass per-function helper restrictions by tail-calling another tracing program that shares the same deduplicated attach_func_proto?
For kernel-function tracers, dst_prog is NULL, so saved_dst_ctx_type is 0 for all of them. The verifier, however, grants or denies helpers per target function in bpf_d_path_allowed() (by attach_btf_id) and bpf_sk_storage_tracing_allowed() (by attach_func_name):
kernel/trace/bpf_trace.c:bpf_d_path_allowed() {
...
if (btf_id_set_contains(&btf_allowlist_d_path,
prog->aux->attach_btf_id))
return true;
if (btf_id_set_contains(&btf_allowlist_d_path_fentry,
prog->aux->attach_btf_id))
return prog->expected_attach_type == BPF_TRACE_FENTRY;
...
}For example, filp_close() (in btf_allowlist_d_path) and filp_close_sync() (in btf_allowlist_d_path_fentry) have identical signatures and parameter names in fs/open.c, so they share the same BTF_KIND_FUNC_PROTO in vmlinux BTF. An fexit/filp_close_sync program can therefore tail-call an fexit/filp_close program and run bpf_d_path(&filp->f_path, ...) after fput_close_sync() has already freed filp and its dentry, causing a use-after-free. Likewise, fentry/bpf_sk_storage_free shares its prototype with fentry/sk_free and can tail-call it to invoke bpf_sk_storage_get() or bpf_sk_storage_delete() while sk->sk_bpf_storage is being freed.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
[email protected]
AI reviewRe: [PATCH bpf 07/47] bpf: Compare what a hook tells next to its prototype at tail calls
In reply to Alexei StarovoitovTL;DR: bpf_prog_hook_key() is 0 for fentry/fexit on kernel functions, so a prog using bpf_d_path() may share a prog array with one on a function sharing its prototype that disallows it, possibly…
Quoted 1 line
bpf: Compare what a hook tells next to its prototype at tail calls
TL;DR: bpf_prog_hook_key() is 0 for fentry/fexit on kernel functions, so a prog using bpf_d_path() may share a prog array with one on a function sharing its prototype that disallows it, possibly causing a use-after-free.
Quoted 3 lines
kernel/bpf/core.c +0
-0
[ ... ]
kernel/bpf/core.c static unsigned int __bpf_prog_ret0_warn(const void *ctx, · line 2524
Quoted 7 lines
kernel/bpf/core.c +7
-0+/* What the verifier took from the hook, next to its prototype */ +static u64 bpf_prog_hook_key (const struct bpf_prog *fp) +{ +if (IS_ENABLED (CONFIG_BPF_SYSCALL ) && fp->aux->attach_btf_trace) +return btf_raw_tp_null_mask (fp); +if (fp->type ==BPF_PROG_TYPE_TRACING && fp->expected_attach_type !=BPF_TRACE_ITER ) +return fp->aux->saved_dst_ctx_type;
For fentry/fexit on a kernel function, saved_dst_ctx_type is always 0, so two such programs are compatible whenever they share the same FUNC_PROTO.
The commit message says "tracers of kernel functions, share a prog array as before", but the verifier does assume something about the hook for these programs. bpf_d_path_allowed() depends on attach_btf_id and on expected_attach_type:
if (btf_id_set_contains(&btf_allowlist_d_path, prog->aux->attach_btf_id))
return true;
if (btf_id_set_contains(&btf_allowlist_d_path_fentry, prog->aux->attach_btf_id))
return prog->expected_attach_type == BPF_TRACE_FENTRY;filp_close() is allowed for every attach type, while filp_close_sync() is allowed for fentry only. Both have the prototype
int (struct file *filp, fl_owner_t id), so they share one FUNC_PROTO and the same attach_func_proto.
Consider program X attached with SEC("fexit/filp_close_sync"), where bpf_d_path() is refused, and which calls bpf_tail_call(). It becomes the owner of the prog array in bpf_check_tail_call() with TRACING, FEXIT, the shared proto and hook_key 0.
Program Y attached with SEC("fexit/filp_close") calls bpf_d_path(&f->f_path, ...), which is allowed for it. Inserting Y passes __bpf_prog_map_compatible(): same type, same expected_attach_type, same attach_func_proto, hook_key 0 == 0 and st_ops NULL == NULL.
Y can then run at the exit of filp_close_sync() and call d_path() on a path that may already be freed. vfs_getattr() (allowlisted) and vfs_getattr_nosec() (not allowlisted) also share one prototype.
Should the key for tracers of kernel functions include what bpf_d_path_allowed() decided, or should the statement in the commit message be narrowed?
kernel/bpf/core.c static unsigned int __bpf_prog_ret0_warn(const void *ctx, · line 2528
Quoted 4 lines
kernel/bpf/core.c +4
-0+if (fp->type ==BPF_PROG_TYPE_TRACING || fp->type ==BPF_PROG_TYPE_LSM ) +return fp->aux->attach_btf_id; +return 0 ; +}
[ ... ]
---
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/45542192835
PATCH 8/47 bpf: Reserve cookie and ip in the trampoline for tail calls
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The trampoline has a session cookie and the address of the function only when the program that is attached asks for them. After a tail call bpf_get_func_ip() returns what is on the stack, and bpf_session_cookie() points to the first argument, which the trampoline passes to the function:
KASAN: maybe wild-memory-access in range [0x4141414141414148-0x414141414141414f] RIP: 0010:vfs_truncate+0x32/0x450
Ask for both when the program has a tail call.
--- kernel/bpf/fixups.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/bpf/fixups.c +4 -0
@@ -2254,6 +2254,10 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)* the program array. */ prog->cb_access =1 ; + prog->call_get_func_ip =1 ; +if (prog_type ==BPF_PROG_TYPE_TRACING && + (eatype ==BPF_TRACE_FSESSION || eatype ==BPF_TRACE_FSESSION_MULTI )) + prog->call_session_cookie =1 ;if (!bpf_allow_tail_call_in_subprogs (env)) prog->aux->stack_depth =MAX_BPF_STACK ; prog->aux->max_pkt_offset =MAX_PACKET_OFF ;
Signature · 1 line
2.55.0
PATCH 9/47 bpf: Check that a program and a struct_ops map are for the same struct
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A map takes a program when the id of the struct and the index of the member are the same. Ids of types are not unique among modules. Compare BTF too.
BPF_PROG_ASSOC_STRUCT_OPS takes any struct_ops map, and the callers of bpf_prog_get_assoc_struct_ops() take the result for their own struct. Pass the struct_ops that the caller wants, return NULL for another one. The callers are scx_prog_sched() of sched_ext and bpf_testmod, they change with the prototype.
--- include/linux/bpf.h | 6 ++++-- kernel/bpf/bpf_struct_ops.c | 8 ++++++-- kernel/sched/ext/internal.h | 5 ++++- tools/testing/selftests/bpf/test_kmods/bpf_testmod.c | 6 ++++-- 4 files changed, 18 insertions(+), 7 deletions(-)
include/linux/bpf.h +4 -2
@@ -2411,7 +2411,8 @@ static inline void bpf_module_put(const void *data, struct module *owner)int bpf_struct_ops_link_create (union bpf_attr *attr);int bpf_prog_assoc_struct_ops (struct bpf_prog *prog,struct bpf_map *map);void bpf_prog_disassoc_struct_ops (struct bpf_prog *prog); -void *bpf_prog_get_assoc_struct_ops (const struct bpf_prog_aux *aux); +void *bpf_prog_get_assoc_struct_ops (const struct bpf_prog_aux *aux, +const struct bpf_struct_ops *st_ops);u32 bpf_struct_ops_id (const void *kdata); int bpf_struct_ops_for_each_prog(const void *kdata, int (*cb)(struct bpf_prog *prog, void *data),
@@ -2475,7 +2476,8 @@ static inline int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_mastatic inline void bpf_prog_disassoc_struct_ops (struct bpf_prog *prog) { } -static inline void *bpf_prog_get_assoc_struct_ops (const struct bpf_prog_aux *aux) +static inline void *bpf_prog_get_assoc_struct_ops (const struct bpf_prog_aux *aux, +const struct bpf_struct_ops *st_ops) {return NULL ; }
kernel/bpf/bpf_struct_ops.c +6 -2
@@ -845,6 +845,7 @@ static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key, }if (prog->type !=BPF_PROG_TYPE_STRUCT_OPS || + prog->aux->attach_btf != st_map->btf || prog->aux->attach_btf_id != st_ops_desc->type_id || prog->expected_attach_type != i) {bpf_prog_put (prog);
@@ -1591,13 +1592,14 @@ void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog)* Get a reference to the struct_ops struct (i.e., kdata) associated with a * program. Should only be called in BPF program context (e.g., in a kfunc). * -* If the returned pointer is not NULL, it must points to a valid struct_ops. +* If the returned pointer is not NULL, it must points to a valid @st_ops. * The struct_ops map is not guaranteed to be initialized nor attached. * Kernel struct_ops implementers are responsible for tracking and checking * the state of the struct_ops if the use case requires an initialized or * attached struct_ops. */ -void *bpf_prog_get_assoc_struct_ops (const struct bpf_prog_aux *aux) +void *bpf_prog_get_assoc_struct_ops (const struct bpf_prog_aux *aux, +const struct bpf_struct_ops *st_ops) {struct bpf_struct_ops_map *st_map;struct bpf_map *st_ops_assoc;
@@ -1607,6 +1609,8 @@ void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux)return NULL ; st_map = (struct bpf_struct_ops_map *)st_ops_assoc; +if (st_map->st_ops_desc->st_ops != st_ops) +return NULL ;return &st_map->kvalue.data; }
kernel/sched/ext/internal.h +4 -1
@@ -2674,6 +2674,8 @@ static inline bool scx_task_on_sched(struct scx_sched *sch,return rcu_access_pointer (p->scx.sched) == sch; } +static struct bpf_struct_ops bpf_sched_ext_ops, bpf_sched_ext_ops_cid; +/** * scx_prog_sched - Find scx_sched associated with a BPF prog * @aux: aux passed in from BPF to a kfunc
@@ -2687,7 +2689,8 @@ static inline struct scx_sched *scx_prog_sched(const struct bpf_prog_aux *aux)struct sched_ext_ops *ops;struct scx_sched *sch, *root; - ops =bpf_prog_get_assoc_struct_ops (aux); + ops =bpf_prog_get_assoc_struct_ops (aux, &bpf_sched_ext_ops) ?: +bpf_prog_get_assoc_struct_ops (aux, &bpf_sched_ext_ops_cid);if (likely (ops)) { sch =rcu_dereference_all (ops->priv);if (sch &&unlikely (READ_ONCE (sch->dead)))
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +4 -2
@@ -2500,13 +2500,15 @@ int bpf_kfunc_multi_st_ops_test_1(struct st_ops_args *args, u32 id)return ret; } +static struct bpf_struct_ops testmod_multi_st_ops; +/* Call test_1() of the associated struct_ops map */ int bpf_kfunc_multi_st_ops_test_1_assoc (struct st_ops_args *args,struct bpf_prog_aux *aux) {struct bpf_testmod_multi_st_ops *st_ops;int ret =-1 ; - st_ops = (struct bpf_testmod_multi_st_ops *)bpf_prog_get_assoc_struct_ops (aux); + st_ops =bpf_prog_get_assoc_struct_ops (aux, &testmod_multi_st_ops);if (st_ops) ret = st_ops->test_1 (args);
@@ -2584,7 +2586,7 @@ static struct bpf_testmod_multi_st_ops multi_st_ops_cfi_stubs = { .test_1 = bpf_testmod_multi_st_ops__test_1, }; -struct bpf_struct_ops testmod_multi_st_ops = { +static struct bpf_struct_ops testmod_multi_st_ops = { .verifier_ops = &bpf_testmod_verifier_ops, .init = multi_st_ops_init, .init_member = multi_st_ops_init_member,
Signature · 1 line
2.55.0
PATCH 10/47 bpf: Keep the names in front of a number in delegate options
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The delegate_* mount options of bpffs take names and numbers. A number overwrites the mask, the names in front of it are lost. That is the order in which /proc/mounts shows them.
--- kernel/bpf/inode.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
kernel/bpf/inode.c +3 -2
@@ -1055,7 +1055,7 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param)struct bpffs_btf_enums info;const struct btf_type *enum_t;const char *enum_pfx; -u64 *delegate_msk, msk =0 ; +u64 *delegate_msk, msk =0 , num;char *p, *str;int val;
@@ -1094,9 +1094,10 @@ static int bpf_parse_param(struct fs_context *fc, struct fs_parameter *param) }else if (find_btf_enum_const (info.btf, enum_t, enum_pfx, p, &val)) { msk |=1ULL << val; }else { - err =kstrtou64 (p,0 , &msk); + err =kstrtou64 (p,0 , &num);if (err)return err; + msk |= num; } }
Signature · 1 line
2.55.0
PATCH 11/47 bpf: Do not trust the neighbour of tp_btf/neigh_create
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
___neigh_create() calls the tracepoint before it tests the result of neigh_alloc(). It is NULL when the table is full. The verifier takes it for a trusted pointer, and a load through it oopses:
BUG: kernel NULL pointer dereference, address: 000000000000013c RIP: 0010:bpf_prog_56e3384dcafb1b5b_on_create+0x61/0xc4
Mark it untrusted, loads through it are probed then. PTR_MAYBE_NULL would refuse programs like bpftune, which pass &n->parms to bpf_probe_read_kernel() without a check. The pointer cannot be passed as memory or as a trusted argument any more.
--- kernel/bpf/btf.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/bpf/btf.c +4 -0
@@ -7444,6 +7444,7 @@ static const struct bpf_raw_tp_null_args raw_tp_null_args[] = {/* iptfs */ { "iptfs_ingress_postq_event", 0x1000 },/* neigh */ + { "neigh_create", 0x4000 }, { "neigh_update", 0x10 },/* snd_firewire_lib */ { "amdtp_packet", 0x100 },
@@ -7656,6 +7657,9 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,/* Is the current arg IS_ERR? */ if (raw_tp_null_args[i].mask & (0x2ULL << (arg *4 ))) ptr_err_raw_tp = true; +/* It can be NULL, and programs that do not check it have to load */ +if (raw_tp_null_args[i].mask & (0x4ULL << (arg *4 ))) + info->reg_type =PTR_TO_BTF_ID |PTR_UNTRUSTED ;break ; }/* If we don't know NULL-ness specification and the tracepoint
Signature · 1 line
2.55.0
PATCH 12/47 bpf: Check for NULL in helpers that take a kernel pointer
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Helpers take a plain PTR_TO_BTF_ID, which can be NULL: an argument of a traced function, or a member of a struct. Some do not check it:
KASAN: null-ptr-deref in range [0x0000000000000048-0x000000000000004f] RIP: 0010:sock_from_file+0x22/0x70
bpf_task_pt_regs(), bpf_get_task_stack(), bpf_copy_from_user_task(), bpf_xdp_get_buff_len(), bpf_getsockopt() and bpf_setsockopt() oops the same way. So does bpf_d_path() on the path of a unix socket that is not bound, it has no dentry.
Check for NULL, as bpf_find_vma() and bpf_skc_to_*() do.
--- kernel/bpf/helpers.c | 2 +- kernel/bpf/stackmap.c | 2 +- kernel/trace/bpf_trace.c | 4 +++- net/core/filter.c | 17 +++++++++++------ 4 files changed, 16 insertions(+), 9 deletions(-)
kernel/bpf/helpers.c +1 -1
@@ -726,7 +726,7 @@ BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,if (unlikely (!size))return 0 ; - mm =get_task_mm (tsk); + mm = tsk ?get_task_mm (tsk) :NULL ;if (!mm) {memset (dst,0 , size);return -EFAULT ;
kernel/bpf/stackmap.c +1 -1
@@ -897,7 +897,7 @@ static long __bpf_get_task_stack(struct task_struct *task, void *buf, u32 size,struct pt_regs *regs;long res = -EINVAL ; -if (!try_get_task_stack (task)) { +if (!task || !try_get_task_stack (task)) {memset (buf,0 , size);return -EFAULT ; }
kernel/trace/bpf_trace.c +3 -1
@@ -807,7 +807,7 @@ const struct bpf_func_proto bpf_get_current_task_btf_proto = { BPF_CALL_1(bpf_task_pt_regs, struct task_struct *, task) { -return (unsigned long )task_pt_regs (task); +return task ? (unsigned long )task_pt_regs (task) :0 ; }BTF_ID_LIST_SINGLE (bpf_task_pt_regs_ids, struct, pt_regs)
@@ -946,6 +946,8 @@ BPF_CALL_3(bpf_d_path, const struct path *, path, char *, buf, u32, sz) len =copy_from_kernel_nofault (©, path,sizeof (*path));if (len <0 )return len; +if (!copy.mnt || !copy.dentry) +return -EFAULT ; p =d_path (©, buf, sz);if (IS_ERR (p)) {
net/core/filter.c +11 -6
@@ -4215,10 +4215,15 @@ static const struct bpf_func_proto bpf_xdp_get_buff_len_proto = { .arg1_type = ARG_PTR_TO_CTX, }; +BPF_CALL_1(bpf_xdp_get_buff_len_trace, struct xdp_buff *, xdp) +{ +return xdp ?xdp_get_buff_len (xdp) :0 ; +} + BTF_ID_LIST_SINGLE(bpf_xdp_get_buff_len_bpf_ids, struct, xdp_buff)const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto = { - .func = bpf_xdp_get_buff_len, + .func = bpf_xdp_get_buff_len_trace, .gpl_only = false, .arg1_type =ARG_PTR_TO_BTF_ID , .arg1_btf_id = &bpf_xdp_get_buff_len_bpf_ids[0 ],
@@ -5856,7 +5861,7 @@ static int sol_ipv6_sockopt(struct sock *sk, int optname,static int __bpf_setsockopt (struct sock *sk,int level,int optname,char *optval,int optlen) { -if (!sk_fullsock (sk)) +if (!sk || !sk_fullsock (sk))return -EINVAL ;if (level ==SOL_SOCKET )
@@ -5879,7 +5884,7 @@ static bool is_locked_tcp_sock_ops(struct bpf_sock_ops_kern *bpf_sock)static int _bpf_setsockopt (struct sock *sk,int level,int optname,char *optval,int optlen) { -if (sk_fullsock (sk)) +if (sk &&sk_fullsock (sk))sock_owned_by_me (sk);return __bpf_setsockopt (sk, level, optname, optval, optlen); }
@@ -5889,7 +5894,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname, {int err, saved_optlen = optlen; -if (!sk_fullsock (sk)) { +if (!sk || !sk_fullsock (sk)) { err = -EINVAL ; goto done; }
@@ -5916,7 +5921,7 @@ static int __bpf_getsockopt(struct sock *sk, int level, int optname,static int _bpf_getsockopt (struct sock *sk,int level,int optname,char *optval,int optlen) { -if (sk_fullsock (sk)) +if (sk &&sk_fullsock (sk))sock_owned_by_me (sk);return __bpf_getsockopt (sk, level, optname, optval, optlen); }
@@ -12469,7 +12474,7 @@ const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = { BPF_CALL_1(bpf_sock_from_file, struct file *, file) { -return (unsigned long )sock_from_file (file); +return file ? (unsigned long )sock_from_file (file) :0 ; }BTF_ID_LIST (bpf_sock_from_file_btf_ids)
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 12/47] bpf: Check for NULL in helpers that take a kernel pointer
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [Critical] bpf: uninitialized memory leak in…
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [Critical] bpf: uninitialized memory leak in bpf_copy_from_user_task()
[1]
--
commit 021b75463c0bf9eb8fa8c4cfc85b4a67aea33848
Author: Alexei Starovoitov <[email protected]>
bpf: Check for NULL in helpers that take a kernel pointer
This commit adds NULL checks for BTF pointer arguments in several BPF helpers to prevent NULL pointer dereferences.
kernel/bpf/helpers.c BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size, · line 732
Quoted 13 lines
kernel/bpf/helpers.c +1
-1@@ -726,7 +726,7 @@ BPF_CALL_5(bpf_copy_from_user_task, void *, dst, u32, size,if (unlikely (!size))return 0 ; - mm =get_task_mm (tsk); + mm = tsk ?get_task_mm (tsk) :NULL ;if (!mm) {memset (dst,0 , size);return -EFAULT ;
[Severity: Critical]
This problem wasn't introduced by this patch, but does the early -EINVAL return for non-zero flags just above in bpf_copy_from_user_task() leave dst uninitialized [1]?
kernel/bpf/helpers.c:bpf_copy_from_user_task() {
/* flags is not used yet */
if (unlikely(flags))
return -EINVAL;bpf_copy_from_user_task_proto marks dst as ARG_PTR_TO_UNINIT_MEM, so the verifier treats dst as initialized after the helper returns even on error, allowing the BPF program to read uninitialized stack or map memory when non-zero flags are passed.
[1] https://sashiko.dev/#/bug/linux-63188542-7120-4444-b9a3-9977c77b0e2d
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
PATCH 13/47 bpf: Leave nothing behind in the frame of bpf_throw()
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
bpf_throw() does not return. What is kept for the return stays behind.
With fexit on bpf_throw() the trampoline is never freed. With kretprobes and function_graph the next traced function up the stack takes the return address of bpf_throw() for its own. Mark it notrace and NOKPROBE_SYMBOL.
kasan_unpoison_task_stack_below() takes the stack for aligned to THREAD_SIZE. The stack for interrupts of x86-64 is aligned to a page. A program that throws in softirq can leave the redzones of bpf_throw() there:
BUG: KASAN: stack-out-of-bounds in stack_trace_consume_entry+0x14e/0x170
It is the only frame with redzones that is skipped. Do not instrument it.
--- kernel/bpf/helpers.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-)
kernel/bpf/helpers.c +4 -9
@@ -22,7 +22,7 @@#include <linux/security.h> #include <linux/btf_ids.h> #include <linux/bpf_mem_alloc.h> -#include <linux/kasan.h> +#include <linux/kprobes.h> #include <linux/bpf_verifier.h> #include <linux/uaccess.h> #include <linux/verification.h>
@@ -3463,7 +3463,8 @@ static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)return false; } -__bpf_kfunc void bpf_throw(u64 cookie) +/* It does not return. What a tracer keeps for the return would stay behind, redzones too. */ +__bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie) {struct bpf_throw_ctx ctx = {};
@@ -3473,16 +3474,10 @@ __bpf_kfunc void bpf_throw(u64 cookie)WARN_ON_ONCE (!ctx.aux->exception_boundary);WARN_ON_ONCE (!ctx.bp);WARN_ON_ONCE (!ctx.cnt); -/* -* Prevent KASAN false positives for CONFIG_KASAN_STACK by unpoisoning -* deeper stack depths than ctx.sp as we do not return from bpf_throw, -* which skips compiler generated instrumentation to do the same. Some -* architectures cannot recover sp while unwinding, so fall back to bp. -*/ -kasan_unpoison_task_stack_below ((void *)(long )(ctx.sp ?: ctx.bp)); ctx.aux->bpf_exception_cb (cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp,0 ,0 );WARN (1 ,"A call to BPF exception callback should never return\n" ); } +NOKPROBE_SYMBOL (bpf_throw); __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags) {
Signature · 1 line
2.55.0
PATCH 14/47 bpf: Add the symbol of a prog before its id
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A prog can be taken by its id and run before bpf_prog_kallsyms_add(). bpf_throw() does not find the main prog and oopses:
KASAN: null-ptr-deref in range [0x0000000000000568-0x000000000000056f] RIP: 0010:bpf_throw+0x129/0x220
The exception table is found by the same symbol.
Add the symbol first. bpf_prog_free() removes it when there is no id.
--- kernel/bpf/syscall.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/bpf/syscall.c +3 -1
@@ -3179,6 +3179,9 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_atif (err <0 ) goto free_used_maps; +/* bpf_throw() and faults look for the symbol. The prog can run once it has the id. */ +bpf_prog_kallsyms_add (prog); + err =bpf_prog_alloc_id (prog);if (err) goto free_used_maps;
@@ -3197,7 +3200,6 @@ static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_at* Also, any failure handling from this point onwards must * be using bpf_prog_put() given the program is exposed. */ -bpf_prog_kallsyms_add (prog);perf_event_bpf_event (prog,PERF_BPF_EVENT_PROG_LOAD ,0 );bpf_audit_prog (prog,BPF_AUDIT_LOAD );
Signature · 1 line
2.55.0
PATCH 15/47 bpf: Do not fill jited line info for a hidden subprog
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
func_idx of the default exception callback is func_cnt, and the test for hidden subprogs is off by one. The address of the callback goes to jited_linfo[0]. libbpf and bpftool refuse the jited line info of the prog.
--- kernel/bpf/core.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/bpf/core.c +2 -1
@@ -233,7 +233,8 @@ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,const struct bpf_line_info *linfo;void **jited_linfo; -if (!prog->aux->jited_linfo || prog->aux->func_idx > prog->aux->func_cnt) +if (!prog->aux->jited_linfo || + (prog->aux->func_idx && prog->aux->func_idx >= prog->aux->func_cnt))/* Userspace did not provide linfo */ return ;
Signature · 1 line
2.55.0
PATCH 16/47 bpf: Fix NULL dereference in XDP redirect from async callbacks
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
bpf_redirect() and bpf_redirect_map() do not take the context, so the timer callback of an XDP program can call them. There is no current->bpf_net_context then:
KASAN: null-ptr-deref in range [0x0000000000000038-0x000000000000003f] RIP: 0010:bpf_xdp_redirect+0x5b/0x170
Return XDP_ABORTED, like the tc helpers return TC_ACT_SHOT. It is one more test and branch on a value that is loaded anyway.
--- include/linux/filter.h | 5 +++-- net/core/filter.c | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-)
include/linux/filter.h +3 -2
@@ -1948,13 +1948,14 @@ static __always_inline long __bpf_xdp_redirect_map(struct bpf_map *map, u64 inde u64 flags, const u64 flag_mask, void *lookup_elem(struct bpf_map *map, u32 key)) { - struct bpf_redirect_info *ri = bpf_net_ctx_get_ri(); const u64 action_mask = XDP_ABORTED | XDP_DROP | XDP_PASS | XDP_TX; +struct bpf_redirect_info *ri;/* Lower bits of the flags are used as return code on lookup failure */ -if (unlikely (flags & ~(action_mask | flag_mask))) +if (unlikely (!bpf_net_ctx_get () || flags & ~(action_mask | flag_mask)))return XDP_ABORTED ; + ri =bpf_net_ctx_get_ri (); ri->tgt_value =lookup_elem (map, index);if (unlikely (!ri->tgt_value) && !(flags &BPF_F_BROADCAST )) {/* If the lookup fails we want to clear out the state in the
net/core/filter.c +3 -2
@@ -4889,11 +4889,12 @@ int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb, BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags) { -struct bpf_redirect_info *ri =bpf_net_ctx_get_ri (); +struct bpf_redirect_info *ri; -if (unlikely (flags)) +if (unlikely (!bpf_net_ctx_get () || flags))return XDP_ABORTED ; + ri =bpf_net_ctx_get_ri ();/* NB! Map type UNSPEC and map_id == INT_MAX (never generated * by map_idr) is used for ifindex based XDP redirect. */
Signature · 1 line
2.55.0
PATCH 17/47 bpf: Check the attach type when a cgroup link gets another program
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
BPF_LINK_UPDATE compares only the type of the program. A program that is verified for one hook runs in another one. In setsockopt the result of bpf_get_retval() is an errno, in getsockopt it is any int.
Check expected_attach_type, as the attach does.
--- kernel/bpf/cgroup.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
kernel/bpf/cgroup.c +20 -1
@@ -1248,6 +1248,24 @@ static bool cgroup_bpf_storages_compatible(struct bpf_prog *old_prog,return true; } +/* See bpf_prog_attach_check_attach_type() */ +static bool prog_is_for_attach_type (const struct bpf_prog *prog,enum bpf_attach_type type) +{ +switch (prog->type) { +case BPF_PROG_TYPE_CGROUP_SKB : +if (!prog->enforce_expected_attach_type) +return true; + fallthrough; +case BPF_PROG_TYPE_CGROUP_SOCK : +case BPF_PROG_TYPE_CGROUP_SOCK_ADDR : +case BPF_PROG_TYPE_CGROUP_SOCKOPT : +case BPF_PROG_TYPE_LSM : +return prog->expected_attach_type == type; +default : +return true; + } +} +/** * __cgroup_bpf_replace() - Replace link's program and propagate the change * to descendants
@@ -1274,7 +1292,8 @@ static int __cgroup_bpf_replace(struct cgroup *cgrp, progs = &cgrp->bpf.progs[atype]; -if (link->link.prog->type != new_prog->type) +if (link->link.prog->type != new_prog->type || + !prog_is_for_attach_type (new_prog, link->link.attach_type))return -EINVAL ;hlist_for_each_entry (pl, progs, node) {
Signature · 1 line
2.55.0
PATCH 18/47 bpf: Refuse metadata maps of signed programs that can be mapped writable
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The signature of a program covers the value of its metadata maps. It holds because they are frozen and exclusive. The freeze is not final for an array that user space was allowed to map for writing, which is why bpf_map_mmap() refuses that for read-only maps. A loader writes to its map, so it's not one of those.
Refuse a map that has BPF_F_MMAPABLE without BPF_F_RDONLY_PROG. Light skeletons do not set it.
--- Documentation/bpf/signing.rst | 3 ++- kernel/bpf/verifier.c | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-)
Documentation/bpf/signing.rst +2 -1
@@ -141,7 +141,8 @@ reuses the existing ``fd_array``: ``excl_prog_sha``) and a plain array map (``BPF_MAP_TYPE_ARRAY``); only an array map exposes its value buffer through ``map_direct_value_addr()`` as a kernel address spanning ``value_size`` bytes. A map that is not exclusive, not - frozen, or not a plain array is rejected, with a verifier log message naming + frozen, not a plain array, or that user space could map for writing + (``BPF_F_MMAPABLE``) is rejected, with a verifier log message naming the offending map. The kernel appends each map's frozen contents to the instruction buffer and verifies the PKCS#7 signature over the concatenation ``insns || metadata_0 || metadata_1 || ...`` in ``used_maps``
kernel/bpf/verifier.c +7 -0
@@ -23850,6 +23850,13 @@ static int bpf_prog_verify_signature(struct bpf_verifier_env *env, err = -EPERM ; goto out; } +/* The freeze is not final for it, see bpf_map_mmap() */ +if ((map->map_flags &BPF_F_MMAPABLE ) && !(map->map_flags &BPF_F_RDONLY_PROG )) { +verbose (env,"signed program metadata map '%s' must not be mmapable\n" , + map->name); + err = -EPERM ; + goto out; + } data_sz += map->value_size; }if (bpf_dynptr_check_size (data_sz)) {
Signature · 1 line
2.55.0
PATCH 19/47 bpf: Take bpf_lock with interrupts disabled
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A program can disable interrupts with bpf_local_irq_save(). bpf_setsockopt(TCP_CONGESTION) can put the last reference of a struct_ops map there, which removes the symbols of the trampolines with spin_lock_bh(). Use the irqsave lock, as bpf_map_free_id() does. PREEMPT_RT is as before, both locks sleep there.
--- kernel/bpf/core.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-)
kernel/bpf/core.c +2 -4
@@ -648,11 +648,10 @@ static struct latch_tree_root bpf_tree __cacheline_aligned;void bpf_ksym_add (struct bpf_ksym *ksym) { -spin_lock_bh (&bpf_lock); +guard (spinlock_irqsave)(&bpf_lock);WARN_ON_ONCE (!list_empty (&ksym->lnode));list_add_tail_rcu (&ksym->lnode, &bpf_kallsyms);latch_tree_insert (&ksym->tnode, &bpf_tree, &bpf_tree_ops); -spin_unlock_bh (&bpf_lock); }static void __bpf_ksym_del (struct bpf_ksym *ksym)
@@ -666,9 +665,8 @@ static void __bpf_ksym_del(struct bpf_ksym *ksym)void bpf_ksym_del (struct bpf_ksym *ksym) { -spin_lock_bh (&bpf_lock); +guard (spinlock_irqsave)(&bpf_lock);__bpf_ksym_del (ksym); -spin_unlock_bh (&bpf_lock); }static bool bpf_prog_kallsyms_candidate (const struct bpf_prog *fp)
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 19/47] bpf: Take bpf_lock with interrupts disabled
TL;DR: Not a regression from this patch: on PREEMPT_RT, bpf_ksym_del() may still take a sleeping bpf_lock with interrupts disabled, via bpf_local_irq_save(). The fix works only on non-RT kernels.
Quoted 1 line
bpf: Take
bpf_lockwith interrupts disabled
TL;DR: Not a regression from this patch: on PREEMPT_RT, bpf_ksym_del() may still take a sleeping bpf_lock with interrupts disabled, via bpf_local_irq_save(). The fix works only on non-RT kernels.
Quoted 3 lines
kernel/bpf/core.c +0
-0
[ ... ]
kernel/bpf/core.c static void __bpf_ksym_del(struct bpf_ksym *ksym) · line 670
Quoted 9 lines
kernel/bpf/core.c +1
-2@@ -666,9 +665,8 @@ static void __bpf_ksym_del(struct bpf_ksym *ksym)void bpf_ksym_del (struct bpf_ksym *ksym) { -spin_lock_bh (&bpf_lock); +guard (spinlock_irqsave)(&bpf_lock);__bpf_ksym_del (ksym); -spin_unlock_bh (&bpf_lock); }
This isn't a bug introduced here, but on PREEMPT_RT can this still take a sleeping lock with interrupts disabled?
bpf_lock is a spinlock_t, so on RT guard(spinlock_irqsave) becomes rt_spin_lock() and disables nothing. The path from the commit message is:
bpf_local_irq_save()
local_irq_save()bpf_setsockopt(TCP_CONGESTION)
do_tcp_setsockopt()
tcp_set_congestion_control()
tcp_reinit_congestion_control()
tcp_cleanup_congestion_control()
bpf_module_put()
bpf_struct_ops_put()
bpf_map_put()
map->ops->map_free_pre_rcu()
bpf_struct_ops_map_del_ksyms()
bpf_image_ksym_del()
bpf_ksym_del()If another CPU holds bpf_lock, for example in bpf_prog_load() -> bpf_prog_kallsyms_add() -> bpf_ksym_add(), rtlock_slowlock_locked() calls schedule_rtlock() with interrupts disabled.
The commit message acknowledges this ("PREEMPT_RT is as before, both locks sleep there"), and bpf_map_free_id() earlier in bpf_map_put() takes map_idr_lock, also a spinlock_t, in the same way, so this is not worse than before. The change fixes the path on non-RT kernels only.
---
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/45542192835
PATCH 20/47 bpf: Bound the time that dumps of the stack take
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
may_goto looks at the time once in BPF_MAX_TIMED_LOOPS trips. A dump of the stack takes long, and it is staged before the stream is asked for room. A may_goto loop over bpf_stream_print_stack(), or one that faults in an arena on each trip, holds up RCU tasks and can end in a soft lockup.
Let the next may_goto of the program look at the time after a dump. Remember the length of a report that did not fit, and skip the next ones until a reader has made room for it.
--- include/linux/bpf.h | 5 ++++- include/linux/filter.h | 1 + kernel/bpf/core.c | 9 +++++++++ kernel/bpf/stream.c | 21 +++++++++++++++++++-- 4 files changed, 33 insertions(+), 3 deletions(-)
include/linux/bpf.h +4 -1
@@ -1841,6 +1841,7 @@ struct bpf_stream {struct llist_node *backlog_tail;/* tail of the list above */ wait_queue_head_t waitq;struct irq_work notify_work; +int refused;/* length of the last stage that did not fit */ bool notify_used;/* notify_work was queued at least once */ bool dead; };
@@ -4339,6 +4340,7 @@ int bpf_prog_stream_init(struct bpf_prog *prog, gfp_t gfp_extra_flags);void bpf_prog_stream_free (struct bpf_prog *prog);int bpf_prog_stream_read (struct bpf_prog *prog,enum bpf_stream_id stream_id,void __user *buf,u32 len);int bpf_prog_stream_new_fd (struct bpf_prog *prog,enum bpf_stream_id stream_id,u32 flags); +bool bpf_stream_has_room (struct bpf_prog *prog,enum bpf_stream_id stream_id);void bpf_stream_stage_init (struct bpf_stream_stage *ss);void bpf_stream_stage_free (struct bpf_stream_stage *ss);__printf (2 ,3 )
@@ -4353,7 +4355,8 @@ int bpf_stream_stage_dump_stack(struct bpf_stream_stage *ss);#define bpf_stream_stage (ss, prog, stream_id, expr) \ ({ \ bpf_stream_stage_init(&ss); \ - (expr); \ + if (bpf_stream_has_room(prog, stream_id)) \ + (expr); \ bpf_stream_stage_commit(&ss, prog, stream_id); \ bpf_stream_stage_free(&ss); \ })
include/linux/filter.h +1 -0
@@ -1334,6 +1334,7 @@ u64 bpf_arch_uaddress_limit(void);void arch_bpf_stack_walk (bool (*consume_fn)(void *cookie,u64 ip,u64 sp,u64 bp),void *cookie);u64 arch_bpf_timed_may_goto (void );u64 bpf_check_timed_may_goto (struct bpf_timed_may_goto *); +void bpf_timed_may_goto_check_time (const struct bpf_prog *prog);void bpf_timed_may_goto_save (const struct bpf_prog *prog,struct bpf_timed_may_goto *saved);void bpf_timed_may_goto_restore (const struct bpf_prog *prog,struct bpf_timed_may_goto *saved);bool bpf_helper_changes_pkt_data (enum bpf_func_id func_id);
kernel/bpf/core.c +9 -0
@@ -3713,6 +3713,15 @@ void bpf_timed_may_goto_restore(const struct bpf_prog *prog, struct bpf_timed_ma *cur = *saved; } +/* A walk of the stack is too long for BPF_MAX_TIMED_LOOPS trips. The next one looks at the time. */ +void bpf_timed_may_goto_check_time (const struct bpf_prog *prog) +{ +struct bpf_timed_may_goto __percpu *tmg = prog->aux->main_prog_aux->timed_may_goto; + +if (tmg &&this_cpu_read (tmg->count)) +this_cpu_write (tmg->count,1 ); +} +/* for configs without MMU or 32-bit */ __weak const struct bpf_map_ops arena_map_ops;__weak u64 bpf_arena_get_user_vm_start (struct bpf_arena *arena)
kernel/bpf/stream.c +19 -2
@@ -74,7 +74,9 @@ static int bpf_stream_consume_capacity(struct bpf_stream *stream, int len)static void bpf_stream_release_capacity (struct bpf_stream *stream,int len) { -atomic_sub (len, &stream->capacity); +if (atomic_sub_return (len, &stream->capacity) +READ_ONCE (stream->refused) < +BPF_STREAM_MAX_CAPACITY ) +WRITE_ONCE (stream->refused,0 ); }static void bpf_stream_notify (struct irq_work *work)
@@ -490,6 +492,15 @@ void bpf_prog_stream_free(struct bpf_prog *prog) } } +/* A dump of the stack is expensive, and a loop can ask for one on each trip */ +bool bpf_stream_has_room (struct bpf_prog *prog,enum bpf_stream_id stream_id) +{ +struct bpf_stream *stream =bpf_stream_get (stream_id, prog->aux); + +return stream &&atomic_read (&stream->capacity) +READ_ONCE (stream->refused) < +BPF_STREAM_MAX_CAPACITY ; +} +void bpf_stream_stage_init (struct bpf_stream_stage *ss) {init_llist_head (&ss->log);
@@ -531,13 +542,19 @@ int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog,struct bpf_stream *stream;int ret; +bpf_timed_may_goto_check_time (prog); + stream =bpf_stream_get (stream_id, prog->aux);if (!stream)return -EINVAL ; +if (!ss->len) +return 0 ; ret =bpf_stream_consume_capacity (stream, ss->len); -if (ret) +if (ret) { +WRITE_ONCE (stream->refused,min (ss->len,BPF_STREAM_MAX_CAPACITY /2 ));return ret; + } list =llist_del_all (&ss->log); head = tail = list;
Signature · 1 line
2.55.0
PATCH 21/47 bpf: Refuse mmap() of a part of an arena
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The first mmap() sets the addresses of an arena that has no map_extra. It can be shorter than max_entries, but all pages stay in the range tree. An allocation without an address gets pages behind the end of the mapping. They can be mapped behind the vmalloc area of the arena.
Require the length of the whole arena, as for an arena with map_extra. libbpf and cilium/ebpf map all pages.
--- kernel/bpf/arena.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-)
kernel/bpf/arena.c +5 -8
@@ -637,16 +637,13 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long adreturn -EINVAL ;if (len > (u64 )map->max_entries *PAGE_SIZE )return -E2BIG ; +/* each page in the range tree needs an address */ +if (len < (u64 )map->max_entries *PAGE_SIZE ) +return -EINVAL ;/* if user_vm_start was specified at arena creation time */ -if (arena->user_vm_start) { -if (len > arena->user_vm_end - arena->user_vm_start) -return -E2BIG ; -if (len != arena->user_vm_end - arena->user_vm_start) -return -EINVAL ; -if (addr != arena->user_vm_start) -return -EINVAL ; - } +if (arena->user_vm_start && addr != arena->user_vm_start) +return -EINVAL ;/* * Without MAP_FIXED the mm finds a free range. Ask for twice the
Signature · 1 line
2.55.0
PATCH 22/47 bpf: Flush TLB when a page of arena replaces the scratch page
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A fault of a kfunc maps the scratch page. An allocation at that address puts a new page in its place. flush_tlb_before_set() is empty on x86, so all cpus that have touched the address keep the scratch page in TLB. The program reads junk from the page that it has got, and its writes are lost.
The flush takes an IPI. Do it after the lock is dropped when the caller can sleep. Otherwise fail and free the range: the work unmaps the scratch page and flushes TLB. The range is taken until then. As with any deferred free, it stays taken when kmalloc_nolock() of the span fails.
--- kernel/bpf/arena.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-)
kernel/bpf/arena.c +16 -4
@@ -149,6 +149,8 @@ struct apply_range_data {struct bpf_arena *arena;struct llist_head *pages;int i; +bool can_flush;/* the caller can flush TLB of all cpus after it drops the lock */ +bool flush; };struct clear_range_data {
@@ -189,6 +191,12 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)continue ;if (WARN_ON_ONCE (pte_page (old) != d->arena->scratch_page))return -EBUSY ; +#ifndef flush_tlb_before_set +/* The scratch page is in TLB, and it takes an IPI to flush it */ +if (!d->can_flush) +return -EBUSY ; + d->flush = true; +#endif ptep_get_and_clear (&init_mm, addr, pte);flush_tlb_before_set (addr); }
@@ -571,6 +579,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf) }llist_add (&new_page->pcp_llist, &pages); data.arena = arena; + data.can_flush = false; data.pages = &pages; data.i =0 ;
@@ -803,6 +812,8 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt goto out_memcg; data.arena = arena; + data.can_flush = sleepable; + data.flush = false; data.pages = &pages; data.i =0 ;
@@ -833,17 +844,18 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cntflush_vmap_cache (kern_vm_start + uaddr32, mapped <<PAGE_SHIFT );raw_res_spin_unlock_irqrestore (&arena->spinlock, flags); +if (data.flush) +flush_tlb_kernel_range (kern_vm_start + uaddr32, + kern_vm_start + uaddr32 + (mapped <<PAGE_SHIFT )); addr =clear_lo32 (arena->user_vm_start) + uaddr32; goto out_memcg; out_unmap: -/* Error handling: Undo partial mappings. */ +/* Error handling: Undo partial mappings, unmap the scratch page. */ flush_vmap_cache (kern_vm_start + uaddr32, mapped <<PAGE_SHIFT ); -range_tree_set (&arena->rt, pgoff + mapped, page_cnt - mapped);raw_res_spin_unlock_irqrestore (&arena->spinlock, flags); -if (mapped) -arena_free_pages (arena, uaddr32, mapped, sleepable); +arena_free_pages (arena, uaddr32, page_cnt, sleepable); out_free_pages:/* Error handling: Free back any unmapped pages. */
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 22/47] bpf: Flush TLB when a page of arena replaces the scratch page
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] arm64/mm: ptep_try_set() undefined when…
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] arm64/mm: ptep_try_set() undefined when CONFIG_ARM64_CONTPTE is disabled [1]
--
commit 4eb6b85f2fe787d069b3bed0effa2468a69cda9e
Author: Alexei Starovoitov <[email protected]>
bpf: Flush TLB when a page of arena replaces the scratch page
This commit flushes the TLB across all CPUs after dropping arena->spinlock when a newly allocated arena page replaces the scratch page on architectures without flush_tlb_before_set(), or fails and defers freeing the range when the caller cannot sleep.
Quoted 16 lines
kernel/bpf/arena.c +2
-0@@ -149,6 +149,8 @@ struct apply_range_data {struct bpf_arena *arena;struct llist_head *pages;int i; +bool can_flush;/* the caller can flush TLB of all cpus after it drops the lock */ +bool flush; };struct clear_range_data {@@ -189,6 +191,12 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)continue ;if (WARN_ON_ONCE (pte_page (old) != d->arena->scratch_page))
kernel/bpf/arena.c static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data) · line 202
Quoted 10 lines
kernel/bpf/arena.c +6
-0return -EBUSY ; +#ifndef flush_tlb_before_set +/* The scratch page is in TLB, and it takes an IPI to flush it */ +if (!d->can_flush) +return -EBUSY ; + d->flush = true; +#endif ptep_get_and_clear (&init_mm, addr, pte);flush_tlb_before_set (addr); }
[Severity: High]
This problem wasn't introduced by this patch, but on arm64 with CONFIG_ARM64_CONTPTE=n, aren't ptep_try_set() and flush_tlb_before_set() left undefined [1]?
arch/arm64/include/asm/pgtable.h defines both helpers inside the #ifdef CONFIG_ARM64_CONTPTE block even though they operate on init_mm and do not depend on contiguous PTEs. When CONFIG_ARM64_CONTPTE is disabled, apply_range_set_cb() skips its #ifdef ptep_try_set path, while a kernel fault on an unmapped arena address still reaches __do_kernel_fault() -> bpf_arena_handle_page_fault() -> apply_range_set_scratch_cb(), which calls the no-op ptep_try_set() stub in include/linux/pgtable.h, reports the fault as handled without mapping the scratch page, and hangs the CPU in an infinite page-fault loop.
[1] https://sashiko.dev/#/bug/linux-b7d0ea8c-0c63-439f-9b21-bfd45fea82bb
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=22
PATCH 23/47 bpf: Fix reads past an enum in prints of BTF data
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
An enum has 1, 2, 4 or 8 bytes. It's read as int, enum64 as u64, whatever the size is. The file of a map in bpffs shows what is behind a key or a value that ends with a short enum.
Read as many bytes as the type has. The check of a member of a struct with bitfields takes any enum for 4 bytes, so an enum of 8 bytes can stick out of it. Use the size there too.
Short enums are printed by their names. BTF with an enum that sticks out of its struct is refused, compilers don't make it.
--- kernel/bpf/btf.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-)
kernel/bpf/btf.c +22 -4
@@ -4579,7 +4579,7 @@ static int btf_enum_check_kflag_member(struct btf_verifier_env *env,return -EINVAL ; } - nr_bits = int_bitsize; + nr_bits = member_type->size *BITS_PER_BYTE ; }else if (nr_bits > int_bitsize) {btf_verifier_log_member (env, struct_type, member,"Invalid member bitfield_size" );
@@ -4662,12 +4662,30 @@ static void btf_enum_log(struct btf_verifier_env *env,btf_verifier_log (env,"size=%u vlen=%u" , t->size,btf_type_vlen (t)); } +static s64 btf_enum_read (const struct btf_type *t,const void *data) +{ +bool sign =btf_type_kflag (t); + +switch (t->size) { +case 1 : +return sign ? *(s8 *)data : *(u8 *)data; +case 2 : +return sign ? *(s16 *)data : *(u16 *)data; +case 4 : +return sign ? (s64)*(s32 *)data : *(u32 *)data; +default : +return *(s64 *)data; + } +} +static void btf_enum_show (const struct btf *btf,const struct btf_type *t,u32 type_id,void *data,u8 bits_offset,struct btf_show *show) {const struct btf_enum *enums =btf_type_enum (t);u32 i, nr_enums =btf_type_vlen (t); +/* Old compilers don't set the flag for negative values */ +u32 mask = t->size <4 ?BIT (t->size *BITS_PER_BYTE ) -1 :U32_MAX ;void *safe_data;int v;
@@ -4675,10 +4693,10 @@ static void btf_enum_show(const struct btf *btf, const struct btf_type *t,if (!safe_data)return ; - v = *(int *)safe_data; + v =btf_enum_read (t, safe_data);for (i =0 ; i < nr_enums; i++) { -if (v != enums[i].val) +if ((v ^ enums[i].val) & mask)continue ; btf_show_type_value(show, "%s",
@@ -4778,7 +4796,7 @@ static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,if (!safe_data)return ; - v = *(u64 *)safe_data; + v =btf_enum_read (t, safe_data);for (i =0 ; i < nr_enums; i++) {if (v !=btf_enum64_value (enums + i))
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 23/47] bpf: Fix reads past an enum in prints of BTF data
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] bpf: truncation of 8-byte enum values to 32-bit int in btf_enum_show() - [Medium] bpf: hardcoded…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] bpf: truncation of 8-byte enum values to 32-bit int in btf_enum_show()
- [Medium] bpf: hardcoded 32-bit bitfield limit in btf_enum_check_kflag_member()
--
commit c14b9d6d46e8fb4261828cf2cb022187e0695c07
Author: Alexei Starovoitov <[email protected]>
bpf: Fix reads past an enum in prints of BTF data
This commit changes BTF enum printing and struct member size validation to use the actual size of the enum type instead of assuming 4 or 8 bytes.
kernel/bpf/btf.c static int btf_enum_check_kflag_member(struct btf_verifier_env *env, · line 4585
Quoted 13 lines
kernel/bpf/btf.c +1
-1@@ -4579,7 +4579,7 @@ static int btf_enum_check_kflag_member(struct btf_verifier_env *env,return -EINVAL ; } - nr_bits = int_bitsize; + nr_bits = member_type->size *BITS_PER_BYTE ; }else if (nr_bits > int_bitsize) {btf_verifier_log_member (env, struct_type, member,"Invalid member bitfield_size" );
[Severity: Medium]
Should int_bitsize also be computed from member_type->size * BITS_PER_BYTE for the bitfield check?
Leaving int_bitsize hardcoded to sizeof(int) * BITS_PER_BYTE causes btf_enum_check_kflag_member() to reject valid 33..64-bit bitfields of 8-byte BTF_KIND_ENUM and BTF_KIND_ENUM64 types, while accepting 1-byte or 2-byte enum bitfields with nr_bits up to 32. When __btf_struct_show() formats such an oversized bitfield on a 1-byte or 2-byte enum, btf_show_start_type() only ensures member_type->size bytes remain in show->obj.safe[], whereas btf_bitfield_show() copies BITS_ROUNDUP_BYTES(bitfield_size + bits8_offset) bytes and can read past the end of show->obj.safe[].
Quoted 34 lines
kernel/bpf/btf.c +18
-0@@ -4662,12 +4662,30 @@ static void btf_enum_log(struct btf_verifier_env *env,btf_verifier_log (env,"size=%u vlen=%u" , t->size,btf_type_vlen (t)); } +static s64 btf_enum_read (const struct btf_type *t,const void *data) +{ +bool sign =btf_type_kflag (t); + +switch (t->size) { +case 1 : +return sign ? *(s8 *)data : *(u8 *)data; +case 2 : +return sign ? *(s16 *)data : *(u16 *)data; +case 4 : +return sign ? (s64)*(s32 *)data : *(u32 *)data; +default : +return *(s64 *)data; + } +} +static void btf_enum_show (const struct btf *btf,const struct btf_type *t,u32 type_id,void *data,u8 bits_offset,struct btf_show *show) {const struct btf_enum *enums =btf_type_enum (t);u32 i, nr_enums =btf_type_vlen (t); +/* Old compilers don't set the flag for negative values */ +u32 mask = t->size <4 ?BIT (t->size *BITS_PER_BYTE ) -1 :U32_MAX ;void *safe_data;int v;@@ -4675,10 +4693,10 @@ static void btf_enum_show(const struct btf *btf, const struct btf_type *t,if (!safe_data)return ;
kernel/bpf/btf.c static void btf_enum_show(const struct btf *btf, const struct btf_type *t, · line 4702
Quoted 10 lines
kernel/bpf/btf.c +2
-2- v = *(int *)safe_data; + v =btf_enum_read (t, safe_data);for (i =0 ; i < nr_enums; i++) { -if (v != enums[i].val) +if ((v ^ enums[i].val) & mask)continue ; btf_show_type_value(show, "%s",
[Severity: Medium]
Does storing the s64 return value of btf_enum_read() into int v (and masking with u32 mask) truncate 8-byte BTF_KIND_ENUM values in btf_enum_show()?
When t->size is 8, btf_enum_read() reads 64 bits via its default branch, but assigning the result to 32-bit int v discards the upper 32 bits. An 8-byte BTF_KIND_ENUM value with non-zero upper bits will falsely match an enumerator whose 32-bit value matches the lower 32 bits, or print a truncated 32-bit integer when unmatched.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=23
PATCH 24/47 bpf: Give the error of bpf_res_spin_lock() a 32-bit range
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The verifier gives r0 the range [-4095, -1] in 64 bits when bpf_res_spin_lock() fails. The kfunc returns int, x86-64 and arm64 leave the upper half zero. Give the range to the lower half only.
GCC extends the result with r0 = (s32)r0. Keep the range of the lower half there, so that a test of the sign still tells the error.
--- kernel/bpf/verifier.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
kernel/bpf/verifier.c +10 -5
@@ -6217,6 +6217,7 @@ static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)u64 top_smax_value, top_smin_value;u64 num_bits = size *8 ;s64 limit =1LL << (num_bits -1 ); +struct cnum32 r32;/* If every value fits the signed N-bit range sign extension is a noop. */ if (reg_smin (reg) >= -limit &®_smax (reg) < limit)
@@ -6271,7 +6272,13 @@ static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) } out: + r32 = reg->r32;set_sext64_default_val (reg, size); +/* the low 32 bits fit, they do not change */ +if (cnum32_smin (r32) >= -limit &&cnum32_smax (r32) < limit) { + reg->r32 = r32; + reg->r64 =cnum64_from_srange (cnum32_smin (r32),cnum32_smax (r32)); + } }static void set_sext32_default_val (struct bpf_reg_state *reg,int size)
@@ -15538,12 +15545,10 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,for (i =0 ; i <CALLER_SAVED_REGS ; i++)bpf_mark_reg_not_init (env, ®s[caller_saved[i]]); +/* The kfunc returns int, the upper half of r0 is not known */ mark_reg_unknown (env, regs,BPF_REG_0 ); - err =__mark_reg_s32_range (env, regs,BPF_REG_0 , -MAX_ERRNO ,-1 ); -if (err) { -verbose (env,"failed to mark s32 range for retval in forked state for lock\n" ); -return err; - } +reg_set_srange32 (®s[BPF_REG_0 ], -MAX_ERRNO ,-1 ); +reg_bounds_sync (®s[BPF_REG_0 ]); }else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {verbose (env,"unexpected __bpf_trap() due to uninitialized variable?\n" );return -EFAULT ;
Signature · 1 line
2.55.0
PATCH 25/47 bpf: Give syscall programs without CAP_PERFMON the base helpers only
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A syscall program needs CAP_BPF only, and it gets all helpers of tracing programs. These don't ask for CAP_PERFMON, the load of a tracing program does.
The helpers for loader programs take current for the loader. It's another task in a callback. bpf_kallsyms_lookup_name() answers in a callback of bpf_wq, as a kworker has all capabilities. bpf_sys_close() in a task work closes a file of any process.
Give the program the base helpers. It loses bpf_perf_event_output() too. Loader programs are not affected, bpf_sys_bpf() needs CAP_PERFMON already.
--- kernel/bpf/syscall.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
kernel/bpf/syscall.c +4 -2
@@ -6747,10 +6747,12 @@ static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {static const struct bpf_func_proto *syscall_prog_func_proto (enum bpf_func_id func_id,const struct bpf_prog *prog) { +if (!bpf_token_capable (prog->aux->token,CAP_PERFMON )) +return bpf_base_func_proto (func_id, prog); +switch (func_id) {case BPF_FUNC_sys_bpf: -return !bpf_token_capable (prog->aux->token,CAP_PERFMON ) - ?NULL : &bpf_sys_bpf_proto; +return &bpf_sys_bpf_proto;case BPF_FUNC_btf_find_by_name_kind:return &bpf_btf_find_by_name_kind_proto;case BPF_FUNC_sys_close:
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 25/47] bpf: Give syscall programs without CAP_PERFMON the base helpers only
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Critical] bpf: syscall_prog_func_proto() still allows loader helpers in async callbacks --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Critical] bpf: syscall_prog_func_proto() still allows loader helpers in async callbacks
--
commit 0b17252c17a9909e5f5169c092eff3dd514adbd9
Author: Alexei Starovoitov <[email protected]>
bpf: Give syscall programs without CAP_PERFMON the base helpers only
This commit restricts BPF_PROG_TYPE_SYSCALL programs loaded without CAP_PERFMON to bpf_base_func_proto() helpers instead of allowing loader and tracing helpers.
Quoted 9 lines
kernel/bpf/syscall.c +1
-0@@ -6747,10 +6747,12 @@ static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {static const struct bpf_func_proto *syscall_prog_func_proto (enum bpf_func_id func_id,const struct bpf_prog *prog) { +if (!bpf_token_capable (prog->aux->token,CAP_PERFMON ))
kernel/bpf/syscall.c static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = { · line 6758
Quoted 10 lines
kernel/bpf/syscall.c +3
-2+return bpf_base_func_proto (func_id, prog); +switch (func_id) {case BPF_FUNC_sys_bpf: -return !bpf_token_capable (prog->aux->token,CAP_PERFMON ) - ?NULL : &bpf_sys_bpf_proto; +return &bpf_sys_bpf_proto;case BPF_FUNC_btf_find_by_name_kind:return &bpf_btf_find_by_name_kind_proto;case BPF_FUNC_sys_close:
[Severity: Critical]
Does this still allow bpf_sys_bpf(), bpf_sys_close(), bpf_btf_find_by_name_kind(), and bpf_kallsyms_lookup_name() to run inside bpf_wq and bpf_task_work callbacks when the program has CAP_PERFMON (including via a delegated bpf_token in a non-initial user namespace)?
As noted in the commit message, these loader helpers operate on current. Because is_async_cb_sleepable() marks bpf_wq and bpf_task_work callbacks as sleepable and neither syscall_prog_func_proto() nor check_helper_call() rejects these helpers in async callbacks, a program passing the CAP_PERFMON check can still invoke them from those callbacks:
- In a bpf_wq callback, current is a kworker running with init_cred in init_user_ns and init_files, so bpf_sys_bpf() executes __sys_bpf() with full init_user_ns capabilities and no token restrictions, and bpf_kallsyms_lookup_name() checks bpf_dump_raw_ok() against the kworker's credentials.
- In a bpf_task_work callback, current is the target task, allowing bpf_sys_close() to close arbitrary file descriptors of another process. If the callback runs from exit_task_work() during do_exit() after exit_files() has set current->files to NULL, calling bpf_sys_close(), bpf_sys_bpf(), or bpf_btf_find_by_name_kind() (for a module BTF) causes a NULL pointer dereference in file_close_fd() or alloc_fd().
Should check_helper_call() reject these चार loader helpers when env->subprog_info[env->cur_state->frame[0]->subprogno].is_async_cb is set?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=25
[email protected]
AI reviewRe: [PATCH bpf 25/47] bpf: Give syscall programs without CAP_PERFMON the base helpers only
In reply to Alexei StarovoitovTL;DR: Possible privilege escalation: a syscall program with CAP_PERFMON may call bpf_sys_bpf() from a bpf_wq callback, which runs in a kworker with full capabilities. The fix doesn't seem to cover…
Quoted 1 line
bpf: Give syscall programs without
CAP_PERFMONthe base helpers only
TL;DR: Possible privilege escalation: a syscall program with CAP_PERFMON may call bpf_sys_bpf() from a bpf_wq callback, which runs in a kworker with full capabilities. The fix doesn't seem to cover this.
Quoted 5 lines
kernel/bpf/syscall.c +0
-0@@ -6747,10 +6747,12 @@ static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = { static const struct bpf_func_proto *
kernel/bpf/syscall.c static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = { · line 6755
Quoted 10 lines
kernel/bpf/syscall.c +4
-2syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) { +if (!bpf_token_capable (prog->aux->token,CAP_PERFMON )) +return bpf_base_func_proto (func_id, prog); +switch (func_id) {case BPF_FUNC_sys_bpf: - return !bpf_token_capable(prog->aux->token, CAP_PERFMON) - ? NULL : &bpf_sys_bpf_proto; +return &bpf_sys_bpf_proto;
This isn't a bug introduced here, but the fix doesn't seem to cover the CAP_PERFMON case of the problem the commit message describes.
The message says the loader helpers use current, which is a different task in a callback, and that a bpf_wq callback runs in a kworker with all capabilities. It then concludes "Loader programs are not affected, bpf_sys_bpf() needs CAP_PERFMON already."
The CAP_PERFMON check runs once, at load time, against the loading task. bpf_sys_bpf() then calls __sys_bpf(), whose permission checks run against current when the helper executes:
BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
{
...
return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size,
KERNEL_BPFPTR(NULL), 0);
}In a bpf_wq callback current is a kworker with init_cred. The bpf_wq kfuncs (bpf_wq_init/bpf_wq_set_callback/bpf_wq_start) are in common_btf_ids, registered for BPF_PROG_TYPE_UNSPEC, and have no KF_PERFMON flag. is_async_cb_sleepable() returns true for bpf_wq callbacks, so check_helper_call() accepts the might_sleep bpf_sys_bpf_proto there. Only timer callbacks reject it (see progs/verifier_async_cb_context.c).
Can a task with CAP_BPF and CAP_PERFMON, but without CAP_SYS_ADMIN or CAP_NET_ADMIN, load a syscall program whose bpf_wq callback calls bpf_sys_bpf()? The command would then run with full capabilities. For example, bpf_map_get_fd_by_id() checks capable(CAP_SYS_ADMIN), so BPF_MAP_GET_FD_BY_ID followed by BPF_MAP_UPDATE_ELEM could modify any BPF map in the system, and BPF_PROG_LOAD would pass the CAP_NET_ADMIN and CAP_SYS_ADMIN checks. That is more than CAP_PERFMON grants.
I found no later commit in the series that changes bpf_sys_bpf, the availability of the bpf_wq kfuncs, or the async callback helper rules.
Should the loader-only helpers (at least bpf_sys_bpf, and also bpf_sys_close, which acts on current->files) be rejected in async callbacks? Alternatively, should they be refused at run time when current is not the task that runs the program through BPF_PROG_TEST_RUN, as the comment in bpf_sys_close() already assumes (sys_bpf->prog_test_run->bpf_prog->bpf_sys_close)?
---
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/45542192835
PATCH 26/47 bpf: Require CAP_PERFMON for kfuncs that leak pointers or touch tasks
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Syscall, tc, XDP and cgroup programs load without CAP_PERFMON and can call kfuncs that give more than CAP_BPF stands for:
- kfuncs of arena take any pointer for the address and can leak it. The check for an arena misses one from a map of maps.
- void * of a kfunc is a number for the verifier.
- bpf_send_signal_task() and the kfuncs of task work act on any task.
Ask for CAP_PERFMON, as the helpers of the same kind do. struct_ops and tracing programs have it.
--- Documentation/bpf/kfuncs.rst | 3 ++- kernel/bpf/arena.c | 7 ++++--- kernel/bpf/helpers.c | 6 +++--- kernel/bpf/verifier.c | 6 ++++++ 4 files changed, 15 insertions(+), 7 deletions(-)
Documentation/bpf/kfuncs.rst +2 -1
@@ -537,7 +537,8 @@ addresses to the BPF program, for example by reading through a pointer that the verifier does not check. Calling such a kfunc requires CAP_PERFMON, or CAP_SYS_ADMIN, in the same way that the equivalent BPF helpers are gated in bpf_base_func_proto(). A program loaded with CAP_BPF alone is rejected at load -time. +time. The flag is implied when the program gets a returned ``void *`` as a +number. 2.6 Registering the kfuncs --------------------------
kernel/bpf/arena.c +4 -3
@@ -1187,9 +1187,10 @@ __bpf_kfunc int bpf_arena_reserve_pages(void *p__map, void *ptr__ign, u32 page_c__bpf_kfunc_end_defs (); BTF_KFUNCS_START(arena_kfuncs) -BTF_ID_FLAGS(func, bpf_arena_alloc_pages, KF_ARENA_RET | KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) -BTF_ID_FLAGS(func, bpf_arena_free_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) -BTF_ID_FLAGS(func, bpf_arena_reserve_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE) +BTF_ID_FLAGS(func, bpf_arena_alloc_pages, + KF_ARENA_RET | KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_free_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_reserve_pages, KF_ARENA_ARG2 | KF_SPINLOCK_SAFE | KF_PERFMON) BTF_KFUNCS_END(arena_kfuncs) static const struct btf_kfunc_id_set common_kfunc_set = {
kernel/bpf/helpers.c +3 -3
@@ -5156,7 +5156,7 @@ BTF_ID_FLAGS(func, bpf_task_from_pid, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_task_from_vpid, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_throw)#ifdef CONFIG_BPF_EVENTS -BTF_ID_FLAGS(func, bpf_send_signal_task) +BTF_ID_FLAGS(func, bpf_send_signal_task, KF_PERFMON)#endif #ifdef CONFIG_KEYS BTF_ID_FLAGS (func, bpf_lookup_user_key,KF_ACQUIRE |KF_RET_NULL |KF_SLEEPABLE )
@@ -5272,8 +5272,8 @@ BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU)#endif BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) BTF_ID_FLAGS(func, bpf_stream_print_stack, KF_IMPLICIT_ARGS | KF_SPINLOCK_SAFE | KF_PERFMON) -BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS) -BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_IMPLICIT_ARGS | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_IMPLICIT_ARGS | KF_PERFMON) BTF_ID_FLAGS(func, bpf_call_rcu, KF_IMPLICIT_ARGS) BTF_ID_FLAGS(func, bpf_call_rcu_tasks_trace, KF_IMPLICIT_ARGS)BTF_ID_FLAGS (func, bpf_dynptr_from_file)
kernel/bpf/verifier.c +6 -0
@@ -15851,6 +15851,12 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,return err; }else if (btf_type_is_void (ptr_type)) {/* kfunc returning 'void *' is equivalent to returning scalar */ +if (!env->allow_ptr_leaks) { +verbose (env, +"%s is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n" , + func_name); +return -EPERM ; + }mark_reg_unknown (env, regs,BPF_REG_0 ); }else if (!__btf_type_is_struct (ptr_type)) {if (!meta.ret_mem.found) {
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 26/47] bpf: Require CAP_PERFMON for kfuncs that leak pointers or touch tasks
TL;DR: Documentation nit: the KF_PERFMON section in kfuncs.rst doesn't cover the task-acting kfuncs (bpf_send_signal_task, task work) that now get the flag, so new such kfuncs may miss it.
Quoted 1 line
bpf: Require
CAP_PERFMONfor kfuncs that leak pointers or touch tasks
TL;DR: Documentation nit: the KF_PERFMON section in kfuncs.rst doesn't cover the task-acting kfuncs (bpf_send_signal_task, task work) that now get the flag, so new such kfuncs may miss it.
Documentation/bpf/kfuncs.rst addresses to the BPF program, for example by reading through a pointer that the · line 541
Quoted 11 lines
Documentation/bpf/kfuncs.rst +2
-1@@ -537,7 +537,8 @@ addresses to the BPF program, for example by reading through a pointer that the verifier does not check. Calling such a kfunc requires CAP_PERFMON, or CAP_SYS_ADMIN, in the same way that the equivalent BPF helpers are gated in bpf_base_func_proto(). A program loaded with CAP_BPF alone is rejected at load -time. +time. The flag is implied when the program gets a returned ``void *`` as a +number.
This isn't a bug, but the KF_PERFMON section still describes the flag as being for kfuncs that "can expose kernel memory or kernel addresses".
The same patch adds KF_PERFMON to bpf_send_signal_task(), bpf_task_work_schedule_signal() and bpf_task_work_schedule_resume(), which return only 0 or -errno and expose neither. The commit message gives a different reason for those: they "act on any task".
Could the first sentence of the section be widened to cover kfuncs that act on any task as well? Otherwise a new kfunc that signals or schedules work on an arbitrary task may not get KF_PERFMON, based on this reference.
---
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/45542192835
PATCH 27/47 bpf: Require CAP_PERFMON to read streams
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A loader that has CAP_BPF only can read the streams of its program. Reports of the kernel have addresses in them: those of locks after a deadlock, and of code that has no symbol in call traces.
Require CAP_PERFMON for BPF_PROG_STREAM_READ_BY_FD and BPF_PROG_STREAM_OPEN, through the token of the program if it has one.
--- include/uapi/linux/bpf.h | 3 ++- kernel/bpf/stream.c | 4 ++++ tools/include/uapi/linux/bpf.h | 3 ++- 3 files changed, 8 insertions(+), 2 deletions(-)
include/uapi/linux/bpf.h +2 -1
@@ -934,6 +934,7 @@ union bpf_iter_link_info {* by *prog_fd*, and the stream is identified by the *stream_id*. * The data is copied to a buffer pointed to by *stream_buf*, and * filled less than or equal to *stream_buf_len* bytes. +* The caller needs **CAP_PERFMON**. * * Return * Number of bytes read from the stream on success, or -1 if an
@@ -953,7 +954,7 @@ union bpf_iter_link_info {* Description * Open a file descriptor for one of the BPF streams associated * with the program identified by *prog_fd*. The stream is selected -* by *stream_id*. +* by *stream_id*. The caller needs **CAP_PERFMON**. * * The returned file descriptor supports **read**\ (2) and * **poll**\ (2). Reads block while the stream is empty unless
kernel/bpf/stream.c +4 -0
@@ -268,6 +268,8 @@ int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, vo {struct bpf_stream *stream; +if (!bpf_token_capable (prog->aux->token,CAP_PERFMON )) +return -EPERM ; stream =bpf_stream_get (stream_id, prog->aux);if (!stream)return -ENOENT ;
@@ -368,6 +370,8 @@ int bpf_prog_stream_new_fd(struct bpf_prog *prog, enum bpf_stream_id stream_id,int fd_flags =O_RDONLY |O_CLOEXEC ;int fd; +if (!bpf_token_capable (prog->aux->token,CAP_PERFMON )) +return -EPERM ; stream =bpf_stream_get (stream_id, prog->aux);if (!stream)return -ENOENT ;
tools/include/uapi/linux/bpf.h +2 -1
@@ -934,6 +934,7 @@ union bpf_iter_link_info {* by *prog_fd*, and the stream is identified by the *stream_id*. * The data is copied to a buffer pointed to by *stream_buf*, and * filled less than or equal to *stream_buf_len* bytes. +* The caller needs **CAP_PERFMON**. * * Return * Number of bytes read from the stream on success, or -1 if an
@@ -953,7 +954,7 @@ union bpf_iter_link_info {* Description * Open a file descriptor for one of the BPF streams associated * with the program identified by *prog_fd*. The stream is selected -* by *stream_id*. +* by *stream_id*. The caller needs **CAP_PERFMON**. * * The returned file descriptor supports **read**\ (2) and * **poll**\ (2). Reads block while the stream is empty unless
Signature · 1 line
2.55.0
PATCH 28/47 bpf: Limit reads of variables of the kernel
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
ld_imm64 of a variable that is not a struct gives readable memory, so do bpf_per_cpu_ptr() and bpf_this_cpu_ptr(). Many variables hold addresses, and CAP_BPF is enough to read them. The size comes from BTF, and that can be BTF of the program. Loads from such memory are not probed.
Ask for CAP_PERFMON, as for the access to a struct. Addresses of functions and of per-cpu variables can be loaded as before. Take BTF of the kernel and of modules only, libbpf passes no other.
--- kernel/bpf/helpers.c | 8 ++++---- kernel/bpf/verifier.c | 11 +++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-)
kernel/bpf/helpers.c +4 -4
@@ -2185,10 +2185,6 @@ bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_spin_unlock_proto;case BPF_FUNC_jiffies64:return &bpf_jiffies64_proto; -case BPF_FUNC_per_cpu_ptr: -return &bpf_per_cpu_ptr_proto; -case BPF_FUNC_this_cpu_ptr: -return &bpf_this_cpu_ptr_proto;case BPF_FUNC_timer_init:return &bpf_timer_init_proto;case BPF_FUNC_timer_set_callback:
@@ -2292,6 +2288,10 @@ bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)return &bpf_get_branch_snapshot_proto;case BPF_FUNC_find_vma:return &bpf_find_vma_proto; +case BPF_FUNC_per_cpu_ptr: +return &bpf_per_cpu_ptr_proto; +case BPF_FUNC_this_cpu_ptr: +return &bpf_this_cpu_ptr_proto;default :return NULL ; }
kernel/bpf/verifier.c +11 -0
@@ -20989,6 +20989,12 @@ static int __check_pseudo_btf_id(struct bpf_verifier_env *env, } } +if (!percpu && !env->allow_ptr_leaks) { +verbose (env,"access to '%s' is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n" , + sym_name); +return -EPERM ; + } + type = t->type; t =btf_type_skip_modifiers (btf, type,NULL );if (percpu) {
@@ -21034,6 +21040,11 @@ static int check_pseudo_btf_id(struct bpf_verifier_env *env,verbose (env,"invalid module BTF object FD specified.\n" );return -EINVAL ; } +if (!btf_is_kernel (btf)) { +verbose (env,"BTF fd for ksym is not a kernel BTF\n" ); +btf_put (btf); +return -EINVAL ; + } }else {if (!btf_vmlinux) {verbose (env,"kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n" );
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 28/47] bpf: Limit reads of variables of the kernel
TL;DR: Commit message only: the Fixes: tags may point at the wrong commits. 4976b718c355 and 6aca583f90b0 look like better fits for the ksym PTR_TO_MEM and helper parts. No code issues raised.
Quoted 1 line
bpf: Limit reads of variables of the kernel
TL;DR: Commit message only: the Fixes: tags may point at the wrong commits. 4976b718c355 and 6aca583f90b0 look like better fits for the ksym PTR_TO_MEM and helper parts. No code issues raised.
Quoted 7 lines
bpf: Limit reads of variables of the kernel
ld_imm64of a variable that is not a struct gives readable memory, so dobpf_per_cpu_ptr()andbpf_this_cpu_ptr(). Many variables hold addresses, andCAP_BPFis enough to read them. The size comes from BTF, and that can be BTF of the program. Loads from such memory are not probed.
Quoted 7 lines
Ask for
CAP_PERFMON, as for the access to a struct. Addresses of functions and of per-cpu variables can be loaded as before. Take BTF of the kernel and of modules only, libbpf passes no other.Fixes eaa6bcb71ef6 ("bpf: Introduce bpf_per_cpu_ptr()")Fixes 541c3bad8dc5 ("bpf: Support BPF ksym variables in kernel modules")Signed-off-by Alexei Starovoitov <[email protected]>
Are these Fixes: tags pointing at the right commits?
The PTR_TO_MEM path for a non-struct ksym variable, with a size taken from BTF and no CAP_PERFMON check, looks like it was added by:
The helpers became reachable without CAP_PERFMON through bpf_base_func_proto() in 6aca583f90b0 ("bpf: Streamline allowed helpers between tracing and base sets"), since eaa6bcb71ef6 added them only to the tracing set. Should that commit be listed for the helper part?
541c3bad8dc5 looks plausible for the non-kernel BTF fd check.
---
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/45542192835
PATCH 29/47 bpf: Require CAP_PERFMON for dumps of xlated insns
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The verifier puts addresses of the kernel to insns: for ksyms, inlined helpers and hidden arguments. The dump of xlated insns hides the ones of maps and calls only, the others look like constants by then. Give no dump, as for a blinded program, to who has no CAP_PERFMON and can't read kallsyms.
--- kernel/bpf/syscall.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/bpf/syscall.c +2 -1
@@ -5261,7 +5261,8 @@ static int bpf_prog_get_info_by_fd(struct file *file,struct bpf_insn *insns_sanitized;bool fault; -if (!prog->blinded ||bpf_dump_raw_ok (file->f_cred)) { +/* The verifier puts addresses to ld_imm64 and mov insns */ +if (bpf_dump_raw_ok (file->f_cred) || (!prog->blinded &&perfmon_capable ())) { insns_sanitized =bpf_insn_prepare_dump (prog, file->f_cred);if (!insns_sanitized)return -ENOMEM ;
Signature · 1 line
2.55.0
PATCH 30/47 bpf: Zero bpf_list_head in copies of map values
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
Lookups from user space copy the value to a buffer and init special fields there. An empty list_head points to itself. The caller gets the address of the buffer.
Fill the fields with zeros. It's what a new element of a map has. bpf_refcount in a value reads as 0.
--- include/linux/bpf.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-)
include/linux/bpf.h +8 -1
@@ -566,7 +566,14 @@ static inline void bpf_obj_init(const struct btf_record *rec, void *obj)*/ static inline void check_and_init_map_value (struct bpf_map *map,void *dst) { -bpf_obj_init (map->record, dst); +const struct btf_record *rec = map->record; +int i; + +if (IS_ERR_OR_NULL (rec)) +return ; +/* Not bpf_obj_init(): an empty list_head has the address of 'dst' */ +for (i =0 ; i < rec->cnt; i++) +memset (dst + rec->fields[i].offset,0 , rec->fields[i].size); }/* memcpy that is used with 8-byte aligned pointers, power-of-8 size and
Signature · 1 line
2.55.0
PATCH 31/47 bpf: Require CAP_PERFMON to read pinned maps with special fields
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A read of a pinned map prints values as they are in memory. bpf_timer, bpf_wq, bpf_list_head and bpf_rb_root are arrays of u64 for BTF and have addresses. Refuse open() of the file. BPF_OBJ_GET works as before.
--- kernel/bpf/inode.c | 5 +++++ 1 file changed, 5 insertions(+)
kernel/bpf/inode.c +5 -0
@@ -310,6 +310,11 @@ static int bpffs_map_open(struct inode *inode, struct file *file)struct seq_file *m;int err; +/* Special fields are printed as they are. Most have addresses. */ +if (btf_record_has_field (map->record, ~(BPF_SPIN_LOCK |BPF_RES_SPIN_LOCK )) && + !perfmon_capable ()) +return -EPERM ; + iter =map_iter_alloc (map);if (!iter)return -ENOMEM ;
Signature · 1 line
2.55.0
PATCH 32/47 bpf: Require CAP_PERFMON to pass values of insn_array as memory
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The value of an insn_array has addresses in the JIT image. Helpers take it for plain memory. Refuse to pass it without CAP_PERFMON. gotox works as before.
--- kernel/bpf/verifier.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/bpf/verifier.c +4 -0
@@ -7970,6 +7970,10 @@ static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_return check_mem_region_access (env, reg, argno,0 , access_size, reg->map_ptr->key_size, false);case PTR_TO_MAP_VALUE : +if (reg->map_ptr->map_type ==BPF_MAP_TYPE_INSN_ARRAY && !env->allow_ptr_leaks) { +verbose (env,"%s leaks addr from insn_array\n" ,reg_arg_name (env, argno)); +return -EACCES ; + }if (check_map_access_type (env, reg,0 , access_size, access_type))return -EACCES ; return check_map_access(env, reg, argno, 0, access_size,
Signature · 1 line
2.55.0
PATCH 33/47 bpf: Require CAP_PERFMON for the dump of all storages of sockets
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
inet_diag dumps values of all sk_storage maps when the request names no map. It takes CAP_BPF and no fd. These are data of other programs, and tracing programs keep addresses and memory of the kernel there.
Ask for CAP_PERFMON. "ss --bpf-maps" needs it then. A request with fds of maps works as before.
--- net/core/bpf_sk_storage.c | 4 ++++ 1 file changed, 4 insertions(+)
net/core/bpf_sk_storage.c +4 -0
@@ -502,6 +502,10 @@ bpf_sk_storage_diag_alloc(const struct nlattr *nla_stgs) nr_maps++; } +/* It's a dump of all maps, see bpf_sk_storage_diag_put() */ +if (!nr_maps && !perfmon_capable ()) +return ERR_PTR (-EPERM ); + diag =kzalloc_flex (*diag, maps, nr_maps);if (!diag)return ERR_PTR (-ENOMEM );
Signature · 1 line
2.55.0
PATCH 34/47 bpf, x86: Do not use the paranoid ITS thunk
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The paranoid thunk completes the check of a hash, it traps when ZF is clear. The JIT emits no such check. With paranoid FineIBT, the default with IBT and no FRED, on a cpu that has ITS the kernel oopses at an indirect tail call, at gotox, and when an XDP program is not in the dispatcher:
CFI failure at __x86_indirect_its_thunk_array+0x3d/0x3e
Take the plain thunk. its_static_thunk() has no user after this.
The miss of the dispatcher is an indirect jump to bpf_func. FineIBT has no ENDBR there, with or without ITS. Jump to bpf_dispatcher_nop_func(), it goes through the preamble.
--- arch/x86/net/bpf_jit_comp.c | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-)
arch/x86/net/bpf_jit_comp.c +14 -3
@@ -683,6 +683,12 @@ static void __emit_indirect_jump(u8 **pprog, int reg, bool ereg) *pprog = prog; } +/* its_static_thunk() can give the one that completes the check of a hash */ +static u8 *its_thunk (int reg) +{ +return IS_ENABLED (CONFIG_MITIGATION_ITS ) ? __x86_indirect_its_thunk_array[reg] :NULL ; +} +static void emit_indirect_jump (u8 **pprog,int bpf_reg,u8 *ip) {u8 *prog = *pprog;
@@ -691,7 +697,7 @@ static void emit_indirect_jump(u8 **pprog, int bpf_reg, u8 *ip)if (cpu_feature_enabled (X86_FEATURE_INDIRECT_THUNK_ITS )) {OPTIMIZER_HIDE_VAR (reg); -emit_jump (&prog,its_static_thunk (reg +8 *ereg), ip); +emit_jump (&prog,its_thunk (reg +8 *ereg), ip); }else if (cpu_feature_enabled (X86_FEATURE_RETPOLINE_LFENCE )) {EMIT_LFENCE ();__emit_indirect_jump (&prog, reg, ereg);
@@ -732,7 +738,7 @@ static int emit_indirect_call(u8 **pprog, int bpf_reg, u8 *ip)if (cpu_feature_enabled (X86_FEATURE_INDIRECT_THUNK_ITS )) {OPTIMIZER_HIDE_VAR (reg); - err =emit_call (&prog,its_static_thunk (reg +8 *ereg), ip); + err =emit_call (&prog,its_thunk (reg +8 *ereg), ip); }else if (cpu_feature_enabled (X86_FEATURE_RETPOLINE_LFENCE )) {EMIT_LFENCE ();__emit_indirect_call (&prog, reg, ereg);
@@ -4675,6 +4681,7 @@ int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,static int emit_bpf_dispatcher (u8 **pprog,int a,int b,s64 *progs,u8 *image,u8 *buf) { +void *nop_func = bpf_dispatcher_nop_func;u8 *jg_reloc, *prog = *pprog;int pivot, err, jg_bytes =1 ;s64 jg_offset;
@@ -4694,7 +4701,11 @@ static int emit_bpf_dispatcher(u8 **pprog, int a, int b, s64 *progs, u8 *image,if (err)return err; -emit_indirect_jump (&prog,BPF_REG_3 /* R3 -> rdx */ , image + (prog - buf)); +/* With FineIBT there is no ENDBR at bpf_func, go through the preamble */ +OPTIMIZER_HIDE_VAR (nop_func); + err =emit_jump (&prog, nop_func, image + (prog - buf)); +if (err) +return err; *pprog = prog;return 0 ;
Signature · 1 line
2.55.0
PATCH 35/47 bpf, x86: Enforce alignment of atomics in arenas
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A program chooses the address of an atomic insn in an arena at run time, the verifier does not check it. A locked insn that crosses a cache line locks the bus, and with split_lock_detect it is fatal in the kernel.
Copy the low bits of the address to its top bits. A misaligned address is not canonical then, and the access goes the way of a fault in the
arena: the insn is skipped, a fetch gives 0, the report is in the stream of the program. That is what arm64 does after an alignment fault.
--- arch/x86/net/bpf_jit_comp.c | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-)
arch/x86/net/bpf_jit_comp.c +23 -2
@@ -1687,6 +1687,23 @@ static int emit_atomic_rmw_index(u8 **pprog, u32 atomic_op, u32 size,return 0 ; } +/* +* AUX_REG = dst_reg, with the low bits of dst_reg + off in the top bits. r12 + AUX_REG + off +* is not canonical when it's not aligned: the access faults, no split lock is taken. +*/ +static void emit_arena_align_check (u8 **pprog,const struct bpf_insn *insn,u32 dst_reg) +{ +int size =BPF_LDST_BYTES (insn); +u8 *prog = *pprog; + +/* lea r11, [dst_reg + off % size] */ +EMIT2 (add_2mod (0x48 , dst_reg,AUX_REG ),0x8D ); +emit_insn_suffix (&prog, dst_reg,AUX_REG , insn->off & (size -1 )); +emit_shift_imm (&prog,BPF_LSH ,AUX_REG ,64 -ilog2 (size), true); +emit_alu_reg (&prog,BPF_OR ,AUX_REG , dst_reg, true); + *pprog = prog; +} +static int emit_atomic_ld_st (struct bpf_verifier_env *env,u8 **pprog,struct bpf_insn *insn,u8 *ip,u32 dst_reg,u32 src_reg,bool accesses_stack_only)
@@ -1771,12 +1788,14 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg, branch_target = prog;/* Load old value */ +if (index_reg >=0 ) +emit_arena_align_check (&prog, insn, dst_reg);if (fault) fault[0 ] = prog;if (index_reg <0 )emit_ldx (&prog,BPF_SIZE (insn->code),BPF_REG_0 , dst_reg, insn->off);else -emit_ldx_index (&prog,BPF_SIZE (insn->code),BPF_REG_0 , dst_reg, +emit_ldx_index (&prog,BPF_SIZE (insn->code),BPF_REG_0 ,AUX_REG , index_reg, insn->off);/*
@@ -3409,6 +3428,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * }break ; } +if (!bpf_atomic_is_load_store (insn)) +emit_arena_align_check (&prog, insn, dst_reg); start_of_ldx = prog;if (bpf_atomic_is_load_store (insn))
@@ -3417,7 +3438,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int * src_reg, X86_REG_R12, insn->off); else err =emit_atomic_rmw_index (&prog, insn->imm,BPF_SIZE (insn->code), - dst_reg, src_reg,X86_REG_R12 , +AUX_REG , src_reg,X86_REG_R12 , insn->off);if (err)return err;
Signature · 1 line
2.55.0
PATCH 36/47 bpf, x86: Fix the range of BPF code that has a frame pointer
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The ORC unwinder trusts rbp between ksym.fp_start and ksym.fp_end. The JIT sets fp_end to an offset in the code of the exit insn, and fp_start counts the CFI preamble, which is in front of the symbol. The main program of a program with subprogs and trampolines of struct_ops get neither. The range ends at the epilogue, compilers put blocks behind it. So stack traces with BPF code in them are not reliable, and livepatch waits for tasks that sleep there.
Behind the prologue of a program only the return has no frame. Record its offset in fp_ret and take all the rest. Count from the start of the symbol, copy the offsets from func[0], and from a struct bpf_tramp_image that struct_ops passes for the time of the call.
--- arch/x86/net/bpf_jit_comp.c | 11 +++++------ include/linux/bpf.h | 5 +++-- kernel/bpf/bpf_struct_ops.c | 12 +++++++++--- kernel/bpf/core.c | 2 +- kernel/bpf/fixups.c | 3 +++ net/bpf/bpf_dummy_struct_ops.c | 2 +- 6 files changed, 22 insertions(+), 13 deletions(-)
arch/x86/net/bpf_jit_comp.c +5 -6
@@ -2600,7 +2600,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *bpf_prog_was_classic (bpf_prog), tail_call_reachable, bpf_is_subprog(bpf_prog), bpf_prog->aux->exception_cb); - bpf_prog->aux->ksym.fp_start = prog - temp; + bpf_prog->aux->ksym.fp_start = prog - temp -cfi_get_offset (); + bpf_prog->aux->ksym.fp_end =U32_MAX ;/* Exception callback will clobber callee regs for its own use, and * restore the original callee regs from main prog's stack frame.
@@ -3828,7 +3829,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *pop_r12 (&prog); }EMIT1 (0xC9 );/* leave */ - bpf_prog->aux->ksym.fp_end = prog - temp; + bpf_prog->aux->ksym.fp_ret = proglen + (prog - temp) -cfi_get_offset ();emit_return (&prog, image + addrs[i -1 ] + (prog - temp));break ;
@@ -4480,8 +4481,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im }EMIT1 (0x55 );/* push rbp */ EMIT3 (0x48 ,0x89 ,0xE5 );/* mov rbp, rsp */ -if (im) - im->ksym.fp_start = prog - (u8 *)rw_image; + im->ksym.fp_start = prog - (u8 *)rw_image;/* sub rsp, stack_size */ emit_sub_rsp (&prog, stack_size);
@@ -4622,8 +4622,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_imemit_ldx (&prog,BPF_DW ,BPF_REG_6 ,BPF_REG_FP , -rbx_off);EMIT1 (0xC9 );/* leave */ -if (im) - im->ksym.fp_end = prog - (u8 *)rw_image; + im->ksym.fp_end = prog - (u8 *)rw_image;if (flags &BPF_TRAMP_F_SKIP_FRAME ) {/* skip our return address and return to parent */
include/linux/bpf.h +3 -2
@@ -1426,6 +1426,7 @@ struct bpf_ksym {bool prog;u32 fp_start;u32 fp_end; +u32 fp_ret;/* a return in between, it has no frame */ };enum bpf_tramp_prog_type {
@@ -1470,7 +1471,7 @@ static inline void bpf_tramp_image_add_skip(struct bpf_tramp_image *im, struct b {struct bpf_tramp_skip *skip; -/* struct_ops trampolines and arch_bpf_trampoline_size() have no image */ +/* struct_ops trampolines and arch_bpf_trampoline_size() have none */ if (!im || !im->skips)return ; skip = &im->skips[im->nr_skips++];
@@ -2400,7 +2401,7 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,const struct btf_func_model *model, void *stub_func, void **image, u32 *image_off, - bool allow_alloc); + bool allow_alloc, struct bpf_ksym *ksym);void bpf_struct_ops_image_free (void *image);static inline bool bpf_try_module_get (const void *data,struct module *owner) {
kernel/bpf/bpf_struct_ops.c +9 -3
@@ -640,9 +640,10 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,const struct btf_func_model *model, void *stub_func, void **_image, u32 *_image_off, - bool allow_alloc) + bool allow_alloc, struct bpf_ksym *ksym) { u32 image_off = *_image_off, flags = BPF_TRAMP_F_INDIRECT; +struct bpf_tramp_image im = {};void *image = *_image;int size;
@@ -667,7 +668,7 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes, image_off =0 ; } - size =arch_prepare_bpf_trampoline (NULL , image + image_off, + size =arch_prepare_bpf_trampoline (&im, image + image_off, image + image_off + size, model, flags, tnodes, stub_func);if (size <=0 ) {
@@ -676,6 +677,10 @@ int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,return size ? : -EFAULT ; } +if (ksym) { + ksym->fp_start = im.ksym.fp_start; + ksym->fp_end = im.ksym.fp_end; + } *_image = image; *_image_off = image_off + size;return 0 ;
@@ -879,7 +884,8 @@ static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key, &st_ops->func_models[i], *(void **)(st_ops->cfi_stubs + moff), &image, &image_off, - st_map->image_pages_cnt < MAX_TRAMP_IMAGE_PAGES); + st_map->image_pages_cnt <MAX_TRAMP_IMAGE_PAGES , + ksym);if (err) goto reset_unlock;
kernel/bpf/core.c +1 -1
@@ -785,7 +785,7 @@ bool bpf_has_frame_pointer(unsigned long ip) offset = ip - ksym->start; -return offset >= ksym->fp_start && offset < ksym->fp_end; +return offset >= ksym->fp_start && offset < ksym->fp_end && offset != ksym->fp_ret; }const struct exception_table_entry *search_bpf_extables (unsigned long addr)
kernel/bpf/fixups.c +3 -0
@@ -1572,6 +1572,9 @@ static int jit_subprogs(struct bpf_verifier_env *env) prog->jited_len = func[0 ]->jited_len; prog->aux->extable = func[0 ]->aux->extable; prog->aux->num_exentries = func[0 ]->aux->num_exentries; + prog->aux->ksym.fp_start = func[0 ]->aux->ksym.fp_start; + prog->aux->ksym.fp_end = func[0 ]->aux->ksym.fp_end; + prog->aux->ksym.fp_ret = func[0 ]->aux->ksym.fp_ret; prog->aux->func = func; prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; prog->aux->real_func_cnt = env->subprog_cnt;
net/bpf/bpf_dummy_struct_ops.c +1 -1
@@ -179,7 +179,7 @@ int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr, &st_ops->func_models[op_idx], &dummy_ops_test_ret_function, &image, &image_off, - true); + true, NULL);if (err <0 ) goto out;
Signature · 1 line
2.55.0
PATCH 37/47 bpf, arm64: Restore the shadow call stack pointer after an exception
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
bpf_throw() does not return, its return address stays on the shadow call stack. The caller of the program takes it for its own. test_progs -t exceptions crashes the kernel with CONFIG_SHADOW_CALL_STACK:
Internal error: Oops - FPAC: 0000000072000000 [#1] SMP pc : bpf_test_run+0x410/0x968
JITed code puts nothing on the shadow call stack, and bpf_throw() skips only frames of JITed code. So that address is the only entry that is left behind. Pop it in the prologue of the exception callback.
--- arch/arm64/net/bpf_jit_comp.c | 7 +++++++ kernel/bpf/helpers.c | 1 + 2 files changed, 8 insertions(+)
arch/arm64/net/bpf_jit_comp.c +7 -0
@@ -15,6 +15,7 @@#include <linux/filter.h> #include <linux/memory.h> #include <linux/printk.h> +#include <linux/scs.h> #include <linux/slab.h> #include <asm/asm-extable.h>
@@ -600,6 +601,12 @@ static int build_prologue(struct jit_ctx *ctx, bool ebpf_from_cbpf)* 12 registers are on the stack */ emit (A64_SUB_I (1 ,A64_SP ,A64_FP ,96 ), ctx); +/* +* Pop the return address of bpf_throw() from the shadow call +* stack. The frames of the JIT put nothing there. +*/ +if (scs_is_enabled ()) +emit (A64_SUB_I (1 ,A64_R (18 ),A64_R (18 ),8 ), ctx);/* The callback may use its own BPF stack, set up fp for it. */ ctx->fp_used = true; }
kernel/bpf/helpers.c +1 -0
@@ -3474,6 +3474,7 @@ __bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie)WARN_ON_ONCE (!ctx.aux->exception_boundary);WARN_ON_ONCE (!ctx.bp);WARN_ON_ONCE (!ctx.cnt); +/* arm64 drops one entry of the shadow call stack, don't move the call to a callee */ ctx.aux->bpf_exception_cb (cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp,0 ,0 );WARN (1 ,"A call to BPF exception callback should never return\n" ); }
Signature · 1 line
2.55.0
PATCH 38/47 bpf: Clear the data that bpf_msg_push_data() adds
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The helper puts a new page into the message as the allocator gave it. Bytes that the program does not write can be read by it, and are sent to the peer. Allocate zeroed memory.
--- net/core/filter.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/filter.c +1 -1
@@ -2902,7 +2902,7 @@ BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,if (unlikely (copy + len < copy))return -EINVAL ; - page =alloc_pages (__GFP_NOWARN |GFP_ATOMIC | __GFP_COMP, + page =alloc_pages (__GFP_NOWARN |GFP_ATOMIC | __GFP_COMP | __GFP_ZERO,get_order (copy + len));if (unlikely (!page))return -ENOMEM ;
Signature · 1 line
2.55.0
PATCH 39/47 bpf: Fail loads from a network header that was not set
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
skb->network_header is 0 until something sets it. Loads at SKF_NET_OFF and bpf_skb_load_bytes_relative() start at skb->head then, and read headroom that nobody has written. qrtr and AF_XDP in copy mode make such skbs.
Fail the load, like for the MAC header. A network header at skb->head counts as set when skb->data or the MAC header is there too. CAN and 6LoWPAN make such skbs.
--- include/linux/filter.h | 9 +++++++++ kernel/bpf/core.c | 2 ++ net/core/filter.c | 5 ++++- 3 files changed, 15 insertions(+), 1 deletion(-)
include/linux/filter.h +9 -0
@@ -1055,6 +1055,15 @@ static inline void bpf_restore_data_end( cb->data_end = saved_data_end; } +/* +* If nothing has set the header, it points to headroom that was not written. +* The packet starts at skb->head when skb->data or the MAC header is there. +*/ +static inline bool bpf_skb_has_network_header (const struct sk_buff *skb) +{ +return skb->network_header || !skb->mac_header || !skb_headroom (skb); +} +static inline u8 *bpf_skb_cb (const struct sk_buff *skb) {/* eBPF programs may read/write skb->cb[] area to transfer meta
kernel/bpf/core.c +2 -0
@@ -83,6 +83,8 @@ void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsu8 *ptr =NULL ;if (k >=SKF_NET_OFF ) { +if (unlikely (!bpf_skb_has_network_header (skb))) +return NULL ; ptr =skb_network_header (skb) + k -SKF_NET_OFF ; }else if (k >=SKF_LL_OFF ) {if (unlikely (!skb_mac_header_was_set (skb)))
net/core/filter.c +4 -1
@@ -232,7 +232,8 @@ static int bpf_skb_load_helper_convert_offset(const struct sk_buff *skb, int offreturn offset;if (offset >=SKF_NET_OFF ) -return offset -SKF_NET_OFF +skb_network_offset (skb); +return bpf_skb_has_network_header (skb) ? + offset -SKF_NET_OFF +skb_network_offset (skb) :INT_MIN ;if (offset >=SKF_LL_OFF &&skb_mac_header_was_set (skb))return offset -SKF_LL_OFF +skb_mac_offset (skb);
@@ -1862,6 +1863,8 @@ BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb, start =skb_mac_header (skb);break ;case BPF_HDR_START_NET : +if (unlikely (!bpf_skb_has_network_header (skb))) + goto err_clear; start =skb_network_header (skb);break ;default :
Signature · 1 line
2.55.0
PATCH 40/47 bpf: Fix slices behind the end of an XDP packet
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
A dynptr keeps the size that the packet had at bpf_dynptr_from_xdp(). When the packet has shrunk since, bpf_dynptr_slice() takes the error of bpf_xdp_pointer() for "not linear" and copies from the frags. A linear packet has none, its skb_shared_info is what the buffer held before.
Return NULL. Don't look at the frags of a linear packet for a length of 0 at its end either.
--- kernel/bpf/helpers.c | 4 +++- net/core/filter.c | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-)
kernel/bpf/helpers.c +3 -1
@@ -13,6 +13,7 @@#include <linux/sched.h> #include <linux/uidgid.h> #include <linux/filter.h> +#include <net/xdp.h> #include <linux/ctype.h> #include <linux/jiffies.h> #include <linux/pid_namespace.h>
@@ -3144,7 +3145,8 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u64 offset,if (!IS_ERR_OR_NULL (xdp_ptr))return xdp_ptr; -if (!buffer__nullable) +/* the packet may be shorter than it was for bpf_dynptr_from_xdp() */ +if (!buffer__nullable || ptr->offset + offset + len >xdp_get_buff_len (ptr->data))return NULL ;bpf_xdp_copy_buf (ptr->data, ptr->offset + offset, buffer__nullable, len, false);return buffer__nullable;
net/core/filter.c +1 -1
@@ -4326,7 +4326,7 @@ void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)if (unlikely (offset + len >xdp_get_buff_len (xdp)))return ERR_PTR (-EINVAL ); -if (likely (offset < size))/* linear area */ +if (likely (offset < size || !xdp_buff_has_frags (xdp)))/* linear area */ goto out; sinfo =xdp_get_shared_info_from_buff (xdp);
Signature · 1 line
2.55.0
PATCH 41/47 bpf: Clear family and port of a short address for cgroup sockaddr hooks
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
recvmsg() from a unix socket that has no name leaves the buffer of the address as it is, and that is on the stack of the kernel. The program reads user_family and user_port whatever the length is. bpf_sock_addr_set_sun_path() sends the family to user space.
Clear the bytes from the length up to 4. Write AF_UNIX next to the path in the kfunc.
--- kernel/bpf/cgroup.c | 4 ++++ net/core/filter.c | 1 + 2 files changed, 5 insertions(+)
kernel/bpf/cgroup.c +4 -0
@@ -2010,6 +2010,10 @@ int __cgroup_bpf_run_filter_sock_addr(struct sock *sk, ctx.uaddrlen =0 ; }else { ctx.uaddrlen = *uaddrlen; +/* Programs read the family and the port also of a short address. */ + if (ctx.uaddrlen < offsetofend(struct sockaddr_in, sin_port)) +memset ((void *)uaddr + ctx.uaddrlen,0 , + offsetofend(struct sockaddr_in, sin_port) - ctx.uaddrlen); } cgrp =sock_cgroup_ptr (&sk->sk_cgrp_data);
net/core/filter.c +1 -0
@@ -12633,6 +12633,7 @@ __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern,return -EINVAL ; un = (struct sockaddr_un *)sa_kern->uaddr; + un->sun_family =AF_UNIX ;memcpy (un->sun_path, sun_path, sun_path__sz); sa_kern->uaddrlen = offsetof(struct sockaddr_un , sun_path) + sun_path__sz;
Signature · 1 line
2.55.0
PATCH 42/47 bpf: Take a neighbour of the L3 master in bpf_redirect_neigh()
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
bpf_redirect_neigh() takes the neighbour from the route, the skb gets the device that the program has named. They are not always the same for IPv4, and the queue of a neighbour is purged with its own device only.
When a L3 master was named take a neighbour of that device, as IPv6 does. Its driver drops the header and routes the packet, one entry does for all.
--- net/core/filter.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
net/core/filter.c +5 -1
@@ -2367,7 +2367,11 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb, }rcu_read_lock (); -if (!nh) { +if (!nh &&netif_is_l3_master (dev)) { +/* The route leads to another device, this one looks it up again */ +skb_dst_drop (skb); + neigh =ip_neigh_gw4 (dev,htonl (INADDR_ANY )); + }else if (!nh) {struct rtable *rt =skb_rtable (skb); neigh =ip_neigh_for_gw (rt, skb, &is_v6gw);
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 42/47] bpf: Take a neighbour of the L3 master in bpf_redirect_neigh()
TL;DR: Commit message only: the Fixes: tag may point at the wrong commit (ba452c9e996d); the review asks whether it should be b4ab31414970, which added bpf_out_neigh_v4().
Quoted 1 line
bpf: Take a neighbour of the L3 master in
bpf_redirect_neigh()
TL;DR: Commit message only: the Fixes: tag may point at the wrong commit (ba452c9e996d); the review asks whether it should be b4ab31414970, which added bpf_out_neigh_v4().
Quoted 10 lines
bpf: Take a neighbour of the L3 master in
bpf_redirect_neigh()
bpf_redirect_neigh()takes the neighbour from the route, the skb gets the device that the program has named. They are not always the same for IPv4, and the queue of a neighbour is purged with its own device only. When a L3 master was named take a neighbour of that device, as IPv6 does. Its driver drops the header and routes the packet, one entry does for all.Fixes ba452c9e996d ("bpf: Fix bpf_redirect_neigh helper api to support supplying nexthop")Signed-off-by Alexei Starovoitov <[email protected]>
The Fixes: tag points to ba452c9e996d, but that commit only added the nexthop-parameter branches (nh != NULL) and left the !nh path, which calls ip_neigh_for_gw(rt, ...), unchanged. The behaviour fixed here, where the neighbour is taken from the route while skb->dev is the L3 master named by the program, was introduced when bpf_out_neigh_v4() was added. Should the tag be:
---
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/45542192835
[email protected]
AI reviewRe: [PATCH bpf 42/47] bpf: Take a neighbour of the L3 master in bpf_redirect_neigh()
In reply to Alexei StarovoitovThank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] bpf: neigh->dev and skb->dev mismatch in bpf_out_neigh_v4() on non-L3-master --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] bpf: neigh->dev and skb->dev mismatch in bpf_out_neigh_v4() on non-L3-master
--
commit 14e765ab115457bb4915055efa26bf5101b3a1a3
Author: Alexei Starovoitov <[email protected]>
bpf: Take a neighbour of the L3 master in bpf_redirect_neigh()
This commit updates bpf_out_neigh_v4() to drop the skb dst and look up a neighbour on the target device itself when no nexthop is supplied and the target device is an L3 master.
Quoted 7 lines
net/core/filter.c +0
-0@@ -2367,7 +2367,11 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb, }
net/core/filter.c static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb, · line 2377
Quoted 10 lines
net/core/filter.c +5
-1rcu_read_lock (); -if (!nh) { +if (!nh &&netif_is_l3_master (dev)) { +/* The route leads to another device, this one looks it up again */ +skb_dst_drop (skb); + neigh =ip_neigh_gw4 (dev,htonl (INADDR_ANY )); + }else if (!nh) {struct rtable *rt =skb_rtable (skb); neigh =ip_neigh_for_gw (rt, skb, &is_v6gw);
[Severity: High]
Can rt->dst.dev still differ from dev in the "else if (!nh)" branch when dev is not an L3 master?
__bpf_redirect_neigh_v4() calls ip_route_output_flow() and accepts both RTN_UNICAST and RTN_LOCAL routes without checking that rt->dst.dev == dev. When ip4h->daddr is a local address (or 0.0.0.0), ip_route_output_key_hash_rcu() produces an RTN_LOCAL route whose rt->dst.dev is net->loopback_dev (or the VRF master device) rather than dev; outbound tunnel-mode XFRM policies matched via xfrm_lookup_route() can likewise switch rt->dst.dev to a different outer egress device.
In that case skb->dev is set to dev while ip_neigh_for_gw() looks up or creates a neighbour on rt->dst.dev. If that neighbour is unresolved, the skb is queued on rt->dst.dev's arp_queue with skb->dev pointing to dev, so unregistering dev will not purge it via neigh_ifdown() and leaves a dangling skb->dev pointer (use-after-free). In addition, headroom was only validated against dev, so if dev has no header_ops while rt->dst.dev uses a cached hardware header (such as loopback_dev or a VRF master), neigh_hh_output() can hit WARN_ON_ONCE(skb_headroom(skb) < hh_alen).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=42
PATCH 43/47 bpf: Keep the MAC header in bpf_skb_change_tail()
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The least length of the skb is the offset of the transport header when it's set, also when that is below the offset of the network header. Callers of tc programs count on a skb that is not shorter than mac_len.
Take the bigger one of the two offsets.
--- net/core/filter.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/filter.c +1 -1
@@ -4044,7 +4044,7 @@ static u32 __bpf_skb_min_len(const struct sk_buff *skb)if (skb_transport_header_was_set (skb)) { offset =skb_transport_offset (skb);if (offset >0 ) - min_len = offset; + min_len =max_t (u32, min_len, offset); }return min_len; }
Signature · 1 line
2.55.0
PATCH 44/47 bpf, sockmap: Keep the parser and sk_data_ready in sync
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
sk_psock_strp_data_ready() takes the psock that the socket has at the call. An update from a program does not wait for the owner of the socket, so that is not always the psock that has set the callback, and it may have no parser. strp_data_ready() dereferences a NULL strp->sk then. Look at SK_PSOCK_RX_STRP_ENABLED, it is set under sk_callback_lock. The event is dropped, as it is when the socket has no psock.
A socket can be in a map with a verdict program and not have it, the program was attached after the update. Another map can start the parser then. The delete from the first map restores sk_data_ready and nobody stops the parser:
WARNING: net/strparser/strparser.c:451 at strp_done+0xef/0x130
Stop the parser when its callback goes away. The psock can outlive the stop, and a later update must not run strp_init() on works that are still pending. Start the stopped parser again instead.
--- net/core/skmsg.c | 12 +++++++++--- net/core/sock_map.c | 3 ++- 2 files changed, 11 insertions(+), 4 deletions(-)
net/core/skmsg.c +9 -3
@@ -1149,7 +1149,9 @@ static void sk_psock_strp_data_ready(struct sock *sk) psock =sk_psock (sk);if (likely (psock)) {read_lock_bh (&sk->sk_callback_lock); -strp_data_ready (&psock->strp); +/* This psock may be not the one that has set the callback */ +if (likely (sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED ))) +strp_data_ready (&psock->strp);read_unlock_bh (&sk->sk_callback_lock); }rcu_read_unlock ();
@@ -1157,7 +1159,7 @@ static void sk_psock_strp_data_ready(struct sock *sk)int sk_psock_init_strp (struct sock *sk,struct sk_psock *psock) { -int ret; +int ret =0 ;static const struct strp_callbacks cb = { .rcv_msg = sk_psock_strp_read,
@@ -1165,7 +1167,11 @@ int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) .parse_msg = sk_psock_strp_parse, }; - ret =strp_init (&psock->strp, sk, &cb); +/* A stopped parser keeps its works and its skb until strp_done() */ +if (sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED )) + psock->strp.stopped =0 ; +else + ret =strp_init (&psock->strp, sk, &cb);if (!ret)sk_psock_set_state (psock,SK_PSOCK_RX_STRP_ENABLED );
net/core/sock_map.c +2 -1
@@ -169,7 +169,8 @@ static void sock_map_del_link(struct sock *sk,write_lock_bh (&sk->sk_callback_lock);if (psock->saved_data_ready) { -if (strp_stop) +/* The parser can be from another map, it loses sk_data_ready too */ +if (strp_stop || psock->progs.stream_parser)sk_psock_stop_strp (sk, psock);if (verdict_stop)sk_psock_stop_verdict (sk, psock);
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 44/47] bpf, sockmap: Keep the parser and sk_data_ready in sync
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] bpf, sockmap: psock->copied_seq rewind on parser restart in sk_psock_init_strp() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] bpf, sockmap: psock->copied_seq rewind on parser restart in sk_psock_init_strp()
--
commit 5ffc4095c0078d67e56f16b091670687eaa8b6e3
Author: Alexei Starovoitov <[email protected]>
bpf, sockmap: Keep the parser and sk_data_ready in sync
This commit checks SK_PSOCK_RX_STRP_ENABLED before calling strp_data_ready(), stops the stream parser when sk_data_ready is restored on sockmap deletion, and restarts an already-initialized parser instead of calling strp_init() again.
Quoted 4 lines
net/core/skmsg.c +0
-0
[ ... ]
Quoted 12 lines
net/core/skmsg.c +1
-1@@ -1157,7 +1159,7 @@ static void sk_psock_strp_data_ready(struct sock *sk)int sk_psock_init_strp (struct sock *sk,struct sk_psock *psock) { -int ret; +int ret =0 ;static const struct strp_callbacks cb = { .rcv_msg = sk_psock_strp_read,@@ -1165,7 +1167,11 @@ int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) .parse_msg = sk_psock_strp_parse, };
net/core/skmsg.c int sk_psock_init_strp(struct sock *sk, struct sk_psock *psock) · line 1177
Quoted 10 lines
net/core/skmsg.c +5
-1- ret =strp_init (&psock->strp, sk, &cb); +/* A stopped parser keeps its works and its skb until strp_done() */ +if (sk_psock_test_state (psock,SK_PSOCK_RX_STRP_ENABLED )) + psock->strp.stopped =0 ; +else + ret =strp_init (&psock->strp, sk, &cb);if (!ret)sk_psock_set_state (psock,SK_PSOCK_RX_STRP_ENABLED );
[Severity: High]
Does restarting a stopped parser here rewind psock->copied_seq and cause incoming TCP segments to be silently dropped?
Just below this hunk, sk_psock_init_strp() runs:
net/core/skmsg.c:sk_psock_init_strp() {
...
if (sk_is_tcp(sk)) {
psock->strp.cb.read_sock = tcp_bpf_strp_read_sock;
psock->copied_seq = tcp_sk(sk)->copied_seq;
}
...
}When tcp_bpf_strp_read_sock() parses skbs and the verdict program returns SK_PASS, the skbs are eaten from sk->sk_receive_queue and psock->copied_seq advances, while tcp_sk(sk)->copied_seq stays behind by psock->ingress_bytes until userspace reads from psock->ingress_msg.
If the parser is stopped and restarted while unread SK_PASS data sits in psock->ingress_msg, resetting psock->copied_seq to tcp_sk(sk)->copied_seq rewinds it below TCP_SKB_CB(skb)->seq of the next arriving segment in sk->sk_receive_queue. On the next read, tcp_recv_skb() computes offset = seq - TCP_SKB_CB(skb)->seq, which underflows u32 to a value >= skb->len and discards the unread skb via tcp_eat_recv_skb().
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=44
PATCH 45/47 bpf, sockmap: Hold the psock of the work in sk_psock_backlog()
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
The socket can leave its map and come back after the test of SK_PSOCK_TX_ENABLED. sk_psock_get() takes a reference to the new psock then, and the work puts the old one that has none left. The new one and its socket are never freed.
Take the reference that is put.
--- net/core/skmsg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/skmsg.c +1 -1
@@ -694,7 +694,7 @@ static void sk_psock_backlog(struct work_struct *work)* before sk_socket freed. If refcnt increment fails, it indicates * sock_map_close() completed with sk_socket potentially already freed. */ -if (!sk_psock_get (psock->sk)) +if (!refcount_inc_not_zero (&psock->refcnt))return ;mutex_lock (&psock->work_mutex);while ((skb =skb_peek (&psock->ingress_skb))) {
Signature · 1 line
2.55.0
PATCH 46/47 libbpf: Fix struct_ops members 59-61 and optional struct_ops maps
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
expected_attach_type of a struct_ops program is the index of the member. For members 59, 60 and 61 it is equal to an attach type of tracing multi, and attach_btf_obj_fd is overwritten. The load fails when the struct is in a module. Look at the type of the program too.
Only the first map of SEC("?.struct_ops") or SEC("?.struct_ops.link") is not created by default. The '?' is skipped in the loop over the variables, so the next ones do not see it. They are created, and their programs are loaded. Look at it once.
--- tools/lib/bpf/libbpf.c | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-)
tools/lib/bpf/libbpf.c +11 -8
@@ -1454,6 +1454,7 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,__s32 type_id, datasec_id;const struct btf *btf;struct bpf_map *map; +bool optional;__u32 i;if (shndx ==-1 )
@@ -1468,6 +1469,14 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,return -EINVAL ; } +/* +* Follow same convention as for programs autoload: +* SEC("?.struct_ops") means map is not created by default. +*/ + optional = sec_name[0 ] =='?' ; +/* from now on forget there was ? in section name */ + sec_name += optional; + datasec =btf__type_by_id (btf, datasec_id); vsi =btf_var_secinfos (datasec);for (i =0 ; i <btf_vlen (datasec); i++, vsi++) {
@@ -1503,14 +1512,8 @@ static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,return -ENOMEM ; map->btf_value_type_id = type_id; -/* Follow same convention as for programs autoload: -* SEC("?.struct_ops") means map is not created by default. -*/ -if (sec_name[0 ] =='?' ) { +if (optional) map->autocreate = false; -/* from now on forget there was ? in section name */ - sec_name++; - } map->def.type =BPF_MAP_TYPE_STRUCT_OPS ; map->def.key_size =sizeof (int );
@@ -8407,7 +8410,7 @@ static int libbpf_prepare_prog_load(struct bpf_program *prog, opts->attach_btf_id = btf_type_id; } -if (is_tracing_multi (prog->expected_attach_type)) { +if (prog->type ==BPF_PROG_TYPE_TRACING &&is_tracing_multi (prog->expected_attach_type)) {int err, btf_obj_fd =0 ; err =tracing_multi_mod_fd (prog, &btf_obj_fd);
Signature · 1 line
2.55.0
PATCH 47/47 bpf: Check the type of R0 at the exit of a struct_ops program
In reply to Alexei StarovoitovFrom: Alexei Starovoitov <[email protected]>
check_return_code() takes reg->btf for valid when it is not NULL. The field is in a union, so for other types of registers it holds something else, and the verifier follows that as a struct btf.
Look at it only when the register is PTR_TO_BTF_ID.
--- kernel/bpf/verifier.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +2 -1
@@ -19608,7 +19608,8 @@ static int check_return_code(struct bpf_verifier_env *env, int regno, const char* matches the operator's return type and is in its unmodified * form. A scalar zero (i.e., a null pointer) is also allowed. */ - reg_type = reg->btf ?btf_type_by_id (reg->btf, reg->btf_id) :NULL ; + reg_type =base_type (reg->type) ==PTR_TO_BTF_ID ? +btf_type_by_id (reg->btf, reg->btf_id) :NULL ; ret_type =btf_type_resolve_ptr (prog->aux->attach_btf, prog->aux->attach_func_proto->type,NULL );
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH bpf 47/47] bpf: Check the type of R0 at the exit of a struct_ops program
TL;DR: Patch looks correct, but a pre-existing gap may remain: a void or int-returning struct_ops program might exit with a referenced R0 and pass verification, leaking a cgroup or skb reference.
Quoted 1 line
bpf: Check the type of R0 at the exit of a
struct_opsprogram
TL;DR: Patch looks correct, but a pre-existing gap may remain: a void or int-returning struct_ops program might exit with a referenced R0 and pass verification, leaking a cgroup or skb reference.
Quoted 5 lines
kernel/bpf/verifier.c +0
-0
kernel/bpf/verifier.c static int check_return_code(struct bpf_verifier_env *env, int regno, const char · line 19615
Quoted 9 lines
kernel/bpf/verifier.c +2
-1@@ -19608,7 +19608,8 @@ static int check_return_code(struct bpf_verifier_env *env, int regno, const char* matches the operator's return type and is in its unmodified * form. A scalar zero (i.e., a null pointer) is also allowed. */ - reg_type = reg->btf ?btf_type_by_id (reg->btf, reg->btf_id) :NULL ; + reg_type =base_type (reg->type) ==PTR_TO_BTF_ID ? +btf_type_by_id (reg->btf, reg->btf_id) :NULL ; ret_type =btf_type_resolve_ptr (prog->aux->attach_btf, prog->aux->attach_func_proto->type,NULL );
This change itself looks correct. The following problem predates this patch (it comes from 8d9f547f74c7), but it is in the same R0 check and this patch does not close it.
check_reference_leak() lets a struct_ops program exit with a REF_TYPE_PTR reference whose id equals R0's id, without looking at the operator's return type:
if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
reg->id == state->refs[i].id)
continue;That exemption relies on check_return_code() verifying that R0 is a referenced kptr matching the operator's return type. Two paths in check_return_code() return 0 without that check.
First, a void operator:
/* LSM and struct_ops func-ptr's return type could be "void" */
if (!frame->in_async_callback_fn && program_returns_void(env))
return 0;Second, an operator returning a non-pointer such as int or u32, where ret_type is NULL. is_pointer_value() returns false for every struct_ops program because is_perfmon_prog_type() includes BPF_PROG_TYPE_STRUCT_OPS, so the function reaches:
if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type)
return 0;Can a tcp_congestion_ops .init program (void) then do this and pass verification?
cg = bpf_cgroup_from_id(1);
if (!cg)
return;
r0 = cg;
exitbpf_cgroup_from_id() is KF_ACQUIRE|KF_RET_NULL in generic_kfunc_set, which is registered for BPF_PROG_TYPE_STRUCT_OPS, so a cgroup reference would be leaked on every call. Similarly, an int-returning op with a __ref argument (such as the skb in Qdisc enqueue) that sets r0 = skb looks like it would be accepted, with the skb neither freed nor enqueued.
Should check_reference_leak() exempt R0 only when the operator returns a struct pointer? Alternatively, could check_return_code() reject a referenced R0 when ret_type is NULL or the operator returns void?
---
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/45542192835
This series was applied to bpf/bpf.git (master) by Alexei Starovoitov <[email protected]>:
Hello:
This series was applied to bpf/bpf.git (master)
by Alexei Starovoitov <[email protected]>:
Quoted 24 lines · On Wed, 25 Nov 2026 03:28:51 +0000 you wrote:
From: Alexei Starovoitov <[email protected]>
These patches fix bugs in BPF:
patches area ------- ---------------------------------------------------------------- 01-04 what the verifier trusts: pointers, attach types, ranges, ids 05-08 extensions and tail calls: they run in the hook of another prog 09 struct_ops: the struct of a prog 10 bpffs: delegate options 11-12 NULL in tracepoints and helpers 13-15 bpf_throw(): tracers, KASAN, symbols, line info 16 XDP redirect in async callbacks 17-18 checks at attach and load: cgroup links, signed programs 19-20 bpf_lock, dumps of the stack 21-22 arena: the length of mmap(), TLB 23-24 prints of BTF enums, the result of bpf_res_spin_lock() 25-33 kernel addresses and tasks: CAP_BPF is not enough 34-37 x86 and arm64 JIT 38-43 skb, XDP, sk_msg and sockaddr helpers 44-45 sockmap 46 libbpf 47 struct_ops: the type of r0 at exit
Quoted 1 line
[...]
Here is the summary with links:
- [bpf,01/47] bpf: Do not trust pointers in flexible arrays
https://git.kernel.org/bpf/bpf/c/2acad73b68ca - [bpf,02/47] bpf: Look at the type of a program next to expected_attach_type https://git.kernel.org/bpf/bpf/c/e74ff9b13b44 - [bpf,03/47] bpf: Do not take bpf_get_retval() of struct bpf_tcp_ops for an errno https://git.kernel.org/bpf/bpf/c/7ee82af6e463 - [bpf,04/47] bpf: Do not allow bpf_d_path() by an id of another BTF https://git.kernel.org/bpf/bpf/c/1139c7d8ffcd - [bpf,05/47] bpf: Check that an extension fits the hook of its target https://git.kernel.org/bpf/bpf/c/f44d0e6a1d68 - [bpf,06/47] bpf: Take the attach type of the target for tail calls of an extension https://git.kernel.org/bpf/bpf/c/3d6d222bb979 - [bpf,07/47] bpf: Compare what a hook tells next to its prototype at tail calls https://git.kernel.org/bpf/bpf/c/98ff9cff0b94 - [bpf,08/47] bpf: Reserve cookie and ip in the trampoline for tail calls https://git.kernel.org/bpf/bpf/c/bf675c921655 - [bpf,09/47] bpf: Check that a program and a struct_ops map are for the same struct https://git.kernel.org/bpf/bpf/c/80184a7381c1 - [bpf,10/47] bpf: Keep the names in front of a number in delegate options https://git.kernel.org/bpf/bpf/c/4151f3558d6e - [bpf,11/47] bpf: Do not trust the neighbour of tp_btf/neigh_create https://git.kernel.org/bpf/bpf/c/2c517088d2ef - [bpf,12/47] bpf: Check for NULL in helpers that take a kernel pointer https://git.kernel.org/bpf/bpf/c/a6de3c4be04d - [bpf,13/47] bpf: Leave nothing behind in the frame of bpf_throw() https://git.kernel.org/bpf/bpf/c/86cedb416c46 - [bpf,14/47] bpf: Add the symbol of a prog before its id https://git.kernel.org/bpf/bpf/c/f7a40c2de8d4 - [bpf,15/47] bpf: Do not fill jited line info for a hidden subprog https://git.kernel.org/bpf/bpf/c/2f2b119ea30d - [bpf,16/47] bpf: Fix NULL dereference in XDP redirect from async callbacks https://git.kernel.org/bpf/bpf/c/f28ed533106b - [bpf,17/47] bpf: Check the attach type when a cgroup link gets another program https://git.kernel.org/bpf/bpf/c/a5e757f6cb34 - [bpf,18/47] bpf: Refuse metadata maps of signed programs that can be mapped writable https://git.kernel.org/bpf/bpf/c/c66c8adf3226 - [bpf,19/47] bpf: Take bpf_lock with interrupts disabled https://git.kernel.org/bpf/bpf/c/2c00b6b35af0 - [bpf,20/47] bpf: Bound the time that dumps of the stack take https://git.kernel.org/bpf/bpf/c/a70da21f98e0 - [bpf,21/47] bpf: Refuse mmap() of a part of an arena https://git.kernel.org/bpf/bpf/c/0cd1f2029b1b - [bpf,22/47] bpf: Flush TLB when a page of arena replaces the scratch page https://git.kernel.org/bpf/bpf/c/16829046f0a0 - [bpf,23/47] bpf: Fix reads past an enum in prints of BTF data https://git.kernel.org/bpf/bpf/c/6c8d5a113c23 - [bpf,24/47] bpf: Give the error of bpf_res_spin_lock() a 32-bit range https://git.kernel.org/bpf/bpf/c/703826e497ff - [bpf,25/47] bpf: Give syscall programs without CAP_PERFMON the base helpers only https://git.kernel.org/bpf/bpf/c/2ff55b023f63 - [bpf,26/47] bpf: Require CAP_PERFMON for kfuncs that leak pointers or touch tasks https://git.kernel.org/bpf/bpf/c/3e03955a6518 - [bpf,27/47] bpf: Require CAP_PERFMON to read streams https://git.kernel.org/bpf/bpf/c/54b59a467bc7 - [bpf,28/47] bpf: Limit reads of variables of the kernel https://git.kernel.org/bpf/bpf/c/419c69483a62 - [bpf,29/47] bpf: Require CAP_PERFMON for dumps of xlated insns https://git.kernel.org/bpf/bpf/c/b8aa487429d4 - [bpf,30/47] bpf: Zero bpf_list_head in copies of map values https://git.kernel.org/bpf/bpf/c/8252c3517f95 - [bpf,31/47] bpf: Require CAP_PERFMON to read pinned maps with special fields https://git.kernel.org/bpf/bpf/c/398557b30b9c - [bpf,32/47] bpf: Require CAP_PERFMON to pass values of insn_array as memory https://git.kernel.org/bpf/bpf/c/5fec973f49da - [bpf,33/47] bpf: Require CAP_PERFMON for the dump of all storages of sockets https://git.kernel.org/bpf/bpf/c/f9e4fda5eb35 - [bpf,34/47] bpf, x86: Do not use the paranoid ITS thunk https://git.kernel.org/bpf/bpf/c/9bc9dab41113 - [bpf,35/47] bpf, x86: Enforce alignment of atomics in arenas https://git.kernel.org/bpf/bpf/c/62a99ab25c91 - [bpf,36/47] bpf, x86: Fix the range of BPF code that has a frame pointer https://git.kernel.org/bpf/bpf/c/1c34522e8b78 - [bpf,37/47] bpf, arm64: Restore the shadow call stack pointer after an exception https://git.kernel.org/bpf/bpf/c/918bea2c6b68 - [bpf,38/47] bpf: Clear the data that bpf_msg_push_data() adds https://git.kernel.org/bpf/bpf/c/401fce9f48b1 - [bpf,39/47] bpf: Fail loads from a network header that was not set https://git.kernel.org/bpf/bpf/c/766907cdaeef - [bpf,40/47] bpf: Fix slices behind the end of an XDP packet https://git.kernel.org/bpf/bpf/c/2fc7a1733992 - [bpf,41/47] bpf: Clear family and port of a short address for cgroup sockaddr hooks https://git.kernel.org/bpf/bpf/c/2abc088aae54 - [bpf,42/47] bpf: Take a neighbour of the L3 master in bpf_redirect_neigh() https://git.kernel.org/bpf/bpf/c/c1b5decc7314 - [bpf,43/47] bpf: Keep the MAC header in bpf_skb_change_tail() https://git.kernel.org/bpf/bpf/c/28ffeb9cb972 - [bpf,44/47] bpf, sockmap: Keep the parser and sk_data_ready in sync https://git.kernel.org/bpf/bpf/c/b3a433f20f0a - [bpf,45/47] bpf, sockmap: Hold the psock of the work in sk_psock_backlog() https://git.kernel.org/bpf/bpf/c/9abfa0ad4f76 - [bpf,46/47] libbpf: Fix struct_ops members 59-61 and optional struct_ops maps https://git.kernel.org/bpf/bpf/c/434ea9c5125a - [bpf,47/47] bpf: Check the type of R0 at the exit of a struct_ops program https://git.kernel.org/bpf/bpf/c/65e362827a6e
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html