Skip to contentSkip to conversation

Introduce bpf_ksock

PATCH Superseded Mahe Tardy 5 participants 21 messages Aug 7 – Aug 12

Subsystems (7)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Mahe Tardy

author
#0 lore raw

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

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 v4: 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  |  36 ++
 tools/testing/selftests/bpf/progs/ksock_wq.c  |  62 ++++
 12 files changed, 812 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 v5 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..8f18f124d92a 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 v5 1/5] net: Add connect_socket() helper

This isn't a bug, but would a name closer to the neighbouring helpers, such as __sys_connect_socket(), read better here? The equivalent socket-level helpers in the same file follow the…
Quoted 18 lines
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 +0 -0
index 63c69a0fa74e..8f18f124d92a 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)
+{

This isn't a bug, but would a name closer to the neighbouring helpers, such as __sys_connect_socket(), read better here? The equivalent socket-level helpers in the same file follow the __sys_<op>_socket() or __sys_<op>_sock() shape (__sys_bind_socket(), __sys_listen_socket(), __sys_shutdown_sock()), and the declaration is added in the middle of that same helpers block in include/linux/socket.h. Also, net/socket.c already has kernel_connect(), which performs the same READ_ONCE(sock->ops)->connect() dispatch and differs only in not calling the LSM hook, so the two names don't signal which one a caller should pick. Could a short comment note how it differs from kernel_connect()?

Quoted 4 lines
net/socket.c +4 -0
+	int err;
+
+	err = security_socket_connect(sock, (struct sockaddr *)address, addrlen);
+	if (err)

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

Quoted 10 lines
net/socket.c +7 -0
+		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.

[ ... ]

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

author
#3 lore raw

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

Quoted 21 lines · On Fri, Aug 07, 2026 at 06:11:50PM +0000, [email protected] wrote:
Quoted 21 lines
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 +0 -0
index 63c69a0fa74e..8f18f124d92a 100644
@@ -2103,6 +2103,20 @@ SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr,
 	return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0);
 }
 
Quoted 10 lines

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

Quoted 3 lines
net/socket.c +3 -0
+int connect_socket(struct socket *sock, struct sockaddr_storage *address,
+		   int addrlen, int flags)
+{

This isn't a bug, but would a name closer to the neighbouring helpers, such as __sys_connect_socket(), read better here? The equivalent socket-level helpers in the same file follow the __sys_<op>_socket() or __sys_<op>_sock() shape (__sys_bind_socket(), __sys_listen_socket(), __sys_shutdown_sock()), and the declaration is added in the middle of that same helpers block in include/linux/socket.h. Also, net/socket.c

The __sys prefix was removed from this comment from Song[^1] which I think makes sense instead of following the convention around.

[^1]: https://lore.kernel.org/bpf/CAPhsuW5ZTqfzpxNf=S6JbmGxWf2m9qPZGberdzRdLuvv2-Xwgw@mail.gmail.com/

Quoted 4 lines

already has kernel_connect(), which performs the same READ_ONCE(sock->ops)->connect() dispatch and differs only in not calling the LSM hook, so the two names don't signal which one a caller should pick. Could a short comment note how it differs from kernel_connect()?

This is the whole point of this new function indeed.

Quoted 23 lines
Quoted 4 lines
net/socket.c +4 -0
+	int err;
+
+	err = security_socket_connect(sock, (struct sockaddr *)address, addrlen);
+	if (err)

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

Quoted 10 lines
net/socket.c +7 -0
+		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.

[ ... ]

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

Reviewed-by on v5 1/5
#4 lore raw

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

In reply to Mahe Tardy
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.

Acked-by on v5 1/5
#5 lore raw

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

In reply to Mahe Tardy
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.

maintainer Reviewed-by on v5 1/5
#6 lore raw

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

In reply to Mahe Tardy
Quoted 37 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..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 +2 -0
index 63c69a0fa74e..8f18f124d92a 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)

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

