xref: /linux/net/ipv4/tcp_bpf.c (revision 376b1446153ca67e7028e6b9555d9b17477f568b)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2017 - 2018 Covalent IO, Inc. http://covalent.io */
3 
4 #include <linux/skmsg.h>
5 #include <linux/filter.h>
6 #include <linux/bpf.h>
7 #include <linux/init.h>
8 #include <linux/wait.h>
9 #include <linux/util_macros.h>
10 
11 #include <net/inet_common.h>
12 #include <net/tls.h>
13 
14 static int bpf_tcp_ingress(struct sock *sk, struct sk_psock *psock,
15 			   struct sk_msg *msg, u32 apply_bytes, int flags)
16 {
17 	bool apply = apply_bytes;
18 	struct scatterlist *sge;
19 	u32 size, copied = 0;
20 	struct sk_msg *tmp;
21 	int i, ret = 0;
22 
23 	tmp = kzalloc(sizeof(*tmp), __GFP_NOWARN | GFP_KERNEL);
24 	if (unlikely(!tmp))
25 		return -ENOMEM;
26 
27 	lock_sock(sk);
28 	tmp->sg.start = msg->sg.start;
29 	i = msg->sg.start;
30 	do {
31 		sge = sk_msg_elem(msg, i);
32 		size = (apply && apply_bytes < sge->length) ?
33 			apply_bytes : sge->length;
34 		if (!sk_wmem_schedule(sk, size)) {
35 			if (!copied)
36 				ret = -ENOMEM;
37 			break;
38 		}
39 
40 		sk_mem_charge(sk, size);
41 		sk_msg_xfer(tmp, msg, i, size);
42 		copied += size;
43 		if (sge->length)
44 			get_page(sk_msg_page(tmp, i));
45 		sk_msg_iter_var_next(i);
46 		tmp->sg.end = i;
47 		if (apply) {
48 			apply_bytes -= size;
49 			if (!apply_bytes) {
50 				if (sge->length)
51 					sk_msg_iter_var_prev(i);
52 				break;
53 			}
54 		}
55 	} while (i != msg->sg.end);
56 
57 	if (!ret) {
58 		msg->sg.start = i;
59 		sk_psock_queue_msg(psock, tmp);
60 		sk_psock_data_ready(sk, psock);
61 	} else {
62 		sk_msg_free(sk, tmp);
63 		kfree(tmp);
64 	}
65 
66 	release_sock(sk);
67 	return ret;
68 }
69 
70 static int tcp_bpf_push(struct sock *sk, struct sk_msg *msg, u32 apply_bytes,
71 			int flags, bool uncharge)
72 {
73 	bool apply = apply_bytes;
74 	struct scatterlist *sge;
75 	struct page *page;
76 	int size, ret = 0;
77 	u32 off;
78 
79 	while (1) {
80 		bool has_tx_ulp;
81 
82 		sge = sk_msg_elem(msg, msg->sg.start);
83 		size = (apply && apply_bytes < sge->length) ?
84 			apply_bytes : sge->length;
85 		off  = sge->offset;
86 		page = sg_page(sge);
87 
88 		tcp_rate_check_app_limited(sk);
89 retry:
90 		has_tx_ulp = tls_sw_has_ctx_tx(sk);
91 		if (has_tx_ulp) {
92 			flags |= MSG_SENDPAGE_NOPOLICY;
93 			ret = kernel_sendpage_locked(sk,
94 						     page, off, size, flags);
95 		} else {
96 			ret = do_tcp_sendpages(sk, page, off, size, flags);
97 		}
98 
99 		if (ret <= 0)
100 			return ret;
101 		if (apply)
102 			apply_bytes -= ret;
103 		msg->sg.size -= ret;
104 		sge->offset += ret;
105 		sge->length -= ret;
106 		if (uncharge)
107 			sk_mem_uncharge(sk, ret);
108 		if (ret != size) {
109 			size -= ret;
110 			off  += ret;
111 			goto retry;
112 		}
113 		if (!sge->length) {
114 			put_page(page);
115 			sk_msg_iter_next(msg, start);
116 			sg_init_table(sge, 1);
117 			if (msg->sg.start == msg->sg.end)
118 				break;
119 		}
120 		if (apply && !apply_bytes)
121 			break;
122 	}
123 
124 	return 0;
125 }
126 
127 static int tcp_bpf_push_locked(struct sock *sk, struct sk_msg *msg,
128 			       u32 apply_bytes, int flags, bool uncharge)
129 {
130 	int ret;
131 
132 	lock_sock(sk);
133 	ret = tcp_bpf_push(sk, msg, apply_bytes, flags, uncharge);
134 	release_sock(sk);
135 	return ret;
136 }
137 
138 int tcp_bpf_sendmsg_redir(struct sock *sk, bool ingress,
139 			  struct sk_msg *msg, u32 bytes, int flags)
140 {
141 	struct sk_psock *psock = sk_psock_get(sk);
142 	int ret;
143 
144 	if (unlikely(!psock))
145 		return -EPIPE;
146 
147 	ret = ingress ? bpf_tcp_ingress(sk, psock, msg, bytes, flags) :
148 			tcp_bpf_push_locked(sk, msg, bytes, flags, false);
149 	sk_psock_put(sk, psock);
150 	return ret;
151 }
152 EXPORT_SYMBOL_GPL(tcp_bpf_sendmsg_redir);
153 
154 #ifdef CONFIG_BPF_SYSCALL
155 static int tcp_msg_wait_data(struct sock *sk, struct sk_psock *psock,
156 			     long timeo)
157 {
158 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
159 	int ret = 0;
160 
161 	if (sk->sk_shutdown & RCV_SHUTDOWN)
162 		return 1;
163 
164 	if (!timeo)
165 		return ret;
166 
167 	add_wait_queue(sk_sleep(sk), &wait);
168 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
169 	ret = sk_wait_event(sk, &timeo,
170 			    !list_empty(&psock->ingress_msg) ||
171 			    !skb_queue_empty(&sk->sk_receive_queue), &wait);
172 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
173 	remove_wait_queue(sk_sleep(sk), &wait);
174 	return ret;
175 }
176 
177 static int tcp_bpf_recvmsg_parser(struct sock *sk,
178 				  struct msghdr *msg,
179 				  size_t len,
180 				  int flags,
181 				  int *addr_len)
182 {
183 	struct sk_psock *psock;
184 	int copied;
185 
186 	if (unlikely(flags & MSG_ERRQUEUE))
187 		return inet_recv_error(sk, msg, len, addr_len);
188 
189 	if (!len)
190 		return 0;
191 
192 	psock = sk_psock_get(sk);
193 	if (unlikely(!psock))
194 		return tcp_recvmsg(sk, msg, len, flags, addr_len);
195 
196 	lock_sock(sk);
197 msg_bytes_ready:
198 	copied = sk_msg_recvmsg(sk, psock, msg, len, flags);
199 	if (!copied) {
200 		long timeo;
201 		int data;
202 
203 		if (sock_flag(sk, SOCK_DONE))
204 			goto out;
205 
206 		if (sk->sk_err) {
207 			copied = sock_error(sk);
208 			goto out;
209 		}
210 
211 		if (sk->sk_shutdown & RCV_SHUTDOWN)
212 			goto out;
213 
214 		if (sk->sk_state == TCP_CLOSE) {
215 			copied = -ENOTCONN;
216 			goto out;
217 		}
218 
219 		timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
220 		if (!timeo) {
221 			copied = -EAGAIN;
222 			goto out;
223 		}
224 
225 		if (signal_pending(current)) {
226 			copied = sock_intr_errno(timeo);
227 			goto out;
228 		}
229 
230 		data = tcp_msg_wait_data(sk, psock, timeo);
231 		if (data && !sk_psock_queue_empty(psock))
232 			goto msg_bytes_ready;
233 		copied = -EAGAIN;
234 	}
235 out:
236 	release_sock(sk);
237 	sk_psock_put(sk, psock);
238 	return copied;
239 }
240 
241 static int tcp_bpf_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
242 			   int flags, int *addr_len)
243 {
244 	struct sk_psock *psock;
245 	int copied, ret;
246 
247 	if (unlikely(flags & MSG_ERRQUEUE))
248 		return inet_recv_error(sk, msg, len, addr_len);
249 
250 	if (!len)
251 		return 0;
252 
253 	psock = sk_psock_get(sk);
254 	if (unlikely(!psock))
255 		return tcp_recvmsg(sk, msg, len, flags, addr_len);
256 	if (!skb_queue_empty(&sk->sk_receive_queue) &&
257 	    sk_psock_queue_empty(psock)) {
258 		sk_psock_put(sk, psock);
259 		return tcp_recvmsg(sk, msg, len, flags, addr_len);
260 	}
261 	lock_sock(sk);
262 msg_bytes_ready:
263 	copied = sk_msg_recvmsg(sk, psock, msg, len, flags);
264 	if (!copied) {
265 		long timeo;
266 		int data;
267 
268 		timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
269 		data = tcp_msg_wait_data(sk, psock, timeo);
270 		if (data) {
271 			if (!sk_psock_queue_empty(psock))
272 				goto msg_bytes_ready;
273 			release_sock(sk);
274 			sk_psock_put(sk, psock);
275 			return tcp_recvmsg(sk, msg, len, flags, addr_len);
276 		}
277 		copied = -EAGAIN;
278 	}
279 	ret = copied;
280 	release_sock(sk);
281 	sk_psock_put(sk, psock);
282 	return ret;
283 }
284 
285 static int tcp_bpf_send_verdict(struct sock *sk, struct sk_psock *psock,
286 				struct sk_msg *msg, int *copied, int flags)
287 {
288 	bool cork = false, enospc = sk_msg_full(msg), redir_ingress;
289 	struct sock *sk_redir;
290 	u32 tosend, origsize, sent, delta = 0;
291 	u32 eval;
292 	int ret;
293 
294 more_data:
295 	if (psock->eval == __SK_NONE) {
296 		/* Track delta in msg size to add/subtract it on SK_DROP from
297 		 * returned to user copied size. This ensures user doesn't
298 		 * get a positive return code with msg_cut_data and SK_DROP
299 		 * verdict.
300 		 */
301 		delta = msg->sg.size;
302 		psock->eval = sk_psock_msg_verdict(sk, psock, msg);
303 		delta -= msg->sg.size;
304 	}
305 
306 	if (msg->cork_bytes &&
307 	    msg->cork_bytes > msg->sg.size && !enospc) {
308 		psock->cork_bytes = msg->cork_bytes - msg->sg.size;
309 		if (!psock->cork) {
310 			psock->cork = kzalloc(sizeof(*psock->cork),
311 					      GFP_ATOMIC | __GFP_NOWARN);
312 			if (!psock->cork)
313 				return -ENOMEM;
314 		}
315 		memcpy(psock->cork, msg, sizeof(*msg));
316 		return 0;
317 	}
318 
319 	tosend = msg->sg.size;
320 	if (psock->apply_bytes && psock->apply_bytes < tosend)
321 		tosend = psock->apply_bytes;
322 	eval = __SK_NONE;
323 
324 	switch (psock->eval) {
325 	case __SK_PASS:
326 		ret = tcp_bpf_push(sk, msg, tosend, flags, true);
327 		if (unlikely(ret)) {
328 			*copied -= sk_msg_free(sk, msg);
329 			break;
330 		}
331 		sk_msg_apply_bytes(psock, tosend);
332 		break;
333 	case __SK_REDIRECT:
334 		redir_ingress = psock->redir_ingress;
335 		sk_redir = psock->sk_redir;
336 		sk_msg_apply_bytes(psock, tosend);
337 		if (!psock->apply_bytes) {
338 			/* Clean up before releasing the sock lock. */
339 			eval = psock->eval;
340 			psock->eval = __SK_NONE;
341 			psock->sk_redir = NULL;
342 		}
343 		if (psock->cork) {
344 			cork = true;
345 			psock->cork = NULL;
346 		}
347 		sk_msg_return(sk, msg, tosend);
348 		release_sock(sk);
349 
350 		origsize = msg->sg.size;
351 		ret = tcp_bpf_sendmsg_redir(sk_redir, redir_ingress,
352 					    msg, tosend, flags);
353 		sent = origsize - msg->sg.size;
354 
355 		if (eval == __SK_REDIRECT)
356 			sock_put(sk_redir);
357 
358 		lock_sock(sk);
359 		if (unlikely(ret < 0)) {
360 			int free = sk_msg_free_nocharge(sk, msg);
361 
362 			if (!cork)
363 				*copied -= free;
364 		}
365 		if (cork) {
366 			sk_msg_free(sk, msg);
367 			kfree(msg);
368 			msg = NULL;
369 			ret = 0;
370 		}
371 		break;
372 	case __SK_DROP:
373 	default:
374 		sk_msg_free_partial(sk, msg, tosend);
375 		sk_msg_apply_bytes(psock, tosend);
376 		*copied -= (tosend + delta);
377 		return -EACCES;
378 	}
379 
380 	if (likely(!ret)) {
381 		if (!psock->apply_bytes) {
382 			psock->eval =  __SK_NONE;
383 			if (psock->sk_redir) {
384 				sock_put(psock->sk_redir);
385 				psock->sk_redir = NULL;
386 			}
387 		}
388 		if (msg &&
389 		    msg->sg.data[msg->sg.start].page_link &&
390 		    msg->sg.data[msg->sg.start].length) {
391 			if (eval == __SK_REDIRECT)
392 				sk_mem_charge(sk, tosend - sent);
393 			goto more_data;
394 		}
395 	}
396 	return ret;
397 }
398 
399 static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
400 {
401 	struct sk_msg tmp, *msg_tx = NULL;
402 	int copied = 0, err = 0;
403 	struct sk_psock *psock;
404 	long timeo;
405 	int flags;
406 
407 	/* Don't let internal do_tcp_sendpages() flags through */
408 	flags = (msg->msg_flags & ~MSG_SENDPAGE_DECRYPTED);
409 	flags |= MSG_NO_SHARED_FRAGS;
410 
411 	psock = sk_psock_get(sk);
412 	if (unlikely(!psock))
413 		return tcp_sendmsg(sk, msg, size);
414 
415 	lock_sock(sk);
416 	timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
417 	while (msg_data_left(msg)) {
418 		bool enospc = false;
419 		u32 copy, osize;
420 
421 		if (sk->sk_err) {
422 			err = -sk->sk_err;
423 			goto out_err;
424 		}
425 
426 		copy = msg_data_left(msg);
427 		if (!sk_stream_memory_free(sk))
428 			goto wait_for_sndbuf;
429 		if (psock->cork) {
430 			msg_tx = psock->cork;
431 		} else {
432 			msg_tx = &tmp;
433 			sk_msg_init(msg_tx);
434 		}
435 
436 		osize = msg_tx->sg.size;
437 		err = sk_msg_alloc(sk, msg_tx, msg_tx->sg.size + copy, msg_tx->sg.end - 1);
438 		if (err) {
439 			if (err != -ENOSPC)
440 				goto wait_for_memory;
441 			enospc = true;
442 			copy = msg_tx->sg.size - osize;
443 		}
444 
445 		err = sk_msg_memcopy_from_iter(sk, &msg->msg_iter, msg_tx,
446 					       copy);
447 		if (err < 0) {
448 			sk_msg_trim(sk, msg_tx, osize);
449 			goto out_err;
450 		}
451 
452 		copied += copy;
453 		if (psock->cork_bytes) {
454 			if (size > psock->cork_bytes)
455 				psock->cork_bytes = 0;
456 			else
457 				psock->cork_bytes -= size;
458 			if (psock->cork_bytes && !enospc)
459 				goto out_err;
460 			/* All cork bytes are accounted, rerun the prog. */
461 			psock->eval = __SK_NONE;
462 			psock->cork_bytes = 0;
463 		}
464 
465 		err = tcp_bpf_send_verdict(sk, psock, msg_tx, &copied, flags);
466 		if (unlikely(err < 0))
467 			goto out_err;
468 		continue;
469 wait_for_sndbuf:
470 		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
471 wait_for_memory:
472 		err = sk_stream_wait_memory(sk, &timeo);
473 		if (err) {
474 			if (msg_tx && msg_tx != psock->cork)
475 				sk_msg_free(sk, msg_tx);
476 			goto out_err;
477 		}
478 	}
479 out_err:
480 	if (err < 0)
481 		err = sk_stream_error(sk, msg->msg_flags, err);
482 	release_sock(sk);
483 	sk_psock_put(sk, psock);
484 	return copied ? copied : err;
485 }
486 
487 static int tcp_bpf_sendpage(struct sock *sk, struct page *page, int offset,
488 			    size_t size, int flags)
489 {
490 	struct sk_msg tmp, *msg = NULL;
491 	int err = 0, copied = 0;
492 	struct sk_psock *psock;
493 	bool enospc = false;
494 
495 	psock = sk_psock_get(sk);
496 	if (unlikely(!psock))
497 		return tcp_sendpage(sk, page, offset, size, flags);
498 
499 	lock_sock(sk);
500 	if (psock->cork) {
501 		msg = psock->cork;
502 	} else {
503 		msg = &tmp;
504 		sk_msg_init(msg);
505 	}
506 
507 	/* Catch case where ring is full and sendpage is stalled. */
508 	if (unlikely(sk_msg_full(msg)))
509 		goto out_err;
510 
511 	sk_msg_page_add(msg, page, size, offset);
512 	sk_mem_charge(sk, size);
513 	copied = size;
514 	if (sk_msg_full(msg))
515 		enospc = true;
516 	if (psock->cork_bytes) {
517 		if (size > psock->cork_bytes)
518 			psock->cork_bytes = 0;
519 		else
520 			psock->cork_bytes -= size;
521 		if (psock->cork_bytes && !enospc)
522 			goto out_err;
523 		/* All cork bytes are accounted, rerun the prog. */
524 		psock->eval = __SK_NONE;
525 		psock->cork_bytes = 0;
526 	}
527 
528 	err = tcp_bpf_send_verdict(sk, psock, msg, &copied, flags);
529 out_err:
530 	release_sock(sk);
531 	sk_psock_put(sk, psock);
532 	return copied ? copied : err;
533 }
534 
535 enum {
536 	TCP_BPF_IPV4,
537 	TCP_BPF_IPV6,
538 	TCP_BPF_NUM_PROTS,
539 };
540 
541 enum {
542 	TCP_BPF_BASE,
543 	TCP_BPF_TX,
544 	TCP_BPF_RX,
545 	TCP_BPF_TXRX,
546 	TCP_BPF_NUM_CFGS,
547 };
548 
549 static struct proto *tcpv6_prot_saved __read_mostly;
550 static DEFINE_SPINLOCK(tcpv6_prot_lock);
551 static struct proto tcp_bpf_prots[TCP_BPF_NUM_PROTS][TCP_BPF_NUM_CFGS];
552 
553 static void tcp_bpf_rebuild_protos(struct proto prot[TCP_BPF_NUM_CFGS],
554 				   struct proto *base)
555 {
556 	prot[TCP_BPF_BASE]			= *base;
557 	prot[TCP_BPF_BASE].destroy		= sock_map_destroy;
558 	prot[TCP_BPF_BASE].close		= sock_map_close;
559 	prot[TCP_BPF_BASE].recvmsg		= tcp_bpf_recvmsg;
560 	prot[TCP_BPF_BASE].sock_is_readable	= sk_msg_is_readable;
561 
562 	prot[TCP_BPF_TX]			= prot[TCP_BPF_BASE];
563 	prot[TCP_BPF_TX].sendmsg		= tcp_bpf_sendmsg;
564 	prot[TCP_BPF_TX].sendpage		= tcp_bpf_sendpage;
565 
566 	prot[TCP_BPF_RX]			= prot[TCP_BPF_BASE];
567 	prot[TCP_BPF_RX].recvmsg		= tcp_bpf_recvmsg_parser;
568 
569 	prot[TCP_BPF_TXRX]			= prot[TCP_BPF_TX];
570 	prot[TCP_BPF_TXRX].recvmsg		= tcp_bpf_recvmsg_parser;
571 }
572 
573 static void tcp_bpf_check_v6_needs_rebuild(struct proto *ops)
574 {
575 	if (unlikely(ops != smp_load_acquire(&tcpv6_prot_saved))) {
576 		spin_lock_bh(&tcpv6_prot_lock);
577 		if (likely(ops != tcpv6_prot_saved)) {
578 			tcp_bpf_rebuild_protos(tcp_bpf_prots[TCP_BPF_IPV6], ops);
579 			smp_store_release(&tcpv6_prot_saved, ops);
580 		}
581 		spin_unlock_bh(&tcpv6_prot_lock);
582 	}
583 }
584 
585 static int __init tcp_bpf_v4_build_proto(void)
586 {
587 	tcp_bpf_rebuild_protos(tcp_bpf_prots[TCP_BPF_IPV4], &tcp_prot);
588 	return 0;
589 }
590 late_initcall(tcp_bpf_v4_build_proto);
591 
592 static int tcp_bpf_assert_proto_ops(struct proto *ops)
593 {
594 	/* In order to avoid retpoline, we make assumptions when we call
595 	 * into ops if e.g. a psock is not present. Make sure they are
596 	 * indeed valid assumptions.
597 	 */
598 	return ops->recvmsg  == tcp_recvmsg &&
599 	       ops->sendmsg  == tcp_sendmsg &&
600 	       ops->sendpage == tcp_sendpage ? 0 : -ENOTSUPP;
601 }
602 
603 int tcp_bpf_update_proto(struct sock *sk, struct sk_psock *psock, bool restore)
604 {
605 	int family = sk->sk_family == AF_INET6 ? TCP_BPF_IPV6 : TCP_BPF_IPV4;
606 	int config = psock->progs.msg_parser   ? TCP_BPF_TX   : TCP_BPF_BASE;
607 
608 	if (psock->progs.stream_verdict || psock->progs.skb_verdict) {
609 		config = (config == TCP_BPF_TX) ? TCP_BPF_TXRX : TCP_BPF_RX;
610 	}
611 
612 	if (restore) {
613 		if (inet_csk_has_ulp(sk)) {
614 			/* TLS does not have an unhash proto in SW cases,
615 			 * but we need to ensure we stop using the sock_map
616 			 * unhash routine because the associated psock is being
617 			 * removed. So use the original unhash handler.
618 			 */
619 			WRITE_ONCE(sk->sk_prot->unhash, psock->saved_unhash);
620 			tcp_update_ulp(sk, psock->sk_proto, psock->saved_write_space);
621 		} else {
622 			sk->sk_write_space = psock->saved_write_space;
623 			/* Pairs with lockless read in sk_clone_lock() */
624 			sock_replace_proto(sk, psock->sk_proto);
625 		}
626 		return 0;
627 	}
628 
629 	if (sk->sk_family == AF_INET6) {
630 		if (tcp_bpf_assert_proto_ops(psock->sk_proto))
631 			return -EINVAL;
632 
633 		tcp_bpf_check_v6_needs_rebuild(psock->sk_proto);
634 	}
635 
636 	/* Pairs with lockless read in sk_clone_lock() */
637 	sock_replace_proto(sk, &tcp_bpf_prots[family][config]);
638 	return 0;
639 }
640 EXPORT_SYMBOL_GPL(tcp_bpf_update_proto);
641 
642 /* If a child got cloned from a listening socket that had tcp_bpf
643  * protocol callbacks installed, we need to restore the callbacks to
644  * the default ones because the child does not inherit the psock state
645  * that tcp_bpf callbacks expect.
646  */
647 void tcp_bpf_clone(const struct sock *sk, struct sock *newsk)
648 {
649 	struct proto *prot = newsk->sk_prot;
650 
651 	if (is_insidevar(prot, tcp_bpf_prots))
652 		newsk->sk_prot = sk->sk_prot_creator;
653 }
654 #endif /* CONFIG_BPF_SYSCALL */
655