Skip to contentSkip to conversation

mptcp: bpf: fix NULL deref and UAF in bpf_mptcp_sock_from_subflow()

PATCH Superseded Kalpan Jani 3 participants 3 messages Nov 23 – Nov 24

Subsystems (8)
Networking BPF Tracing BPF core +4 more subsystems

v7 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

PATCH v7 1/1 mptcp: bpf: fix NULL deref and UAF in bpf_mptcp_sock_from_subflow()

bpf_mptcp_sock_from_subflow() is reachable from BPF programs via bpf_skc_to_mptcp_sock() on an arbitrary socket, without the subflow socket lock held. It assumes sk_is_mptcp(sk) implies a valid subflow context whose ->conn points to a live parent mptcp_sock. That invariant does not hold in three windows:

- Fallback: subflow_ulp_fallback() clears icsk_ulp_data via rcu_assign_pointer(..., NULL) before clearing tcp_sk(sk)->is_mptcp, so a concurrent reader can observe is_mptcp == 1 with a NULL context.

- Init: subflow_ulp_init() sets is_mptcp = 1 while ->conn is still NULL; ->conn is only assigned later in subflow_syn_recv_sock() or mptcp_subflow_create_socket(). On CONFIG_DEBUG_NET, mptcp_sk() dereferences its argument in a WARN_ON(), so mptcp_sk(NULL) faults.

- Teardown: subflow_ulp_release() drops the subflow-owned parent reference without clearing ->conn. A lockless reader can therefore access a parent socket after its reference has been dropped.

Load the context with rcu_dereference_check() and the parent socket with smp_load_acquire(). Publish ->conn with smp_store_release() in the MP_CAPABLE, MP_JOIN and outgoing subflow paths. Clear ->conn with a release store before dropping the subflow-owned reference.

Give the parent msk RCU-grace lifetime by setting SOCK_RCU_FREE in the shared __mptcp_init_sock(), covering both active and passive paths, and dropping the reset in mptcp_sk_clone_init(). This ensures a reader that obtains the parent under the applicable RCU protection does not access freed memory.

Keep bpf_skc_to_mptcp_sock() available to non-sleepable tracing programs for compatibility, while rejecting sleepable tracing programs because classic RCU does not protect the parent socket through sleepable execution.

Fixes 3bc253c2e652 ("bpf: Add bpf_skc_to_mptcp_sock_proto")

---
Changes since v6:
- Add needs_rcu metadata to struct bpf_func_proto to identify helpers requiring RCU protection.
- Validate RCU protection in the verifier for RCU-dependent helpers called from sleepable BPF contexts.
- Mark bpf_skc_to_mptcp_sock_proto as requiring RCU protection.
- Set SOCK_RCU_FREE on subflow sockets in subflow_create_ctx() to defer socket destruction until after an RCU grace period.

v6: https://lore.kernel.org/all/[email protected]/

---
 include/linux/bpf.h      |  1 +
 kernel/bpf/verifier.c    |  8 ++++++++
 kernel/trace/bpf_trace.c |  2 +-
 net/core/filter.c        |  1 +
 net/mptcp/bpf.c          | 15 +++++++++++++--
 net/mptcp/protocol.c     |  6 +++++-
 net/mptcp/subflow.c      | 31 ++++++++++++++++++++++++-------
 7 files changed, 53 insertions(+), 11 deletions(-)
include/linux/bpf.h +1 -0
index cd191c5fdb0a..8cc3323ec200 100644
@@ -963,6 +963,7 @@ struct bpf_func_proto {
 	};
 	int *ret_btf_id; /* return value btf_id */
 	bool (*allowed)(const struct bpf_prog *prog);
+	bool needs_rcu;
 };
 
 /* bpf_context is intentionally undefined structure. Pointer to bpf_context is
kernel/bpf/verifier.c +8 -0
index 7fb88e1cd7c4..11527de6af8e 100644
@@ -10333,6 +10333,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		return -EINVAL;
 	}
 
+	if (fn->needs_rcu && in_sleepable(env) &&
+	    !env->cur_state->active_rcu_locks) {
+		verbose(env,
+			"helper %s#%d requires bpf_rcu_read_lock() in sleepable context\n",
+			func_id_name(func_id), func_id);
+		return -EINVAL;
+	}
+
 	/* Track non-sleepable context for helpers. */
 	if (!in_sleepable_context(env))
 		env->insn_aux_data[insn_idx].non_sleepable = true;
kernel/trace/bpf_trace.c +1 -1
index a02bd258677e..ea489edbecec 100644
@@ -1715,7 +1715,7 @@ tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 	case BPF_FUNC_skc_to_unix_sock:
 		return &bpf_skc_to_unix_sock_proto;
 	case BPF_FUNC_skc_to_mptcp_sock:
