Skip to contentSkip to conversation

Introduce bpf_ksock

PATCH Superseded Mahe Tardy 3 participants 13 messages Aug 6 – Aug 7

Subsystems (7)

v4 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Mahe Tardy

author
#0 lore raw

v4 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.

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 v3: 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                          | 331 ++++++++++++++++++
 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        |  58 +++
 tools/testing/selftests/bpf/progs/ksock_lsm.c |  88 +++++
 .../selftests/bpf/progs/ksock_lsm_verifier.c  |  36 ++
 tools/testing/selftests/bpf/progs/ksock_wq.c  |  62 ++++
 12 files changed, 804 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 v4 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..8964528e3823 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);
+extern 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..126a674f534d 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

reviewer Acked-by on v4 1/5
#2 lore raw

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

Quoted 8 lines · Mahe Tardy

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.

#3 lore raw

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

In reply to Mahe Tardy
Quoted 30 lines · Mahe Tardy

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..8964528e3823 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);
+extern 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 +0 -0
index 63c69a0fa74e..126a674f534d 100644

net/socket.c SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, · line 2108

Quoted 6 lines
net/socket.c +3 -0
@@ -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)
+{

Please fix the checkpatch warning if revise

CHECK: extern prototypes should be avoided in .h files
#27: FILE: include/linux/socket.h:464:
+extern int connect_socket(struct socket *sock, struct sockaddr_storage *addr,

CHECK: Alignment should match open parenthesis
#28: FILE: include/linux/socket.h:465:
+extern int connect_socket(struct socket *sock, struct sockaddr_storage *addr, +                int addrlen, int flags);

CHECK: Alignment should match open parenthesis
#41: FILE: net/socket.c:2107:
+int connect_socket(struct socket *sock, struct sockaddr_storage *address, +             int addrlen, int flags)

author
#4 lore raw

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

Quoted 53 lines · Jiayuan Chen
Quoted 30 lines · Mahe Tardy

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..8964528e3823 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);
+extern 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 +0 -0
index 63c69a0fa74e..126a674f534d 100644

net/socket.c SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, · line 2108

Quoted 6 lines
net/socket.c +3 -0
@@ -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)
+{

Please fix the checkpatch warning if revise

CHECK: extern prototypes should be avoided in .h files
#27: FILE: include/linux/socket.h:464:
+extern int connect_socket(struct socket *sock, struct sockaddr_storage *addr,

CHECK: Alignment should match open parenthesis
#28: FILE: include/linux/socket.h:465:
+extern int connect_socket(struct socket *sock, struct sockaddr_storage *addr,
+                int addrlen, int flags);

Quoted 5 lines

CHECK: Alignment should match open parenthesis
#41: FILE: net/socket.c:2107:
+int connect_socket(struct socket *sock, struct sockaddr_storage *address, +             int addrlen, int flags)

Yep fixed for next revision, thanks.

author
#5 lore raw

PATCH v4 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      | 331 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 373 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 +331 -0

331 lines not on this page · raw message

--
2.34.1

#6 lore raw

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

On 8/7/26 2:22 AM, Mahe Tardy wrote:

[...]

Quoted 13 lines
net/core/bpf_ksock.c new file +13 -0
+	return ret;
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(ksock_init_kfunc_btf_ids)
+BTF_ID_FLAGS(func, bpf_ksock_create, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
+BTF_ID_FLAGS(func, bpf_ksock_connect, KF_SLEEPABLE)
+BTF_KFUNCS_END(ksock_init_kfunc_btf_ids)
+
+static const struct btf_kfunc_id_set ksock_init_kfunc_set = {
+	.owner = THIS_MODULE,
+	.set = &ksock_init_kfunc_btf_ids,

net/core/bpf_ksock.c line 284

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+};
+
+BTF_KFUNCS_START(ksock_kfunc_btf_ids)
+BTF_ID_FLAGS(func, bpf_ksock_release, KF_RELEASE)
+BTF_ID_FLAGS(func, bpf_ksock_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
+BTF_ID_FLAGS(func, bpf_ksock_send, KF_SLEEPABLE)
+BTF_KFUNCS_END(ksock_kfunc_btf_ids)
+
+BTF_ID_LIST_SINGLE(bpf_lsm_socket_sendmsg_id, func, bpf_lsm_socket_sendmsg)
+

I guess bpf_lsm_socket_sendmsg will not be compiled when CONFIG_BPF_LSM is disabled

author
#7 lore raw

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

Quoted 25 lines · Jiayuan Chen

On 8/7/26 2:22 AM, Mahe Tardy wrote:

[...]

Quoted 19 lines
net/core/bpf_ksock.c new file +19 -0
+	return ret;
+}
+
+__bpf_kfunc_end_defs();
+
+BTF_KFUNCS_START(ksock_init_kfunc_btf_ids)
+BTF_ID_FLAGS(func, bpf_ksock_create, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
+BTF_ID_FLAGS(func, bpf_ksock_connect, KF_SLEEPABLE)
+BTF_KFUNCS_END(ksock_init_kfunc_btf_ids)
+
+static const struct btf_kfunc_id_set ksock_init_kfunc_set = {
+	.owner = THIS_MODULE,
+	.set = &ksock_init_kfunc_btf_ids,
+};
+
+BTF_KFUNCS_START(ksock_kfunc_btf_ids)
+BTF_ID_FLAGS(func, bpf_ksock_release, KF_RELEASE)
+BTF_ID_FLAGS(func, bpf_ksock_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
+BTF_ID_FLAGS(func, bpf_ksock_send, KF_SLEEPABLE)
Quoted 9 lines

net/core/bpf_ksock.c line 284

Quoted 4 lines
net/core/bpf_ksock.c new file +4 -0
+BTF_KFUNCS_END(ksock_kfunc_btf_ids)
+
+BTF_ID_LIST_SINGLE(bpf_lsm_socket_sendmsg_id, func, bpf_lsm_socket_sendmsg)
+

I guess bpf_lsm_socket_sendmsg will not be compiled when CONFIG_BPF_LSM is disabled

Yes indeed we can guard this with CONFIG_BPF_LSM as it might produce a warning on building with CONFIG_BPF_LSM disabled. Thanks.

author
#8 lore raw

PATCH v4 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        |  58 ++++++++
 tools/testing/selftests/bpf/progs/ksock_lsm.c |  88 ++++++++++++
 3 files changed, 273 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 +58 -0

58 lines not on this page · raw message

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

88 lines not on this page · raw message

--
2.34.1

#9 lore raw

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

Quoted 1 line · Mahe Tardy

Add

[...]

Quoted 20 lines
tools/testing/selftests/bpf/progs/ksock_lsm.c new file +20 -0
+
+SEC("lsm.s/socket_bind")
+int BPF_PROG(ksock_socket_bind, struct socket *sock, struct sockaddr *address,
+	     int addrlen, int ret)
+{
+	struct __ksock_ctx_value *v;
+	struct bpf_ksock *ks, *tmp;
+	u32 pid = bpf_get_current_pid_tgid() >> 32;
+
+	if (ret || pid != target_pid)
+		return ret;
+
+	v = ksock_ctx_value_lookup();
+	if (!v) {
+		send_ret = -ENOENT;
+		return ret;
+	}
+
+	ks = NULL;
+	bpf_rcu_read_lock();

tools/testing/selftests/bpf/progs/ksock_lsm.c line 81

Quoted 10 lines
tools/testing/selftests/bpf/progs/ksock_lsm.c new file +10 -0
+	tmp = v->ctx;
+	if (tmp)
+		ks = bpf_ksock_acquire(tmp);
+	bpf_rcu_read_unlock();
+
+	if (!ks) {
+		send_ret = -ENOENT;
+		return ret;
+	}
+

Since bpf_ksock_send() is sleepable, every consumer of the kptr is necessarily a sleepable program and thus has to open-code the same bpf_rcu_read_lock()/acquire/unlock sequence before each send.

Given ksock_common.h already wraps the insert side, how about also providing the get side, e.g.:

static inline struct bpf_ksock *ksock_ctx_get(void) {
    struct __ksock_ctx_value *v = ksock_ctx_value_lookup(); struct bpf_ksock *ks = NULL, *tmp;

    if (!v)
            return NULL;
    bpf_rcu_read_lock();
    tmp = v->ctx;
    if (tmp)
            ks = bpf_ksock_acquire(tmp);
    bpf_rcu_read_unlock();
    return ks;
}

These selftests will be the reference everyone copies from, so encapsulating the RCU dance here also documents the correct usage.

author
#10 lore raw

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

Quoted 58 lines · Jiayuan Chen
Quoted 1 line · Mahe Tardy

Add

[...]

Quoted 20 lines
tools/testing/selftests/bpf/progs/ksock_lsm.c new file +20 -0
+
+SEC("lsm.s/socket_bind")
+int BPF_PROG(ksock_socket_bind, struct socket *sock, struct sockaddr *address,
+	     int addrlen, int ret)
+{
+	struct __ksock_ctx_value *v;
+	struct bpf_ksock *ks, *tmp;
+	u32 pid = bpf_get_current_pid_tgid() >> 32;
+
+	if (ret || pid != target_pid)
+		return ret;
+
+	v = ksock_ctx_value_lookup();
+	if (!v) {
+		send_ret = -ENOENT;
+		return ret;
+	}
+
+	ks = NULL;
+	bpf_rcu_read_lock();

tools/testing/selftests/bpf/progs/ksock_lsm.c line 81

Quoted 10 lines
tools/testing/selftests/bpf/progs/ksock_lsm.c new file +10 -0
+	tmp = v->ctx;
+	if (tmp)
+		ks = bpf_ksock_acquire(tmp);
+	bpf_rcu_read_unlock();
+
+	if (!ks) {
+		send_ret = -ENOENT;
+		return ret;
+	}
+

Since bpf_ksock_send() is sleepable, every consumer of the kptr is necessarily a sleepable program and thus has to open-code the same bpf_rcu_read_lock()/acquire/unlock sequence before each send.

Given ksock_common.h already wraps the insert side, how about also providing the get side, e.g.:

static inline struct bpf_ksock *ksock_ctx_get(void) {
    struct __ksock_ctx_value *v = ksock_ctx_value_lookup(); struct bpf_ksock *ks = NULL, *tmp;

    if (!v)
            return NULL;
    bpf_rcu_read_lock();
    tmp = v->ctx;
    if (tmp)
            ks = bpf_ksock_acquire(tmp);
    bpf_rcu_read_unlock();
    return ks;
}

Quoted 3 lines

These selftests will be the reference everyone copies from, so encapsulating the RCU dance here also documents the correct usage.

Yeah good idea, I'll just keep a slightly difference dance using bpf_kptr_xchg() in the ksock_lsm_verifier.c program because I want the verifier to bump against bpf_ksock_send() restriction explicitely and not bpf_ksock_acquire().

author
#11 lore raw

PATCH v4 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  | 36 +++++++++++++++++++
 2 files changed, 42 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 +36 -0
new file mode 100644
index 000000000000..5b969e03b6d6
@@ -0,0 +1,36 @@
+// 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 "bpf_tracing_net.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

author
#12 lore raw

PATCH v4 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