Quoted 10 lines
net/socket.c +10 -0
+{
+       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);

nit: indentation is weird, and

Quoted 20 lines
net/socket.c +2 -9
+}
+
 /*
  *     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)

net/socket.c int __sys_connect_file(struct file *file, struct sockaddr_storage *address, · line 2142

Quoted 10 lines
net/socket.c +4 -5
-               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);

same here, otherwise looks good.

author
#7 lore raw

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

Quoted 36 lines · Kuniyuki Iwashima
Quoted 35 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..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 +0 -0
index 63c69a0fa74e..8f18f124d92a 100644
@@ -2103,6 +2103,20 @@ SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr,
        return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0);
 }
 
Quoted 14 lines

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

Quoted 12 lines
net/socket.c +12 -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);

nit: indentation is weird, and

agree, ran clang-format on it, should be better in the next revision.

Quoted 25 lines
Quoted 25 lines
net/socket.c +4 -10
+}
+
 /*
  *     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;
 
Quoted 8 lines

net/socket.c int __sys_connect_file(struct file *file, struct sockaddr_storage *address, · line 2142

Quoted 6 lines
net/socket.c +2 -4
-       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);

same here, otherwise looks good.

same answer.

Quoted 2 lines
author
#8 lore raw

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

Reviewed-by on v5 2/5
#9 lore raw

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

Quoted 37 lines · 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.

Quoted 6 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.

Acked-by on v5 2/5
#10 lore raw

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

In reply to Mahe Tardy
Quoted 37 lines · 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.

Quoted 6 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.

#11 lore raw

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

In reply to Mahe Tardy
Quoted 154 lines · 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 +25 -0
new file mode 100644
index 000000000000..8a4f0150a0a4
@@ -0,0 +1,335 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 Isovalent */
+
+#include <linux/bpf.h>
+#include <linux/bpf_ksock.h>
+#include <linux/btf.h>
+#include <linux/btf_ids.h>
+#include <linux/in.h>
+#include <linux/in6.h>
+#include <linux/net.h>
+#include <linux/refcount.h>
+#include <linux/sched.h>
+#include <linux/slab.h>
+#include <linux/socket.h>
+#include <linux/unaligned.h>
+#include <linux/workqueue.h>
+#include <linux/ip.h>
+#include <net/sock.h>
+
+/**
+ * struct bpf_ksock - refcounted BPF kernel socket context
+ * @sock:      The underlying kernel socket.
+ * @usage:     Reference counter.
+ * @rwork:     RCU work for deferred cleanup (sock_release may sleep).
+ */

