Skip to contentSkip to conversation

Introduce bpf_ksock

PATCH Superseded Mahe Tardy 3 participants 17 messages Aug 12 – Aug 13

Subsystems (7)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Mahe Tardy

author
#0 lore raw

v6 cover Introduce bpf_ksock

This patch series introduces bpf_ksock, a set of BPF kfuncs to allow BPF programs to create UDP sockets and send data. This provides a mechanism for BPF LSM progs to emit telemetry over UDP independently of userspace.

The main use case is to be able to completely dispense with agents/daemons for BPF programs after startup. In the case of Isovalent's Tetragon, the idea would be to be able to emit security alerts or export data from BPF even when the agent is down. For meta, according to Liam presentation[^2], this could replace logging via ringbuffers which created cross-binary versioning issues.

The implementation follows the established kfunc lifecycle pattern (create/acquire/release with refcounting, kptr map storage, dtor registration), for example used by the network bpf_crypto kfuncs.

For reference, this was discussed at LSF/MM/BPF 2025[^1] in Montreal, again at Plumbers 2025 in Tokyo. Liam Wisehart mentioned this work during his presentation of BpfJailer[^2]. Then it was also discussed during LSF/MM/BPF 2026 in Zagreb.

A first version of it, called bpf_netpoll was submitted to the mailing list but eventually NACKED by Jakub Kicinski[^3]. The discussion eventually reached an agreement that we should use regular kernel sockets if we want to do network from BPF programs[^4]. This was fundamentally more complex to implement but here is a first proposition of how it could look like after several automated reviews using sashiko.

For more details, here are some of the main adjustements I had to make during the preparation of these patches:

Initially, the goal was to register the ksock_kfunc_set with BPF_PROG_TYPE_UNSPEC to allow send to be called from any programs. This introduces significant challenges (but might be doable). The limitation is still that the programs should be able to sleep but combining this with bpf workqueue allows to send from virtually anywhere. However, not by-passing LSM socket hooks make it impossible to be called from the workqueue context as the credential of the initial caller would not be preserved. Also, it would be easy for users to shoot themselves in the foot and attach a program that sends asynchronously over the network on a network hook. So the idea for now is to restrict the ksock_kfunc_set (which is acquire, release and send) to SYSCALL and LSM to make it simpler. Also to make the patch set easier to start with, the sockets are restricted to UDP.

v6 updates:
- add Stanislav, Jiayuan and Kuniyuki acked-by and reviewed-by tags.
- reformat some weird indents and nits (Kuniyuki)
- remove unused import in ksock_lsm_verifier.c (bot+bpf-ci)

v5 updates:
- add Song Liu ack on first patch (Song)
- guard BTF ID of bpf_lsm_socket_sendmsg on CONFIG_BPF_LSM (Jiayuan)
- fix checkpatch warnings on style (Jiayuan)
- encapsulate RCU dance in new ksock_ctx_get() selftest helper (Jiayuan)

v4 updates:
- drop the __sys_ prefix on connect_socket() (Song)
- replace recursion protection with a verifier filter on calling bpf_ksock_send() on a program attached to the security_socket_sendmsg() LSM hook (Song)

v3 updates:
Simplifies bpf_ksock_connect arg by using a union (union bpf_ksock_addr) containing struct sockaddr_in and struct sockaddr_in6 to remove most of bpf_ksock_parse_addr() code (Stanislav).

Note that I initially tried to put the union inside of struct bpf_ksock_addr_opts but we ended up with too much struct nesting depth from bpf, for example when trying to write the ipv4 address:

	addr_opts.addr.sin.sin_addr.s_addr = ipv4_remote;

It resulted in:

max struct nesting depth exceeded
R2 pointer type STRUCT bpf_ksock_addr_opts must point to void, scalar, or struct with scalar

v2 updates:
This second version simplifies the patch set by removing bind, keeping connect + send for now (could be replaced per sendto if needed). It also removes the sysctl limit and the whole hashtable ksock_send guard with a single bit in task_struct.

- remove bind from the API (Stanislav, Amery, Kuniyuki)
- remove the bpf_ksock_max sysctl limit (Stanislav, Kuniyuki)
- replace ksock_send_guard with a bit in task_struct (Kuniyuki)
- remove unnecessary init struct sockaddr_storage addr = {}; (Kuniyuki)
- remove redundant ASSERT_OK_FD (sashiko)
- fix typos in ksock test patch commit log (bot+bpf-ci)
- fix return statement in kfunc registration (bot+bpf-ci)

v1 updates (from local sashiko iterations):
- do not bypass the LSM and thus add send re-enter protection;
- limit the number of socket creation through the kfunc per ns;
- copy the arg values to avoid TOCTOU race since kfunc can sleep;
- prevent calling bpf_ksock_create from workqueue with improper creds.

[^1]: https://lwn.net/Articles/1022034/
[^2]: https://lpc.events/event/19/contributions/2159/
[^3]: https://lore.kernel.org/bpf/[email protected]/
[^4]: https://lore.kernel.org/bpf/CAPhsuW71P58XqsXrLbqsShgnozg66TA=T_c=fYrqSSzvL1tTWA@mail.gmail.com/

Link to v5: https://lore.kernel.org/bpf/[email protected]/

Mahe Tardy (5):
net: Add connect_socket() helper
bpf: Add ksock kfuncs
selftests/bpf: Add ksock kfunc test selftests/bpf: Test forbidden bpf_ksock_send() LSM attach selftests/bpf: Add ksock test for async callback guard

 include/linux/bpf_ksock.h                     |  36 ++
 include/linux/socket.h                        |   2 +
 kernel/bpf/verifier.c                         |   3 +
 net/core/Makefile                             |   3 +
 net/core/bpf_ksock.c                          | 335 ++++++++++++++++++
 net/socket.c                                  |  32 +-
 .../testing/selftests/bpf/prog_tests/ksock.c  | 133 +++++++
 .../selftests/bpf/prog_tests/ksock_wq.c       |  34 ++
 .../selftests/bpf/progs/ksock_common.h        |  78 ++++
 tools/testing/selftests/bpf/progs/ksock_lsm.c |  72 ++++
 .../selftests/bpf/progs/ksock_lsm_verifier.c  |  35 ++
 tools/testing/selftests/bpf/progs/ksock_wq.c  |  62 ++++
 12 files changed, 811 insertions(+), 14 deletions(-)
 create mode 100644 include/linux/bpf_ksock.h
 create mode 100644 net/core/bpf_ksock.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/ksock.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/ksock_wq.c
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_common.h
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_lsm.c
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_wq.c

