xref: /linux/net/core/bpf_ksock.c (revision 74be619845bdc09de15613b304c390e7bbddfea8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2026 Isovalent */
3 
4 #include <linux/bpf.h>
5 #include <linux/bpf_ksock.h>
6 #include <linux/btf.h>
7 #include <linux/btf_ids.h>
8 #include <linux/in.h>
9 #include <linux/in6.h>
10 #include <linux/net.h>
11 #include <linux/refcount.h>
12 #include <linux/sched.h>
13 #include <linux/slab.h>
14 #include <linux/socket.h>
15 #include <linux/unaligned.h>
16 #include <linux/workqueue.h>
17 #include <net/sock.h>
18 
19 /**
20  * struct bpf_ksock - refcounted BPF kernel socket context
21  * @sock:	The underlying kernel socket.
22  * @usage:	Reference counter.
23  * @rwork:	RCU work for deferred cleanup (sock_release may sleep).
24  */
25 struct bpf_ksock {
26 	struct socket *sock;
27 	refcount_t usage;
28 	struct rcu_work rwork;
29 };
30 
31 static void ksock_release_work_fn(struct work_struct *work)
32 {
33 	struct bpf_ksock *ks;
34 
35 	ks = container_of(to_rcu_work(work), struct bpf_ksock, rwork);
36 	sock_release(ks->sock);
37 	kfree(ks);
38 }
39 
40 static int bpf_ksock_addr_to_sockaddr(const union bpf_ksock_addr *addr,
41 				      u32 addr_sz, struct sockaddr_storage *sa)
42 {
43 	if (!addr || addr_sz != sizeof(*addr))
44 		return -EINVAL;
45 
46 	/* Kfunc memory arguments may be unaligned. */
47 	memcpy(sa, addr, sizeof(*addr));
48 
49 	switch (sa->ss_family) {
50 	case AF_INET:
51 		return sizeof(struct sockaddr_in);
52 	case AF_INET6:
53 		return sizeof(struct sockaddr_in6);
54 	default:
55 		return -EAFNOSUPPORT;
56 	}
57 }
58 
59 static int ksock_sendto(struct bpf_ksock *ks, const void *data, u32 data_sz,
60 			const union bpf_ksock_addr *addr, u32 addr_sz)
61 {
62 	struct sockaddr_storage sa;
63 	struct msghdr msg = {
64 		.msg_flags = MSG_DONTWAIT,
65 	};
66 	struct kvec iov = {
67 		.iov_base = (void *)data,
68 		.iov_len = data_sz,
69 	};
70 	int addrlen;
71 
72 	if (addr) {
73 		addrlen = bpf_ksock_addr_to_sockaddr(addr, addr_sz, &sa);
74 		if (addrlen < 0)
75 			return addrlen;
76 		msg.msg_name = &sa;
77 		msg.msg_namelen = addrlen;
78 	}
79 
80 	return kernel_sendmsg(ks->sock, &msg, &iov, 1, data_sz);
81 }
82 
83 __bpf_kfunc_start_defs();
84 
85 /**
86  * bpf_ksock_create() - Create a BPF kernel socket.
87  *
88  * Allocates and creates a kernel socket.
89  *
90  * The returned context must either be stored in a map as a kptr, or
91  * freed with bpf_ksock_release().
92  *
93  * This function may sleep (sock_create), so it can only be used
94  * in sleepable BPF programs (SYSCALL).
95  * It cannot be called from a BPF workqueue callback because that callback
96  * does not retain the invoking task's namespace.
97  *
98  * @opts:	Pointer to struct bpf_ksock_create_opts with socket parameters.
99  * @opts__sz:	Size of the opts struct.
100  * @err__uninit:	Integer to store error code when NULL is returned.
101  */
102 __bpf_kfunc struct bpf_ksock *
103 bpf_ksock_create(const struct bpf_ksock_create_opts *opts, u32 opts__sz,
104 		 int *err__uninit)
105 {
106 	struct bpf_ksock_create_opts opts_copy;
107 	struct bpf_ksock *ks;
108 	int err;
109 
110 	/*
111 	 * sock_create() derives the network namespace from current and task
112 	 * work can run from do_exit() after exit_nsproxy_namespaces()
113 	 */
114 	if ((current->flags & PF_KTHREAD) || !current->nsproxy) {
115 		err = -EOPNOTSUPP;
116 		goto err_out;
117 	}
118 
119 	if (!opts || opts__sz != sizeof(struct bpf_ksock_create_opts)) {
120 		err = -EINVAL;
121 		goto err_out;
122 	}
123 
124 	opts_copy = (struct bpf_ksock_create_opts){
125 		.family = READ_ONCE(opts->family),
126 		.type = READ_ONCE(opts->type),
127 		.protocol = READ_ONCE(opts->protocol),
128 		.reserved = READ_ONCE(opts->reserved),
129 	};
130 
131 	if (opts_copy.reserved) {
132 		err = -EINVAL;
133 		goto err_out;
134 	}
135 
136 	if (opts_copy.family != AF_INET && opts_copy.family != AF_INET6) {
137 		err = -EAFNOSUPPORT;
138 		goto err_out;
139 	}
140 
141 	if (opts_copy.type != SOCK_DGRAM) {
142 		err = -EPROTONOSUPPORT;
143 		goto err_out;
144 	}
145 
146 	if (opts_copy.protocol != IPPROTO_UDP && opts_copy.protocol != 0) {
147 		err = -EPROTONOSUPPORT;
148 		goto err_out;
149 	}
150 
151 	ks = kzalloc_obj(*ks);
152 	if (!ks) {
153 		err = -ENOMEM;
154 		goto err_out;
155 	}
156 
157 	/*
158 	 * Use the normal current-task socket path so LSM/cgroup policy,
159 	 * socket labels, and the active netns reference match a socket(2)
160 	 * created by the BPF program's caller.
161 	 */
162 	err = sock_create(opts_copy.family, opts_copy.type, opts_copy.protocol,
163 			  &ks->sock);
164 	if (err)
165 		goto err_free;
166 
167 	ks->sock->sk->sk_rcvbuf = SOCK_MIN_RCVBUF;
168 	ks->sock->sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
169 
170 	refcount_set(&ks->usage, 1);
171 	put_unaligned(0, err__uninit);
172 	return ks;
173 
174 err_free:
175 	kfree(ks);
176 err_out:
177 	put_unaligned(err, err__uninit);
178 	return NULL;
179 }
180 
181 /**
182  * bpf_ksock_connect() - Connect a BPF kernel socket to a remote address.
183  * @ks:		The BPF kernel socket context.
184  * @addr:	Pointer to an IPv4 or IPv6 socket address.
185  * @addr__sz:	Size of the address union.
186  *
187  * Connects the socket to the specified remote address and port.
188  *
189  * This function may sleep while connecting the socket, so it can only be used
190  * in sleepable BPF programs (SYSCALL).
191  *
192  * Return: 0 on success, negative errno on error.
193  */
194 __bpf_kfunc int bpf_ksock_connect(struct bpf_ksock *ks,
195 				  const union bpf_ksock_addr *addr,
196 				  u32 addr__sz)
197 {
198 	struct sockaddr_storage sa;
199 	int addrlen;
200 
201 	addrlen = bpf_ksock_addr_to_sockaddr(addr, addr__sz, &sa);
202 	if (addrlen < 0)
203 		return addrlen;
204 
205 	return connect_socket(ks->sock, &sa, addrlen, 0);
206 }
207 
208 /**
209  * bpf_ksock_acquire() - Acquire a reference to a BPF kernel socket.
210  * @ks:	The BPF kernel socket context to acquire. Must be a
211  *	trusted pointer (e.g. RCU-protected kptr from a map).
212  *
213  * The acquired context must either be stored in a map as a kptr, or
214  * freed with bpf_ksock_release().
215  */
216 __bpf_kfunc struct bpf_ksock *bpf_ksock_acquire(struct bpf_ksock *ks)
217 {
218 	if (!refcount_inc_not_zero(&ks->usage))
219 		return NULL;
220 	return ks;
221 }
222 
223 /**
224  * bpf_ksock_release() - Release a BPF kernel socket.
225  * @ks:	The BPF kernel socket context to release.
226  *
227  * When the final reference is released, the socket is cleaned up via
228  * queue_rcu_work() (since sock_release may sleep).
229  */
230 __bpf_kfunc void bpf_ksock_release(struct bpf_ksock *ks)
231 {
232 	if (refcount_dec_and_test(&ks->usage)) {
233 		INIT_RCU_WORK(&ks->rwork, ksock_release_work_fn);
234 		queue_rcu_work(system_dfl_wq, &ks->rwork);
235 	}
236 }
237 
238 __bpf_kfunc void bpf_ksock_release_dtor(void *ks)
239 {
240 	bpf_ksock_release(ks);
241 }
242 CFI_NOSEAL(bpf_ksock_release_dtor);
243 
244 /**
245  * bpf_ksock_send() - Send data through a BPF kernel socket.
246  * @ks:		The BPF kernel socket context. Must be an acquired reference.
247  * @data:	Pointer to the data to send.
248  * @data__sz:	Size of the data to send.
249  *
250  * Sends data on a connected socket, best-effort and nonblocking. This may sleep
251  * (kernel_sendmsg), so it can only be called from sleepable BPF programs.
252  *
253  * Return: Number of bytes sent on success, negative errno on error.
254  */
255 __bpf_kfunc int bpf_ksock_send(struct bpf_ksock *ks, const void *data,
256 			       u32 data__sz)
257 {
258 	return ksock_sendto(ks, data, data__sz, NULL, 0);
259 }
260 
261 /**
262  * bpf_ksock_sendto() - Send data through a BPF kernel socket to a remote address.
263  * @ks:		The BPF kernel socket context. Must be an acquired reference.
264  * @data:	Pointer to the data to send.
265  * @data__sz:	Size of the data to send.
266  * @addr__nullable: Pointer to an IPv4 or IPv6 socket address, or NULL to use
267  *		   the connected destination.
268  * @addr__sz:	Size of the address union, ignored when the address is NULL.
269  *
270  * Sends data to the specified address, or to the connected destination when
271  * the address is NULL, best-effort and nonblocking. This may sleep
272  * (kernel_sendmsg), so it can only be called from sleepable BPF programs.
273  *
274  * Return: Number of bytes sent on success, negative errno on error.
275  */
276 __bpf_kfunc int bpf_ksock_sendto(struct bpf_ksock *ks, const void *data, u32 data__sz,
277 				 const union bpf_ksock_addr *addr__nullable,
278 				 u32 addr__sz)
279 {
280 	return ksock_sendto(ks, data, data__sz, addr__nullable, addr__sz);
281 }
282 
283 __bpf_kfunc_end_defs();
284 
285 BTF_KFUNCS_START(ksock_init_kfunc_btf_ids)
286 BTF_ID_FLAGS(func, bpf_ksock_create, KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
287 BTF_ID_FLAGS(func, bpf_ksock_connect, KF_SLEEPABLE)
288 BTF_KFUNCS_END(ksock_init_kfunc_btf_ids)
289 
290 static const struct btf_kfunc_id_set ksock_init_kfunc_set = {
291 	.owner = THIS_MODULE,
292 	.set = &ksock_init_kfunc_btf_ids,
293 };
294 
295 BTF_KFUNCS_START(ksock_kfunc_btf_ids)
296 BTF_ID_FLAGS(func, bpf_ksock_release, KF_RELEASE)
297 BTF_ID_FLAGS(func, bpf_ksock_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
298 BTF_ID_FLAGS(func, bpf_ksock_send, KF_SLEEPABLE)
299 BTF_ID_FLAGS(func, bpf_ksock_sendto, KF_SLEEPABLE)
300 BTF_KFUNCS_END(ksock_kfunc_btf_ids)
301 
302 #ifdef CONFIG_BPF_LSM
303 BTF_ID_LIST(bpf_lsm_socket_sendmsg_id)
304 #ifdef CONFIG_SECURITY_NETWORK
305 BTF_ID(func, bpf_lsm_socket_sendmsg)
306 #else
307 BTF_ID_UNUSED
308 #endif
309 #endif
310 
311 static int bpf_ksock_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id)
312 {
313 	if (!btf_id_set8_contains(&ksock_kfunc_btf_ids, kfunc_id))
314 		return 0;
315 
316 	if (prog->type == BPF_PROG_TYPE_SYSCALL)
317 		return 0;
318 
319 #ifdef CONFIG_BPF_LSM
320 	if (prog->type == BPF_PROG_TYPE_LSM &&
321 	    prog->aux->attach_btf_id != bpf_lsm_socket_sendmsg_id[0])
322 		return 0;
323 #endif
324 
325 	return -EACCES;
326 }
327 
328 static const struct btf_kfunc_id_set ksock_kfunc_set = {
329 	.owner = THIS_MODULE,
330 	.set = &ksock_kfunc_btf_ids,
331 	.filter = bpf_ksock_kfunc_filter,
332 };
333 
334 BTF_ID_LIST(bpf_ksock_dtor_ids)
335 BTF_ID(struct, bpf_ksock)
336 BTF_ID(func, bpf_ksock_release_dtor)
337 
338 static int __init bpf_ksock_kfunc_init(void)
339 {
340 	int ret;
341 	const struct btf_id_dtor_kfunc bpf_ksock_dtors[] = {
342 		{
343 			.btf_id = bpf_ksock_dtor_ids[0],
344 			.kfunc_btf_id = bpf_ksock_dtor_ids[1],
345 		},
346 	};
347 
348 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
349 					&ksock_init_kfunc_set);
350 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL,
351 					       &ksock_kfunc_set);
352 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LSM,
353 					       &ksock_kfunc_set);
354 	return ret ?: register_btf_id_dtor_kfuncs(bpf_ksock_dtors,
355 						  ARRAY_SIZE(bpf_ksock_dtors),
356 						  THIS_MODULE);
357 }
358 
359 late_initcall(bpf_ksock_kfunc_init);
360