net/core/bpf_ksock.c line 35

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+struct bpf_ksock {
+       struct socket *sock;
+       refcount_t usage;
+       struct rcu_work rwork;
+};
+
+static void ksock_release_work_fn(struct work_struct *work)
+{
+       struct bpf_ksock *ks =
+               container_of(to_rcu_work(work), struct bpf_ksock, rwork);

nit: if you need respin:

struct bpf_ksock *ks;

ks = container_of(to_rcu_work(work), struct bpf_ksock, rwork);

Quoted 48 lines
net/core/bpf_ksock.c new file +48 -0
+
+       sock_release(ks->sock);
+       kfree(ks);
+}
+
+static bool bpf_ksock_has_user_task_context(void)
+{
+       /*
+        * Task work can run from do_exit() after exit_nsproxy_namespaces()
+        * cleared current->nsproxy, while current is still not a kthread.
+        */
+       return !(current->flags & PF_KTHREAD) && current->nsproxy;
+}
+
+__bpf_kfunc_start_defs();
+
+/**
+ * bpf_ksock_create() - Create a BPF kernel socket.
+ *
+ * Allocates and creates a kernel socket.
+ *
+ * The returned context must either be stored in a map as a kptr, or
+ * freed with bpf_ksock_release().
+ *
+ * This function may sleep (sock_create), so it can only be used
+ * in sleepable BPF programs (SYSCALL).
+ * It cannot be called from a BPF workqueue callback because that callback
+ * does not retain the invoking task's namespace or security context.
+ *
+ * @opts:      Pointer to struct bpf_ksock_create_opts with socket parameters.
+ * @opts__sz:  Size of the opts struct.
+ * @err__uninit:       Integer to store error code when NULL is returned.
+ */
+__bpf_kfunc struct bpf_ksock *
+bpf_ksock_create(const struct bpf_ksock_create_opts *opts, u32 opts__sz,
+                int *err__uninit)
+{
+       struct bpf_ksock_create_opts opts_copy;
+       struct bpf_ksock *ks;
+       int err;
+
+       /*
+        * sock_create() derives the network namespace, credentials, and cgroup
+        * from current. Kernel threads, including BPF workqueue callbacks, do
+        * not carry the context of the task that invoked the BPF program.
+        */
+       if (!bpf_ksock_has_user_task_context()) {
+               err = -EOPNOTSUPP;

net/core/bpf_ksock.c line 93

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+               goto err_out;
+       }
+
+       if (!opts || opts__sz != sizeof(struct bpf_ksock_create_opts)) {
+               err = -EINVAL;
+               goto err_out;
+       }
+
+       opts_copy = (struct bpf_ksock_create_opts){
+               .family = READ_ONCE(opts->family),

I'm not sure if we really want to care about such an arch, but since you mentioned unaligned access in bpf_ksock_connect(), is READ_OCNE() safe here ?

Quoted 245 lines
net/core/bpf_ksock.c new file +242 -1
+               .type = READ_ONCE(opts->type),
+               .protocol = READ_ONCE(opts->protocol),
+               .reserved = READ_ONCE(opts->reserved),
+       };
+
+       if (opts_copy.reserved) {
+               err = -EINVAL;
+               goto err_out;
+       }
+
+       if (opts_copy.family != AF_INET && opts_copy.family != AF_INET6) {
+               err = -EAFNOSUPPORT;
+               goto err_out;
+       }
+
+       if (opts_copy.type != SOCK_DGRAM) {
+               err = -EPROTONOSUPPORT;
+               goto err_out;
+       }
+
+       if (opts_copy.protocol != IPPROTO_UDP && opts_copy.protocol != 0) {
+               err = -EPROTONOSUPPORT;
+               goto err_out;
+       }
+
+       ks = kzalloc_obj(*ks);
+       if (!ks) {
+               err = -ENOMEM;
+               goto err_out;
+       }
+
+       /*
+        * Use the normal current-task socket path so LSM/cgroup policy,
+        * socket labels, and the active netns reference match a socket(2)
+        * created by the BPF program's caller.
+        */
+       err = sock_create(opts_copy.family, opts_copy.type, opts_copy.protocol,
+                         &ks->sock);
+       if (err)
+               goto err_free;
+
+       ks->sock->sk->sk_rcvbuf = SOCK_MIN_RCVBUF;
+       ks->sock->sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
+
+       refcount_set(&ks->usage, 1);
+       put_unaligned(0, err__uninit);
+       return ks;
+
+err_free:
+       kfree(ks);
+err_out:
+       put_unaligned(err, err__uninit);
+       return NULL;
+}
+
+/**
+ * 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)
+       case AF_INET6:
+               addrlen = sizeof(struct sockaddr_in6);
+               break;
+#endif
+       default:
+               return -EAFNOSUPPORT;
+       }
+
+       return connect_socket(ks->sock, &sa, addrlen, 0);
+}
+
+/**
+ * bpf_ksock_acquire() - Acquire a reference to a BPF kernel socket.
+ * @ks:        The BPF kernel socket context to acquire. Must be a
+ *     trusted pointer (e.g. RCU-protected kptr from a map).
+ *
+ * The acquired context must either be stored in a map as a kptr, or
+ * freed with bpf_ksock_release().
+ */
+__bpf_kfunc struct bpf_ksock *bpf_ksock_acquire(struct bpf_ksock *ks)
+{
+       if (!refcount_inc_not_zero(&ks->usage))
+               return NULL;
+       return ks;
+}
+
+/**
+ * bpf_ksock_release() - Release a BPF kernel socket.
+ * @ks:        The BPF kernel socket context to release.
+ *
+ * When the final reference is released, the socket is cleaned up via
+ * queue_rcu_work() (since sock_release may sleep).
+ */
+__bpf_kfunc void bpf_ksock_release(struct bpf_ksock *ks)
+{
+       if (refcount_dec_and_test(&ks->usage)) {
+               INIT_RCU_WORK(&ks->rwork, ksock_release_work_fn);
+               queue_rcu_work(system_dfl_wq, &ks->rwork);
+       }
+}
+
+__bpf_kfunc void bpf_ksock_release_dtor(void *ks)
+{
+       bpf_ksock_release(ks);
+}
+CFI_NOSEAL(bpf_ksock_release_dtor);
+
+/**
+ * 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())
+               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;
+}
+
+__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)
+BTF_KFUNCS_END(ksock_kfunc_btf_ids)
+
+#ifdef CONFIG_BPF_LSM
+BTF_ID_LIST_SINGLE(bpf_lsm_socket_sendmsg_id, func, bpf_lsm_socket_sendmsg)
+#endif
+
+static int bpf_ksock_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id)
+{
+       if (!btf_id_set8_contains(&ksock_kfunc_btf_ids, kfunc_id))
+               return 0;
+
+       if (prog->type == BPF_PROG_TYPE_SYSCALL)
+               return 0;
+
+#ifdef CONFIG_BPF_LSM
+       if (prog->type == BPF_PROG_TYPE_LSM &&
+           prog->aux->attach_btf_id != bpf_lsm_socket_sendmsg_id[0])
+               return 0;
+#endif
+
+       return -EACCES;
+}
+
+static const struct btf_kfunc_id_set ksock_kfunc_set = {
+       .owner = THIS_MODULE,
+       .set = &ksock_kfunc_btf_ids,
+       .filter = bpf_ksock_kfunc_filter,
+};
+
+BTF_ID_LIST(bpf_ksock_dtor_ids)
+BTF_ID(struct, bpf_ksock)
+BTF_ID(func, bpf_ksock_release_dtor)
+
+static int __init bpf_ksock_kfunc_init(void)
+{
+       int ret;
+       const struct btf_id_dtor_kfunc bpf_ksock_dtors[] = {
+               {
+                       .btf_id = bpf_ksock_dtor_ids[0],
+                       .kfunc_btf_id = bpf_ksock_dtor_ids[1],
+               },
+       };
+
+       ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
+                                       &ksock_init_kfunc_set);
+       ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
+                                              &ksock_kfunc_set);
+       ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LSM,
+                                              &ksock_kfunc_set);
+       return ret ?: register_btf_id_dtor_kfuncs(bpf_ksock_dtors,
+                                                 ARRAY_SIZE(bpf_ksock_dtors),
+                                                 THIS_MODULE);
+}
+
+late_initcall(bpf_ksock_kfunc_init);
--

2.34.1

author
#12 lore raw

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

Quoted 17 lines · Kuniyuki Iwashima
Quoted 16 lines · 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)

[...]

Quoted 20 lines
Quoted 7 lines
net/core/bpf_ksock.c new file +7 -0
+
+/**
+ * struct bpf_ksock - refcounted BPF kernel socket context
+ * @sock:      The underlying kernel socket.
+ * @usage:     Reference counter.
+ * @rwork:     RCU work for deferred cleanup (sock_release may sleep).
+ */