--
2.34.1

author
#1 lore raw

PATCH v6 1/5 net: Add connect_socket() helper

Add a helper that connects an existing socket while invoking the LSM hook. Reuse it in __sys_connect_file() to avoid duplicating the connect logic. Other socket operations have equivalent helpers that trigger the appropriate LSM hooks that can be reused, this one was the only one missing.

---
 include/linux/socket.h |  2 ++
 net/socket.c           | 32 ++++++++++++++++++--------------
 2 files changed, 20 insertions(+), 14 deletions(-)
include/linux/socket.h +2 -0
index 2a8d7b14f1d1..5a5eb1250103 100644
@@ -461,6 +461,8 @@ extern struct file *__sys_socket_file(int family, int type, int protocol);
 extern int __sys_bind(int fd, struct sockaddr __user *umyaddr, int addrlen);
 extern int __sys_bind_socket(struct socket *sock, struct sockaddr_storage *address,
 			     int addrlen);
+int connect_socket(struct socket *sock, struct sockaddr_storage *addr,
+		   int addrlen, int flags);
 extern int __sys_connect_file(struct file *file, struct sockaddr_storage *addr,
 			      int addrlen, int file_flags);
 extern int __sys_connect(int fd, struct sockaddr __user *uservaddr,
net/socket.c +18 -14
index 63c69a0fa74e..5b02e6217c68 100644
@@ -2103,6 +2103,20 @@ SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr,
 	return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0);
 }
 
+int connect_socket(struct socket *sock, struct sockaddr_storage *address,
+		   int addrlen, int flags)
+{
+	int err;
+
+	err = security_socket_connect(sock, (struct sockaddr *)address,
+				      addrlen);
+	if (err)
+		return err;
+
+	return READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)address,
+					     addrlen, flags);
+}
+
 /*
  *	Attempt to connect to a socket with the server address.  The address
  *	is in user space so we verify it is OK and move it to kernel space.
@@ -2119,23 +2133,13 @@ int __sys_connect_file(struct file *file, struct sockaddr_storage *address,
 		       int addrlen, int file_flags)
 {
 	struct socket *sock;
-	int err;
 
 	sock = sock_from_file(file);
-	if (!sock) {
-		err = -ENOTSOCK;
-		goto out;
-	}
-
-	err =
-	    security_socket_connect(sock, (struct sockaddr *)address, addrlen);
-	if (err)
-		goto out;
+	if (!sock)
+		return -ENOTSOCK;
 
-	err = READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)address,
-					    addrlen, sock->file->f_flags | file_flags);
-out:
-	return err;
+	return connect_socket(sock, address, addrlen,
+			      sock->file->f_flags | file_flags);
 }
 
 int __sys_connect(int fd, struct sockaddr __user *uservaddr, int addrlen)

--
2.34.1

#2 lore raw

Re: [PATCH bpf-next v6 1/5] net: Add connect_socket() helper

This isn't a bug, but could the changelog note which follow-up user needs connect_socket() to be global (rather than static in net/socket.c), so the new header declaration is justified within this…
Quoted 5 lines

Add a helper that connects an existing socket while invoking the LSM hook. Reuse it in __sys_connect_file() to avoid duplicating the connect logic. Other socket operations have equivalent helpers that trigger the appropriate LSM hooks that can be reused, this one was the only one missing.

This isn't a bug, but could the changelog note which follow-up user needs connect_socket() to be global (rather than static in net/socket.c), so the new header declaration is justified within this patch?

The changelog motivates the helper only by the in-file reuse, but on its own that would not require a new global symbol: connect_socket() is declared in include/linux/socket.h while its single caller is 26 lines below it in net/socket.c. The actual consumer is the bpf_ksock_connect() kfunc added later in the series, which the message does not mention, so a reader of this patch alone cannot tell why the helper is not static.

---
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/31618864886

author
#3 lore raw

Re: [PATCH bpf-next v6 1/5] net: Add connect_socket() helper

Quoted 10 lines · On Wed, Aug 12, 2026 at 05:25:37PM +0000, [email protected] wrote:
Quoted 5 lines

Add a helper that connects an existing socket while invoking the LSM hook. Reuse it in __sys_connect_file() to avoid duplicating the connect logic. Other socket operations have equivalent helpers that trigger the appropriate LSM hooks that can be reused, this one was the only one missing.

This isn't a bug, but could the changelog note which follow-up user needs connect_socket() to be global (rather than static in net/socket.c), so the new header declaration is justified within this patch?

Quoted 6 lines

The changelog motivates the helper only by the in-file reuse, but on its own that would not require a new global symbol: connect_socket() is declared in include/linux/socket.h while its single caller is 26 lines below it in net/socket.c. The actual consumer is the bpf_ksock_connect() kfunc added later in the series, which the message does not mention, so a reader of this patch alone cannot tell why the helper is not static.

Indeed if needed, this could be made more explicit. Currently it's implied that one helper was missing "for the next patches".

Quoted 11 lines
Quoted 3 lines

Other socket operations have equivalent helpers that trigger the appropriate LSM hooks that can be reused, this one was the only one missing.

---
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/31618864886

author
#4 lore raw

PATCH v6 2/5 bpf: Add ksock kfuncs

In reply to Mahe Tardy

Add BPF kfuncs that allow BPF LSM programs to create and use sockets for sending data. This provides a mechanism for BPF programs to emit telemetry. For this first patch set, it's restricted to SOCK_DGRAM socket types with IPPROTO_UDP protocol but could be easily extended to SOCK_STREAM and IPPROTO_TCP in the future.

The API consists of five kfuncs:

  bpf_ksock_create()   - Create a socket (sleepable)
  bpf_ksock_connect()  - Connect socket to remote address (sleepable)
  bpf_ksock_send()     - Send data through the socket (sleepable)
  bpf_ksock_acquire()  - Acquire a reference to a socket context
  bpf_ksock_release()  - Release a reference (cleanup via

queue_rcu_work since sock_release sleeps)

The setup kfuncs bpf_ksock_create, bpf_ksock_connect, can be called from SYSCALL programs only. While bpf_ksock_acquire, bpf_ksock_release and bpf_ksock_send can be called from SYSCALL and LSM programs.

The implementation follows the established kfunc lifecycle pattern (create/acquire/release with refcounting, kptr map storage, dtor registration). The kernel socket is wrapped in a refcounted bpf_ksock struct. Cleanup is deferred via queue_rcu_work() because sock_release() may sleep.

The kfuncs are only compiled when CONFIG_INET is enabled, as they specifically support AF_INET and AF_INET6 sockets.

The socket operations go through the expected LSM hooks instead of by-passing them like many kernel sockets since those are created by BPF programs and thus system users. Thus, the bpf_ksock_send() kfunc, which is exposed to LSM progs has a verifier filter protection to avoid recursion so that the whole bpf_kfunc_set kfunc set cannot be called in a program attached to security_socket_sendmsg(). Also, because of the LSM checks, we prevent the use of the kfuncs from asynchronous workqueue as the current value would then be invalid.

In bpf_ksock_create(), we copy the arg values to avoid TOCTOU races since the kfunc can sleep and the arg values could be stored in a map that could be re-written by BPF progs or even userspace programs if the map is mmaped.

---
 include/linux/bpf_ksock.h |  36 ++++
 kernel/bpf/verifier.c     |   3 +
 net/core/Makefile         |   3 +
 net/core/bpf_ksock.c      | 335 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 377 insertions(+)
 create mode 100644 include/linux/bpf_ksock.h
 create mode 100644 net/core/bpf_ksock.c
include/linux/bpf_ksock.h new file +36 -0
new file mode 100644
index 000000000000..cb387fb75e43
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* Copyright (c) 2026 Isovalent */
+
+#ifndef _BPF_KSOCK_H
+#define _BPF_KSOCK_H
+
+#include <linux/types.h>
+#include <linux/in.h>
+#include <linux/in6.h>
+
+/**
+ * struct bpf_ksock_create_opts - BPF kernel socket creation parameters
+ * @family:	Address family: AF_INET or AF_INET6.
+ * @type:	Socket type: only SOCK_DGRAM supported for now.
+ * @protocol:	Protocol number (e.g. IPPROTO_UDP), or 0 for the default protocol
+ *		of the given type.
+ * @reserved:	Must be zero. Reserved for future use.
+ */
+struct bpf_ksock_create_opts {
+	__u8 family;
+	__u8 type;
+	__u8 protocol;
+	__u8 reserved;
+};
+
+/**
+ * union bpf_ksock_addr - IPv4 or IPv6 socket address
+ * @sin: IPv4 socket address.
+ * @sin6: IPv6 socket address.
+ */
+union bpf_ksock_addr {
+	struct sockaddr_in sin;
+	struct sockaddr_in6 sin6;
+};
+
+#endif /* _BPF_KSOCK_H */
kernel/bpf/verifier.c +3 -0
index 52be0a118cce..4f3de0a4b0c1 100644
@@ -4445,6 +4445,9 @@ BTF_ID(struct, task_struct)
 #ifdef CONFIG_CRYPTO
 BTF_ID(struct, bpf_crypto_ctx)
 #endif