-		return &bpf_skc_to_mptcp_sock_proto;
+		return prog->sleepable ? NULL : &bpf_skc_to_mptcp_sock_proto;
 	case BPF_FUNC_sk_storage_get:
 		return &bpf_sk_storage_get_tracing_proto;
 	case BPF_FUNC_sk_storage_delete:
net/core/filter.c +1 -0
index 80439767e0ee..8dfb83d72503 100644
@@ -12091,6 +12091,7 @@ const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = {
 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
 	.ret_btf_id	= &btf_sock_ids[BTF_SOCK_TYPE_MPTCP],
+	.needs_rcu	= true,
 };
 
 BPF_CALL_1(bpf_sock_from_file, struct file *, file)
net/mptcp/bpf.c +13 -2
index 08bb037f0951..f43f9a2acc3f 100644
@@ -193,8 +193,19 @@ static struct bpf_struct_ops bpf_mptcp_sched_ops = {
 
 struct mptcp_sock *bpf_mptcp_sock_from_subflow(struct sock *sk)
 {
-	if (sk && sk_fullsock(sk) && sk_is_tcp(sk) && sk_is_mptcp(sk))
-		return mptcp_sk(mptcp_subflow_ctx(sk)->conn);
+	struct mptcp_subflow_context *ctx;
+	struct sock *conn;
+
+	if (sk && sk_fullsock(sk) && sk_is_tcp(sk) && sk_is_mptcp(sk)) {
+		ctx = rcu_dereference_check(inet_csk(sk)->icsk_ulp_data,
+					    lockdep_sock_is_held(sk));
+		if (ctx) {
+			/* Pair with release stores publishing or clearing ctx->conn. */
+			conn = smp_load_acquire(&ctx->conn);
+			if (conn)
+				return mptcp_sk(conn);
+		}
+	}
 
 	return NULL;
 }
net/mptcp/protocol.c +5 -1
index a4f7e99b30db..fa85ad0dc5a8 100644
@@ -3177,6 +3177,11 @@ static void __mptcp_init_sock(struct sock *sk)
 	mptcp_pm_data_init(msk);
 	spin_lock_init(&msk->fallback_lock);
 
+	/* the returned parent msk may be handed to lockless readers
+	 * (bpf_skc_to_mptcp_sock()); free it after an RCU grace period
+	 */
+	sock_set_flag(sk, SOCK_RCU_FREE);
+
 	/* re-use the csk retrans timer for MPTCP-level retrans */
 	timer_setup(&sk->mptcp_retransmit_timer, mptcp_retransmit_timer, 0);
 	timer_setup(&msk->sk.mptcp_tout_timer, mptcp_tout_timer, 0);
@@ -3712,7 +3717,6 @@ struct sock *mptcp_sk_clone_init(const struct sock *sk,
 	/* passive msk is created after the first/MPC subflow */
 	msk->subflow_id = 2;
 
-	sock_reset_flag(nsk, SOCK_RCU_FREE);
 	security_inet_csk_clone(nsk, req);
 
 	/* this can't race with mptcp_close(), as the msk is
net/mptcp/subflow.c +24 -7
index 8e386899ceb9..54ac450af6f6 100644
@@ -780,6 +780,7 @@ static void subflow_ulp_fallback(struct sock *sk,
 void mptcp_subflow_drop_ctx(struct sock *ssk)
 {
 	struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(ssk);
+	struct sock *conn;
 
 	if (!ctx)
 		return;
@@ -787,8 +788,12 @@ void mptcp_subflow_drop_ctx(struct sock *ssk)
 	list_del(&mptcp_subflow_ctx(ssk)->node);
 	if (inet_csk(ssk)->icsk_ulp_ops) {
 		subflow_ulp_fallback(ssk, ctx);
-		if (ctx->conn)
-			sock_put(ctx->conn);
+		conn = ctx->conn;
+		if (conn) {
+			/* Clear the pointer before dropping its reference. */
+			smp_store_release(&ctx->conn, NULL);
+			sock_put(conn);
+		}
 	}
 
 	kfree_rcu(ctx, rcu);