net/core/bpf_ksock.c line 35

Quoted 10 lines
net/core/bpf_ksock.c new file +10 -0
+struct bpf_ksock {
+       struct socket *sock;
+       refcount_t usage;
+       struct rcu_work rwork;
+};
+
+static void ksock_release_work_fn(struct work_struct *work)
+{
+       struct bpf_ksock *ks =
+               container_of(to_rcu_work(work), struct bpf_ksock, rwork);

nit: if you need respin:

Quoted 3 lines

struct bpf_ksock *ks;

ks = container_of(to_rcu_work(work), struct bpf_ksock, rwork);

sure!

Quoted 6 lines
Quoted 6 lines
net/core/bpf_ksock.c new file +5 -0
+
+       sock_release(ks->sock);
+       kfree(ks);
+}
+

[...]

Quoted 21 lines
Quoted 21 lines
net/core/bpf_ksock.c new file +21 -0
+__bpf_kfunc struct bpf_ksock *
+bpf_ksock_create(const struct bpf_ksock_create_opts *opts, u32 opts__sz,
+                int *err__uninit)
+{
+       struct bpf_ksock_create_opts opts_copy;
+       struct bpf_ksock *ks;
+       int err;
+
+       /*
+        * sock_create() derives the network namespace, credentials, and cgroup
+        * from current. Kernel threads, including BPF workqueue callbacks, do
+        * not carry the context of the task that invoked the BPF program.
+        */
+       if (!bpf_ksock_has_user_task_context()) {
+               err = -EOPNOTSUPP;
+               goto err_out;
+       }
+
+       if (!opts || opts__sz != sizeof(struct bpf_ksock_create_opts)) {
+               err = -EINVAL;
+               goto err_out;
Quoted 8 lines

net/core/bpf_ksock.c line 93

Quoted 4 lines
net/core/bpf_ksock.c new file +4 -0
+       }
+
+       opts_copy = (struct bpf_ksock_create_opts){
+               .family = READ_ONCE(opts->family),

I'm not sure if we really want to care about such an arch, but since you mentioned unaligned access in bpf_ksock_connect(), is READ_OCNE() safe here ?

To my understanding, there's no issue regarding alignement here since these four fields are __u8. The READ_ONCE is only used so that the compiler does not do smart things like moving load or reloading a field between time of check and time of use.

Quoted 7 lines
Quoted 7 lines
net/core/bpf_ksock.c new file +5 -0
+               .type = READ_ONCE(opts->type),
+               .protocol = READ_ONCE(opts->protocol),
+               .reserved = READ_ONCE(opts->reserved),
+       };
+

[...]

author
#13 lore raw

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

Reviewed-by on v5 3/5
#14 lore raw

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

Quoted 8 lines · 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.

Acked-by on v5 3/5
#15 lore raw

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

In reply to Mahe Tardy
Quoted 8 lines · 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.

author
#16 lore raw

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

#17 lore raw

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

This isn't a bug, but does ksock_lsm_verifier.c still need bpf_tracing_net.h? The AF_INET/SOCK_DGRAM constants it provides look like they're only used by ksock_lsm.c, so the include could probably…
Quoted 6 lines
tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c new file +0 -0
new file mode 100644
index 000000000000..5b969e03b6d6

tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c line 8

Quoted 8 lines
tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c new file +8 -0
@@ -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"

This isn't a bug, but does ksock_lsm_verifier.c still need bpf_tracing_net.h? The AF_INET/SOCK_DGRAM constants it provides look like they're only used by ksock_lsm.c, so the include could probably be dropped here.

Quoted 18 lines
tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c new file +18 -0
+#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);

tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c line 36

Quoted 10 lines
tools/testing/selftests/bpf/progs/ksock_lsm_verifier.c new file +10 -0
+	if (!ks)
+		return ret;
+
+	bpf_ksock_send(ks, send_data, sizeof(send_data));
+	bpf_ksock_release(ks);
+
+	return ret;
+}
+
+char __license[] SEC("license") = "GPL";

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

Acked-by on v5 4/5
#18 lore raw

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

In reply to Mahe Tardy
Quoted 8 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
#19 lore raw

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