+#ifdef CONFIG_INET
+BTF_ID(struct, bpf_ksock)
+#endif
 BTF_SET_END(rcu_protected_types)
 
 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
net/core/Makefile +3 -0
index b3fdcb4e355f..a9295b785901 100644
@@ -44,6 +44,9 @@ obj-$(CONFIG_FAILOVER) += failover.o
 obj-$(CONFIG_NET_SOCK_MSG) += skmsg.o
 obj-$(CONFIG_BPF_SYSCALL) += sock_map.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_sk_storage.o
+ifneq ($(CONFIG_INET),)
+obj-$(CONFIG_BPF_SYSCALL) += bpf_ksock.o
+endif
 obj-$(CONFIG_OF)	+= of_net.o
 obj-$(CONFIG_NET_TEST) += net_test.o
 obj-$(CONFIG_NET_DEVMEM) += devmem.o
net/core/bpf_ksock.c new file +335 -0

335 lines not on this page · raw message

--
2.34.1

reviewer Acked-by on v6 2/5
#5 lore raw

Re: [PATCH bpf-next v6 2/5] bpf: Add ksock kfuncs

On Wed, Aug 12, 2026 at 8:43 AM Mahe Tardy <[email protected]> wrote:
[...]

Quoted 9 lines

In bpf_ksock_create(), we copy the arg values to avoid TOCTOU races since the kfunc can sleep and the arg values could be stored in a map that could be re-written by BPF progs or even userspace programs if the map is mmaped.

#6 lore raw

Re: [PATCH bpf-next v6 2/5] bpf: Add ksock kfuncs

In reply to Mahe Tardy
This isn't a bug, but would 'ifdef CONFIG_INET' be preferable here to match the rest of net/? There are zero occurrences of 'ifneq ($(CONFIG_...),)' and fourteen occurrences of 'ifdef CONFIG_...'…
Quoted 5 lines
net/core/Makefile +0 -0
index b3fdcb4e355fa..a9295b7859010 100644

net/core/Makefile obj-$(CONFIG_FAILOVER) += failover.o · line 52

Quoted 9 lines
net/core/Makefile +3 -0
@@ -44,6 +44,9 @@ obj-$(CONFIG_FAILOVER) += failover.o
 obj-$(CONFIG_NET_SOCK_MSG) += skmsg.o
 obj-$(CONFIG_BPF_SYSCALL) += sock_map.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_sk_storage.o
+ifneq ($(CONFIG_INET),)
+obj-$(CONFIG_BPF_SYSCALL) += bpf_ksock.o
+endif
 obj-$(CONFIG_OF)	+= of_net.o
 obj-$(CONFIG_NET_TEST) += net_test.o
 obj-$(CONFIG_NET_DEVMEM) += devmem.o

This isn't a bug, but would 'ifdef CONFIG_INET' be preferable here to match the rest of net/? There are zero occurrences of 'ifneq ($(CONFIG_...),)' and fourteen occurrences of 'ifdef CONFIG_...' across net/**/Makefile, and this is the only conditional block in net/core/Makefile.

Quoted 5 lines
net/core/bpf_ksock.c new file +0 -0
new file mode 100644
index 0000000000000..d65200679b65d

[ ... ]