@@ -861,6 +866,7 @@ static struct sock *subflow_syn_recv_sock(const struct sock *sk,
 
 	if (child && *own_req) {
 		struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(child);
+		struct sock *conn;
 
 		tcp_rsk(req)->drop_req = false;
 
@@ -880,12 +886,14 @@ static struct sock *subflow_syn_recv_sock(const struct sock *sk,
 		ctx->setsockopt_seq = listener->setsockopt_seq;
 
 		if (ctx->mp_capable) {
-			ctx->conn = mptcp_sk_clone_init(listener->conn, &mp_opt, child, req);
-			if (!ctx->conn)
+			conn = mptcp_sk_clone_init(listener->conn, &mp_opt, child, req);
+			if (!conn)
 				goto fallback;
 
+			/* Publish the initialized parent socket to lockless readers. */
+			smp_store_release(&ctx->conn, conn);
 			ctx->subflow_id = 1;
-			owner = mptcp_sk(ctx->conn);
+			owner = mptcp_sk(conn);
 
 			if (mp_opt.deny_join_id0)
 				WRITE_ONCE(owner->pm.remote_deny_join_id0, true);
@@ -920,7 +928,8 @@ static struct sock *subflow_syn_recv_sock(const struct sock *sk,
 
 			/* move the msk reference ownership to the subflow */
 			subflow_req->msk = NULL;
-			ctx->conn = (struct sock *)owner;
+			/* Publish the parent socket to lockless readers. */
+			smp_store_release(&ctx->conn, (struct sock *)owner);
 
 			if (subflow_use_different_sport(owner, sk)) {
 				pr_debug("ack inet_sport=%d %d\n",
@@ -1827,7 +1836,8 @@ int mptcp_subflow_create_socket(struct sock *sk, unsigned short family,
 
 	*new_sock = sf;
 	sock_hold(sk);
-	subflow->conn = sk;
+	/* Publish the parent socket after taking its reference. */
+	smp_store_release(&subflow->conn, sk);
 	mptcp_subflow_ops_override(sf->sk);
 
 	return 0;
@@ -1848,6 +1858,8 @@ static struct mptcp_subflow_context *subflow_create_ctx(struct sock *sk,
 	if (!ctx)
 		return NULL;
 
+	/* BPF readers may access the subflow socket under RCU. */
+	sock_set_flag(sk, SOCK_RCU_FREE);
 	rcu_assign_pointer(icsk->icsk_ulp_data, ctx);
 	INIT_LIST_HEAD(&ctx->node);
 	INIT_LIST_HEAD(&ctx->delegated_node);
@@ -2024,6 +2036,11 @@ static void subflow_ulp_release(struct sock *ssk)
 		if (!release && !test_and_set_bit(MPTCP_WORK_CLOSE_SUBFLOW,
 						  &mptcp_sk(sk)->flags))
 			mptcp_schedule_work(sk);
+
+		/* hide the parent from lockless readers (e.g. BPF) before
+		 * dropping the subflow-owned reference
+		 */
+		smp_store_release(&ctx->conn, NULL);
 		sock_put(sk);
 	}
 
Signature · 1 line
2.43.0
#1 lore raw
Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] bpf: missing MEM_RCU tagging and sleepable gate in check_helper_call() - [High] mptcp: NULL deref in…

Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] bpf: missing MEM_RCU tagging and sleepable gate in check_helper_call()
- [High] mptcp: NULL deref in mptcp_subflow_process_delegated() after ULP release
- [High] mptcp: setting SOCK_RCU_FREE in subflow_create_ctx() leaks socket refs
- [High] mptcp: NULL deref in subflow_data_ready() racing with listener close
- [Medium] mptcp: bpf: UAF on subflow ctx due to uncleared icsk_ulp_data --

commit f52b13bf0febdfcc37197ba78c9e6dab39011b6b
Author: Kalpan Jani <[email protected]>

mptcp: bpf: fix NULL deref and UAF in bpf_mptcp_sock_from_subflow()

This commit uses RCU and release/acquire ordering to synchronize bpf_mptcp_sock_from_subflow() with subflow creation, fallback and teardown, sets SOCK_RCU_FREE on parent and subflow sockets, and adds a needs_rcu helper check in the BPF verifier.

Quoted 24 lines
kernel/bpf/verifier.c +8 -0
index 5f874979b8d75..15f3136fafa52 100644
@@ -10912,6 +10912,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		return -EINVAL;
 	}
 
+	if (fn->needs_rcu && in_sleepable(env) &&
+	    !env->cur_state->active_rcu_locks) {
+		verbose(env,
+			"helper %s#%d requires bpf_rcu_read_lock() in sleepable context\n",
+			func_id_name(func_id), func_id);
+		return -EINVAL;
+	}
+
 	/* Track non-sleepable context for helpers. */
 	if (!in_sleepable_context(env))
 		env->insn_aux_data[insn_idx].non_sleepable = true;
kernel/trace/bpf_trace.c +0 -0
index 29260951aa871..c6032fe843627 100644

kernel/trace/bpf_trace.c tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog) · line 1752

Quoted 8 lines
kernel/trace/bpf_trace.c +1 -1
@@ -1746,7 +1746,7 @@ tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 	case BPF_FUNC_skc_to_unix_sock:
 		return &bpf_skc_to_unix_sock_proto;
 	case BPF_FUNC_skc_to_mptcp_sock:
-		return &bpf_skc_to_mptcp_sock_proto;
+		return prog->sleepable ? NULL : &bpf_skc_to_mptcp_sock_proto;
 	case BPF_FUNC_sk_storage_get:
 		return &bpf_sk_storage_get_tracing_proto;
 	case BPF_FUNC_sk_storage_delete:

[Severity: High]
Does check_helper_call() leave the returned mptcp_sock pointer untagged with MEM_RCU when fn->needs_rcu is true?

When a sleepable context such as a bpf_wq or bpf_task_work callback calls bpf_skc_to_mptcp_sock() inside bpf_rcu_read_lock(), check_helper_call() sets R0 to PTR_TO_BTF_ID | ret_flag without MEM_RCU. On bpf_rcu_read_unlock(), invalidate_rcu_protected_refs() only demotes registers carrying MEM_RCU to PTR_UNTRUSTED, so the BPF program can keep using the unreferenced mptcp_sock pointer after the RCU read section ends and trigger a use-after-free.

In addition, tracing_prog_func_proto() returns NULL whenever prog->sleepable is set, which rejects bpf_skc_to_mptcp_sock() in sleepable tracing, LSM and syscall programs before check_helper_call() reaches the fn->needs_rcu check, even when the call is wrapped in bpf_rcu_read_lock().

[ ... ]

Quoted 4 lines
net/mptcp/subflow.c +0 -0
index f0a6725d2c376..d8721d38467ec 100644

[ ... ]

net/mptcp/subflow.c static struct mptcp_subflow_context *subflow_create_ctx(struct sock *sk, · line 1874

Quoted 9 lines
net/mptcp/subflow.c +2 -0
@@ -1857,6 +1867,8 @@ static struct mptcp_subflow_context *subflow_create_ctx(struct sock *sk,
 	if (!ctx)
 		return NULL;
 
+	/* BPF readers may access the subflow socket under RCU. */
+	sock_set_flag(sk, SOCK_RCU_FREE);
 	rcu_assign_pointer(icsk->icsk_ulp_data, ctx);
 	INIT_LIST_HEAD(&ctx->node);
 	INIT_LIST_HEAD(&ctx->delegated_node);

[Severity: High]
Does setting SOCK_RCU_FREE on full TCP subflow sockets break sk_is_refcounted() and leak socket references on BPF lookups?

include/net/sock.h:sk_is_refcounted() {
	/* Only full sockets have sk->sk_flags. */
	return !sk_fullsock(sk) || !sock_flag(sk, SOCK_RCU_FREE);
}

When a BPF program looks up an established or connecting subflow socket via bpf_sk_lookup_tcp() or bpf_skc_lookup_tcp(), __inet_lookup_established() increments sk->sk_refcnt. Because SOCK_RCU_FREE is now set on the subflow socket, sk_is_refcounted(sk) returns false, so bpf_sk_release() skips sock_gen_put(sk) and permanently leaks the socket reference. bpf_sk_assign() also relies on sk_is_refcounted(sk) and will skip taking a reference on the subflow socket.

net/mptcp/subflow.c static void subflow_ulp_release(struct sock *ssk) · line 2062

Quoted 12 lines
net/mptcp/subflow.c +5 -0
@@ -2040,6 +2052,11 @@ static void subflow_ulp_release(struct sock *ssk)
 		if (!release && !test_and_set_bit(MPTCP_WORK_CLOSE_SUBFLOW,
 						  &mptcp_sk(sk)->flags))
 			mptcp_schedule_work(sk);
+
+		/* hide the parent from lockless readers (e.g. BPF) before
+		 * dropping the subflow-owned reference
+		 */
+		smp_store_release(&ctx->conn, NULL);
 		sock_put(sk);
 	}
 

[Severity: High]
Can clearing ctx->conn here and in mptcp_subflow_drop_ctx() cause a NULL pointer dereference in mptcp_subflow_process_delegated()?

CPU0 CPU1
mptcp_subflow_delegate(ssk,
MPTCP_DELEGATE_SEND)
set_bit(MPTCP_DELEGATE_SEND,

    &subflow->delegated_status)
  list_add_tail(&subflow->delegated_node,
    &delegated->head)
                                      __mptcp_close_ssk(..., ssk, ...)
                                        __tcp_close(ssk, 0)
                                          inet_csk_destroy_sock(ssk)
                                            ...
                                              subflow_ulp_release(ssk)
                                                smp_store_release(&ctx->conn,
                                                  NULL)
                                                mptcp_subflow_ops_undo_override(ssk)
                                        release_sock(ssk)
mptcp_napi_poll()
  mptcp_subflow_process_delegated(ssk,
    xchg(&subflow->delegated_status, 0))
    sk = subflow->conn
    mptcp_data_lock(sk)  <-- NULL pointer dereference

Once mptcp_subflow_delegate() queues ssk on the per-CPU mptcp_delegated_actions list, only mptcp_napi_poll() on that CPU dequeues it. When subflow_ulp_release() runs first, it clears ctx->conn and restores ssk->sk_prot, so release_sock(ssk) no longer runs tcp_release_cb_override() to drain delegated_status. mptcp_napi_poll() then calls mptcp_subflow_process_delegated() with pending status bits and a NULL subflow->conn.

[Severity: High]
Can clearing ctx->conn in subflow_ulp_release() also cause a NULL pointer dereference in subflow_data_ready() when racing with listener close?

CPU0 (<softirq>) CPU1
tcp_v4_rcv()
tcp_child_process(listener_ssk, ...)

                                      __mptcp_destroy_sock()
                                        ...
                                          __mptcp_close_ssk(..., listener_ssk, ...)
                                            __tcp_close(listener_ssk, 0)
                                              ...
                                                subflow_ulp_release(listener_ssk)
                                                  smp_store_release(&ctx->conn,
                                                    NULL)
    listener_ssk->sk_data_ready(listener_ssk)
      subflow_data_ready(listener_ssk)
        parent = subflow->conn
        msk = mptcp_sk(parent)
        parent->sk_data_ready(parent)  <-- NULL pointer dereference

tcp_child_process() calls parent->sk_data_ready(parent) under rcu_read_lock() without holding the listener socket lock. Because subflow_ulp_release() sets ctx->conn to NULL while leaving sk_data_ready set to subflow_data_ready(), subflow_data_ready() loads a NULL parent pointer and dereferences it in mptcp_sk(parent) (when CONFIG_DEBUG_NET is enabled) or parent->sk_data_ready(parent).

[Severity: Medium]
Can bpf_mptcp_sock_from_subflow() still read a freed subflow context after kfree_rcu(ctx, rcu)?

net/mptcp/subflow.c:subflow_ulp_release() {
	...
	mptcp_subflow_ops_undo_override(ssk);
	if (release)
		kfree_rcu(ctx, rcu);
}

subflow_ulp_release() (as well as __mptcp_close_ssk() and mptcp_subflow_drop_ctx() when icsk_ulp_ops has already been cleared by tcp_cleanup_ulp()) frees ctx via kfree_rcu() without clearing inet_csk(ssk)->icsk_ulp_data or tcp_sk(ssk)->is_mptcp. If ssk outlives ctx's RCU grace period, such as while in-flight TX skbs still hold ssk->sk_wmem_alloc, a BPF program calling bpf_skc_to_mptcp_sock(ssk) will observe sk_is_mptcp(ssk) == 1 and dereference the dangling icsk_ulp_data pointer at smp_load_acquire(&ctx->conn).

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#2 lore raw
In reply to Kalpan Jani
Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider.

Critical: 0 · High: 3 · Medium: 2 · Low: 3

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [High] subflow_create_ctx() now sets SOCK_RCU_FREE on every MPTCP subflow TCP socket.
- [High] The RCU teardown fix is incomplete: the subflow context is freed with kfree_rcu() while it is still published in icsk_ulp_data and…
- [High] mptcp: NULL deref in subflow_data_ready() racing with listener close
- [Medium] subflow_ulp_release() now runs smp_store_release(&ctx->conn, NULL) unconditionally, including when release == false.
- [Medium] The commit body leaves out two significant parts of the diff:
(a) setting SOCK_RCU_FREE on every MPTCP subflow TCP socket in…
- [Low] The new needs_rcu verifier rule in check_helper_call() can never fire.
- [Low] In bpf_mptcp_sock_from_subflow(), rcu_dereference_check(inet_csk(sk)->icsk_ulp_data,…
- [Low] mptcp_subflow_ctx() in net/mptcp/protocol.h still says '/* Use RCU on icsk_ulp_data only for sock diag code */'.

--

mptcp: bpf: fix NULL deref and UAF in bpf_mptcp_sock_from_subflow()

This commit changes bpf_mptcp_sock_from_subflow() to load icsk_ulp_data under RCU. ctx->conn is now published and cleared with release/acquire ordering, SOCK_RCU_FREE is set on the parent msk and on subflow sockets, and sleepable tracing programs can no longer use bpf_skc_to_mptcp_sock(). It also adds a needs_rcu flag to struct bpf_func_proto and checks it in check_helper_call().

Quoted 10 lines

Give the parent msk RCU-grace lifetime by setting SOCK_RCU_FREE in the shared __mptcp_init_sock(), covering both active and passive paths, and dropping the reset in mptcp_sk_clone_init(). This ensures a reader that obtains the parent under the applicable RCU protection does not access freed memory.

Keep bpf_skc_to_mptcp_sock() available to non-sleepable tracing programs for compatibility, while rejecting sleepable tracing programs because classic RCU does not protect the parent socket through sleepable execution.

[Severity: Medium]
The commit message covers SOCK_RCU_FREE on the parent msk. The diff also does two things the message does not mention:

- it sets SOCK_RCU_FREE on every subflow TCP socket in subflow_create_ctx()
- it adds a generic needs_rcu field to struct bpf_func_proto and a new rejection path in check_helper_call()

Both appear only in the "Changes since v6" notes below the --- separator, so they won't be in the applied commit.

Could the commit message describe both changes? The subflow change alters sk_is_refcounted() behaviour for established TCP sockets, and the verifier change touches core BPF.

Quoted 5 lines
kernel/bpf/verifier.c +0 -0
index 5f874979b8d75..15f3136fafa52 100644

kernel/bpf/verifier.c static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn · line 10921

Quoted 10 lines
kernel/bpf/verifier.c +7 -0
@@ -10912,6 +10912,14 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		return -EINVAL;
 	}
 
+	if (fn->needs_rcu && in_sleepable(env) &&
+	    !env->cur_state->active_rcu_locks) {
+		verbose(env,
+			"helper %s#%d requires bpf_rcu_read_lock() in sleepable context\n",
+			func_id_name(func_id), func_id);
+		return -EINVAL;
+	}

[Severity: Low]
Can this new check ever fire?

bpf_skc_to_mptcp_sock_proto is the only proto that sets needs_rcu. It is reachable from two places:

- bpf_sk_base_func_proto(), whose program types can't be sleepable
- tracing_prog_func_proto(), which this patch changes to:

    case BPF_FUNC_skc_to_mptcp_sock:
        return prog->sleepable ? NULL : &bpf_skc_to_mptcp_sock_proto;

bpf_lsm_func_proto() and syscall_prog_func_proto() also fall through to tracing_prog_func_proto(). So any sleepable program fails earlier in bpf_get_helper_proto() with "program of this type cannot use helper".

The two changes also set different policies for the same helper. One allows it in sleepable programs under bpf_rcu_read_lock(), the other never allows it in sleepable programs. Is one of them meant to go?

There is also the argument type. arg1 is ARG_PTR_TO_SOCK_COMMON, which doesn't accept PTR_TO_BTF_ID, so tracing and LSM programs can't easily pass a valid socket here. Does the "compatibility" reason for keeping it in non-sleepable tracing programs still hold?

[ ... ]

Quoted 6 lines
net/mptcp/bpf.c +0 -0
index 4cc16cbeb3281..f6d6d31395eae 100644
@@ -14,8 +14,19 @@
 

net/mptcp/bpf.c line 22

Quoted 10 lines
net/mptcp/bpf.c +6 -2
 struct mptcp_sock *bpf_mptcp_sock_from_subflow(struct sock *sk)
 {
-	if (sk && sk_fullsock(sk) && sk_is_tcp(sk) && sk_is_mptcp(sk))
-		return mptcp_sk(mptcp_subflow_ctx(sk)->conn);
+	struct mptcp_subflow_context *ctx;
+	struct sock *conn;
+
+	if (sk && sk_fullsock(sk) && sk_is_tcp(sk) && sk_is_mptcp(sk)) {
+		ctx = rcu_dereference_check(inet_csk(sk)->icsk_ulp_data,
+					    lockdep_sock_is_held(sk));

[Severity: Low]
Will this produce a "suspicious rcu_dereference_check() usage" splat with CONFIG_PROVE_RCU when the helper is called from TC egress or XDP?

bpf_skc_to_mptcp_sock_proto is also exposed through bpf_sk_base_func_proto(). Some of those callers don't hold classic RCU:

- TC egress runs from __dev_queue_xmit() under rcu_read_lock_bh() only
- native XDP runs in NAPI with BH disabled

If the socket comes from bpf_skc_lookup_tcp(), both rcu_read_lock_held() and lockdep_sock_is_held() are false. The old code used a __force cast with no check, so the splat would be new.

The access itself is safe, because BH-disabled sections are RCU readers. Should the condition also accept rcu_read_lock_bh_held(), or use rcu_read_lock_any_held()?

net/mptcp/bpf.c static struct bpf_struct_ops bpf_mptcp_sched_ops = { · line 204

Quoted 3 lines
net/mptcp/bpf.c +3 -0
+		if (ctx) {
+			/* Pair with release stores publishing or clearing ctx->conn. */
+			conn = smp_load_acquire(&ctx->conn);

[Severity: Low]
This isn't a bug, but mptcp_subflow_ctx() in net/mptcp/protocol.h still says:

    /* Use RCU on icsk_ulp_data only for sock diag code */

The conn field in struct mptcp_subflow_context is still documented only as "parent mptcp_sock".

This patch adds a second RCU reader, and every writer of ->conn now has to use smp_store_release() to pair with this smp_load_acquire(). Could both comments be updated so a later plain store to ->conn doesn't silently break the pairing?

Quoted 4 lines
net/mptcp/bpf.c +4 -0
+			if (conn)
+				return mptcp_sk(conn);
+		}
+	}

[ ... ]

Quoted 4 lines
net/mptcp/subflow.c +0 -0
index f0a6725d2c376..d8721d38467ec 100644

[ ... ]

net/mptcp/subflow.c static struct mptcp_subflow_context *subflow_create_ctx(struct sock *sk, · line 1871

Quoted 6 lines
net/mptcp/subflow.c +2 -0
@@ -1857,6 +1867,8 @@ static struct mptcp_subflow_context *subflow_create_ctx(struct sock *sk,
 	if (!ctx)
 		return NULL;
 
+	/* BPF readers may access the subflow socket under RCU. */
+	sock_set_flag(sk, SOCK_RCU_FREE);

[Severity: High]
Does setting SOCK_RCU_FREE here leak socket references through the BPF socket lookup helpers?

For passive subflows, inet_csk_clone_lock() clears the flag on purpose:

    /* listeners have SOCK_RCU_FREE, not the children */
    sock_reset_flag(newsk, SOCK_RCU_FREE);

It then calls inet_clone_ulp(), which reaches subflow_ulp_clone() and then subflow_create_ctx(), so the flag is set again. Nothing clears it when the subflow falls back to plain TCP.

Established lookups always take a reference. In sk_lookup()->__inet_lookup()->__inet_lookup_established(), *refcounted is set to true.

bpf_sk_release() only drops that reference when sk_is_refcounted() is true:

    if (sk && sk_is_refcounted(sk))
        sock_gen_put(sk);

sk_is_refcounted() is:

    return !sk_fullsock(sk) || !sock_flag(sk, SOCK_RCU_FREE);

For an established subflow this is now false.

So would each bpf_sk_lookup_tcp() or bpf_skc_lookup_tcp() followed by bpf_sk_release() leak one sk_refcnt? That applies to established MPTCP subflows and to connections that fell back from MPTCP.

If so, the subflow socket would never be freed, and its netns reference would keep the namespace pinned. A program can do this once per packet.

Quoted 1 line
net/mptcp/subflow.c +0 -0
 	rcu_assign_pointer(icsk->icsk_ulp_data, ctx);

[ ... ]

net/mptcp/subflow.c static void subflow_ulp_release(struct sock *ssk) · line 2059

Quoted 9 lines
net/mptcp/subflow.c +5 -0
@@ -2040,6 +2052,11 @@ static void subflow_ulp_release(struct sock *ssk)
 		if (!release && !test_and_set_bit(MPTCP_WORK_CLOSE_SUBFLOW,
 						  &mptcp_sk(sk)->flags))
 			mptcp_schedule_work(sk);
+
+		/* hide the parent from lockless readers (e.g. BPF) before
+		 * dropping the subflow-owned reference
+		 */
+		smp_store_release(&ctx->conn, NULL);

[Severity: High]
Can this NULL store race with subflow_data_ready() on the MPTCP listener subflow?

On 3WHS completion, tcp_child_process() runs in softirq under rcu_read_lock() without the listener socket lock, and calls READ_ONCE(parent->sk_data_ready)(parent). For an MPTCP listener that parent is the listener ssk, so the call lands in subflow_data_ready(), which does:

    u16 state = 1 << inet_sk_state_load(sk);
    struct sock *parent = subflow->conn;
    ...
    msk = mptcp_sk(parent);
    if (state & TCPF_LISTEN) {
        ...
        parent->sk_data_ready(parent);

Meanwhile, close() on the MPTCP listener goes through mptcp_check_listen_stop() and then reaches subflow_ulp_release() via this path:

    __mptcp_destroy_sock()
      mptcp_destroy_common()
        __mptcp_close_ssk()
          __tcp_close()
            inet_csk_destroy_sock()
              tcp_cleanup_ulp()
                subflow_ulp_release()

Nothing on that path restores listener_ssk->sk_data_ready. A concurrent softirq can therefore still enter subflow_data_ready() after this store.

Before this patch, subflow->conn kept pointing at the listener msk. Commit 5e20087d1b67 ("mptcp: handle mptcp listener destruction via rcu") made that msk SOCK_RCU_FREE so that this lockless reader stays safe. With this patch the reader can load NULL instead:

- with CONFIG_DEBUG_NET, mptcp_sk(NULL) faults in its WARN_ON() check on sk_protocol
- without it, the state load can still see TCP_LISTEN while the conn load happens after subflow_ulp_release(). Then parent->sk_data_ready(parent) is a NULL dereference in softirq

This looks reachable by an unprivileged local user who closes a listening MPTCP socket while connections are completing.

Should the clear be skipped for listener subflows? Alternatively, should subflow_data_ready() and the other in-kernel lockless users of subflow->conn read it with READ_ONCE() and bail out on NULL? A third option would be to leave ->conn intact for in-kernel users and give the BPF helper a separate way to tell that the parent reference is gone.

[Severity: Medium]
This store now runs even when release is false. That happens when inet_child_forget() runs on an unaccepted MPC subflow. The ctx is then kept on msk->conn_list on purpose, and possibly on the per-CPU delegated list, until __mptcp_close_ssk() frees it.

Can mptcp_subflow_process_delegated() then dereference NULL? It does:

    struct sock *sk = subflow->conn;

    if (status & BIT(MPTCP_DELEGATE_SEND)) {
        mptcp_data_lock(sk);

mptcp_napi_poll() calls it after bh_lock_sock_nested(ssk). It doesn't check whether the ssk was destroyed or its ULP released.

Suppose a delegation was queued before inet_csk_listen_stop()->inet_child_forget() destroyed the child. The later NAPI pass would see conn == NULL, where before this patch it saw the still-valid msk.

I haven't confirmed a path that queues a delegated action on an unaccepted passive subflow. Nothing removes the subflow from the delegated list on ULP release, though.

Should the clear be skipped when release is false, or should the in-kernel users of subflow->conn handle NULL?

net/mptcp/subflow.c static void subflow_ulp_release(struct sock *ssk) · line 2046

Quoted 3 lines
net/mptcp/subflow.c +0 -0
 		sock_put(sk);
 	}
 

[Severity: High]
Is the teardown window fully closed here? After clearing ctx->conn, subflow_ulp_release() continues with:

    mptcp_subflow_ops_undo_override(ssk);
    if (release)
        kfree_rcu(ctx, rcu);

At that point icsk_ulp_data still points to ctx and tcp_sk(ssk)->is_mptcp is still 1. Afterwards, tcp_cleanup_ulp() only clears icsk_ulp_ops.

The same pattern shows up in two other places:

- __mptcp_close_ssk(), in the !icsk_ulp_ops branch
- mptcp_subflow_drop_ctx() when icsk_ulp_ops is already NULL, because subflow_ulp_fallback() is skipped there

The ssk can outlive the grace period. For example, in-flight TX skbs hold sk_wmem_alloc and delay sk_free(), and the ssk is now SOCK_RCU_FREE as well.

Consider a TC egress program on a lower device that reads skb->sk from a delayed TX clone. It would pass every check in bpf_mptcp_sock_from_subflow():

    tcp_v4_destroy_sock()
      tcp_cleanup_ulp()
        subflow_ulp_release()
          kfree_rcu(ctx, rcu)
    ... grace period ...
    TC egress prog: bpf_skc_to_mptcp_sock(skb->sk)
      bpf_mptcp_sock_from_subflow()
        ctx = rcu_dereference_check(icsk_ulp_data, ...)  /* freed ctx */
        conn = smp_load_acquire(&ctx->conn)

Wouldn't that read freed slab memory? If the slot has been reused, it could also hand a garbage pointer to BPF as a trusted mptcp_sock.

The old code had the same ctx dereference. However, the commit message says this patch fixes the teardown use-after-free by relying on RCU.

Should icsk_ulp_data and is_mptcp be cleared before kfree_rcu(), the way subflow_ulp_fallback() does?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261123084836.1704274-1-kalpan.jani%40mpiricsoftware.com