Quoted 34 lines
net/core/bpf_ksock.c new file +34 -0
+/**
+ * bpf_ksock_connect() - Connect a BPF kernel socket to a remote address.
+ * @ks:		The BPF kernel socket context.
+ * @addr:	Pointer to an IPv4 or IPv6 socket address.
+ * @addr__sz:	Size of the address union.
+ *
+ * Connects the socket to the specified remote address and port.
+ *
+ * This function may sleep while connecting the socket, so it can only be used
+ * in sleepable BPF programs (SYSCALL).
+ *
+ * Return: 0 on success, negative errno on error.
+ */
+__bpf_kfunc int bpf_ksock_connect(struct bpf_ksock *ks,
+				  const union bpf_ksock_addr *addr,
+				  u32 addr__sz)
+{
+	struct sockaddr_storage sa;
+	int addrlen;
+
+	if (!bpf_ksock_has_user_task_context())
+		return -EOPNOTSUPP;
+
+	if (!addr || addr__sz != sizeof(*addr))
+		return -EINVAL;
+
+	/* Kfunc memory arguments may be unaligned. */
+	memcpy(&sa, addr, sizeof(*addr));
+
+	switch (sa.ss_family) {
+	case AF_INET:
+		addrlen = sizeof(struct sockaddr_in);
+		break;
+#if IS_ENABLED(CONFIG_IPV6)

net/core/bpf_ksock.c line 192

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+	case AF_INET6:
+		addrlen = sizeof(struct sockaddr_in6);
+		break;
+#endif
+	default:
+		return -EAFNOSUPPORT;
+	}
+
+	return connect_socket(ks->sock, &sa, addrlen, 0);
+}

This isn't a bug, but could the #if IS_ENABLED(CONFIG_IPV6) guard be dropped? struct sockaddr_in6 is defined unconditionally in include/uapi/linux/in6.h, and union bpf_ksock_addr in the new header already references it without a guard. bpf_ksock_create() accepts opts_copy.family == AF_INET6 unconditionally and relies on sock_create() to return -EAFNOSUPPORT when IPv6 is not built. With CONFIG_IPV6=n, the net effect is identical (-EAFNOSUPPORT either way), so dropping the guard would make bpf_ksock_connect() and bpf_ksock_create() validate families the same way.

[ ... ]

Quoted 24 lines
net/core/bpf_ksock.c new file +24 -0
+/**
+ * bpf_ksock_send() - Send data through a BPF kernel socket.
+ * @ks:		The BPF kernel socket context. Must be an acquired reference.
+ * @data:	Pointer to the data to send.
+ * @data__sz:	Size of the data to send (max 65535 bytes).
+ *
+ * Sends data on a connected socket, best-effort and nonblocking. This may sleep
+ * (kernel_sendmsg), so it can only be called from sleepable BPF programs.
+ *
+ * Return: Number of bytes sent on success, negative errno on error.
+ */
+__bpf_kfunc int bpf_ksock_send(struct bpf_ksock *ks, const void *data,
+			       u32 data__sz)
+{
+	struct msghdr msg = {
+		.msg_flags = MSG_DONTWAIT,
+	};
+	struct kvec iov = {
+		.iov_base = (void *)data,
+		.iov_len = data__sz,
+	};
+	int ret;
+
+	if (!bpf_ksock_has_user_task_context())

net/core/bpf_ksock.c line 263

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+		return -EOPNOTSUPP;
+
+	/* Early check for UDP. Exact limits enforced by kernel_sendmsg(). */
+	if (data__sz > IP_MAX_MTU)
+		return -EMSGSIZE;
+
+	ret = kernel_sendmsg(ks->sock, &msg, &iov, 1, data__sz);
+
+	return ret;
+}

This isn't a bug, but is the 64K cap intentional for AF_INET6 sockets? The early size check uses IP_MAX_MTU, an IPv4-specific constant (0xFFFF), even though bpf_ksock_create() also accepts AF_INET6. udp_sendmsg() rejects len > 0xFFFF so the bound matches exactly for IPv4, but udpv6_sendmsg() allows up to INT_MAX - sizeof(struct udphdr), so AF_INET6 sockets are silently capped at 64K by this kfunc rather than by the protocol. Also, should the comment say udp_sendmsg()/udpv6_sendmsg() instead of kernel_sendmsg()? kernel_sendmsg() performs no length validation - the limits come from udp_sendmsg()/udpv6_sendmsg() and ip_append_data().

---
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/31618864886

author
#7 lore raw

Re: [PATCH bpf-next v6 2/5] bpf: Add ksock kfuncs

Quoted 12 lines · On Wed, Aug 12, 2026 at 05:39:05PM +0000, [email protected] wrote:
Quoted 12 lines
net/core/Makefile +3 -0
index b3fdcb4e355fa..a9295b7859010 100644
@@ -44,6 +44,9 @@ obj-$(CONFIG_FAILOVER) += failover.o
 obj-$(CONFIG_NET_SOCK_MSG) += skmsg.o
 obj-$(CONFIG_BPF_SYSCALL) += sock_map.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_sk_storage.o
+ifneq ($(CONFIG_INET),)
+obj-$(CONFIG_BPF_SYSCALL) += bpf_ksock.o
+endif
 obj-$(CONFIG_OF)	+= of_net.o
Quoted 8 lines

net/core/Makefile obj-$(CONFIG_FAILOVER) += failover.o · line 52

Quoted 2 lines
net/core/Makefile +0 -0
 obj-$(CONFIG_NET_TEST) += net_test.o
 obj-$(CONFIG_NET_DEVMEM) += devmem.o

This isn't a bug, but would 'ifdef CONFIG_INET' be preferable here to match the rest of net/? There are zero occurrences of 'ifneq ($(CONFIG_...),)' and fourteen occurrences of 'ifdef CONFIG_...' across net/**/Makefile, and this is the only conditional block in net/core/Makefile.

whatever is fine by me.

Quoted 55 lines
Quoted 6 lines
net/core/bpf_ksock.c new file +0 -0
new file mode 100644
index 0000000000000..d65200679b65d

[ ... ]

Quoted 34 lines
net/core/bpf_ksock.c new file +34 -0
+/**
+ * bpf_ksock_connect() - Connect a BPF kernel socket to a remote address.
+ * @ks:		The BPF kernel socket context.
+ * @addr:	Pointer to an IPv4 or IPv6 socket address.
+ * @addr__sz:	Size of the address union.
+ *
+ * Connects the socket to the specified remote address and port.
+ *
+ * This function may sleep while connecting the socket, so it can only be used
+ * in sleepable BPF programs (SYSCALL).
+ *
+ * Return: 0 on success, negative errno on error.
+ */
+__bpf_kfunc int bpf_ksock_connect(struct bpf_ksock *ks,
+				  const union bpf_ksock_addr *addr,
+				  u32 addr__sz)
+{
+	struct sockaddr_storage sa;
+	int addrlen;
+
+	if (!bpf_ksock_has_user_task_context())
+		return -EOPNOTSUPP;
+
+	if (!addr || addr__sz != sizeof(*addr))
+		return -EINVAL;
+
+	/* Kfunc memory arguments may be unaligned. */
+	memcpy(&sa, addr, sizeof(*addr));
+
+	switch (sa.ss_family) {
+	case AF_INET:
+		addrlen = sizeof(struct sockaddr_in);
+		break;
+#if IS_ENABLED(CONFIG_IPV6)

net/core/bpf_ksock.c line 192

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+	case AF_INET6:
+		addrlen = sizeof(struct sockaddr_in6);
+		break;
+#endif
+	default:
+		return -EAFNOSUPPORT;
+	}
+
+	return connect_socket(ks->sock, &sa, addrlen, 0);
+}

This isn't a bug, but could the #if IS_ENABLED(CONFIG_IPV6) guard be

Quoted 8 lines

dropped? struct sockaddr_in6 is defined unconditionally in include/uapi/linux/in6.h, and union bpf_ksock_addr in the new header already references it without a guard. bpf_ksock_create() accepts opts_copy.family == AF_INET6 unconditionally and relies on sock_create() to return -EAFNOSUPPORT when IPv6 is not built. With CONFIG_IPV6=n, the net effect is identical (-EAFNOSUPPORT either way), so dropping the guard would make bpf_ksock_connect() and bpf_ksock_create() validate families the same way.

Yep let's drop this if unecessary.

Quoted 40 lines

[ ... ]

Quoted 24 lines
net/core/bpf_ksock.c new file +24 -0
+/**
+ * bpf_ksock_send() - Send data through a BPF kernel socket.
+ * @ks:		The BPF kernel socket context. Must be an acquired reference.
+ * @data:	Pointer to the data to send.
+ * @data__sz:	Size of the data to send (max 65535 bytes).
+ *
+ * Sends data on a connected socket, best-effort and nonblocking. This may sleep
+ * (kernel_sendmsg), so it can only be called from sleepable BPF programs.
+ *
+ * Return: Number of bytes sent on success, negative errno on error.
+ */
+__bpf_kfunc int bpf_ksock_send(struct bpf_ksock *ks, const void *data,
+			       u32 data__sz)
+{
+	struct msghdr msg = {
+		.msg_flags = MSG_DONTWAIT,
+	};
+	struct kvec iov = {
+		.iov_base = (void *)data,
+		.iov_len = data__sz,
+	};
+	int ret;
+
+	if (!bpf_ksock_has_user_task_context())

net/core/bpf_ksock.c line 263

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+		return -EOPNOTSUPP;
+
+	/* Early check for UDP. Exact limits enforced by kernel_sendmsg(). */
+	if (data__sz > IP_MAX_MTU)
+		return -EMSGSIZE;
+
+	ret = kernel_sendmsg(ks->sock, &msg, &iov, 1, data__sz);
+
+	return ret;
+}

This isn't a bug, but is the 64K cap intentional for AF_INET6 sockets? The early size check uses IP_MAX_MTU, an IPv4-specific constant (0xFFFF),

Quoted 8 lines

even though bpf_ksock_create() also accepts AF_INET6. udp_sendmsg() rejects len > 0xFFFF so the bound matches exactly for IPv4, but udpv6_sendmsg() allows up to INT_MAX - sizeof(struct udphdr), so AF_INET6 sockets are silently capped at 64K by this kfunc rather than by the protocol. Also, should the comment say udp_sendmsg()/udpv6_sendmsg() instead of kernel_sendmsg()? kernel_sendmsg() performs no length validation - the limits come from udp_sendmsg()/udpv6_sendmsg() and ip_append_data().

I think we can just remove this check for now.

Quoted 7 lines

---
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/31618864886

author
#8 lore raw

PATCH v6 3/5 selftests/bpf: Add ksock kfunc test

In reply to Mahe Tardy

Add a selftest that exercises the ksock kfuncs end-to-end. One syscall bpf setup program creates a ksock context and connects the socket. Another LSM sleepable bpf program looks up the context and send test data. The userspace harness creates a network namespace and a new socket on loopback, run the setup and send syscall bpf progs then check that the userspace socket received the data from bpf.

---
 .../testing/selftests/bpf/prog_tests/ksock.c  | 127 ++++++++++++++++++
 .../selftests/bpf/progs/ksock_common.h        |  78 +++++++++++
 tools/testing/selftests/bpf/progs/ksock_lsm.c |  72 ++++++++++
 3 files changed, 277 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/ksock.c
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_common.h
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_lsm.c
tools/testing/selftests/bpf/prog_tests/ksock.c new file +127 -0
new file mode 100644
index 000000000000..30e89d34d388
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <arpa/inet.h>
+
+#include "test_progs.h"
+#include "network_helpers.h"
+#include "ksock_lsm.skel.h"
+
+#define NS_TEST "ksock_lsm_ns"
+#define RECV_PORT 7777
+#define RECV_TIMEOUT_SEC 5
+
+struct ksock_test_env {
+	bool netns_created;
+	struct nstoken *nstoken;
+	int rfd;
+};
+
+static bool ksock_test_env_setup(struct ksock_test_env *env)
+{
+	struct sockaddr_in addr = {
+		.sin_family = AF_INET,
+		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+		.sin_port = htons(RECV_PORT),
+	};
+	struct timeval tv = { .tv_sec = RECV_TIMEOUT_SEC };
+	int err;
+
+	memset(env, 0, sizeof(*env));
+	env->rfd = -1;
+
+	SYS(fail, "ip netns add %s", NS_TEST);
+	env->netns_created = true;
+	SYS(fail, "ip -net %s link set lo up", NS_TEST);
+
+	env->nstoken = open_netns(NS_TEST);
+	if (!ASSERT_OK_PTR(env->nstoken, "open_netns"))
+		goto fail;
+
+	env->rfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+	if (!ASSERT_OK_FD(env->rfd, "receiver socket"))
+		goto fail;
+
+	err = bind(env->rfd, (struct sockaddr *)&addr, sizeof(addr));
+	if (!ASSERT_OK(err, "bind receiver"))
+		goto fail;
+
+	err = setsockopt(env->rfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+	if (!ASSERT_OK(err, "set rcvtimeo"))
+		goto fail;
+
+	return true;
+
+fail:
+	return false;
+}
+
+void test_ksock_lsm(void)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct ksock_test_env env;
+	struct sockaddr_in trigger_addr = {
+		.sin_family = AF_INET,
+		.sin_addr.s_addr = htonl(INADDR_LOOPBACK),
+	};
+	struct ksock_lsm *skel;
+	char recv_data[sizeof(skel->data->send_data)] = {};
+	ssize_t n;
+	int tfd = -1;
+	int err;
+
+	skel = ksock_lsm__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel open_and_load"))
+		return;
+
+	if (!ksock_test_env_setup(&env))
+		goto fail;
+
+	/* Step 1: Run the setup SYSCALL prog to create the ksock */
+	skel->bss->ipv4_remote = htonl(INADDR_LOOPBACK);
+	skel->bss->remote_port = RECV_PORT;
+	err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.ksock_setup),
+				     &opts);
+	if (!ASSERT_OK(err, "ksock_setup run"))
+		goto fail;
+	if (!ASSERT_OK(opts.retval, "ksock_setup retval"))
+		goto fail;
+
+	/* Step 2: Attach LSM prog and trigger socket_bind from userspace */
+	skel->links.ksock_socket_bind =
+		bpf_program__attach_lsm(skel->progs.ksock_socket_bind);
+	if (!ASSERT_OK_PTR(skel->links.ksock_socket_bind,
+			   "attach socket_bind lsm"))
+		goto fail;
+
+	tfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+	if (!ASSERT_OK_FD(tfd, "trigger socket"))
+		goto fail;
+
+	skel->bss->target_pid = getpid();
+	err = bind(tfd, (struct sockaddr *)&trigger_addr, sizeof(trigger_addr));
+	skel->bss->target_pid = 0;
+	if (!ASSERT_OK(err, "trigger bind"))
+		goto fail;
+
+	/* Step 3: Verify the LSM hook sent the notification */
+	if (!ASSERT_EQ(skel->data->send_ret, sizeof(skel->data->send_data),
+		       "LSM send bytes"))
+		goto fail;
+
+	n = recvfrom(env.rfd, recv_data, sizeof(recv_data), 0, NULL, NULL);
+	if (ASSERT_EQ(n, sizeof(recv_data), "recvfrom len"))
+		ASSERT_MEMEQ(recv_data, skel->data->send_data, sizeof(recv_data),
+			     "payload match");
+
+fail:
+	if (tfd >= 0)
+		close(tfd);
+	if (env.rfd >= 0)
+		close(env.rfd);
+	if (env.nstoken)
+		close_netns(env.nstoken);
+	if (env.netns_created)
+		SYS_NOFAIL("ip netns del %s >/dev/null 2>&1", NS_TEST);
+	ksock_lsm__destroy(skel);
+}
tools/testing/selftests/bpf/progs/ksock_common.h new file +78 -0

78 lines not on this page · raw message

tools/testing/selftests/bpf/progs/ksock_lsm.c new file +72 -0

72 lines not on this page · raw message

--
2.34.1

#9 lore raw

Re: [PATCH bpf-next v6 3/5] selftests/bpf: Add ksock kfunc test

The description says "run the setup and send syscall bpf progs" but the test adds only one SEC("syscall") program, ksock_setup:
Quoted 6 lines

Add a selftest that exercises the ksock kfuncs end-to-end. One syscall bpf setup program creates a ksock context and connects the socket. Another LSM sleepable bpf program looks up the context and send test data. The userspace harness creates a network namespace and a new socket on loopback, run the setup and send syscall bpf progs then check that the userspace socket received the data from bpf.

The description says "run the setup and send syscall bpf progs" but the test adds only one SEC("syscall") program, ksock_setup:

tools/testing/selftests/bpf/progs/ksock_lsm.c:

    SEC("syscall")
    int ksock_setup(void *ctx)
    { ... }

which the harness runs once:

    err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.ksock_setup), &opts);

The send doesn't happen in a syscall program at all. It happens in the sleepable LSM program ksock_socket_bind (SEC("lsm.s/socket_bind")), which the harness triggers indirectly:

    skel->links.ksock_socket_bind = bpf_program__attach_lsm(skel->progs.ksock_socket_bind);
    ...
    skel->bss->target_pid = getpid();
    err = bind(tfd, (struct sockaddr *)&trigger_addr, sizeof(trigger_addr));

This also contradicts the preceding sentence which correctly states the sender is "Another LSM sleepable bpf program". Should this say "run the setup syscall bpf prog and trigger the LSM send hook" or similar?

Also in the same sentences: "looks up the context and send test data" (sends) and "The userspace harness ... run the setup" (runs).

Quoted 27 lines
tools/testing/selftests/bpf/prog_tests/ksock.c new file +21 -0
new file mode 100644
index 0000000000000..30e89d34d388f
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <arpa/inet.h>
+
+#include "test_progs.h"
+#include "network_helpers.h"
+#include "ksock_lsm.skel.h"
+
+#define NS_TEST "ksock_lsm_ns"
+#define RECV_PORT 7777
+#define RECV_TIMEOUT_SEC 5
+
+struct ksock_test_env {
+	bool netns_created;
+	struct nstoken *nstoken;
+	int rfd;
+};
+
+static bool ksock_test_env_setup(struct ksock_test_env *env)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/ksock.c line 35

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/ksock.c new file +6 -0
+	memset(env, 0, sizeof(*env));
+	env->rfd = -1;
+
+	SYS(fail, "ip netns add %s", NS_TEST);
+	env->netns_created = true;
+	SYS(fail, "ip -net %s link set lo up", NS_TEST);

This isn't a bug, but the test hand-rolls network namespace setup that network_helpers.h (already included at the top) provides verbatim. Could ksock_test_env_setup() use make_netns() here?

make_netns() in tools/testing/selftests/bpf/network_helpers.c runs exactly those two commands:

    r = asprintf(&cmd, "ip netns add %s", name);
    ...
    r = asprintf(&cmd, "ip -n %s link set lo up", name);

and it also unwinds the namespace if bringing lo up fails, which the open-coded version does not do. The current path leaves the netns to be cleaned up by the caller's fail: label instead.

The teardown at the end of test_ksock_lsm():

    SYS_NOFAIL("ip netns del %s >/dev/null 2>&1", NS_TEST);

is also what remove_netns() does, and SYS_NOFAIL() already appends " >/dev/null 2>&1" (test_progs.h), so the explicit redirection is applied twice and the command ends up as
"ip netns del ksock_lsm_ns >/dev/null 2>&1 >/dev/null 2>&1".

Using make_netns()/remove_netns() would remove the duplicated redirection, drop the env->netns_created bookkeeping field, and inherit the shared helper's teardown-on-partial-failure behaviour.

tools/testing/selftests/bpf/prog_tests/ksock.c

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/ksock.c new file +2 -0
+
+	env->nstoken = open_netns(NS_TEST);

[ ... ]

---
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/31618864886

author
#10 lore raw

Re: [PATCH bpf-next v6 3/5] selftests/bpf: Add ksock kfunc test

Quoted 28 lines · On Wed, Aug 12, 2026 at 05:25:42PM +0000, [email protected] wrote:
Quoted 6 lines

Add a selftest that exercises the ksock kfuncs end-to-end. One syscall bpf setup program creates a ksock context and connects the socket. Another LSM sleepable bpf program looks up the context and send test data. The userspace harness creates a network namespace and a new socket on loopback, run the setup and send syscall bpf progs then check that the userspace socket received the data from bpf.

The description says "run the setup and send syscall bpf progs" but the test adds only one SEC("syscall") program, ksock_setup:

tools/testing/selftests/bpf/progs/ksock_lsm.c:

    SEC("syscall")
    int ksock_setup(void *ctx)
    { ... }

which the harness runs once:

    err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.ksock_setup), &opts);

The send doesn't happen in a syscall program at all. It happens in the sleepable LSM program ksock_socket_bind (SEC("lsm.s/socket_bind")), which the harness triggers indirectly:

    skel->links.ksock_socket_bind = bpf_program__attach_lsm(skel->progs.ksock_socket_bind);
    ...
    skel->bss->target_pid = getpid();
    err = bind(tfd, (struct sockaddr *)&trigger_addr, sizeof(trigger_addr));
Quoted 6 lines

This also contradicts the preceding sentence which correctly states the sender is "Another LSM sleepable bpf program". Should this say "run the setup syscall bpf prog and trigger the LSM send hook" or similar?

Also in the same sentences: "looks up the context and send test data" (sends) and "The userspace harness ... run the setup" (runs).

Yeah this is from a earlier version of this, will fix it.

Quoted 57 lines
Quoted 28 lines
tools/testing/selftests/bpf/prog_tests/ksock.c new file +21 -0
new file mode 100644
index 0000000000000..30e89d34d388f
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <arpa/inet.h>
+
+#include "test_progs.h"
+#include "network_helpers.h"
+#include "ksock_lsm.skel.h"
+
+#define NS_TEST "ksock_lsm_ns"
+#define RECV_PORT 7777
+#define RECV_TIMEOUT_SEC 5
+
+struct ksock_test_env {
+	bool netns_created;
+	struct nstoken *nstoken;
+	int rfd;
+};
+
+static bool ksock_test_env_setup(struct ksock_test_env *env)
+{

[ ... ]

tools/testing/selftests/bpf/prog_tests/ksock.c line 35

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/ksock.c new file +6 -0
+	memset(env, 0, sizeof(*env));
+	env->rfd = -1;
+
+	SYS(fail, "ip netns add %s", NS_TEST);
+	env->netns_created = true;
+	SYS(fail, "ip -net %s link set lo up", NS_TEST);

This isn't a bug, but the test hand-rolls network namespace setup that network_helpers.h (already included at the top) provides verbatim. Could ksock_test_env_setup() use make_netns() here?

make_netns() in tools/testing/selftests/bpf/network_helpers.c runs exactly those two commands:

    r = asprintf(&cmd, "ip netns add %s", name);
    ...
    r = asprintf(&cmd, "ip -n %s link set lo up", name);

and it also unwinds the namespace if bringing lo up fails, which the open-coded version does not do. The current path leaves the netns to be cleaned up by the caller's fail: label instead.

The teardown at the end of test_ksock_lsm():

    SYS_NOFAIL("ip netns del %s >/dev/null 2>&1", NS_TEST);
Quoted 8 lines

is also what remove_netns() does, and SYS_NOFAIL() already appends " >/dev/null 2>&1" (test_progs.h), so the explicit redirection is applied twice and the command ends up as
"ip netns del ksock_lsm_ns >/dev/null 2>&1 >/dev/null 2>&1".

Using make_netns()/remove_netns() would remove the duplicated redirection, drop the env->netns_created bookkeeping field, and inherit the shared helper's teardown-on-partial-failure behaviour.

Good point.

Quoted 12 lines

tools/testing/selftests/bpf/prog_tests/ksock.c

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/ksock.c new file +2 -0
+
+	env->nstoken = open_netns(NS_TEST);

[ ... ]

---
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/31618864886

author
#11 lore raw

PATCH v6 4/5 selftests/bpf: Test forbidden bpf_ksock_send() LSM attach

In reply to Mahe Tardy

The bpf_ksock_send() kfunc eventually calls security_socket_sendmsg(), thus creating a possible recursion if a program calling the kfunc is attached on that specific hook. A filter is added on the kfunc registration to prevent that at load time from the verifier. This test exercises that the verifier will reject such program on that attach point.

---
 .../testing/selftests/bpf/prog_tests/ksock.c  |  6 ++++
 .../selftests/bpf/progs/ksock_lsm_verifier.c  | 35 +++++++++++++++++++
 2 files changed, 41 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c
tools/testing/selftests/bpf/prog_tests/ksock.c +6 -0
index 30e89d34d388..fb1a332eb3da 100644
@@ -6,6 +6,7 @@
 #include "test_progs.h"
 #include "network_helpers.h"
 #include "ksock_lsm.skel.h"
+#include "ksock_lsm_verifier.skel.h"
 
 #define NS_TEST "ksock_lsm_ns"
 #define RECV_PORT 7777
@@ -125,3 +126,8 @@ void test_ksock_lsm(void)
 		SYS_NOFAIL("ip netns del %s >/dev/null 2>&1", NS_TEST);
 	ksock_lsm__destroy(skel);
 }
+
+void test_ksock_lsm_verifier(void)
+{
+	RUN_TESTS(ksock_lsm_verifier);
+}
tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c new file +35 -0
new file mode 100644
index 000000000000..fd2ccfdb5802
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+#include "bpf_misc.h"
+#include "ksock_common.h"
+
+char send_data[11] = "dummy data";
+
+SEC("lsm.s/socket_sendmsg")
+__description("bpf_ksock_send is rejected from socket_sendmsg LSM hook")
+__failure __msg("calling kernel function bpf_ksock_send is not allowed")
+int BPF_PROG(ksock_socket_sendmsg, struct socket *sock, struct msghdr *msg,
+	     int size, int ret)
+{
+	struct __ksock_ctx_value *v;
+	struct bpf_ksock *ks;
+
+	v = ksock_ctx_value_lookup();
+	if (!v)
+		return ret;
+
+	ks = bpf_kptr_xchg(&v->ctx, NULL);
+	if (!ks)
+		return ret;
+
+	bpf_ksock_send(ks, send_data, sizeof(send_data));
+	bpf_ksock_release(ks);
+
+	return ret;
+}
+
+char __license[] SEC("license") = "GPL";

--
2.34.1

reviewer Acked-by on v6 4/5
#12 lore raw

Re: [PATCH bpf-next v6 4/5] selftests/bpf: Test forbidden bpf_ksock_send() LSM attach

Quoted 10 lines · Mahe Tardy

The bpf_ksock_send() kfunc eventually calls security_socket_sendmsg(), thus creating a possible recursion if a program calling the kfunc is attached on that specific hook. A filter is added on the kfunc registration to prevent that at load time from the verifier. This test exercises that the verifier will reject such program on that attach point.

author
#13 lore raw

PATCH v6 5/5 selftests/bpf: Add ksock test for async callback guard

In reply to Mahe Tardy

Because the kfuncs are going through LSM hooks, allowing their use via workqueue callbacks would expose the wrong credentials. This test ensures the kfunc are preventing any use from these contexts.

---
 .../selftests/bpf/prog_tests/ksock_wq.c       | 34 ++++++++++
 tools/testing/selftests/bpf/progs/ksock_wq.c  | 62 +++++++++++++++++++
 2 files changed, 96 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/ksock_wq.c
 create mode 100644 tools/testing/selftests/bpf/progs/ksock_wq.c
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +34 -0
new file mode 100644
index 000000000000..5b9c6cc30392
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <unistd.h>
+
+#include "test_progs.h"
+#include "ksock_wq.skel.h"
+
+void test_ksock_wq(void)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct ksock_wq *skel;
+	int err;
+
+	skel = ksock_wq__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "ksock_wq open and load"))
+		return;
+
+	err = bpf_prog_test_run_opts(
+		bpf_program__fd(skel->progs.ksock_wq_start), &opts);
+	if (!ASSERT_OK(err, "run ksock_wq_start"))
+		goto out;
+	if (!ASSERT_OK(opts.retval, "ksock_wq_start retval"))
+		goto out;
+
+	while (!__atomic_load_n(&skel->bss->callback_done, __ATOMIC_ACQUIRE))
+		usleep(1000);
+
+	ASSERT_EQ(skel->bss->create_err, -EOPNOTSUPP,
+		  "workqueue create rejected");
+
+out:
+	ksock_wq__destroy(skel);
+}
tools/testing/selftests/bpf/progs/ksock_wq.c new file +62 -0

62 lines not on this page · raw message

--
2.34.1

reviewer Acked-by on v6 5/5
#14 lore raw

Re: [PATCH bpf-next v6 5/5] selftests/bpf: Add ksock test for async callback guard

Quoted 7 lines · Mahe Tardy

Because the kfuncs are going through LSM hooks, allowing their use via workqueue callbacks would expose the wrong credentials. This test ensures the kfunc are preventing any use from these contexts.

#15 lore raw

Re: [PATCH bpf-next v6 5/5] selftests/bpf: Add ksock test for async callback guard

In reply to Mahe Tardy
What happens if the workqueue callback never runs or blocks? This loop is unbounded, so the test would hang forever rather than failing. test_progs has no per-test timeout, so a hang here would…
Quoted 23 lines
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +17 -0
new file mode 100644
index 0000000000000..5b9c6cc303922
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <unistd.h>
+
+#include "test_progs.h"
+#include "ksock_wq.skel.h"
+
+void test_ksock_wq(void)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct ksock_wq *skel;
+	int err;
+
+	skel = ksock_wq__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "ksock_wq open and load"))
+		return;

tools/testing/selftests/bpf/prog_tests/ksock_wq.c line 27

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +10 -0
+
+	err = bpf_prog_test_run_opts(
+		bpf_program__fd(skel->progs.ksock_wq_start), &opts);
+	if (!ASSERT_OK(err, "run ksock_wq_start"))
+		goto out;
+	if (!ASSERT_OK(opts.retval, "ksock_wq_start retval"))
+		goto out;
+
+	while (!__atomic_load_n(&skel->bss->callback_done, __ATOMIC_ACQUIRE))
+		usleep(1000);

What happens if the workqueue callback never runs or blocks? This loop is unbounded, so the test would hang forever rather than failing. test_progs has no per-test timeout, so a hang here would block the entire test run.

Adding an iteration cap (e.g. a bounded retry count followed by an ASSERT on callback_done) would turn a CI hang into a normal test failure. For comparison, prog_tests/wq.c uses a bounded usleep(50) before asserting.

tools/testing/selftests/bpf/prog_tests/ksock_wq.c line 34

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +7 -0
+
+	ASSERT_EQ(skel->bss->create_err, -EOPNOTSUPP,
+		  "workqueue create rejected");
+
+out:
+	ksock_wq__destroy(skel);
+}

[ ... ]

---
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/31618864886

author
#16 lore raw

Re: [PATCH bpf-next v6 5/5] selftests/bpf: Add ksock test for async callback guard

Quoted 38 lines · On Wed, Aug 12, 2026 at 05:25:40PM +0000, [email protected] wrote:
Quoted 23 lines
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +17 -0
new file mode 100644
index 0000000000000..5b9c6cc303922
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2026 Isovalent */
+
+#include <unistd.h>
+
+#include "test_progs.h"
+#include "ksock_wq.skel.h"
+
+void test_ksock_wq(void)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct ksock_wq *skel;
+	int err;
+
+	skel = ksock_wq__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "ksock_wq open and load"))
+		return;

tools/testing/selftests/bpf/prog_tests/ksock_wq.c line 27

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +10 -0
+
+	err = bpf_prog_test_run_opts(
+		bpf_program__fd(skel->progs.ksock_wq_start), &opts);
+	if (!ASSERT_OK(err, "run ksock_wq_start"))
+		goto out;
+	if (!ASSERT_OK(opts.retval, "ksock_wq_start retval"))
+		goto out;
+
+	while (!__atomic_load_n(&skel->bss->callback_done, __ATOMIC_ACQUIRE))
+		usleep(1000);

What happens if the workqueue callback never runs or blocks? This loop is unbounded, so the test would hang forever rather than failing. test_progs has no per-test timeout, so a hang here would block the entire test run.

Quoted 3 lines

Adding an iteration cap (e.g. a bounded retry count followed by an ASSERT on callback_done) would turn a CI hang into a normal test failure. For comparison, prog_tests/wq.c uses a bounded usleep(50) before asserting.

Unsure how likely it is but it could be indeed improved in this way.

Quoted 17 lines

tools/testing/selftests/bpf/prog_tests/ksock_wq.c line 34

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/ksock_wq.c new file +7 -0
+
+	ASSERT_EQ(skel->bss->create_err, -EOPNOTSUPP,
+		  "workqueue create rejected");
+
+out:
+	ksock_wq__destroy(skel);
+}

[ ... ]

---
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/31618864886