xref: /linux/net/core/filter.c (revision b676ac484f847bbe5c7d29603f41475b64fefe55)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Linux Socket Filter - Kernel level socket filtering
4  *
5  * Based on the design of the Berkeley Packet Filter. The new
6  * internal format has been designed by PLUMgrid:
7  *
8  *	Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
9  *
10  * Authors:
11  *
12  *	Jay Schulist <jschlst@samba.org>
13  *	Alexei Starovoitov <ast@plumgrid.com>
14  *	Daniel Borkmann <dborkman@redhat.com>
15  *
16  * Andi Kleen - Fix a few bad bugs and races.
17  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
18  */
19 
20 #include <linux/atomic.h>
21 #include <linux/bpf_verifier.h>
22 #include <linux/module.h>
23 #include <linux/types.h>
24 #include <linux/mm.h>
25 #include <linux/fcntl.h>
26 #include <linux/socket.h>
27 #include <linux/sock_diag.h>
28 #include <linux/in.h>
29 #include <linux/inet.h>
30 #include <linux/netdevice.h>
31 #include <linux/if_packet.h>
32 #include <linux/if_arp.h>
33 #include <linux/gfp.h>
34 #include <net/inet_common.h>
35 #include <net/ip.h>
36 #include <net/protocol.h>
37 #include <net/netlink.h>
38 #include <linux/skbuff.h>
39 #include <linux/skmsg.h>
40 #include <net/sock.h>
41 #include <net/flow_dissector.h>
42 #include <linux/errno.h>
43 #include <linux/timer.h>
44 #include <linux/uaccess.h>
45 #include <linux/unaligned.h>
46 #include <linux/filter.h>
47 #include <linux/ratelimit.h>
48 #include <linux/seccomp.h>
49 #include <linux/if_vlan.h>
50 #include <linux/bpf.h>
51 #include <linux/btf.h>
52 #include <net/sch_generic.h>
53 #include <net/cls_cgroup.h>
54 #include <net/dst_metadata.h>
55 #include <net/dst.h>
56 #include <net/sock_reuseport.h>
57 #include <net/busy_poll.h>
58 #include <net/tcp.h>
59 #include <net/xfrm.h>
60 #include <net/udp.h>
61 #include <linux/bpf_trace.h>
62 #include <net/xdp_sock.h>
63 #include <linux/inetdevice.h>
64 #include <net/inet_hashtables.h>
65 #include <net/inet6_hashtables.h>
66 #include <net/ip_fib.h>
67 #include <net/nexthop.h>
68 #include <net/flow.h>
69 #include <net/arp.h>
70 #include <net/ipv6.h>
71 #include <net/net_namespace.h>
72 #include <linux/seg6_local.h>
73 #include <net/seg6.h>
74 #include <net/seg6_local.h>
75 #include <net/lwtunnel.h>
76 #include <net/ipv6_stubs.h>
77 #include <net/bpf_sk_storage.h>
78 #include <net/transp_v6.h>
79 #include <linux/btf_ids.h>
80 #include <net/tls.h>
81 #include <net/xdp.h>
82 #include <net/mptcp.h>
83 #include <net/netfilter/nf_conntrack_bpf.h>
84 #include <net/netkit.h>
85 #include <linux/un.h>
86 #include <net/xdp_sock_drv.h>
87 #include <net/inet_dscp.h>
88 
89 #include "dev.h"
90 
91 /* Keep the struct bpf_fib_lookup small so that it fits into a cacheline */
92 static_assert(sizeof(struct bpf_fib_lookup) == 64, "struct bpf_fib_lookup size check");
93 
94 static const struct bpf_func_proto *
95 bpf_sk_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog);
96 
copy_bpf_fprog_from_user(struct sock_fprog * dst,sockptr_t src,int len)97 int copy_bpf_fprog_from_user(struct sock_fprog *dst, sockptr_t src, int len)
98 {
99 	if (in_compat_syscall()) {
100 		struct compat_sock_fprog f32;
101 
102 		if (len != sizeof(f32))
103 			return -EINVAL;
104 		if (copy_from_sockptr(&f32, src, sizeof(f32)))
105 			return -EFAULT;
106 		memset(dst, 0, sizeof(*dst));
107 		dst->len = f32.len;
108 		dst->filter = compat_ptr(f32.filter);
109 	} else {
110 		if (len != sizeof(*dst))
111 			return -EINVAL;
112 		if (copy_from_sockptr(dst, src, sizeof(*dst)))
113 			return -EFAULT;
114 	}
115 
116 	return 0;
117 }
118 EXPORT_SYMBOL_GPL(copy_bpf_fprog_from_user);
119 
120 /**
121  *	sk_filter_trim_cap - run a packet through a socket filter
122  *	@sk: sock associated with &sk_buff
123  *	@skb: buffer to filter
124  *	@cap: limit on how short the eBPF program may trim the packet
125  *
126  * Run the eBPF program and then cut skb->data to correct size returned by
127  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
128  * than pkt_len we keep whole skb->data. This is the socket level
129  * wrapper to bpf_prog_run. It returns 0 if the packet should
130  * be accepted or -EPERM if the packet should be tossed.
131  *
132  */
sk_filter_trim_cap(struct sock * sk,struct sk_buff * skb,unsigned int cap)133 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
134 {
135 	int err;
136 	struct sk_filter *filter;
137 
138 	/*
139 	 * If the skb was allocated from pfmemalloc reserves, only
140 	 * allow SOCK_MEMALLOC sockets to use it as this socket is
141 	 * helping free memory
142 	 */
143 	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
144 		NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
145 		return -ENOMEM;
146 	}
147 	err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
148 	if (err)
149 		return err;
150 
151 	err = security_sock_rcv_skb(sk, skb);
152 	if (err)
153 		return err;
154 
155 	rcu_read_lock();
156 	filter = rcu_dereference(sk->sk_filter);
157 	if (filter) {
158 		struct sock *save_sk = skb->sk;
159 		unsigned int pkt_len;
160 
161 		skb->sk = sk;
162 		pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
163 		skb->sk = save_sk;
164 		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
165 	}
166 	rcu_read_unlock();
167 
168 	return err;
169 }
170 EXPORT_SYMBOL(sk_filter_trim_cap);
171 
BPF_CALL_1(bpf_skb_get_pay_offset,struct sk_buff *,skb)172 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
173 {
174 	return skb_get_poff(skb);
175 }
176 
BPF_CALL_3(bpf_skb_get_nlattr,struct sk_buff *,skb,u32,a,u32,x)177 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
178 {
179 	struct nlattr *nla;
180 
181 	if (skb_is_nonlinear(skb))
182 		return 0;
183 
184 	if (skb->len < sizeof(struct nlattr))
185 		return 0;
186 
187 	if (a > skb->len - sizeof(struct nlattr))
188 		return 0;
189 
190 	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
191 	if (nla)
192 		return (void *) nla - (void *) skb->data;
193 
194 	return 0;
195 }
196 
BPF_CALL_3(bpf_skb_get_nlattr_nest,struct sk_buff *,skb,u32,a,u32,x)197 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
198 {
199 	struct nlattr *nla;
200 
201 	if (skb_is_nonlinear(skb))
202 		return 0;
203 
204 	if (skb->len < sizeof(struct nlattr))
205 		return 0;
206 
207 	if (a > skb->len - sizeof(struct nlattr))
208 		return 0;
209 
210 	nla = (struct nlattr *) &skb->data[a];
211 	if (!nla_ok(nla, skb->len - a))
212 		return 0;
213 
214 	nla = nla_find_nested(nla, x);
215 	if (nla)
216 		return (void *) nla - (void *) skb->data;
217 
218 	return 0;
219 }
220 
bpf_skb_load_helper_convert_offset(const struct sk_buff * skb,int offset)221 static int bpf_skb_load_helper_convert_offset(const struct sk_buff *skb, int offset)
222 {
223 	if (likely(offset >= 0))
224 		return offset;
225 
226 	if (offset >= SKF_NET_OFF)
227 		return offset - SKF_NET_OFF + skb_network_offset(skb);
228 
229 	if (offset >= SKF_LL_OFF && skb_mac_header_was_set(skb))
230 		return offset - SKF_LL_OFF + skb_mac_offset(skb);
231 
232 	return INT_MIN;
233 }
234 
BPF_CALL_4(bpf_skb_load_helper_8,const struct sk_buff *,skb,const void *,data,int,headlen,int,offset)235 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
236 	   data, int, headlen, int, offset)
237 {
238 	u8 tmp;
239 	const int len = sizeof(tmp);
240 
241 	offset = bpf_skb_load_helper_convert_offset(skb, offset);
242 	if (offset == INT_MIN)
243 		return -EFAULT;
244 
245 	if (headlen - offset >= len)
246 		return *(u8 *)(data + offset);
247 	if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
248 		return tmp;
249 	else
250 		return -EFAULT;
251 }
252 
BPF_CALL_2(bpf_skb_load_helper_8_no_cache,const struct sk_buff *,skb,int,offset)253 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
254 	   int, offset)
255 {
256 	return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
257 					 offset);
258 }
259 
BPF_CALL_4(bpf_skb_load_helper_16,const struct sk_buff *,skb,const void *,data,int,headlen,int,offset)260 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
261 	   data, int, headlen, int, offset)
262 {
263 	__be16 tmp;
264 	const int len = sizeof(tmp);
265 
266 	offset = bpf_skb_load_helper_convert_offset(skb, offset);
267 	if (offset == INT_MIN)
268 		return -EFAULT;
269 
270 	if (headlen - offset >= len)
271 		return get_unaligned_be16(data + offset);
272 	if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
273 		return be16_to_cpu(tmp);
274 	else
275 		return -EFAULT;
276 }
277 
BPF_CALL_2(bpf_skb_load_helper_16_no_cache,const struct sk_buff *,skb,int,offset)278 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
279 	   int, offset)
280 {
281 	return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
282 					  offset);
283 }
284 
BPF_CALL_4(bpf_skb_load_helper_32,const struct sk_buff *,skb,const void *,data,int,headlen,int,offset)285 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
286 	   data, int, headlen, int, offset)
287 {
288 	__be32 tmp;
289 	const int len = sizeof(tmp);
290 
291 	offset = bpf_skb_load_helper_convert_offset(skb, offset);
292 	if (offset == INT_MIN)
293 		return -EFAULT;
294 
295 	if (headlen - offset >= len)
296 		return get_unaligned_be32(data + offset);
297 	if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
298 		return be32_to_cpu(tmp);
299 	else
300 		return -EFAULT;
301 }
302 
BPF_CALL_2(bpf_skb_load_helper_32_no_cache,const struct sk_buff *,skb,int,offset)303 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
304 	   int, offset)
305 {
306 	return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
307 					  offset);
308 }
309 
convert_skb_access(int skb_field,int dst_reg,int src_reg,struct bpf_insn * insn_buf)310 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
311 			      struct bpf_insn *insn_buf)
312 {
313 	struct bpf_insn *insn = insn_buf;
314 
315 	switch (skb_field) {
316 	case SKF_AD_MARK:
317 		BUILD_BUG_ON(sizeof_field(struct sk_buff, mark) != 4);
318 
319 		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
320 				      offsetof(struct sk_buff, mark));
321 		break;
322 
323 	case SKF_AD_PKTTYPE:
324 		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET);
325 		*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
326 #ifdef __BIG_ENDIAN_BITFIELD
327 		*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
328 #endif
329 		break;
330 
331 	case SKF_AD_QUEUE:
332 		BUILD_BUG_ON(sizeof_field(struct sk_buff, queue_mapping) != 2);
333 
334 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
335 				      offsetof(struct sk_buff, queue_mapping));
336 		break;
337 
338 	case SKF_AD_VLAN_TAG:
339 		BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_tci) != 2);
340 
341 		/* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
342 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
343 				      offsetof(struct sk_buff, vlan_tci));
344 		break;
345 	case SKF_AD_VLAN_TAG_PRESENT:
346 		BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_all) != 4);
347 		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
348 				      offsetof(struct sk_buff, vlan_all));
349 		*insn++ = BPF_JMP_IMM(BPF_JEQ, dst_reg, 0, 1);
350 		*insn++ = BPF_ALU32_IMM(BPF_MOV, dst_reg, 1);
351 		break;
352 	}
353 
354 	return insn - insn_buf;
355 }
356 
convert_bpf_extensions(struct sock_filter * fp,struct bpf_insn ** insnp)357 static bool convert_bpf_extensions(struct sock_filter *fp,
358 				   struct bpf_insn **insnp)
359 {
360 	struct bpf_insn *insn = *insnp;
361 	u32 cnt;
362 
363 	switch (fp->k) {
364 	case SKF_AD_OFF + SKF_AD_PROTOCOL:
365 		BUILD_BUG_ON(sizeof_field(struct sk_buff, protocol) != 2);
366 
367 		/* A = *(u16 *) (CTX + offsetof(protocol)) */
368 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
369 				      offsetof(struct sk_buff, protocol));
370 		/* A = ntohs(A) [emitting a nop or swap16] */
371 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
372 		break;
373 
374 	case SKF_AD_OFF + SKF_AD_PKTTYPE:
375 		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
376 		insn += cnt - 1;
377 		break;
378 
379 	case SKF_AD_OFF + SKF_AD_IFINDEX:
380 	case SKF_AD_OFF + SKF_AD_HATYPE:
381 		BUILD_BUG_ON(sizeof_field(struct net_device, ifindex) != 4);
382 		BUILD_BUG_ON(sizeof_field(struct net_device, type) != 2);
383 
384 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
385 				      BPF_REG_TMP, BPF_REG_CTX,
386 				      offsetof(struct sk_buff, dev));
387 		/* if (tmp != 0) goto pc + 1 */
388 		*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
389 		*insn++ = BPF_EXIT_INSN();
390 		if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
391 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
392 					    offsetof(struct net_device, ifindex));
393 		else
394 			*insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
395 					    offsetof(struct net_device, type));
396 		break;
397 
398 	case SKF_AD_OFF + SKF_AD_MARK:
399 		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
400 		insn += cnt - 1;
401 		break;
402 
403 	case SKF_AD_OFF + SKF_AD_RXHASH:
404 		BUILD_BUG_ON(sizeof_field(struct sk_buff, hash) != 4);
405 
406 		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
407 				    offsetof(struct sk_buff, hash));
408 		break;
409 
410 	case SKF_AD_OFF + SKF_AD_QUEUE:
411 		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
412 		insn += cnt - 1;
413 		break;
414 
415 	case SKF_AD_OFF + SKF_AD_VLAN_TAG:
416 		cnt = convert_skb_access(SKF_AD_VLAN_TAG,
417 					 BPF_REG_A, BPF_REG_CTX, insn);
418 		insn += cnt - 1;
419 		break;
420 
421 	case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
422 		cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
423 					 BPF_REG_A, BPF_REG_CTX, insn);
424 		insn += cnt - 1;
425 		break;
426 
427 	case SKF_AD_OFF + SKF_AD_VLAN_TPID:
428 		BUILD_BUG_ON(sizeof_field(struct sk_buff, vlan_proto) != 2);
429 
430 		/* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
431 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
432 				      offsetof(struct sk_buff, vlan_proto));
433 		/* A = ntohs(A) [emitting a nop or swap16] */
434 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
435 		break;
436 
437 	case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
438 	case SKF_AD_OFF + SKF_AD_NLATTR:
439 	case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
440 	case SKF_AD_OFF + SKF_AD_CPU:
441 	case SKF_AD_OFF + SKF_AD_RANDOM:
442 		/* arg1 = CTX */
443 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
444 		/* arg2 = A */
445 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
446 		/* arg3 = X */
447 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
448 		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
449 		switch (fp->k) {
450 		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
451 			*insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
452 			break;
453 		case SKF_AD_OFF + SKF_AD_NLATTR:
454 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
455 			break;
456 		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
457 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
458 			break;
459 		case SKF_AD_OFF + SKF_AD_CPU:
460 			*insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
461 			break;
462 		case SKF_AD_OFF + SKF_AD_RANDOM:
463 			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
464 			bpf_user_rnd_init_once();
465 			break;
466 		}
467 		break;
468 
469 	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
470 		/* A ^= X */
471 		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
472 		break;
473 
474 	default:
475 		/* This is just a dummy call to avoid letting the compiler
476 		 * evict __bpf_call_base() as an optimization. Placed here
477 		 * where no-one bothers.
478 		 */
479 		BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
480 		return false;
481 	}
482 
483 	*insnp = insn;
484 	return true;
485 }
486 
convert_bpf_ld_abs(struct sock_filter * fp,struct bpf_insn ** insnp)487 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
488 {
489 	const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
490 	int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
491 	bool endian = BPF_SIZE(fp->code) == BPF_H ||
492 		      BPF_SIZE(fp->code) == BPF_W;
493 	bool indirect = BPF_MODE(fp->code) == BPF_IND;
494 	const int ip_align = NET_IP_ALIGN;
495 	struct bpf_insn *insn = *insnp;
496 	int offset = fp->k;
497 
498 	if (!indirect &&
499 	    ((unaligned_ok && offset >= 0) ||
500 	     (!unaligned_ok && offset >= 0 &&
501 	      offset + ip_align >= 0 &&
502 	      offset + ip_align % size == 0))) {
503 		bool ldx_off_ok = offset <= S16_MAX;
504 
505 		*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
506 		if (offset)
507 			*insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
508 		*insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
509 				      size, 2 + endian + (!ldx_off_ok * 2));
510 		if (ldx_off_ok) {
511 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
512 					      BPF_REG_D, offset);
513 		} else {
514 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
515 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
516 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
517 					      BPF_REG_TMP, 0);
518 		}
519 		if (endian)
520 			*insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
521 		*insn++ = BPF_JMP_A(8);
522 	}
523 
524 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
525 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
526 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
527 	if (!indirect) {
528 		*insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
529 	} else {
530 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
531 		if (fp->k)
532 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
533 	}
534 
535 	switch (BPF_SIZE(fp->code)) {
536 	case BPF_B:
537 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
538 		break;
539 	case BPF_H:
540 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
541 		break;
542 	case BPF_W:
543 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
544 		break;
545 	default:
546 		return false;
547 	}
548 
549 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
550 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
551 	*insn   = BPF_EXIT_INSN();
552 
553 	*insnp = insn;
554 	return true;
555 }
556 
557 /**
558  *	bpf_convert_filter - convert filter program
559  *	@prog: the user passed filter program
560  *	@len: the length of the user passed filter program
561  *	@new_prog: allocated 'struct bpf_prog' or NULL
562  *	@new_len: pointer to store length of converted program
563  *	@seen_ld_abs: bool whether we've seen ld_abs/ind
564  *
565  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
566  * style extended BPF (eBPF).
567  * Conversion workflow:
568  *
569  * 1) First pass for calculating the new program length:
570  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
571  *
572  * 2) 2nd pass to remap in two passes: 1st pass finds new
573  *    jump offsets, 2nd pass remapping:
574  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
575  */
bpf_convert_filter(struct sock_filter * prog,int len,struct bpf_prog * new_prog,int * new_len,bool * seen_ld_abs)576 static int bpf_convert_filter(struct sock_filter *prog, int len,
577 			      struct bpf_prog *new_prog, int *new_len,
578 			      bool *seen_ld_abs)
579 {
580 	int new_flen = 0, pass = 0, target, i, stack_off;
581 	struct bpf_insn *new_insn, *first_insn = NULL;
582 	struct sock_filter *fp;
583 	int *addrs = NULL;
584 	u8 bpf_src;
585 
586 	BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
587 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
588 
589 	if (len <= 0 || len > BPF_MAXINSNS)
590 		return -EINVAL;
591 
592 	if (new_prog) {
593 		first_insn = new_prog->insnsi;
594 		addrs = kcalloc(len, sizeof(*addrs),
595 				GFP_KERNEL | __GFP_NOWARN);
596 		if (!addrs)
597 			return -ENOMEM;
598 	}
599 
600 do_pass:
601 	new_insn = first_insn;
602 	fp = prog;
603 
604 	/* Classic BPF related prologue emission. */
605 	if (new_prog) {
606 		/* Classic BPF expects A and X to be reset first. These need
607 		 * to be guaranteed to be the first two instructions.
608 		 */
609 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
610 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
611 
612 		/* All programs must keep CTX in callee saved BPF_REG_CTX.
613 		 * In eBPF case it's done by the compiler, here we need to
614 		 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
615 		 */
616 		*new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
617 		if (*seen_ld_abs) {
618 			/* For packet access in classic BPF, cache skb->data
619 			 * in callee-saved BPF R8 and skb->len - skb->data_len
620 			 * (headlen) in BPF R9. Since classic BPF is read-only
621 			 * on CTX, we only need to cache it once.
622 			 */
623 			*new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
624 						  BPF_REG_D, BPF_REG_CTX,
625 						  offsetof(struct sk_buff, data));
626 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
627 						  offsetof(struct sk_buff, len));
628 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
629 						  offsetof(struct sk_buff, data_len));
630 			*new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
631 		}
632 	} else {
633 		new_insn += 3;
634 	}
635 
636 	for (i = 0; i < len; fp++, i++) {
637 		struct bpf_insn tmp_insns[32] = { };
638 		struct bpf_insn *insn = tmp_insns;
639 
640 		if (addrs)
641 			addrs[i] = new_insn - first_insn;
642 
643 		switch (fp->code) {
644 		/* All arithmetic insns and skb loads map as-is. */
645 		case BPF_ALU | BPF_ADD | BPF_X:
646 		case BPF_ALU | BPF_ADD | BPF_K:
647 		case BPF_ALU | BPF_SUB | BPF_X:
648 		case BPF_ALU | BPF_SUB | BPF_K:
649 		case BPF_ALU | BPF_AND | BPF_X:
650 		case BPF_ALU | BPF_AND | BPF_K:
651 		case BPF_ALU | BPF_OR | BPF_X:
652 		case BPF_ALU | BPF_OR | BPF_K:
653 		case BPF_ALU | BPF_LSH | BPF_X:
654 		case BPF_ALU | BPF_LSH | BPF_K:
655 		case BPF_ALU | BPF_RSH | BPF_X:
656 		case BPF_ALU | BPF_RSH | BPF_K:
657 		case BPF_ALU | BPF_XOR | BPF_X:
658 		case BPF_ALU | BPF_XOR | BPF_K:
659 		case BPF_ALU | BPF_MUL | BPF_X:
660 		case BPF_ALU | BPF_MUL | BPF_K:
661 		case BPF_ALU | BPF_DIV | BPF_X:
662 		case BPF_ALU | BPF_DIV | BPF_K:
663 		case BPF_ALU | BPF_MOD | BPF_X:
664 		case BPF_ALU | BPF_MOD | BPF_K:
665 		case BPF_ALU | BPF_NEG:
666 		case BPF_LD | BPF_ABS | BPF_W:
667 		case BPF_LD | BPF_ABS | BPF_H:
668 		case BPF_LD | BPF_ABS | BPF_B:
669 		case BPF_LD | BPF_IND | BPF_W:
670 		case BPF_LD | BPF_IND | BPF_H:
671 		case BPF_LD | BPF_IND | BPF_B:
672 			/* Check for overloaded BPF extension and
673 			 * directly convert it if found, otherwise
674 			 * just move on with mapping.
675 			 */
676 			if (BPF_CLASS(fp->code) == BPF_LD &&
677 			    BPF_MODE(fp->code) == BPF_ABS &&
678 			    convert_bpf_extensions(fp, &insn))
679 				break;
680 			if (BPF_CLASS(fp->code) == BPF_LD &&
681 			    convert_bpf_ld_abs(fp, &insn)) {
682 				*seen_ld_abs = true;
683 				break;
684 			}
685 
686 			if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
687 			    fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
688 				*insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
689 				/* Error with exception code on div/mod by 0.
690 				 * For cBPF programs, this was always return 0.
691 				 */
692 				*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
693 				*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
694 				*insn++ = BPF_EXIT_INSN();
695 			}
696 
697 			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
698 			break;
699 
700 		/* Jump transformation cannot use BPF block macros
701 		 * everywhere as offset calculation and target updates
702 		 * require a bit more work than the rest, i.e. jump
703 		 * opcodes map as-is, but offsets need adjustment.
704 		 */
705 
706 #define BPF_EMIT_JMP							\
707 	do {								\
708 		const s32 off_min = S16_MIN, off_max = S16_MAX;		\
709 		s32 off;						\
710 									\
711 		if (target >= len || target < 0)			\
712 			goto err;					\
713 		off = addrs ? addrs[target] - addrs[i] - 1 : 0;		\
714 		/* Adjust pc relative offset for 2nd or 3rd insn. */	\
715 		off -= insn - tmp_insns;				\
716 		/* Reject anything not fitting into insn->off. */	\
717 		if (off < off_min || off > off_max)			\
718 			goto err;					\
719 		insn->off = off;					\
720 	} while (0)
721 
722 		case BPF_JMP | BPF_JA:
723 			target = i + fp->k + 1;
724 			insn->code = fp->code;
725 			BPF_EMIT_JMP;
726 			break;
727 
728 		case BPF_JMP | BPF_JEQ | BPF_K:
729 		case BPF_JMP | BPF_JEQ | BPF_X:
730 		case BPF_JMP | BPF_JSET | BPF_K:
731 		case BPF_JMP | BPF_JSET | BPF_X:
732 		case BPF_JMP | BPF_JGT | BPF_K:
733 		case BPF_JMP | BPF_JGT | BPF_X:
734 		case BPF_JMP | BPF_JGE | BPF_K:
735 		case BPF_JMP | BPF_JGE | BPF_X:
736 			if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
737 				/* BPF immediates are signed, zero extend
738 				 * immediate into tmp register and use it
739 				 * in compare insn.
740 				 */
741 				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
742 
743 				insn->dst_reg = BPF_REG_A;
744 				insn->src_reg = BPF_REG_TMP;
745 				bpf_src = BPF_X;
746 			} else {
747 				insn->dst_reg = BPF_REG_A;
748 				insn->imm = fp->k;
749 				bpf_src = BPF_SRC(fp->code);
750 				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
751 			}
752 
753 			/* Common case where 'jump_false' is next insn. */
754 			if (fp->jf == 0) {
755 				insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
756 				target = i + fp->jt + 1;
757 				BPF_EMIT_JMP;
758 				break;
759 			}
760 
761 			/* Convert some jumps when 'jump_true' is next insn. */
762 			if (fp->jt == 0) {
763 				switch (BPF_OP(fp->code)) {
764 				case BPF_JEQ:
765 					insn->code = BPF_JMP | BPF_JNE | bpf_src;
766 					break;
767 				case BPF_JGT:
768 					insn->code = BPF_JMP | BPF_JLE | bpf_src;
769 					break;
770 				case BPF_JGE:
771 					insn->code = BPF_JMP | BPF_JLT | bpf_src;
772 					break;
773 				default:
774 					goto jmp_rest;
775 				}
776 
777 				target = i + fp->jf + 1;
778 				BPF_EMIT_JMP;
779 				break;
780 			}
781 jmp_rest:
782 			/* Other jumps are mapped into two insns: Jxx and JA. */
783 			target = i + fp->jt + 1;
784 			insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
785 			BPF_EMIT_JMP;
786 			insn++;
787 
788 			insn->code = BPF_JMP | BPF_JA;
789 			target = i + fp->jf + 1;
790 			BPF_EMIT_JMP;
791 			break;
792 
793 		/* ldxb 4 * ([14] & 0xf) is remapped into 6 insns. */
794 		case BPF_LDX | BPF_MSH | BPF_B: {
795 			struct sock_filter tmp = {
796 				.code	= BPF_LD | BPF_ABS | BPF_B,
797 				.k	= fp->k,
798 			};
799 
800 			*seen_ld_abs = true;
801 
802 			/* X = A */
803 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
804 			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
805 			convert_bpf_ld_abs(&tmp, &insn);
806 			insn++;
807 			/* A &= 0xf */
808 			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
809 			/* A <<= 2 */
810 			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
811 			/* tmp = X */
812 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
813 			/* X = A */
814 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
815 			/* A = tmp */
816 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
817 			break;
818 		}
819 		/* RET_K is remapped into 2 insns. RET_A case doesn't need an
820 		 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
821 		 */
822 		case BPF_RET | BPF_A:
823 		case BPF_RET | BPF_K:
824 			if (BPF_RVAL(fp->code) == BPF_K)
825 				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
826 							0, fp->k);
827 			*insn = BPF_EXIT_INSN();
828 			break;
829 
830 		/* Store to stack. */
831 		case BPF_ST:
832 		case BPF_STX:
833 			stack_off = fp->k * 4  + 4;
834 			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
835 					    BPF_ST ? BPF_REG_A : BPF_REG_X,
836 					    -stack_off);
837 			/* check_load_and_stores() verifies that classic BPF can
838 			 * load from stack only after write, so tracking
839 			 * stack_depth for ST|STX insns is enough
840 			 */
841 			if (new_prog && new_prog->aux->stack_depth < stack_off)
842 				new_prog->aux->stack_depth = stack_off;
843 			break;
844 
845 		/* Load from stack. */
846 		case BPF_LD | BPF_MEM:
847 		case BPF_LDX | BPF_MEM:
848 			stack_off = fp->k * 4  + 4;
849 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
850 					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
851 					    -stack_off);
852 			break;
853 
854 		/* A = K or X = K */
855 		case BPF_LD | BPF_IMM:
856 		case BPF_LDX | BPF_IMM:
857 			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
858 					      BPF_REG_A : BPF_REG_X, fp->k);
859 			break;
860 
861 		/* X = A */
862 		case BPF_MISC | BPF_TAX:
863 			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
864 			break;
865 
866 		/* A = X */
867 		case BPF_MISC | BPF_TXA:
868 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
869 			break;
870 
871 		/* A = skb->len or X = skb->len */
872 		case BPF_LD | BPF_W | BPF_LEN:
873 		case BPF_LDX | BPF_W | BPF_LEN:
874 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
875 					    BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
876 					    offsetof(struct sk_buff, len));
877 			break;
878 
879 		/* Access seccomp_data fields. */
880 		case BPF_LDX | BPF_ABS | BPF_W:
881 			/* A = *(u32 *) (ctx + K) */
882 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
883 			break;
884 
885 		/* Unknown instruction. */
886 		default:
887 			goto err;
888 		}
889 
890 		insn++;
891 		if (new_prog)
892 			memcpy(new_insn, tmp_insns,
893 			       sizeof(*insn) * (insn - tmp_insns));
894 		new_insn += insn - tmp_insns;
895 	}
896 
897 	if (!new_prog) {
898 		/* Only calculating new length. */
899 		*new_len = new_insn - first_insn;
900 		if (*seen_ld_abs)
901 			*new_len += 4; /* Prologue bits. */
902 		return 0;
903 	}
904 
905 	pass++;
906 	if (new_flen != new_insn - first_insn) {
907 		new_flen = new_insn - first_insn;
908 		if (pass > 2)
909 			goto err;
910 		goto do_pass;
911 	}
912 
913 	kfree(addrs);
914 	BUG_ON(*new_len != new_flen);
915 	return 0;
916 err:
917 	kfree(addrs);
918 	return -EINVAL;
919 }
920 
921 /* Security:
922  *
923  * As we dont want to clear mem[] array for each packet going through
924  * __bpf_prog_run(), we check that filter loaded by user never try to read
925  * a cell if not previously written, and we check all branches to be sure
926  * a malicious user doesn't try to abuse us.
927  */
check_load_and_stores(const struct sock_filter * filter,int flen)928 static int check_load_and_stores(const struct sock_filter *filter, int flen)
929 {
930 	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
931 	int pc, ret = 0;
932 
933 	BUILD_BUG_ON(BPF_MEMWORDS > 16);
934 
935 	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
936 	if (!masks)
937 		return -ENOMEM;
938 
939 	memset(masks, 0xff, flen * sizeof(*masks));
940 
941 	for (pc = 0; pc < flen; pc++) {
942 		memvalid &= masks[pc];
943 
944 		switch (filter[pc].code) {
945 		case BPF_ST:
946 		case BPF_STX:
947 			memvalid |= (1 << filter[pc].k);
948 			break;
949 		case BPF_LD | BPF_MEM:
950 		case BPF_LDX | BPF_MEM:
951 			if (!(memvalid & (1 << filter[pc].k))) {
952 				ret = -EINVAL;
953 				goto error;
954 			}
955 			break;
956 		case BPF_JMP | BPF_JA:
957 			/* A jump must set masks on target */
958 			masks[pc + 1 + filter[pc].k] &= memvalid;
959 			memvalid = ~0;
960 			break;
961 		case BPF_JMP | BPF_JEQ | BPF_K:
962 		case BPF_JMP | BPF_JEQ | BPF_X:
963 		case BPF_JMP | BPF_JGE | BPF_K:
964 		case BPF_JMP | BPF_JGE | BPF_X:
965 		case BPF_JMP | BPF_JGT | BPF_K:
966 		case BPF_JMP | BPF_JGT | BPF_X:
967 		case BPF_JMP | BPF_JSET | BPF_K:
968 		case BPF_JMP | BPF_JSET | BPF_X:
969 			/* A jump must set masks on targets */
970 			masks[pc + 1 + filter[pc].jt] &= memvalid;
971 			masks[pc + 1 + filter[pc].jf] &= memvalid;
972 			memvalid = ~0;
973 			break;
974 		}
975 	}
976 error:
977 	kfree(masks);
978 	return ret;
979 }
980 
chk_code_allowed(u16 code_to_probe)981 static bool chk_code_allowed(u16 code_to_probe)
982 {
983 	static const bool codes[] = {
984 		/* 32 bit ALU operations */
985 		[BPF_ALU | BPF_ADD | BPF_K] = true,
986 		[BPF_ALU | BPF_ADD | BPF_X] = true,
987 		[BPF_ALU | BPF_SUB | BPF_K] = true,
988 		[BPF_ALU | BPF_SUB | BPF_X] = true,
989 		[BPF_ALU | BPF_MUL | BPF_K] = true,
990 		[BPF_ALU | BPF_MUL | BPF_X] = true,
991 		[BPF_ALU | BPF_DIV | BPF_K] = true,
992 		[BPF_ALU | BPF_DIV | BPF_X] = true,
993 		[BPF_ALU | BPF_MOD | BPF_K] = true,
994 		[BPF_ALU | BPF_MOD | BPF_X] = true,
995 		[BPF_ALU | BPF_AND | BPF_K] = true,
996 		[BPF_ALU | BPF_AND | BPF_X] = true,
997 		[BPF_ALU | BPF_OR | BPF_K] = true,
998 		[BPF_ALU | BPF_OR | BPF_X] = true,
999 		[BPF_ALU | BPF_XOR | BPF_K] = true,
1000 		[BPF_ALU | BPF_XOR | BPF_X] = true,
1001 		[BPF_ALU | BPF_LSH | BPF_K] = true,
1002 		[BPF_ALU | BPF_LSH | BPF_X] = true,
1003 		[BPF_ALU | BPF_RSH | BPF_K] = true,
1004 		[BPF_ALU | BPF_RSH | BPF_X] = true,
1005 		[BPF_ALU | BPF_NEG] = true,
1006 		/* Load instructions */
1007 		[BPF_LD | BPF_W | BPF_ABS] = true,
1008 		[BPF_LD | BPF_H | BPF_ABS] = true,
1009 		[BPF_LD | BPF_B | BPF_ABS] = true,
1010 		[BPF_LD | BPF_W | BPF_LEN] = true,
1011 		[BPF_LD | BPF_W | BPF_IND] = true,
1012 		[BPF_LD | BPF_H | BPF_IND] = true,
1013 		[BPF_LD | BPF_B | BPF_IND] = true,
1014 		[BPF_LD | BPF_IMM] = true,
1015 		[BPF_LD | BPF_MEM] = true,
1016 		[BPF_LDX | BPF_W | BPF_LEN] = true,
1017 		[BPF_LDX | BPF_B | BPF_MSH] = true,
1018 		[BPF_LDX | BPF_IMM] = true,
1019 		[BPF_LDX | BPF_MEM] = true,
1020 		/* Store instructions */
1021 		[BPF_ST] = true,
1022 		[BPF_STX] = true,
1023 		/* Misc instructions */
1024 		[BPF_MISC | BPF_TAX] = true,
1025 		[BPF_MISC | BPF_TXA] = true,
1026 		/* Return instructions */
1027 		[BPF_RET | BPF_K] = true,
1028 		[BPF_RET | BPF_A] = true,
1029 		/* Jump instructions */
1030 		[BPF_JMP | BPF_JA] = true,
1031 		[BPF_JMP | BPF_JEQ | BPF_K] = true,
1032 		[BPF_JMP | BPF_JEQ | BPF_X] = true,
1033 		[BPF_JMP | BPF_JGE | BPF_K] = true,
1034 		[BPF_JMP | BPF_JGE | BPF_X] = true,
1035 		[BPF_JMP | BPF_JGT | BPF_K] = true,
1036 		[BPF_JMP | BPF_JGT | BPF_X] = true,
1037 		[BPF_JMP | BPF_JSET | BPF_K] = true,
1038 		[BPF_JMP | BPF_JSET | BPF_X] = true,
1039 	};
1040 
1041 	if (code_to_probe >= ARRAY_SIZE(codes))
1042 		return false;
1043 
1044 	return codes[code_to_probe];
1045 }
1046 
bpf_check_basics_ok(const struct sock_filter * filter,unsigned int flen)1047 static bool bpf_check_basics_ok(const struct sock_filter *filter,
1048 				unsigned int flen)
1049 {
1050 	if (filter == NULL)
1051 		return false;
1052 	if (flen == 0 || flen > BPF_MAXINSNS)
1053 		return false;
1054 
1055 	return true;
1056 }
1057 
1058 /**
1059  *	bpf_check_classic - verify socket filter code
1060  *	@filter: filter to verify
1061  *	@flen: length of filter
1062  *
1063  * Check the user's filter code. If we let some ugly
1064  * filter code slip through kaboom! The filter must contain
1065  * no references or jumps that are out of range, no illegal
1066  * instructions, and must end with a RET instruction.
1067  *
1068  * All jumps are forward as they are not signed.
1069  *
1070  * Returns 0 if the rule set is legal or -EINVAL if not.
1071  */
bpf_check_classic(const struct sock_filter * filter,unsigned int flen)1072 static int bpf_check_classic(const struct sock_filter *filter,
1073 			     unsigned int flen)
1074 {
1075 	bool anc_found;
1076 	int pc;
1077 
1078 	/* Check the filter code now */
1079 	for (pc = 0; pc < flen; pc++) {
1080 		const struct sock_filter *ftest = &filter[pc];
1081 
1082 		/* May we actually operate on this code? */
1083 		if (!chk_code_allowed(ftest->code))
1084 			return -EINVAL;
1085 
1086 		/* Some instructions need special checks */
1087 		switch (ftest->code) {
1088 		case BPF_ALU | BPF_DIV | BPF_K:
1089 		case BPF_ALU | BPF_MOD | BPF_K:
1090 			/* Check for division by zero */
1091 			if (ftest->k == 0)
1092 				return -EINVAL;
1093 			break;
1094 		case BPF_ALU | BPF_LSH | BPF_K:
1095 		case BPF_ALU | BPF_RSH | BPF_K:
1096 			if (ftest->k >= 32)
1097 				return -EINVAL;
1098 			break;
1099 		case BPF_LD | BPF_MEM:
1100 		case BPF_LDX | BPF_MEM:
1101 		case BPF_ST:
1102 		case BPF_STX:
1103 			/* Check for invalid memory addresses */
1104 			if (ftest->k >= BPF_MEMWORDS)
1105 				return -EINVAL;
1106 			break;
1107 		case BPF_JMP | BPF_JA:
1108 			/* Note, the large ftest->k might cause loops.
1109 			 * Compare this with conditional jumps below,
1110 			 * where offsets are limited. --ANK (981016)
1111 			 */
1112 			if (ftest->k >= (unsigned int)(flen - pc - 1))
1113 				return -EINVAL;
1114 			break;
1115 		case BPF_JMP | BPF_JEQ | BPF_K:
1116 		case BPF_JMP | BPF_JEQ | BPF_X:
1117 		case BPF_JMP | BPF_JGE | BPF_K:
1118 		case BPF_JMP | BPF_JGE | BPF_X:
1119 		case BPF_JMP | BPF_JGT | BPF_K:
1120 		case BPF_JMP | BPF_JGT | BPF_X:
1121 		case BPF_JMP | BPF_JSET | BPF_K:
1122 		case BPF_JMP | BPF_JSET | BPF_X:
1123 			/* Both conditionals must be safe */
1124 			if (pc + ftest->jt + 1 >= flen ||
1125 			    pc + ftest->jf + 1 >= flen)
1126 				return -EINVAL;
1127 			break;
1128 		case BPF_LD | BPF_W | BPF_ABS:
1129 		case BPF_LD | BPF_H | BPF_ABS:
1130 		case BPF_LD | BPF_B | BPF_ABS:
1131 			anc_found = false;
1132 			if (bpf_anc_helper(ftest) & BPF_ANC)
1133 				anc_found = true;
1134 			/* Ancillary operation unknown or unsupported */
1135 			if (anc_found == false && ftest->k >= SKF_AD_OFF)
1136 				return -EINVAL;
1137 		}
1138 	}
1139 
1140 	/* Last instruction must be a RET code */
1141 	switch (filter[flen - 1].code) {
1142 	case BPF_RET | BPF_K:
1143 	case BPF_RET | BPF_A:
1144 		return check_load_and_stores(filter, flen);
1145 	}
1146 
1147 	return -EINVAL;
1148 }
1149 
bpf_prog_store_orig_filter(struct bpf_prog * fp,const struct sock_fprog * fprog)1150 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1151 				      const struct sock_fprog *fprog)
1152 {
1153 	unsigned int fsize = bpf_classic_proglen(fprog);
1154 	struct sock_fprog_kern *fkprog;
1155 
1156 	fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1157 	if (!fp->orig_prog)
1158 		return -ENOMEM;
1159 
1160 	fkprog = fp->orig_prog;
1161 	fkprog->len = fprog->len;
1162 
1163 	fkprog->filter = kmemdup(fp->insns, fsize,
1164 				 GFP_KERNEL | __GFP_NOWARN);
1165 	if (!fkprog->filter) {
1166 		kfree(fp->orig_prog);
1167 		return -ENOMEM;
1168 	}
1169 
1170 	return 0;
1171 }
1172 
bpf_release_orig_filter(struct bpf_prog * fp)1173 static void bpf_release_orig_filter(struct bpf_prog *fp)
1174 {
1175 	struct sock_fprog_kern *fprog = fp->orig_prog;
1176 
1177 	if (fprog) {
1178 		kfree(fprog->filter);
1179 		kfree(fprog);
1180 	}
1181 }
1182 
__bpf_prog_release(struct bpf_prog * prog)1183 static void __bpf_prog_release(struct bpf_prog *prog)
1184 {
1185 	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1186 		bpf_prog_put(prog);
1187 	} else {
1188 		bpf_release_orig_filter(prog);
1189 		bpf_prog_free(prog);
1190 	}
1191 }
1192 
__sk_filter_release(struct sk_filter * fp)1193 static void __sk_filter_release(struct sk_filter *fp)
1194 {
1195 	__bpf_prog_release(fp->prog);
1196 	kfree(fp);
1197 }
1198 
1199 /**
1200  * 	sk_filter_release_rcu - Release a socket filter by rcu_head
1201  *	@rcu: rcu_head that contains the sk_filter to free
1202  */
sk_filter_release_rcu(struct rcu_head * rcu)1203 static void sk_filter_release_rcu(struct rcu_head *rcu)
1204 {
1205 	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1206 
1207 	__sk_filter_release(fp);
1208 }
1209 
1210 /**
1211  *	sk_filter_release - release a socket filter
1212  *	@fp: filter to remove
1213  *
1214  *	Remove a filter from a socket and release its resources.
1215  */
sk_filter_release(struct sk_filter * fp)1216 static void sk_filter_release(struct sk_filter *fp)
1217 {
1218 	if (refcount_dec_and_test(&fp->refcnt))
1219 		call_rcu(&fp->rcu, sk_filter_release_rcu);
1220 }
1221 
sk_filter_uncharge(struct sock * sk,struct sk_filter * fp)1222 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1223 {
1224 	u32 filter_size = bpf_prog_size(fp->prog->len);
1225 
1226 	atomic_sub(filter_size, &sk->sk_omem_alloc);
1227 	sk_filter_release(fp);
1228 }
1229 
1230 /* try to charge the socket memory if there is space available
1231  * return true on success
1232  */
__sk_filter_charge(struct sock * sk,struct sk_filter * fp)1233 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1234 {
1235 	int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1236 	u32 filter_size = bpf_prog_size(fp->prog->len);
1237 
1238 	/* same check as in sock_kmalloc() */
1239 	if (filter_size <= optmem_max &&
1240 	    atomic_read(&sk->sk_omem_alloc) + filter_size < optmem_max) {
1241 		atomic_add(filter_size, &sk->sk_omem_alloc);
1242 		return true;
1243 	}
1244 	return false;
1245 }
1246 
sk_filter_charge(struct sock * sk,struct sk_filter * fp)1247 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1248 {
1249 	if (!refcount_inc_not_zero(&fp->refcnt))
1250 		return false;
1251 
1252 	if (!__sk_filter_charge(sk, fp)) {
1253 		sk_filter_release(fp);
1254 		return false;
1255 	}
1256 	return true;
1257 }
1258 
bpf_migrate_filter(struct bpf_prog * fp)1259 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1260 {
1261 	struct sock_filter *old_prog;
1262 	struct bpf_prog *old_fp;
1263 	int err, new_len, old_len = fp->len;
1264 	bool seen_ld_abs = false;
1265 
1266 	/* We are free to overwrite insns et al right here as it won't be used at
1267 	 * this point in time anymore internally after the migration to the eBPF
1268 	 * instruction representation.
1269 	 */
1270 	BUILD_BUG_ON(sizeof(struct sock_filter) !=
1271 		     sizeof(struct bpf_insn));
1272 
1273 	/* Conversion cannot happen on overlapping memory areas,
1274 	 * so we need to keep the user BPF around until the 2nd
1275 	 * pass. At this time, the user BPF is stored in fp->insns.
1276 	 */
1277 	old_prog = kmemdup_array(fp->insns, old_len, sizeof(struct sock_filter),
1278 				 GFP_KERNEL | __GFP_NOWARN);
1279 	if (!old_prog) {
1280 		err = -ENOMEM;
1281 		goto out_err;
1282 	}
1283 
1284 	/* 1st pass: calculate the new program length. */
1285 	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1286 				 &seen_ld_abs);
1287 	if (err)
1288 		goto out_err_free;
1289 
1290 	/* Expand fp for appending the new filter representation. */
1291 	old_fp = fp;
1292 	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1293 	if (!fp) {
1294 		/* The old_fp is still around in case we couldn't
1295 		 * allocate new memory, so uncharge on that one.
1296 		 */
1297 		fp = old_fp;
1298 		err = -ENOMEM;
1299 		goto out_err_free;
1300 	}
1301 
1302 	fp->len = new_len;
1303 
1304 	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1305 	err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1306 				 &seen_ld_abs);
1307 	if (err)
1308 		/* 2nd bpf_convert_filter() can fail only if it fails
1309 		 * to allocate memory, remapping must succeed. Note,
1310 		 * that at this time old_fp has already been released
1311 		 * by krealloc().
1312 		 */
1313 		goto out_err_free;
1314 
1315 	fp = bpf_prog_select_runtime(fp, &err);
1316 	if (err)
1317 		goto out_err_free;
1318 
1319 	kfree(old_prog);
1320 	return fp;
1321 
1322 out_err_free:
1323 	kfree(old_prog);
1324 out_err:
1325 	__bpf_prog_release(fp);
1326 	return ERR_PTR(err);
1327 }
1328 
bpf_prepare_filter(struct bpf_prog * fp,bpf_aux_classic_check_t trans)1329 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1330 					   bpf_aux_classic_check_t trans)
1331 {
1332 	int err;
1333 
1334 	fp->bpf_func = NULL;
1335 	fp->jited = 0;
1336 
1337 	err = bpf_check_classic(fp->insns, fp->len);
1338 	if (err) {
1339 		__bpf_prog_release(fp);
1340 		return ERR_PTR(err);
1341 	}
1342 
1343 	/* There might be additional checks and transformations
1344 	 * needed on classic filters, f.e. in case of seccomp.
1345 	 */
1346 	if (trans) {
1347 		err = trans(fp->insns, fp->len);
1348 		if (err) {
1349 			__bpf_prog_release(fp);
1350 			return ERR_PTR(err);
1351 		}
1352 	}
1353 
1354 	/* Probe if we can JIT compile the filter and if so, do
1355 	 * the compilation of the filter.
1356 	 */
1357 	bpf_jit_compile(fp);
1358 
1359 	/* JIT compiler couldn't process this filter, so do the eBPF translation
1360 	 * for the optimized interpreter.
1361 	 */
1362 	if (!fp->jited)
1363 		fp = bpf_migrate_filter(fp);
1364 
1365 	return fp;
1366 }
1367 
1368 /**
1369  *	bpf_prog_create - create an unattached filter
1370  *	@pfp: the unattached filter that is created
1371  *	@fprog: the filter program
1372  *
1373  * Create a filter independent of any socket. We first run some
1374  * sanity checks on it to make sure it does not explode on us later.
1375  * If an error occurs or there is insufficient memory for the filter
1376  * a negative errno code is returned. On success the return is zero.
1377  */
bpf_prog_create(struct bpf_prog ** pfp,struct sock_fprog_kern * fprog)1378 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1379 {
1380 	unsigned int fsize = bpf_classic_proglen(fprog);
1381 	struct bpf_prog *fp;
1382 
1383 	/* Make sure new filter is there and in the right amounts. */
1384 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1385 		return -EINVAL;
1386 
1387 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1388 	if (!fp)
1389 		return -ENOMEM;
1390 
1391 	memcpy(fp->insns, fprog->filter, fsize);
1392 
1393 	fp->len = fprog->len;
1394 	/* Since unattached filters are not copied back to user
1395 	 * space through sk_get_filter(), we do not need to hold
1396 	 * a copy here, and can spare us the work.
1397 	 */
1398 	fp->orig_prog = NULL;
1399 
1400 	/* bpf_prepare_filter() already takes care of freeing
1401 	 * memory in case something goes wrong.
1402 	 */
1403 	fp = bpf_prepare_filter(fp, NULL);
1404 	if (IS_ERR(fp))
1405 		return PTR_ERR(fp);
1406 
1407 	*pfp = fp;
1408 	return 0;
1409 }
1410 EXPORT_SYMBOL_GPL(bpf_prog_create);
1411 
1412 /**
1413  *	bpf_prog_create_from_user - create an unattached filter from user buffer
1414  *	@pfp: the unattached filter that is created
1415  *	@fprog: the filter program
1416  *	@trans: post-classic verifier transformation handler
1417  *	@save_orig: save classic BPF program
1418  *
1419  * This function effectively does the same as bpf_prog_create(), only
1420  * that it builds up its insns buffer from user space provided buffer.
1421  * It also allows for passing a bpf_aux_classic_check_t handler.
1422  */
bpf_prog_create_from_user(struct bpf_prog ** pfp,struct sock_fprog * fprog,bpf_aux_classic_check_t trans,bool save_orig)1423 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1424 			      bpf_aux_classic_check_t trans, bool save_orig)
1425 {
1426 	unsigned int fsize = bpf_classic_proglen(fprog);
1427 	struct bpf_prog *fp;
1428 	int err;
1429 
1430 	/* Make sure new filter is there and in the right amounts. */
1431 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1432 		return -EINVAL;
1433 
1434 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1435 	if (!fp)
1436 		return -ENOMEM;
1437 
1438 	if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1439 		__bpf_prog_free(fp);
1440 		return -EFAULT;
1441 	}
1442 
1443 	fp->len = fprog->len;
1444 	fp->orig_prog = NULL;
1445 
1446 	if (save_orig) {
1447 		err = bpf_prog_store_orig_filter(fp, fprog);
1448 		if (err) {
1449 			__bpf_prog_free(fp);
1450 			return -ENOMEM;
1451 		}
1452 	}
1453 
1454 	/* bpf_prepare_filter() already takes care of freeing
1455 	 * memory in case something goes wrong.
1456 	 */
1457 	fp = bpf_prepare_filter(fp, trans);
1458 	if (IS_ERR(fp))
1459 		return PTR_ERR(fp);
1460 
1461 	*pfp = fp;
1462 	return 0;
1463 }
1464 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1465 
bpf_prog_destroy(struct bpf_prog * fp)1466 void bpf_prog_destroy(struct bpf_prog *fp)
1467 {
1468 	__bpf_prog_release(fp);
1469 }
1470 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1471 
__sk_attach_prog(struct bpf_prog * prog,struct sock * sk)1472 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1473 {
1474 	struct sk_filter *fp, *old_fp;
1475 
1476 	fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1477 	if (!fp)
1478 		return -ENOMEM;
1479 
1480 	fp->prog = prog;
1481 
1482 	if (!__sk_filter_charge(sk, fp)) {
1483 		kfree(fp);
1484 		return -ENOMEM;
1485 	}
1486 	refcount_set(&fp->refcnt, 1);
1487 
1488 	old_fp = rcu_dereference_protected(sk->sk_filter,
1489 					   lockdep_sock_is_held(sk));
1490 	rcu_assign_pointer(sk->sk_filter, fp);
1491 
1492 	if (old_fp)
1493 		sk_filter_uncharge(sk, old_fp);
1494 
1495 	return 0;
1496 }
1497 
1498 static
__get_filter(struct sock_fprog * fprog,struct sock * sk)1499 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1500 {
1501 	unsigned int fsize = bpf_classic_proglen(fprog);
1502 	struct bpf_prog *prog;
1503 	int err;
1504 
1505 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1506 		return ERR_PTR(-EPERM);
1507 
1508 	/* Make sure new filter is there and in the right amounts. */
1509 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1510 		return ERR_PTR(-EINVAL);
1511 
1512 	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1513 	if (!prog)
1514 		return ERR_PTR(-ENOMEM);
1515 
1516 	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1517 		__bpf_prog_free(prog);
1518 		return ERR_PTR(-EFAULT);
1519 	}
1520 
1521 	prog->len = fprog->len;
1522 
1523 	err = bpf_prog_store_orig_filter(prog, fprog);
1524 	if (err) {
1525 		__bpf_prog_free(prog);
1526 		return ERR_PTR(-ENOMEM);
1527 	}
1528 
1529 	/* bpf_prepare_filter() already takes care of freeing
1530 	 * memory in case something goes wrong.
1531 	 */
1532 	return bpf_prepare_filter(prog, NULL);
1533 }
1534 
1535 /**
1536  *	sk_attach_filter - attach a socket filter
1537  *	@fprog: the filter program
1538  *	@sk: the socket to use
1539  *
1540  * Attach the user's filter code. We first run some sanity checks on
1541  * it to make sure it does not explode on us later. If an error
1542  * occurs or there is insufficient memory for the filter a negative
1543  * errno code is returned. On success the return is zero.
1544  */
sk_attach_filter(struct sock_fprog * fprog,struct sock * sk)1545 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1546 {
1547 	struct bpf_prog *prog = __get_filter(fprog, sk);
1548 	int err;
1549 
1550 	if (IS_ERR(prog))
1551 		return PTR_ERR(prog);
1552 
1553 	err = __sk_attach_prog(prog, sk);
1554 	if (err < 0) {
1555 		__bpf_prog_release(prog);
1556 		return err;
1557 	}
1558 
1559 	return 0;
1560 }
1561 EXPORT_SYMBOL_GPL(sk_attach_filter);
1562 
sk_reuseport_attach_filter(struct sock_fprog * fprog,struct sock * sk)1563 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1564 {
1565 	struct bpf_prog *prog = __get_filter(fprog, sk);
1566 	int err, optmem_max;
1567 
1568 	if (IS_ERR(prog))
1569 		return PTR_ERR(prog);
1570 
1571 	optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1572 	if (bpf_prog_size(prog->len) > optmem_max)
1573 		err = -ENOMEM;
1574 	else
1575 		err = reuseport_attach_prog(sk, prog);
1576 
1577 	if (err)
1578 		__bpf_prog_release(prog);
1579 
1580 	return err;
1581 }
1582 
__get_bpf(u32 ufd,struct sock * sk)1583 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1584 {
1585 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1586 		return ERR_PTR(-EPERM);
1587 
1588 	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1589 }
1590 
sk_attach_bpf(u32 ufd,struct sock * sk)1591 int sk_attach_bpf(u32 ufd, struct sock *sk)
1592 {
1593 	struct bpf_prog *prog = __get_bpf(ufd, sk);
1594 	int err;
1595 
1596 	if (IS_ERR(prog))
1597 		return PTR_ERR(prog);
1598 
1599 	err = __sk_attach_prog(prog, sk);
1600 	if (err < 0) {
1601 		bpf_prog_put(prog);
1602 		return err;
1603 	}
1604 
1605 	return 0;
1606 }
1607 
sk_reuseport_attach_bpf(u32 ufd,struct sock * sk)1608 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1609 {
1610 	struct bpf_prog *prog;
1611 	int err, optmem_max;
1612 
1613 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1614 		return -EPERM;
1615 
1616 	prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1617 	if (PTR_ERR(prog) == -EINVAL)
1618 		prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1619 	if (IS_ERR(prog))
1620 		return PTR_ERR(prog);
1621 
1622 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1623 		/* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1624 		 * bpf prog (e.g. sockmap).  It depends on the
1625 		 * limitation imposed by bpf_prog_load().
1626 		 * Hence, sysctl_optmem_max is not checked.
1627 		 */
1628 		if ((sk->sk_type != SOCK_STREAM &&
1629 		     sk->sk_type != SOCK_DGRAM) ||
1630 		    (sk->sk_protocol != IPPROTO_UDP &&
1631 		     sk->sk_protocol != IPPROTO_TCP) ||
1632 		    (sk->sk_family != AF_INET &&
1633 		     sk->sk_family != AF_INET6)) {
1634 			err = -ENOTSUPP;
1635 			goto err_prog_put;
1636 		}
1637 	} else {
1638 		/* BPF_PROG_TYPE_SOCKET_FILTER */
1639 		optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
1640 		if (bpf_prog_size(prog->len) > optmem_max) {
1641 			err = -ENOMEM;
1642 			goto err_prog_put;
1643 		}
1644 	}
1645 
1646 	err = reuseport_attach_prog(sk, prog);
1647 err_prog_put:
1648 	if (err)
1649 		bpf_prog_put(prog);
1650 
1651 	return err;
1652 }
1653 
sk_reuseport_prog_free(struct bpf_prog * prog)1654 void sk_reuseport_prog_free(struct bpf_prog *prog)
1655 {
1656 	if (!prog)
1657 		return;
1658 
1659 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1660 		bpf_prog_put(prog);
1661 	else
1662 		bpf_prog_destroy(prog);
1663 }
1664 
__bpf_try_make_writable(struct sk_buff * skb,unsigned int write_len)1665 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1666 					  unsigned int write_len)
1667 {
1668 #ifdef CONFIG_DEBUG_NET
1669 	/* Avoid a splat in pskb_may_pull_reason() */
1670 	if (write_len > INT_MAX)
1671 		return -EINVAL;
1672 #endif
1673 	return skb_ensure_writable(skb, write_len);
1674 }
1675 
bpf_try_make_writable(struct sk_buff * skb,unsigned int write_len)1676 static inline int bpf_try_make_writable(struct sk_buff *skb,
1677 					unsigned int write_len)
1678 {
1679 	int err = __bpf_try_make_writable(skb, write_len);
1680 
1681 	bpf_compute_data_pointers(skb);
1682 	return err;
1683 }
1684 
bpf_try_make_head_writable(struct sk_buff * skb)1685 static int bpf_try_make_head_writable(struct sk_buff *skb)
1686 {
1687 	return bpf_try_make_writable(skb, skb_headlen(skb));
1688 }
1689 
bpf_push_mac_rcsum(struct sk_buff * skb)1690 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1691 {
1692 	if (skb_at_tc_ingress(skb))
1693 		skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1694 }
1695 
bpf_pull_mac_rcsum(struct sk_buff * skb)1696 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1697 {
1698 	if (skb_at_tc_ingress(skb))
1699 		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1700 }
1701 
BPF_CALL_5(bpf_skb_store_bytes,struct sk_buff *,skb,u32,offset,const void *,from,u32,len,u64,flags)1702 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1703 	   const void *, from, u32, len, u64, flags)
1704 {
1705 	void *ptr;
1706 
1707 	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1708 		return -EINVAL;
1709 	if (unlikely(offset > INT_MAX))
1710 		return -EFAULT;
1711 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
1712 		return -EFAULT;
1713 
1714 	ptr = skb->data + offset;
1715 	if (flags & BPF_F_RECOMPUTE_CSUM)
1716 		__skb_postpull_rcsum(skb, ptr, len, offset);
1717 
1718 	memcpy(ptr, from, len);
1719 
1720 	if (flags & BPF_F_RECOMPUTE_CSUM)
1721 		__skb_postpush_rcsum(skb, ptr, len, offset);
1722 	if (flags & BPF_F_INVALIDATE_HASH)
1723 		skb_clear_hash(skb);
1724 
1725 	return 0;
1726 }
1727 
1728 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1729 	.func		= bpf_skb_store_bytes,
1730 	.gpl_only	= false,
1731 	.ret_type	= RET_INTEGER,
1732 	.arg1_type	= ARG_PTR_TO_CTX,
1733 	.arg2_type	= ARG_ANYTHING,
1734 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
1735 	.arg4_type	= ARG_CONST_SIZE,
1736 	.arg5_type	= ARG_ANYTHING,
1737 };
1738 
__bpf_skb_store_bytes(struct sk_buff * skb,u32 offset,const void * from,u32 len,u64 flags)1739 int __bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from,
1740 			  u32 len, u64 flags)
1741 {
1742 	return ____bpf_skb_store_bytes(skb, offset, from, len, flags);
1743 }
1744 
BPF_CALL_4(bpf_skb_load_bytes,const struct sk_buff *,skb,u32,offset,void *,to,u32,len)1745 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1746 	   void *, to, u32, len)
1747 {
1748 	void *ptr;
1749 
1750 	if (unlikely(offset > INT_MAX))
1751 		goto err_clear;
1752 
1753 	ptr = skb_header_pointer(skb, offset, len, to);
1754 	if (unlikely(!ptr))
1755 		goto err_clear;
1756 	if (ptr != to)
1757 		memcpy(to, ptr, len);
1758 
1759 	return 0;
1760 err_clear:
1761 	memset(to, 0, len);
1762 	return -EFAULT;
1763 }
1764 
1765 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1766 	.func		= bpf_skb_load_bytes,
1767 	.gpl_only	= false,
1768 	.ret_type	= RET_INTEGER,
1769 	.arg1_type	= ARG_PTR_TO_CTX,
1770 	.arg2_type	= ARG_ANYTHING,
1771 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1772 	.arg4_type	= ARG_CONST_SIZE,
1773 };
1774 
__bpf_skb_load_bytes(const struct sk_buff * skb,u32 offset,void * to,u32 len)1775 int __bpf_skb_load_bytes(const struct sk_buff *skb, u32 offset, void *to, u32 len)
1776 {
1777 	return ____bpf_skb_load_bytes(skb, offset, to, len);
1778 }
1779 
BPF_CALL_4(bpf_flow_dissector_load_bytes,const struct bpf_flow_dissector *,ctx,u32,offset,void *,to,u32,len)1780 BPF_CALL_4(bpf_flow_dissector_load_bytes,
1781 	   const struct bpf_flow_dissector *, ctx, u32, offset,
1782 	   void *, to, u32, len)
1783 {
1784 	void *ptr;
1785 
1786 	if (unlikely(offset > 0xffff))
1787 		goto err_clear;
1788 
1789 	if (unlikely(!ctx->skb))
1790 		goto err_clear;
1791 
1792 	ptr = skb_header_pointer(ctx->skb, offset, len, to);
1793 	if (unlikely(!ptr))
1794 		goto err_clear;
1795 	if (ptr != to)
1796 		memcpy(to, ptr, len);
1797 
1798 	return 0;
1799 err_clear:
1800 	memset(to, 0, len);
1801 	return -EFAULT;
1802 }
1803 
1804 static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1805 	.func		= bpf_flow_dissector_load_bytes,
1806 	.gpl_only	= false,
1807 	.ret_type	= RET_INTEGER,
1808 	.arg1_type	= ARG_PTR_TO_CTX,
1809 	.arg2_type	= ARG_ANYTHING,
1810 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1811 	.arg4_type	= ARG_CONST_SIZE,
1812 };
1813 
BPF_CALL_5(bpf_skb_load_bytes_relative,const struct sk_buff *,skb,u32,offset,void *,to,u32,len,u32,start_header)1814 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1815 	   u32, offset, void *, to, u32, len, u32, start_header)
1816 {
1817 	u8 *end = skb_tail_pointer(skb);
1818 	u8 *start, *ptr;
1819 
1820 	if (unlikely(offset > 0xffff))
1821 		goto err_clear;
1822 
1823 	switch (start_header) {
1824 	case BPF_HDR_START_MAC:
1825 		if (unlikely(!skb_mac_header_was_set(skb)))
1826 			goto err_clear;
1827 		start = skb_mac_header(skb);
1828 		break;
1829 	case BPF_HDR_START_NET:
1830 		start = skb_network_header(skb);
1831 		break;
1832 	default:
1833 		goto err_clear;
1834 	}
1835 
1836 	ptr = start + offset;
1837 
1838 	if (likely(ptr + len <= end)) {
1839 		memcpy(to, ptr, len);
1840 		return 0;
1841 	}
1842 
1843 err_clear:
1844 	memset(to, 0, len);
1845 	return -EFAULT;
1846 }
1847 
1848 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1849 	.func		= bpf_skb_load_bytes_relative,
1850 	.gpl_only	= false,
1851 	.ret_type	= RET_INTEGER,
1852 	.arg1_type	= ARG_PTR_TO_CTX,
1853 	.arg2_type	= ARG_ANYTHING,
1854 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1855 	.arg4_type	= ARG_CONST_SIZE,
1856 	.arg5_type	= ARG_ANYTHING,
1857 };
1858 
BPF_CALL_2(bpf_skb_pull_data,struct sk_buff *,skb,u32,len)1859 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1860 {
1861 	/* Idea is the following: should the needed direct read/write
1862 	 * test fail during runtime, we can pull in more data and redo
1863 	 * again, since implicitly, we invalidate previous checks here.
1864 	 *
1865 	 * Or, since we know how much we need to make read/writeable,
1866 	 * this can be done once at the program beginning for direct
1867 	 * access case. By this we overcome limitations of only current
1868 	 * headroom being accessible.
1869 	 */
1870 	return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1871 }
1872 
1873 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1874 	.func		= bpf_skb_pull_data,
1875 	.gpl_only	= false,
1876 	.ret_type	= RET_INTEGER,
1877 	.arg1_type	= ARG_PTR_TO_CTX,
1878 	.arg2_type	= ARG_ANYTHING,
1879 };
1880 
BPF_CALL_1(bpf_sk_fullsock,struct sock *,sk)1881 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1882 {
1883 	return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1884 }
1885 
1886 static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1887 	.func		= bpf_sk_fullsock,
1888 	.gpl_only	= false,
1889 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
1890 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
1891 };
1892 
sk_skb_try_make_writable(struct sk_buff * skb,unsigned int write_len)1893 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1894 					   unsigned int write_len)
1895 {
1896 	return __bpf_try_make_writable(skb, write_len);
1897 }
1898 
BPF_CALL_2(sk_skb_pull_data,struct sk_buff *,skb,u32,len)1899 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1900 {
1901 	/* Idea is the following: should the needed direct read/write
1902 	 * test fail during runtime, we can pull in more data and redo
1903 	 * again, since implicitly, we invalidate previous checks here.
1904 	 *
1905 	 * Or, since we know how much we need to make read/writeable,
1906 	 * this can be done once at the program beginning for direct
1907 	 * access case. By this we overcome limitations of only current
1908 	 * headroom being accessible.
1909 	 */
1910 	return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1911 }
1912 
1913 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1914 	.func		= sk_skb_pull_data,
1915 	.gpl_only	= false,
1916 	.ret_type	= RET_INTEGER,
1917 	.arg1_type	= ARG_PTR_TO_CTX,
1918 	.arg2_type	= ARG_ANYTHING,
1919 };
1920 
BPF_CALL_5(bpf_l3_csum_replace,struct sk_buff *,skb,u32,offset,u64,from,u64,to,u64,flags)1921 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1922 	   u64, from, u64, to, u64, flags)
1923 {
1924 	__sum16 *ptr;
1925 
1926 	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1927 		return -EINVAL;
1928 	if (unlikely(offset > 0xffff || offset & 1))
1929 		return -EFAULT;
1930 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1931 		return -EFAULT;
1932 
1933 	ptr = (__sum16 *)(skb->data + offset);
1934 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1935 	case 0:
1936 		if (unlikely(from != 0))
1937 			return -EINVAL;
1938 
1939 		csum_replace_by_diff(ptr, to);
1940 		break;
1941 	case 2:
1942 		csum_replace2(ptr, from, to);
1943 		break;
1944 	case 4:
1945 		csum_replace4(ptr, from, to);
1946 		break;
1947 	default:
1948 		return -EINVAL;
1949 	}
1950 
1951 	return 0;
1952 }
1953 
1954 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1955 	.func		= bpf_l3_csum_replace,
1956 	.gpl_only	= false,
1957 	.ret_type	= RET_INTEGER,
1958 	.arg1_type	= ARG_PTR_TO_CTX,
1959 	.arg2_type	= ARG_ANYTHING,
1960 	.arg3_type	= ARG_ANYTHING,
1961 	.arg4_type	= ARG_ANYTHING,
1962 	.arg5_type	= ARG_ANYTHING,
1963 };
1964 
BPF_CALL_5(bpf_l4_csum_replace,struct sk_buff *,skb,u32,offset,u64,from,u64,to,u64,flags)1965 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1966 	   u64, from, u64, to, u64, flags)
1967 {
1968 	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1969 	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1970 	bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1971 	__sum16 *ptr;
1972 
1973 	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1974 			       BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1975 		return -EINVAL;
1976 	if (unlikely(offset > 0xffff || offset & 1))
1977 		return -EFAULT;
1978 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1979 		return -EFAULT;
1980 
1981 	ptr = (__sum16 *)(skb->data + offset);
1982 	if (is_mmzero && !do_mforce && !*ptr)
1983 		return 0;
1984 
1985 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1986 	case 0:
1987 		if (unlikely(from != 0))
1988 			return -EINVAL;
1989 
1990 		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1991 		break;
1992 	case 2:
1993 		inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1994 		break;
1995 	case 4:
1996 		inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1997 		break;
1998 	default:
1999 		return -EINVAL;
2000 	}
2001 
2002 	if (is_mmzero && !*ptr)
2003 		*ptr = CSUM_MANGLED_0;
2004 	return 0;
2005 }
2006 
2007 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
2008 	.func		= bpf_l4_csum_replace,
2009 	.gpl_only	= false,
2010 	.ret_type	= RET_INTEGER,
2011 	.arg1_type	= ARG_PTR_TO_CTX,
2012 	.arg2_type	= ARG_ANYTHING,
2013 	.arg3_type	= ARG_ANYTHING,
2014 	.arg4_type	= ARG_ANYTHING,
2015 	.arg5_type	= ARG_ANYTHING,
2016 };
2017 
BPF_CALL_5(bpf_csum_diff,__be32 *,from,u32,from_size,__be32 *,to,u32,to_size,__wsum,seed)2018 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
2019 	   __be32 *, to, u32, to_size, __wsum, seed)
2020 {
2021 	/* This is quite flexible, some examples:
2022 	 *
2023 	 * from_size == 0, to_size > 0,  seed := csum --> pushing data
2024 	 * from_size > 0,  to_size == 0, seed := csum --> pulling data
2025 	 * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
2026 	 *
2027 	 * Even for diffing, from_size and to_size don't need to be equal.
2028 	 */
2029 
2030 	__wsum ret = seed;
2031 
2032 	if (from_size && to_size)
2033 		ret = csum_sub(csum_partial(to, to_size, ret),
2034 			       csum_partial(from, from_size, 0));
2035 	else if (to_size)
2036 		ret = csum_partial(to, to_size, ret);
2037 
2038 	else if (from_size)
2039 		ret = ~csum_partial(from, from_size, ~ret);
2040 
2041 	return csum_from32to16((__force unsigned int)ret);
2042 }
2043 
2044 static const struct bpf_func_proto bpf_csum_diff_proto = {
2045 	.func		= bpf_csum_diff,
2046 	.gpl_only	= false,
2047 	.pkt_access	= true,
2048 	.ret_type	= RET_INTEGER,
2049 	.arg1_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2050 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
2051 	.arg3_type	= ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2052 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
2053 	.arg5_type	= ARG_ANYTHING,
2054 };
2055 
BPF_CALL_2(bpf_csum_update,struct sk_buff *,skb,__wsum,csum)2056 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
2057 {
2058 	/* The interface is to be used in combination with bpf_csum_diff()
2059 	 * for direct packet writes. csum rotation for alignment as well
2060 	 * as emulating csum_sub() can be done from the eBPF program.
2061 	 */
2062 	if (skb->ip_summed == CHECKSUM_COMPLETE)
2063 		return (skb->csum = csum_add(skb->csum, csum));
2064 
2065 	return -ENOTSUPP;
2066 }
2067 
2068 static const struct bpf_func_proto bpf_csum_update_proto = {
2069 	.func		= bpf_csum_update,
2070 	.gpl_only	= false,
2071 	.ret_type	= RET_INTEGER,
2072 	.arg1_type	= ARG_PTR_TO_CTX,
2073 	.arg2_type	= ARG_ANYTHING,
2074 };
2075 
BPF_CALL_2(bpf_csum_level,struct sk_buff *,skb,u64,level)2076 BPF_CALL_2(bpf_csum_level, struct sk_buff *, skb, u64, level)
2077 {
2078 	/* The interface is to be used in combination with bpf_skb_adjust_room()
2079 	 * for encap/decap of packet headers when BPF_F_ADJ_ROOM_NO_CSUM_RESET
2080 	 * is passed as flags, for example.
2081 	 */
2082 	switch (level) {
2083 	case BPF_CSUM_LEVEL_INC:
2084 		__skb_incr_checksum_unnecessary(skb);
2085 		break;
2086 	case BPF_CSUM_LEVEL_DEC:
2087 		__skb_decr_checksum_unnecessary(skb);
2088 		break;
2089 	case BPF_CSUM_LEVEL_RESET:
2090 		__skb_reset_checksum_unnecessary(skb);
2091 		break;
2092 	case BPF_CSUM_LEVEL_QUERY:
2093 		return skb->ip_summed == CHECKSUM_UNNECESSARY ?
2094 		       skb->csum_level : -EACCES;
2095 	default:
2096 		return -EINVAL;
2097 	}
2098 
2099 	return 0;
2100 }
2101 
2102 static const struct bpf_func_proto bpf_csum_level_proto = {
2103 	.func		= bpf_csum_level,
2104 	.gpl_only	= false,
2105 	.ret_type	= RET_INTEGER,
2106 	.arg1_type	= ARG_PTR_TO_CTX,
2107 	.arg2_type	= ARG_ANYTHING,
2108 };
2109 
__bpf_rx_skb(struct net_device * dev,struct sk_buff * skb)2110 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2111 {
2112 	return dev_forward_skb_nomtu(dev, skb);
2113 }
2114 
__bpf_rx_skb_no_mac(struct net_device * dev,struct sk_buff * skb)2115 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2116 				      struct sk_buff *skb)
2117 {
2118 	int ret = ____dev_forward_skb(dev, skb, false);
2119 
2120 	if (likely(!ret)) {
2121 		skb->dev = dev;
2122 		ret = netif_rx(skb);
2123 	}
2124 
2125 	return ret;
2126 }
2127 
__bpf_tx_skb(struct net_device * dev,struct sk_buff * skb)2128 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2129 {
2130 	int ret;
2131 
2132 	if (dev_xmit_recursion()) {
2133 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2134 		kfree_skb(skb);
2135 		return -ENETDOWN;
2136 	}
2137 
2138 	skb->dev = dev;
2139 	skb_set_redirected_noclear(skb, skb_at_tc_ingress(skb));
2140 	skb_clear_tstamp(skb);
2141 
2142 	dev_xmit_recursion_inc();
2143 	ret = dev_queue_xmit(skb);
2144 	dev_xmit_recursion_dec();
2145 
2146 	return ret;
2147 }
2148 
__bpf_redirect_no_mac(struct sk_buff * skb,struct net_device * dev,u32 flags)2149 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2150 				 u32 flags)
2151 {
2152 	unsigned int mlen = skb_network_offset(skb);
2153 
2154 	if (unlikely(skb->len <= mlen)) {
2155 		kfree_skb(skb);
2156 		return -ERANGE;
2157 	}
2158 
2159 	if (mlen) {
2160 		__skb_pull(skb, mlen);
2161 
2162 		/* At ingress, the mac header has already been pulled once.
2163 		 * At egress, skb_pospull_rcsum has to be done in case that
2164 		 * the skb is originated from ingress (i.e. a forwarded skb)
2165 		 * to ensure that rcsum starts at net header.
2166 		 */
2167 		if (!skb_at_tc_ingress(skb))
2168 			skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2169 	}
2170 	skb_pop_mac_header(skb);
2171 	skb_reset_mac_len(skb);
2172 	return flags & BPF_F_INGRESS ?
2173 	       __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2174 }
2175 
__bpf_redirect_common(struct sk_buff * skb,struct net_device * dev,u32 flags)2176 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2177 				 u32 flags)
2178 {
2179 	/* Verify that a link layer header is carried */
2180 	if (unlikely(skb->mac_header >= skb->network_header || skb->len == 0)) {
2181 		kfree_skb(skb);
2182 		return -ERANGE;
2183 	}
2184 
2185 	bpf_push_mac_rcsum(skb);
2186 	return flags & BPF_F_INGRESS ?
2187 	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2188 }
2189 
__bpf_redirect(struct sk_buff * skb,struct net_device * dev,u32 flags)2190 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2191 			  u32 flags)
2192 {
2193 	if (dev_is_mac_header_xmit(dev))
2194 		return __bpf_redirect_common(skb, dev, flags);
2195 	else
2196 		return __bpf_redirect_no_mac(skb, dev, flags);
2197 }
2198 
2199 #if IS_ENABLED(CONFIG_IPV6)
bpf_out_neigh_v6(struct net * net,struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2200 static int bpf_out_neigh_v6(struct net *net, struct sk_buff *skb,
2201 			    struct net_device *dev, struct bpf_nh_params *nh)
2202 {
2203 	u32 hh_len = LL_RESERVED_SPACE(dev);
2204 	const struct in6_addr *nexthop;
2205 	struct dst_entry *dst = NULL;
2206 	struct neighbour *neigh;
2207 
2208 	if (dev_xmit_recursion()) {
2209 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2210 		goto out_drop;
2211 	}
2212 
2213 	skb->dev = dev;
2214 	skb_clear_tstamp(skb);
2215 
2216 	if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
2217 		skb = skb_expand_head(skb, hh_len);
2218 		if (!skb)
2219 			return -ENOMEM;
2220 	}
2221 
2222 	rcu_read_lock();
2223 	if (!nh) {
2224 		dst = skb_dst(skb);
2225 		nexthop = rt6_nexthop(dst_rt6_info(dst),
2226 				      &ipv6_hdr(skb)->daddr);
2227 	} else {
2228 		nexthop = &nh->ipv6_nh;
2229 	}
2230 	neigh = ip_neigh_gw6(dev, nexthop);
2231 	if (likely(!IS_ERR(neigh))) {
2232 		int ret;
2233 
2234 		sock_confirm_neigh(skb, neigh);
2235 		local_bh_disable();
2236 		dev_xmit_recursion_inc();
2237 		ret = neigh_output(neigh, skb, false);
2238 		dev_xmit_recursion_dec();
2239 		local_bh_enable();
2240 		rcu_read_unlock();
2241 		return ret;
2242 	}
2243 	rcu_read_unlock();
2244 	if (dst)
2245 		IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
2246 out_drop:
2247 	kfree_skb(skb);
2248 	return -ENETDOWN;
2249 }
2250 
__bpf_redirect_neigh_v6(struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2251 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
2252 				   struct bpf_nh_params *nh)
2253 {
2254 	const struct ipv6hdr *ip6h = ipv6_hdr(skb);
2255 	struct net *net = dev_net(dev);
2256 	int err, ret = NET_XMIT_DROP;
2257 
2258 	if (!nh) {
2259 		struct dst_entry *dst;
2260 		struct flowi6 fl6 = {
2261 			.flowi6_flags = FLOWI_FLAG_ANYSRC,
2262 			.flowi6_mark  = skb->mark,
2263 			.flowlabel    = ip6_flowinfo(ip6h),
2264 			.flowi6_oif   = dev->ifindex,
2265 			.flowi6_proto = ip6h->nexthdr,
2266 			.daddr	      = ip6h->daddr,
2267 			.saddr	      = ip6h->saddr,
2268 		};
2269 
2270 		dst = ipv6_stub->ipv6_dst_lookup_flow(net, NULL, &fl6, NULL);
2271 		if (IS_ERR(dst))
2272 			goto out_drop;
2273 
2274 		skb_dst_set(skb, dst);
2275 	} else if (nh->nh_family != AF_INET6) {
2276 		goto out_drop;
2277 	}
2278 
2279 	err = bpf_out_neigh_v6(net, skb, dev, nh);
2280 	if (unlikely(net_xmit_eval(err)))
2281 		DEV_STATS_INC(dev, tx_errors);
2282 	else
2283 		ret = NET_XMIT_SUCCESS;
2284 	goto out_xmit;
2285 out_drop:
2286 	DEV_STATS_INC(dev, tx_errors);
2287 	kfree_skb(skb);
2288 out_xmit:
2289 	return ret;
2290 }
2291 #else
__bpf_redirect_neigh_v6(struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2292 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
2293 				   struct bpf_nh_params *nh)
2294 {
2295 	kfree_skb(skb);
2296 	return NET_XMIT_DROP;
2297 }
2298 #endif /* CONFIG_IPV6 */
2299 
2300 #if IS_ENABLED(CONFIG_INET)
bpf_out_neigh_v4(struct net * net,struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2301 static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
2302 			    struct net_device *dev, struct bpf_nh_params *nh)
2303 {
2304 	u32 hh_len = LL_RESERVED_SPACE(dev);
2305 	struct neighbour *neigh;
2306 	bool is_v6gw = false;
2307 
2308 	if (dev_xmit_recursion()) {
2309 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2310 		goto out_drop;
2311 	}
2312 
2313 	skb->dev = dev;
2314 	skb_clear_tstamp(skb);
2315 
2316 	if (unlikely(skb_headroom(skb) < hh_len && dev->header_ops)) {
2317 		skb = skb_expand_head(skb, hh_len);
2318 		if (!skb)
2319 			return -ENOMEM;
2320 	}
2321 
2322 	rcu_read_lock();
2323 	if (!nh) {
2324 		struct rtable *rt = skb_rtable(skb);
2325 
2326 		neigh = ip_neigh_for_gw(rt, skb, &is_v6gw);
2327 	} else if (nh->nh_family == AF_INET6) {
2328 		neigh = ip_neigh_gw6(dev, &nh->ipv6_nh);
2329 		is_v6gw = true;
2330 	} else if (nh->nh_family == AF_INET) {
2331 		neigh = ip_neigh_gw4(dev, nh->ipv4_nh);
2332 	} else {
2333 		rcu_read_unlock();
2334 		goto out_drop;
2335 	}
2336 
2337 	if (likely(!IS_ERR(neigh))) {
2338 		int ret;
2339 
2340 		sock_confirm_neigh(skb, neigh);
2341 		local_bh_disable();
2342 		dev_xmit_recursion_inc();
2343 		ret = neigh_output(neigh, skb, is_v6gw);
2344 		dev_xmit_recursion_dec();
2345 		local_bh_enable();
2346 		rcu_read_unlock();
2347 		return ret;
2348 	}
2349 	rcu_read_unlock();
2350 out_drop:
2351 	kfree_skb(skb);
2352 	return -ENETDOWN;
2353 }
2354 
__bpf_redirect_neigh_v4(struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2355 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
2356 				   struct bpf_nh_params *nh)
2357 {
2358 	const struct iphdr *ip4h = ip_hdr(skb);
2359 	struct net *net = dev_net(dev);
2360 	int err, ret = NET_XMIT_DROP;
2361 
2362 	if (!nh) {
2363 		struct flowi4 fl4 = {
2364 			.flowi4_flags = FLOWI_FLAG_ANYSRC,
2365 			.flowi4_mark  = skb->mark,
2366 			.flowi4_tos   = inet_dscp_to_dsfield(ip4h_dscp(ip4h)),
2367 			.flowi4_oif   = dev->ifindex,
2368 			.flowi4_proto = ip4h->protocol,
2369 			.daddr	      = ip4h->daddr,
2370 			.saddr	      = ip4h->saddr,
2371 		};
2372 		struct rtable *rt;
2373 
2374 		rt = ip_route_output_flow(net, &fl4, NULL);
2375 		if (IS_ERR(rt))
2376 			goto out_drop;
2377 		if (rt->rt_type != RTN_UNICAST && rt->rt_type != RTN_LOCAL) {
2378 			ip_rt_put(rt);
2379 			goto out_drop;
2380 		}
2381 
2382 		skb_dst_set(skb, &rt->dst);
2383 	}
2384 
2385 	err = bpf_out_neigh_v4(net, skb, dev, nh);
2386 	if (unlikely(net_xmit_eval(err)))
2387 		DEV_STATS_INC(dev, tx_errors);
2388 	else
2389 		ret = NET_XMIT_SUCCESS;
2390 	goto out_xmit;
2391 out_drop:
2392 	DEV_STATS_INC(dev, tx_errors);
2393 	kfree_skb(skb);
2394 out_xmit:
2395 	return ret;
2396 }
2397 #else
__bpf_redirect_neigh_v4(struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2398 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
2399 				   struct bpf_nh_params *nh)
2400 {
2401 	kfree_skb(skb);
2402 	return NET_XMIT_DROP;
2403 }
2404 #endif /* CONFIG_INET */
2405 
__bpf_redirect_neigh(struct sk_buff * skb,struct net_device * dev,struct bpf_nh_params * nh)2406 static int __bpf_redirect_neigh(struct sk_buff *skb, struct net_device *dev,
2407 				struct bpf_nh_params *nh)
2408 {
2409 	struct ethhdr *ethh = eth_hdr(skb);
2410 
2411 	if (unlikely(skb->mac_header >= skb->network_header))
2412 		goto out;
2413 	bpf_push_mac_rcsum(skb);
2414 	if (is_multicast_ether_addr(ethh->h_dest))
2415 		goto out;
2416 
2417 	skb_pull(skb, sizeof(*ethh));
2418 	skb_unset_mac_header(skb);
2419 	skb_reset_network_header(skb);
2420 
2421 	if (skb->protocol == htons(ETH_P_IP))
2422 		return __bpf_redirect_neigh_v4(skb, dev, nh);
2423 	else if (skb->protocol == htons(ETH_P_IPV6))
2424 		return __bpf_redirect_neigh_v6(skb, dev, nh);
2425 out:
2426 	kfree_skb(skb);
2427 	return -ENOTSUPP;
2428 }
2429 
2430 /* Internal, non-exposed redirect flags. */
2431 enum {
2432 	BPF_F_NEIGH	= (1ULL << 16),
2433 	BPF_F_PEER	= (1ULL << 17),
2434 	BPF_F_NEXTHOP	= (1ULL << 18),
2435 #define BPF_F_REDIRECT_INTERNAL	(BPF_F_NEIGH | BPF_F_PEER | BPF_F_NEXTHOP)
2436 };
2437 
BPF_CALL_3(bpf_clone_redirect,struct sk_buff *,skb,u32,ifindex,u64,flags)2438 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2439 {
2440 	struct net_device *dev;
2441 	struct sk_buff *clone;
2442 	int ret;
2443 
2444 	BUILD_BUG_ON(BPF_F_REDIRECT_INTERNAL & BPF_F_REDIRECT_FLAGS);
2445 
2446 	if (unlikely(flags & (~(BPF_F_INGRESS) | BPF_F_REDIRECT_INTERNAL)))
2447 		return -EINVAL;
2448 
2449 	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2450 	if (unlikely(!dev))
2451 		return -EINVAL;
2452 
2453 	clone = skb_clone(skb, GFP_ATOMIC);
2454 	if (unlikely(!clone))
2455 		return -ENOMEM;
2456 
2457 	/* For direct write, we need to keep the invariant that the skbs
2458 	 * we're dealing with need to be uncloned. Should uncloning fail
2459 	 * here, we need to free the just generated clone to unclone once
2460 	 * again.
2461 	 */
2462 	ret = bpf_try_make_head_writable(skb);
2463 	if (unlikely(ret)) {
2464 		kfree_skb(clone);
2465 		return -ENOMEM;
2466 	}
2467 
2468 	return __bpf_redirect(clone, dev, flags);
2469 }
2470 
2471 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2472 	.func           = bpf_clone_redirect,
2473 	.gpl_only       = false,
2474 	.ret_type       = RET_INTEGER,
2475 	.arg1_type      = ARG_PTR_TO_CTX,
2476 	.arg2_type      = ARG_ANYTHING,
2477 	.arg3_type      = ARG_ANYTHING,
2478 };
2479 
skb_get_peer_dev(struct net_device * dev)2480 static struct net_device *skb_get_peer_dev(struct net_device *dev)
2481 {
2482 	const struct net_device_ops *ops = dev->netdev_ops;
2483 
2484 	if (likely(ops->ndo_get_peer_dev))
2485 		return INDIRECT_CALL_1(ops->ndo_get_peer_dev,
2486 				       netkit_peer_dev, dev);
2487 	return NULL;
2488 }
2489 
skb_do_redirect(struct sk_buff * skb)2490 int skb_do_redirect(struct sk_buff *skb)
2491 {
2492 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
2493 	struct net *net = dev_net(skb->dev);
2494 	struct net_device *dev;
2495 	u32 flags = ri->flags;
2496 
2497 	dev = dev_get_by_index_rcu(net, ri->tgt_index);
2498 	ri->tgt_index = 0;
2499 	ri->flags = 0;
2500 	if (unlikely(!dev))
2501 		goto out_drop;
2502 	if (flags & BPF_F_PEER) {
2503 		if (unlikely(!skb_at_tc_ingress(skb)))
2504 			goto out_drop;
2505 		dev = skb_get_peer_dev(dev);
2506 		if (unlikely(!dev ||
2507 			     !(dev->flags & IFF_UP) ||
2508 			     net_eq(net, dev_net(dev))))
2509 			goto out_drop;
2510 		skb->dev = dev;
2511 		dev_sw_netstats_rx_add(dev, skb->len);
2512 		return -EAGAIN;
2513 	}
2514 	return flags & BPF_F_NEIGH ?
2515 	       __bpf_redirect_neigh(skb, dev, flags & BPF_F_NEXTHOP ?
2516 				    &ri->nh : NULL) :
2517 	       __bpf_redirect(skb, dev, flags);
2518 out_drop:
2519 	kfree_skb(skb);
2520 	return -EINVAL;
2521 }
2522 
BPF_CALL_2(bpf_redirect,u32,ifindex,u64,flags)2523 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2524 {
2525 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
2526 
2527 	if (unlikely(flags & (~(BPF_F_INGRESS) | BPF_F_REDIRECT_INTERNAL)))
2528 		return TC_ACT_SHOT;
2529 
2530 	ri->flags = flags;
2531 	ri->tgt_index = ifindex;
2532 
2533 	return TC_ACT_REDIRECT;
2534 }
2535 
2536 static const struct bpf_func_proto bpf_redirect_proto = {
2537 	.func           = bpf_redirect,
2538 	.gpl_only       = false,
2539 	.ret_type       = RET_INTEGER,
2540 	.arg1_type      = ARG_ANYTHING,
2541 	.arg2_type      = ARG_ANYTHING,
2542 };
2543 
BPF_CALL_2(bpf_redirect_peer,u32,ifindex,u64,flags)2544 BPF_CALL_2(bpf_redirect_peer, u32, ifindex, u64, flags)
2545 {
2546 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
2547 
2548 	if (unlikely(flags))
2549 		return TC_ACT_SHOT;
2550 
2551 	ri->flags = BPF_F_PEER;
2552 	ri->tgt_index = ifindex;
2553 
2554 	return TC_ACT_REDIRECT;
2555 }
2556 
2557 static const struct bpf_func_proto bpf_redirect_peer_proto = {
2558 	.func           = bpf_redirect_peer,
2559 	.gpl_only       = false,
2560 	.ret_type       = RET_INTEGER,
2561 	.arg1_type      = ARG_ANYTHING,
2562 	.arg2_type      = ARG_ANYTHING,
2563 };
2564 
BPF_CALL_4(bpf_redirect_neigh,u32,ifindex,struct bpf_redir_neigh *,params,int,plen,u64,flags)2565 BPF_CALL_4(bpf_redirect_neigh, u32, ifindex, struct bpf_redir_neigh *, params,
2566 	   int, plen, u64, flags)
2567 {
2568 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
2569 
2570 	if (unlikely((plen && plen < sizeof(*params)) || flags))
2571 		return TC_ACT_SHOT;
2572 
2573 	ri->flags = BPF_F_NEIGH | (plen ? BPF_F_NEXTHOP : 0);
2574 	ri->tgt_index = ifindex;
2575 
2576 	BUILD_BUG_ON(sizeof(struct bpf_redir_neigh) != sizeof(struct bpf_nh_params));
2577 	if (plen)
2578 		memcpy(&ri->nh, params, sizeof(ri->nh));
2579 
2580 	return TC_ACT_REDIRECT;
2581 }
2582 
2583 static const struct bpf_func_proto bpf_redirect_neigh_proto = {
2584 	.func		= bpf_redirect_neigh,
2585 	.gpl_only	= false,
2586 	.ret_type	= RET_INTEGER,
2587 	.arg1_type	= ARG_ANYTHING,
2588 	.arg2_type      = ARG_PTR_TO_MEM | PTR_MAYBE_NULL | MEM_RDONLY,
2589 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
2590 	.arg4_type	= ARG_ANYTHING,
2591 };
2592 
BPF_CALL_2(bpf_msg_apply_bytes,struct sk_msg *,msg,u32,bytes)2593 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2594 {
2595 	msg->apply_bytes = bytes;
2596 	return 0;
2597 }
2598 
2599 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2600 	.func           = bpf_msg_apply_bytes,
2601 	.gpl_only       = false,
2602 	.ret_type       = RET_INTEGER,
2603 	.arg1_type	= ARG_PTR_TO_CTX,
2604 	.arg2_type      = ARG_ANYTHING,
2605 };
2606 
BPF_CALL_2(bpf_msg_cork_bytes,struct sk_msg *,msg,u32,bytes)2607 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2608 {
2609 	msg->cork_bytes = bytes;
2610 	return 0;
2611 }
2612 
sk_msg_reset_curr(struct sk_msg * msg)2613 static void sk_msg_reset_curr(struct sk_msg *msg)
2614 {
2615 	if (!msg->sg.size) {
2616 		msg->sg.curr = msg->sg.start;
2617 		msg->sg.copybreak = 0;
2618 	} else {
2619 		u32 i = msg->sg.end;
2620 
2621 		sk_msg_iter_var_prev(i);
2622 		msg->sg.curr = i;
2623 		msg->sg.copybreak = msg->sg.data[i].length;
2624 	}
2625 }
2626 
2627 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2628 	.func           = bpf_msg_cork_bytes,
2629 	.gpl_only       = false,
2630 	.ret_type       = RET_INTEGER,
2631 	.arg1_type	= ARG_PTR_TO_CTX,
2632 	.arg2_type      = ARG_ANYTHING,
2633 };
2634 
BPF_CALL_4(bpf_msg_pull_data,struct sk_msg *,msg,u32,start,u32,end,u64,flags)2635 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2636 	   u32, end, u64, flags)
2637 {
2638 	u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2639 	u32 first_sge, last_sge, i, shift, bytes_sg_total;
2640 	struct scatterlist *sge;
2641 	u8 *raw, *to, *from;
2642 	struct page *page;
2643 
2644 	if (unlikely(flags || end <= start))
2645 		return -EINVAL;
2646 
2647 	/* First find the starting scatterlist element */
2648 	i = msg->sg.start;
2649 	do {
2650 		offset += len;
2651 		len = sk_msg_elem(msg, i)->length;
2652 		if (start < offset + len)
2653 			break;
2654 		sk_msg_iter_var_next(i);
2655 	} while (i != msg->sg.end);
2656 
2657 	if (unlikely(start >= offset + len))
2658 		return -EINVAL;
2659 
2660 	first_sge = i;
2661 	/* The start may point into the sg element so we need to also
2662 	 * account for the headroom.
2663 	 */
2664 	bytes_sg_total = start - offset + bytes;
2665 	if (!test_bit(i, msg->sg.copy) && bytes_sg_total <= len)
2666 		goto out;
2667 
2668 	/* At this point we need to linearize multiple scatterlist
2669 	 * elements or a single shared page. Either way we need to
2670 	 * copy into a linear buffer exclusively owned by BPF. Then
2671 	 * place the buffer in the scatterlist and fixup the original
2672 	 * entries by removing the entries now in the linear buffer
2673 	 * and shifting the remaining entries. For now we do not try
2674 	 * to copy partial entries to avoid complexity of running out
2675 	 * of sg_entry slots. The downside is reading a single byte
2676 	 * will copy the entire sg entry.
2677 	 */
2678 	do {
2679 		copy += sk_msg_elem(msg, i)->length;
2680 		sk_msg_iter_var_next(i);
2681 		if (bytes_sg_total <= copy)
2682 			break;
2683 	} while (i != msg->sg.end);
2684 	last_sge = i;
2685 
2686 	if (unlikely(bytes_sg_total > copy))
2687 		return -EINVAL;
2688 
2689 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2690 			   get_order(copy));
2691 	if (unlikely(!page))
2692 		return -ENOMEM;
2693 
2694 	raw = page_address(page);
2695 	i = first_sge;
2696 	do {
2697 		sge = sk_msg_elem(msg, i);
2698 		from = sg_virt(sge);
2699 		len = sge->length;
2700 		to = raw + poffset;
2701 
2702 		memcpy(to, from, len);
2703 		poffset += len;
2704 		sge->length = 0;
2705 		put_page(sg_page(sge));
2706 
2707 		sk_msg_iter_var_next(i);
2708 	} while (i != last_sge);
2709 
2710 	sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2711 
2712 	/* To repair sg ring we need to shift entries. If we only
2713 	 * had a single entry though we can just replace it and
2714 	 * be done. Otherwise walk the ring and shift the entries.
2715 	 */
2716 	WARN_ON_ONCE(last_sge == first_sge);
2717 	shift = last_sge > first_sge ?
2718 		last_sge - first_sge - 1 :
2719 		NR_MSG_FRAG_IDS - first_sge + last_sge - 1;
2720 	if (!shift)
2721 		goto out;
2722 
2723 	i = first_sge;
2724 	sk_msg_iter_var_next(i);
2725 	do {
2726 		u32 move_from;
2727 
2728 		if (i + shift >= NR_MSG_FRAG_IDS)
2729 			move_from = i + shift - NR_MSG_FRAG_IDS;
2730 		else
2731 			move_from = i + shift;
2732 		if (move_from == msg->sg.end)
2733 			break;
2734 
2735 		msg->sg.data[i] = msg->sg.data[move_from];
2736 		msg->sg.data[move_from].length = 0;
2737 		msg->sg.data[move_from].page_link = 0;
2738 		msg->sg.data[move_from].offset = 0;
2739 		sk_msg_iter_var_next(i);
2740 	} while (1);
2741 
2742 	msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2743 		      msg->sg.end - shift + NR_MSG_FRAG_IDS :
2744 		      msg->sg.end - shift;
2745 out:
2746 	sk_msg_reset_curr(msg);
2747 	msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2748 	msg->data_end = msg->data + bytes;
2749 	return 0;
2750 }
2751 
2752 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2753 	.func		= bpf_msg_pull_data,
2754 	.gpl_only	= false,
2755 	.ret_type	= RET_INTEGER,
2756 	.arg1_type	= ARG_PTR_TO_CTX,
2757 	.arg2_type	= ARG_ANYTHING,
2758 	.arg3_type	= ARG_ANYTHING,
2759 	.arg4_type	= ARG_ANYTHING,
2760 };
2761 
BPF_CALL_4(bpf_msg_push_data,struct sk_msg *,msg,u32,start,u32,len,u64,flags)2762 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2763 	   u32, len, u64, flags)
2764 {
2765 	struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2766 	u32 new, i = 0, l = 0, space, copy = 0, offset = 0;
2767 	u8 *raw, *to, *from;
2768 	struct page *page;
2769 
2770 	if (unlikely(flags))
2771 		return -EINVAL;
2772 
2773 	if (unlikely(len == 0))
2774 		return 0;
2775 
2776 	/* First find the starting scatterlist element */
2777 	i = msg->sg.start;
2778 	do {
2779 		offset += l;
2780 		l = sk_msg_elem(msg, i)->length;
2781 
2782 		if (start < offset + l)
2783 			break;
2784 		sk_msg_iter_var_next(i);
2785 	} while (i != msg->sg.end);
2786 
2787 	if (start > offset + l)
2788 		return -EINVAL;
2789 
2790 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2791 
2792 	/* If no space available will fallback to copy, we need at
2793 	 * least one scatterlist elem available to push data into
2794 	 * when start aligns to the beginning of an element or two
2795 	 * when it falls inside an element. We handle the start equals
2796 	 * offset case because its the common case for inserting a
2797 	 * header.
2798 	 */
2799 	if (!space || (space == 1 && start != offset))
2800 		copy = msg->sg.data[i].length;
2801 
2802 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2803 			   get_order(copy + len));
2804 	if (unlikely(!page))
2805 		return -ENOMEM;
2806 
2807 	if (copy) {
2808 		int front, back;
2809 
2810 		raw = page_address(page);
2811 
2812 		if (i == msg->sg.end)
2813 			sk_msg_iter_var_prev(i);
2814 		psge = sk_msg_elem(msg, i);
2815 		front = start - offset;
2816 		back = psge->length - front;
2817 		from = sg_virt(psge);
2818 
2819 		if (front)
2820 			memcpy(raw, from, front);
2821 
2822 		if (back) {
2823 			from += front;
2824 			to = raw + front + len;
2825 
2826 			memcpy(to, from, back);
2827 		}
2828 
2829 		put_page(sg_page(psge));
2830 		new = i;
2831 		goto place_new;
2832 	}
2833 
2834 	if (start - offset) {
2835 		if (i == msg->sg.end)
2836 			sk_msg_iter_var_prev(i);
2837 		psge = sk_msg_elem(msg, i);
2838 		rsge = sk_msg_elem_cpy(msg, i);
2839 
2840 		psge->length = start - offset;
2841 		rsge.length -= psge->length;
2842 		rsge.offset += start;
2843 
2844 		sk_msg_iter_var_next(i);
2845 		sg_unmark_end(psge);
2846 		sg_unmark_end(&rsge);
2847 	}
2848 
2849 	/* Slot(s) to place newly allocated data */
2850 	sk_msg_iter_next(msg, end);
2851 	new = i;
2852 	sk_msg_iter_var_next(i);
2853 
2854 	if (i == msg->sg.end) {
2855 		if (!rsge.length)
2856 			goto place_new;
2857 		sk_msg_iter_next(msg, end);
2858 		goto place_new;
2859 	}
2860 
2861 	/* Shift one or two slots as needed */
2862 	sge = sk_msg_elem_cpy(msg, new);
2863 	sg_unmark_end(&sge);
2864 
2865 	nsge = sk_msg_elem_cpy(msg, i);
2866 	if (rsge.length) {
2867 		sk_msg_iter_var_next(i);
2868 		nnsge = sk_msg_elem_cpy(msg, i);
2869 		sk_msg_iter_next(msg, end);
2870 	}
2871 
2872 	while (i != msg->sg.end) {
2873 		msg->sg.data[i] = sge;
2874 		sge = nsge;
2875 		sk_msg_iter_var_next(i);
2876 		if (rsge.length) {
2877 			nsge = nnsge;
2878 			nnsge = sk_msg_elem_cpy(msg, i);
2879 		} else {
2880 			nsge = sk_msg_elem_cpy(msg, i);
2881 		}
2882 	}
2883 
2884 place_new:
2885 	/* Place newly allocated data buffer */
2886 	sk_mem_charge(msg->sk, len);
2887 	msg->sg.size += len;
2888 	__clear_bit(new, msg->sg.copy);
2889 	sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2890 	if (rsge.length) {
2891 		get_page(sg_page(&rsge));
2892 		sk_msg_iter_var_next(new);
2893 		msg->sg.data[new] = rsge;
2894 	}
2895 
2896 	sk_msg_reset_curr(msg);
2897 	sk_msg_compute_data_pointers(msg);
2898 	return 0;
2899 }
2900 
2901 static const struct bpf_func_proto bpf_msg_push_data_proto = {
2902 	.func		= bpf_msg_push_data,
2903 	.gpl_only	= false,
2904 	.ret_type	= RET_INTEGER,
2905 	.arg1_type	= ARG_PTR_TO_CTX,
2906 	.arg2_type	= ARG_ANYTHING,
2907 	.arg3_type	= ARG_ANYTHING,
2908 	.arg4_type	= ARG_ANYTHING,
2909 };
2910 
sk_msg_shift_left(struct sk_msg * msg,int i)2911 static void sk_msg_shift_left(struct sk_msg *msg, int i)
2912 {
2913 	struct scatterlist *sge = sk_msg_elem(msg, i);
2914 	int prev;
2915 
2916 	put_page(sg_page(sge));
2917 	do {
2918 		prev = i;
2919 		sk_msg_iter_var_next(i);
2920 		msg->sg.data[prev] = msg->sg.data[i];
2921 	} while (i != msg->sg.end);
2922 
2923 	sk_msg_iter_prev(msg, end);
2924 }
2925 
sk_msg_shift_right(struct sk_msg * msg,int i)2926 static void sk_msg_shift_right(struct sk_msg *msg, int i)
2927 {
2928 	struct scatterlist tmp, sge;
2929 
2930 	sk_msg_iter_next(msg, end);
2931 	sge = sk_msg_elem_cpy(msg, i);
2932 	sk_msg_iter_var_next(i);
2933 	tmp = sk_msg_elem_cpy(msg, i);
2934 
2935 	while (i != msg->sg.end) {
2936 		msg->sg.data[i] = sge;
2937 		sk_msg_iter_var_next(i);
2938 		sge = tmp;
2939 		tmp = sk_msg_elem_cpy(msg, i);
2940 	}
2941 }
2942 
BPF_CALL_4(bpf_msg_pop_data,struct sk_msg *,msg,u32,start,u32,len,u64,flags)2943 BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
2944 	   u32, len, u64, flags)
2945 {
2946 	u32 i = 0, l = 0, space, offset = 0;
2947 	u64 last = start + len;
2948 	int pop;
2949 
2950 	if (unlikely(flags))
2951 		return -EINVAL;
2952 
2953 	if (unlikely(len == 0))
2954 		return 0;
2955 
2956 	/* First find the starting scatterlist element */
2957 	i = msg->sg.start;
2958 	do {
2959 		offset += l;
2960 		l = sk_msg_elem(msg, i)->length;
2961 
2962 		if (start < offset + l)
2963 			break;
2964 		sk_msg_iter_var_next(i);
2965 	} while (i != msg->sg.end);
2966 
2967 	/* Bounds checks: start and pop must be inside message */
2968 	if (start >= offset + l || last > msg->sg.size)
2969 		return -EINVAL;
2970 
2971 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2972 
2973 	pop = len;
2974 	/* --------------| offset
2975 	 * -| start      |-------- len -------|
2976 	 *
2977 	 *  |----- a ----|-------- pop -------|----- b ----|
2978 	 *  |______________________________________________| length
2979 	 *
2980 	 *
2981 	 * a:   region at front of scatter element to save
2982 	 * b:   region at back of scatter element to save when length > A + pop
2983 	 * pop: region to pop from element, same as input 'pop' here will be
2984 	 *      decremented below per iteration.
2985 	 *
2986 	 * Two top-level cases to handle when start != offset, first B is non
2987 	 * zero and second B is zero corresponding to when a pop includes more
2988 	 * than one element.
2989 	 *
2990 	 * Then if B is non-zero AND there is no space allocate space and
2991 	 * compact A, B regions into page. If there is space shift ring to
2992 	 * the right free'ing the next element in ring to place B, leaving
2993 	 * A untouched except to reduce length.
2994 	 */
2995 	if (start != offset) {
2996 		struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
2997 		int a = start - offset;
2998 		int b = sge->length - pop - a;
2999 
3000 		sk_msg_iter_var_next(i);
3001 
3002 		if (b > 0) {
3003 			if (space) {
3004 				sge->length = a;
3005 				sk_msg_shift_right(msg, i);
3006 				nsge = sk_msg_elem(msg, i);
3007 				get_page(sg_page(sge));
3008 				sg_set_page(nsge,
3009 					    sg_page(sge),
3010 					    b, sge->offset + pop + a);
3011 			} else {
3012 				struct page *page, *orig;
3013 				u8 *to, *from;
3014 
3015 				page = alloc_pages(__GFP_NOWARN |
3016 						   __GFP_COMP   | GFP_ATOMIC,
3017 						   get_order(a + b));
3018 				if (unlikely(!page))
3019 					return -ENOMEM;
3020 
3021 				orig = sg_page(sge);
3022 				from = sg_virt(sge);
3023 				to = page_address(page);
3024 				memcpy(to, from, a);
3025 				memcpy(to + a, from + a + pop, b);
3026 				sg_set_page(sge, page, a + b, 0);
3027 				put_page(orig);
3028 			}
3029 			pop = 0;
3030 		} else {
3031 			pop -= (sge->length - a);
3032 			sge->length = a;
3033 		}
3034 	}
3035 
3036 	/* From above the current layout _must_ be as follows,
3037 	 *
3038 	 * -| offset
3039 	 * -| start
3040 	 *
3041 	 *  |---- pop ---|---------------- b ------------|
3042 	 *  |____________________________________________| length
3043 	 *
3044 	 * Offset and start of the current msg elem are equal because in the
3045 	 * previous case we handled offset != start and either consumed the
3046 	 * entire element and advanced to the next element OR pop == 0.
3047 	 *
3048 	 * Two cases to handle here are first pop is less than the length
3049 	 * leaving some remainder b above. Simply adjust the element's layout
3050 	 * in this case. Or pop >= length of the element so that b = 0. In this
3051 	 * case advance to next element decrementing pop.
3052 	 */
3053 	while (pop) {
3054 		struct scatterlist *sge = sk_msg_elem(msg, i);
3055 
3056 		if (pop < sge->length) {
3057 			sge->length -= pop;
3058 			sge->offset += pop;
3059 			pop = 0;
3060 		} else {
3061 			pop -= sge->length;
3062 			sk_msg_shift_left(msg, i);
3063 		}
3064 	}
3065 
3066 	sk_mem_uncharge(msg->sk, len - pop);
3067 	msg->sg.size -= (len - pop);
3068 	sk_msg_reset_curr(msg);
3069 	sk_msg_compute_data_pointers(msg);
3070 	return 0;
3071 }
3072 
3073 static const struct bpf_func_proto bpf_msg_pop_data_proto = {
3074 	.func		= bpf_msg_pop_data,
3075 	.gpl_only	= false,
3076 	.ret_type	= RET_INTEGER,
3077 	.arg1_type	= ARG_PTR_TO_CTX,
3078 	.arg2_type	= ARG_ANYTHING,
3079 	.arg3_type	= ARG_ANYTHING,
3080 	.arg4_type	= ARG_ANYTHING,
3081 };
3082 
3083 #ifdef CONFIG_CGROUP_NET_CLASSID
BPF_CALL_0(bpf_get_cgroup_classid_curr)3084 BPF_CALL_0(bpf_get_cgroup_classid_curr)
3085 {
3086 	return __task_get_classid(current);
3087 }
3088 
3089 const struct bpf_func_proto bpf_get_cgroup_classid_curr_proto = {
3090 	.func		= bpf_get_cgroup_classid_curr,
3091 	.gpl_only	= false,
3092 	.ret_type	= RET_INTEGER,
3093 };
3094 
BPF_CALL_1(bpf_skb_cgroup_classid,const struct sk_buff *,skb)3095 BPF_CALL_1(bpf_skb_cgroup_classid, const struct sk_buff *, skb)
3096 {
3097 	struct sock *sk = skb_to_full_sk(skb);
3098 
3099 	if (!sk || !sk_fullsock(sk))
3100 		return 0;
3101 
3102 	return sock_cgroup_classid(&sk->sk_cgrp_data);
3103 }
3104 
3105 static const struct bpf_func_proto bpf_skb_cgroup_classid_proto = {
3106 	.func		= bpf_skb_cgroup_classid,
3107 	.gpl_only	= false,
3108 	.ret_type	= RET_INTEGER,
3109 	.arg1_type	= ARG_PTR_TO_CTX,
3110 };
3111 #endif
3112 
BPF_CALL_1(bpf_get_cgroup_classid,const struct sk_buff *,skb)3113 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
3114 {
3115 	return task_get_classid(skb);
3116 }
3117 
3118 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
3119 	.func           = bpf_get_cgroup_classid,
3120 	.gpl_only       = false,
3121 	.ret_type       = RET_INTEGER,
3122 	.arg1_type      = ARG_PTR_TO_CTX,
3123 };
3124 
BPF_CALL_1(bpf_get_route_realm,const struct sk_buff *,skb)3125 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
3126 {
3127 	return dst_tclassid(skb);
3128 }
3129 
3130 static const struct bpf_func_proto bpf_get_route_realm_proto = {
3131 	.func           = bpf_get_route_realm,
3132 	.gpl_only       = false,
3133 	.ret_type       = RET_INTEGER,
3134 	.arg1_type      = ARG_PTR_TO_CTX,
3135 };
3136 
BPF_CALL_1(bpf_get_hash_recalc,struct sk_buff *,skb)3137 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
3138 {
3139 	/* If skb_clear_hash() was called due to mangling, we can
3140 	 * trigger SW recalculation here. Later access to hash
3141 	 * can then use the inline skb->hash via context directly
3142 	 * instead of calling this helper again.
3143 	 */
3144 	return skb_get_hash(skb);
3145 }
3146 
3147 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
3148 	.func		= bpf_get_hash_recalc,
3149 	.gpl_only	= false,
3150 	.ret_type	= RET_INTEGER,
3151 	.arg1_type	= ARG_PTR_TO_CTX,
3152 };
3153 
BPF_CALL_1(bpf_set_hash_invalid,struct sk_buff *,skb)3154 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
3155 {
3156 	/* After all direct packet write, this can be used once for
3157 	 * triggering a lazy recalc on next skb_get_hash() invocation.
3158 	 */
3159 	skb_clear_hash(skb);
3160 	return 0;
3161 }
3162 
3163 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
3164 	.func		= bpf_set_hash_invalid,
3165 	.gpl_only	= false,
3166 	.ret_type	= RET_INTEGER,
3167 	.arg1_type	= ARG_PTR_TO_CTX,
3168 };
3169 
BPF_CALL_2(bpf_set_hash,struct sk_buff *,skb,u32,hash)3170 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
3171 {
3172 	/* Set user specified hash as L4(+), so that it gets returned
3173 	 * on skb_get_hash() call unless BPF prog later on triggers a
3174 	 * skb_clear_hash().
3175 	 */
3176 	__skb_set_sw_hash(skb, hash, true);
3177 	return 0;
3178 }
3179 
3180 static const struct bpf_func_proto bpf_set_hash_proto = {
3181 	.func		= bpf_set_hash,
3182 	.gpl_only	= false,
3183 	.ret_type	= RET_INTEGER,
3184 	.arg1_type	= ARG_PTR_TO_CTX,
3185 	.arg2_type	= ARG_ANYTHING,
3186 };
3187 
BPF_CALL_3(bpf_skb_vlan_push,struct sk_buff *,skb,__be16,vlan_proto,u16,vlan_tci)3188 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
3189 	   u16, vlan_tci)
3190 {
3191 	int ret;
3192 
3193 	if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
3194 		     vlan_proto != htons(ETH_P_8021AD)))
3195 		vlan_proto = htons(ETH_P_8021Q);
3196 
3197 	bpf_push_mac_rcsum(skb);
3198 	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
3199 	bpf_pull_mac_rcsum(skb);
3200 	skb_reset_mac_len(skb);
3201 
3202 	bpf_compute_data_pointers(skb);
3203 	return ret;
3204 }
3205 
3206 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
3207 	.func           = bpf_skb_vlan_push,
3208 	.gpl_only       = false,
3209 	.ret_type       = RET_INTEGER,
3210 	.arg1_type      = ARG_PTR_TO_CTX,
3211 	.arg2_type      = ARG_ANYTHING,
3212 	.arg3_type      = ARG_ANYTHING,
3213 };
3214 
BPF_CALL_1(bpf_skb_vlan_pop,struct sk_buff *,skb)3215 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
3216 {
3217 	int ret;
3218 
3219 	bpf_push_mac_rcsum(skb);
3220 	ret = skb_vlan_pop(skb);
3221 	bpf_pull_mac_rcsum(skb);
3222 
3223 	bpf_compute_data_pointers(skb);
3224 	return ret;
3225 }
3226 
3227 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
3228 	.func           = bpf_skb_vlan_pop,
3229 	.gpl_only       = false,
3230 	.ret_type       = RET_INTEGER,
3231 	.arg1_type      = ARG_PTR_TO_CTX,
3232 };
3233 
bpf_skb_generic_push(struct sk_buff * skb,u32 off,u32 len)3234 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
3235 {
3236 	/* Caller already did skb_cow() with len as headroom,
3237 	 * so no need to do it here.
3238 	 */
3239 	skb_push(skb, len);
3240 	memmove(skb->data, skb->data + len, off);
3241 	memset(skb->data + off, 0, len);
3242 
3243 	/* No skb_postpush_rcsum(skb, skb->data + off, len)
3244 	 * needed here as it does not change the skb->csum
3245 	 * result for checksum complete when summing over
3246 	 * zeroed blocks.
3247 	 */
3248 	return 0;
3249 }
3250 
bpf_skb_generic_pop(struct sk_buff * skb,u32 off,u32 len)3251 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
3252 {
3253 	void *old_data;
3254 
3255 	/* skb_ensure_writable() is not needed here, as we're
3256 	 * already working on an uncloned skb.
3257 	 */
3258 	if (unlikely(!pskb_may_pull(skb, off + len)))
3259 		return -ENOMEM;
3260 
3261 	old_data = skb->data;
3262 	__skb_pull(skb, len);
3263 	skb_postpull_rcsum(skb, old_data + off, len);
3264 	memmove(skb->data, old_data, off);
3265 
3266 	return 0;
3267 }
3268 
bpf_skb_net_hdr_push(struct sk_buff * skb,u32 off,u32 len)3269 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
3270 {
3271 	bool trans_same = skb->transport_header == skb->network_header;
3272 	int ret;
3273 
3274 	/* There's no need for __skb_push()/__skb_pull() pair to
3275 	 * get to the start of the mac header as we're guaranteed
3276 	 * to always start from here under eBPF.
3277 	 */
3278 	ret = bpf_skb_generic_push(skb, off, len);
3279 	if (likely(!ret)) {
3280 		skb->mac_header -= len;
3281 		skb->network_header -= len;
3282 		if (trans_same)
3283 			skb->transport_header = skb->network_header;
3284 	}
3285 
3286 	return ret;
3287 }
3288 
bpf_skb_net_hdr_pop(struct sk_buff * skb,u32 off,u32 len)3289 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
3290 {
3291 	bool trans_same = skb->transport_header == skb->network_header;
3292 	int ret;
3293 
3294 	/* Same here, __skb_push()/__skb_pull() pair not needed. */
3295 	ret = bpf_skb_generic_pop(skb, off, len);
3296 	if (likely(!ret)) {
3297 		skb->mac_header += len;
3298 		skb->network_header += len;
3299 		if (trans_same)
3300 			skb->transport_header = skb->network_header;
3301 	}
3302 
3303 	return ret;
3304 }
3305 
bpf_skb_proto_4_to_6(struct sk_buff * skb)3306 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
3307 {
3308 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
3309 	u32 off = skb_mac_header_len(skb);
3310 	int ret;
3311 
3312 	ret = skb_cow(skb, len_diff);
3313 	if (unlikely(ret < 0))
3314 		return ret;
3315 
3316 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3317 	if (unlikely(ret < 0))
3318 		return ret;
3319 
3320 	if (skb_is_gso(skb)) {
3321 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3322 
3323 		/* SKB_GSO_TCPV4 needs to be changed into SKB_GSO_TCPV6. */
3324 		if (shinfo->gso_type & SKB_GSO_TCPV4) {
3325 			shinfo->gso_type &= ~SKB_GSO_TCPV4;
3326 			shinfo->gso_type |=  SKB_GSO_TCPV6;
3327 		}
3328 	}
3329 
3330 	skb->protocol = htons(ETH_P_IPV6);
3331 	skb_clear_hash(skb);
3332 
3333 	return 0;
3334 }
3335 
bpf_skb_proto_6_to_4(struct sk_buff * skb)3336 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
3337 {
3338 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
3339 	u32 off = skb_mac_header_len(skb);
3340 	int ret;
3341 
3342 	ret = skb_unclone(skb, GFP_ATOMIC);
3343 	if (unlikely(ret < 0))
3344 		return ret;
3345 
3346 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3347 	if (unlikely(ret < 0))
3348 		return ret;
3349 
3350 	if (skb_is_gso(skb)) {
3351 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3352 
3353 		/* SKB_GSO_TCPV6 needs to be changed into SKB_GSO_TCPV4. */
3354 		if (shinfo->gso_type & SKB_GSO_TCPV6) {
3355 			shinfo->gso_type &= ~SKB_GSO_TCPV6;
3356 			shinfo->gso_type |=  SKB_GSO_TCPV4;
3357 		}
3358 	}
3359 
3360 	skb->protocol = htons(ETH_P_IP);
3361 	skb_clear_hash(skb);
3362 
3363 	return 0;
3364 }
3365 
bpf_skb_proto_xlat(struct sk_buff * skb,__be16 to_proto)3366 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
3367 {
3368 	__be16 from_proto = skb->protocol;
3369 
3370 	if (from_proto == htons(ETH_P_IP) &&
3371 	      to_proto == htons(ETH_P_IPV6))
3372 		return bpf_skb_proto_4_to_6(skb);
3373 
3374 	if (from_proto == htons(ETH_P_IPV6) &&
3375 	      to_proto == htons(ETH_P_IP))
3376 		return bpf_skb_proto_6_to_4(skb);
3377 
3378 	return -ENOTSUPP;
3379 }
3380 
BPF_CALL_3(bpf_skb_change_proto,struct sk_buff *,skb,__be16,proto,u64,flags)3381 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
3382 	   u64, flags)
3383 {
3384 	int ret;
3385 
3386 	if (unlikely(flags))
3387 		return -EINVAL;
3388 
3389 	/* General idea is that this helper does the basic groundwork
3390 	 * needed for changing the protocol, and eBPF program fills the
3391 	 * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
3392 	 * and other helpers, rather than passing a raw buffer here.
3393 	 *
3394 	 * The rationale is to keep this minimal and without a need to
3395 	 * deal with raw packet data. F.e. even if we would pass buffers
3396 	 * here, the program still needs to call the bpf_lX_csum_replace()
3397 	 * helpers anyway. Plus, this way we keep also separation of
3398 	 * concerns, since f.e. bpf_skb_store_bytes() should only take
3399 	 * care of stores.
3400 	 *
3401 	 * Currently, additional options and extension header space are
3402 	 * not supported, but flags register is reserved so we can adapt
3403 	 * that. For offloads, we mark packet as dodgy, so that headers
3404 	 * need to be verified first.
3405 	 */
3406 	ret = bpf_skb_proto_xlat(skb, proto);
3407 	bpf_compute_data_pointers(skb);
3408 	return ret;
3409 }
3410 
3411 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
3412 	.func		= bpf_skb_change_proto,
3413 	.gpl_only	= false,
3414 	.ret_type	= RET_INTEGER,
3415 	.arg1_type	= ARG_PTR_TO_CTX,
3416 	.arg2_type	= ARG_ANYTHING,
3417 	.arg3_type	= ARG_ANYTHING,
3418 };
3419 
BPF_CALL_2(bpf_skb_change_type,struct sk_buff *,skb,u32,pkt_type)3420 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
3421 {
3422 	/* We only allow a restricted subset to be changed for now. */
3423 	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
3424 		     !skb_pkt_type_ok(pkt_type)))
3425 		return -EINVAL;
3426 
3427 	skb->pkt_type = pkt_type;
3428 	return 0;
3429 }
3430 
3431 static const struct bpf_func_proto bpf_skb_change_type_proto = {
3432 	.func		= bpf_skb_change_type,
3433 	.gpl_only	= false,
3434 	.ret_type	= RET_INTEGER,
3435 	.arg1_type	= ARG_PTR_TO_CTX,
3436 	.arg2_type	= ARG_ANYTHING,
3437 };
3438 
bpf_skb_net_base_len(const struct sk_buff * skb)3439 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
3440 {
3441 	switch (skb->protocol) {
3442 	case htons(ETH_P_IP):
3443 		return sizeof(struct iphdr);
3444 	case htons(ETH_P_IPV6):
3445 		return sizeof(struct ipv6hdr);
3446 	default:
3447 		return ~0U;
3448 	}
3449 }
3450 
3451 #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK	(BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3452 					 BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3453 
3454 #define BPF_F_ADJ_ROOM_DECAP_L3_MASK	(BPF_F_ADJ_ROOM_DECAP_L3_IPV4 | \
3455 					 BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3456 
3457 #define BPF_F_ADJ_ROOM_MASK		(BPF_F_ADJ_ROOM_FIXED_GSO | \
3458 					 BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3459 					 BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3460 					 BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3461 					 BPF_F_ADJ_ROOM_ENCAP_L2_ETH | \
3462 					 BPF_F_ADJ_ROOM_ENCAP_L2( \
3463 					  BPF_ADJ_ROOM_ENCAP_L2_MASK) | \
3464 					 BPF_F_ADJ_ROOM_DECAP_L3_MASK)
3465 
bpf_skb_net_grow(struct sk_buff * skb,u32 off,u32 len_diff,u64 flags)3466 static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3467 			    u64 flags)
3468 {
3469 	u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3470 	bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3471 	u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3472 	unsigned int gso_type = SKB_GSO_DODGY;
3473 	int ret;
3474 
3475 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3476 		/* udp gso_size delineates datagrams, only allow if fixed */
3477 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3478 		    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3479 			return -ENOTSUPP;
3480 	}
3481 
3482 	ret = skb_cow_head(skb, len_diff);
3483 	if (unlikely(ret < 0))
3484 		return ret;
3485 
3486 	if (encap) {
3487 		if (skb->protocol != htons(ETH_P_IP) &&
3488 		    skb->protocol != htons(ETH_P_IPV6))
3489 			return -ENOTSUPP;
3490 
3491 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3492 		    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3493 			return -EINVAL;
3494 
3495 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3496 		    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3497 			return -EINVAL;
3498 
3499 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L2_ETH &&
3500 		    inner_mac_len < ETH_HLEN)
3501 			return -EINVAL;
3502 
3503 		if (skb->encapsulation)
3504 			return -EALREADY;
3505 
3506 		mac_len = skb->network_header - skb->mac_header;
3507 		inner_net = skb->network_header;
3508 		if (inner_mac_len > len_diff)
3509 			return -EINVAL;
3510 		inner_trans = skb->transport_header;
3511 	}
3512 
3513 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3514 	if (unlikely(ret < 0))
3515 		return ret;
3516 
3517 	if (encap) {
3518 		skb->inner_mac_header = inner_net - inner_mac_len;
3519 		skb->inner_network_header = inner_net;
3520 		skb->inner_transport_header = inner_trans;
3521 
3522 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L2_ETH)
3523 			skb_set_inner_protocol(skb, htons(ETH_P_TEB));
3524 		else
3525 			skb_set_inner_protocol(skb, skb->protocol);
3526 
3527 		skb->encapsulation = 1;
3528 		skb_set_network_header(skb, mac_len);
3529 
3530 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3531 			gso_type |= SKB_GSO_UDP_TUNNEL;
3532 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3533 			gso_type |= SKB_GSO_GRE;
3534 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3535 			gso_type |= SKB_GSO_IPXIP6;
3536 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3537 			gso_type |= SKB_GSO_IPXIP4;
3538 
3539 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3540 		    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3541 			int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3542 					sizeof(struct ipv6hdr) :
3543 					sizeof(struct iphdr);
3544 
3545 			skb_set_transport_header(skb, mac_len + nh_len);
3546 		}
3547 
3548 		/* Match skb->protocol to new outer l3 protocol */
3549 		if (skb->protocol == htons(ETH_P_IP) &&
3550 		    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3551 			skb->protocol = htons(ETH_P_IPV6);
3552 		else if (skb->protocol == htons(ETH_P_IPV6) &&
3553 			 flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3554 			skb->protocol = htons(ETH_P_IP);
3555 	}
3556 
3557 	if (skb_is_gso(skb)) {
3558 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3559 
3560 		/* Header must be checked, and gso_segs recomputed. */
3561 		shinfo->gso_type |= gso_type;
3562 		shinfo->gso_segs = 0;
3563 
3564 		/* Due to header growth, MSS needs to be downgraded.
3565 		 * There is a BUG_ON() when segmenting the frag_list with
3566 		 * head_frag true, so linearize the skb after downgrading
3567 		 * the MSS.
3568 		 */
3569 		if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO)) {
3570 			skb_decrease_gso_size(shinfo, len_diff);
3571 			if (shinfo->frag_list)
3572 				return skb_linearize(skb);
3573 		}
3574 	}
3575 
3576 	return 0;
3577 }
3578 
bpf_skb_net_shrink(struct sk_buff * skb,u32 off,u32 len_diff,u64 flags)3579 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3580 			      u64 flags)
3581 {
3582 	int ret;
3583 
3584 	if (unlikely(flags & ~(BPF_F_ADJ_ROOM_FIXED_GSO |
3585 			       BPF_F_ADJ_ROOM_DECAP_L3_MASK |
3586 			       BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3587 		return -EINVAL;
3588 
3589 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3590 		/* udp gso_size delineates datagrams, only allow if fixed */
3591 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3592 		    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3593 			return -ENOTSUPP;
3594 	}
3595 
3596 	ret = skb_unclone(skb, GFP_ATOMIC);
3597 	if (unlikely(ret < 0))
3598 		return ret;
3599 
3600 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3601 	if (unlikely(ret < 0))
3602 		return ret;
3603 
3604 	/* Match skb->protocol to new outer l3 protocol */
3605 	if (skb->protocol == htons(ETH_P_IP) &&
3606 	    flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV6)
3607 		skb->protocol = htons(ETH_P_IPV6);
3608 	else if (skb->protocol == htons(ETH_P_IPV6) &&
3609 		 flags & BPF_F_ADJ_ROOM_DECAP_L3_IPV4)
3610 		skb->protocol = htons(ETH_P_IP);
3611 
3612 	if (skb_is_gso(skb)) {
3613 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3614 
3615 		/* Due to header shrink, MSS can be upgraded. */
3616 		if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3617 			skb_increase_gso_size(shinfo, len_diff);
3618 
3619 		/* Header must be checked, and gso_segs recomputed. */
3620 		shinfo->gso_type |= SKB_GSO_DODGY;
3621 		shinfo->gso_segs = 0;
3622 	}
3623 
3624 	return 0;
3625 }
3626 
3627 #define BPF_SKB_MAX_LEN SKB_MAX_ALLOC
3628 
BPF_CALL_4(sk_skb_adjust_room,struct sk_buff *,skb,s32,len_diff,u32,mode,u64,flags)3629 BPF_CALL_4(sk_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3630 	   u32, mode, u64, flags)
3631 {
3632 	u32 len_diff_abs = abs(len_diff);
3633 	bool shrink = len_diff < 0;
3634 	int ret = 0;
3635 
3636 	if (unlikely(flags || mode))
3637 		return -EINVAL;
3638 	if (unlikely(len_diff_abs > 0xfffU))
3639 		return -EFAULT;
3640 
3641 	if (!shrink) {
3642 		ret = skb_cow(skb, len_diff);
3643 		if (unlikely(ret < 0))
3644 			return ret;
3645 		__skb_push(skb, len_diff_abs);
3646 		memset(skb->data, 0, len_diff_abs);
3647 	} else {
3648 		if (unlikely(!pskb_may_pull(skb, len_diff_abs)))
3649 			return -ENOMEM;
3650 		__skb_pull(skb, len_diff_abs);
3651 	}
3652 	if (tls_sw_has_ctx_rx(skb->sk)) {
3653 		struct strp_msg *rxm = strp_msg(skb);
3654 
3655 		rxm->full_len += len_diff;
3656 	}
3657 	return ret;
3658 }
3659 
3660 static const struct bpf_func_proto sk_skb_adjust_room_proto = {
3661 	.func		= sk_skb_adjust_room,
3662 	.gpl_only	= false,
3663 	.ret_type	= RET_INTEGER,
3664 	.arg1_type	= ARG_PTR_TO_CTX,
3665 	.arg2_type	= ARG_ANYTHING,
3666 	.arg3_type	= ARG_ANYTHING,
3667 	.arg4_type	= ARG_ANYTHING,
3668 };
3669 
BPF_CALL_4(bpf_skb_adjust_room,struct sk_buff *,skb,s32,len_diff,u32,mode,u64,flags)3670 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3671 	   u32, mode, u64, flags)
3672 {
3673 	u32 len_cur, len_diff_abs = abs(len_diff);
3674 	u32 len_min = bpf_skb_net_base_len(skb);
3675 	u32 len_max = BPF_SKB_MAX_LEN;
3676 	__be16 proto = skb->protocol;
3677 	bool shrink = len_diff < 0;
3678 	u32 off;
3679 	int ret;
3680 
3681 	if (unlikely(flags & ~(BPF_F_ADJ_ROOM_MASK |
3682 			       BPF_F_ADJ_ROOM_NO_CSUM_RESET)))
3683 		return -EINVAL;
3684 	if (unlikely(len_diff_abs > 0xfffU))
3685 		return -EFAULT;
3686 	if (unlikely(proto != htons(ETH_P_IP) &&
3687 		     proto != htons(ETH_P_IPV6)))
3688 		return -ENOTSUPP;
3689 
3690 	off = skb_mac_header_len(skb);
3691 	switch (mode) {
3692 	case BPF_ADJ_ROOM_NET:
3693 		off += bpf_skb_net_base_len(skb);
3694 		break;
3695 	case BPF_ADJ_ROOM_MAC:
3696 		break;
3697 	default:
3698 		return -ENOTSUPP;
3699 	}
3700 
3701 	if (flags & BPF_F_ADJ_ROOM_DECAP_L3_MASK) {
3702 		if (!shrink)
3703 			return -EINVAL;
3704 
3705 		switch (flags & BPF_F_ADJ_ROOM_DECAP_L3_MASK) {
3706 		case BPF_F_ADJ_ROOM_DECAP_L3_IPV4:
3707 			len_min = sizeof(struct iphdr);
3708 			break;
3709 		case BPF_F_ADJ_ROOM_DECAP_L3_IPV6:
3710 			len_min = sizeof(struct ipv6hdr);
3711 			break;
3712 		default:
3713 			return -EINVAL;
3714 		}
3715 	}
3716 
3717 	len_cur = skb->len - skb_network_offset(skb);
3718 	if ((shrink && (len_diff_abs >= len_cur ||
3719 			len_cur - len_diff_abs < len_min)) ||
3720 	    (!shrink && (skb->len + len_diff_abs > len_max &&
3721 			 !skb_is_gso(skb))))
3722 		return -ENOTSUPP;
3723 
3724 	ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3725 		       bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3726 	if (!ret && !(flags & BPF_F_ADJ_ROOM_NO_CSUM_RESET))
3727 		__skb_reset_checksum_unnecessary(skb);
3728 
3729 	bpf_compute_data_pointers(skb);
3730 	return ret;
3731 }
3732 
3733 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3734 	.func		= bpf_skb_adjust_room,
3735 	.gpl_only	= false,
3736 	.ret_type	= RET_INTEGER,
3737 	.arg1_type	= ARG_PTR_TO_CTX,
3738 	.arg2_type	= ARG_ANYTHING,
3739 	.arg3_type	= ARG_ANYTHING,
3740 	.arg4_type	= ARG_ANYTHING,
3741 };
3742 
__bpf_skb_min_len(const struct sk_buff * skb)3743 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3744 {
3745 	int offset = skb_network_offset(skb);
3746 	u32 min_len = 0;
3747 
3748 	if (offset > 0)
3749 		min_len = offset;
3750 	if (skb_transport_header_was_set(skb)) {
3751 		offset = skb_transport_offset(skb);
3752 		if (offset > 0)
3753 			min_len = offset;
3754 	}
3755 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
3756 		offset = skb_checksum_start_offset(skb) +
3757 			 skb->csum_offset + sizeof(__sum16);
3758 		if (offset > 0)
3759 			min_len = offset;
3760 	}
3761 	return min_len;
3762 }
3763 
bpf_skb_grow_rcsum(struct sk_buff * skb,unsigned int new_len)3764 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3765 {
3766 	unsigned int old_len = skb->len;
3767 	int ret;
3768 
3769 	ret = __skb_grow_rcsum(skb, new_len);
3770 	if (!ret)
3771 		memset(skb->data + old_len, 0, new_len - old_len);
3772 	return ret;
3773 }
3774 
bpf_skb_trim_rcsum(struct sk_buff * skb,unsigned int new_len)3775 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3776 {
3777 	return __skb_trim_rcsum(skb, new_len);
3778 }
3779 
__bpf_skb_change_tail(struct sk_buff * skb,u32 new_len,u64 flags)3780 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3781 					u64 flags)
3782 {
3783 	u32 max_len = BPF_SKB_MAX_LEN;
3784 	u32 min_len = __bpf_skb_min_len(skb);
3785 	int ret;
3786 
3787 	if (unlikely(flags || new_len > max_len || new_len < min_len))
3788 		return -EINVAL;
3789 	if (skb->encapsulation)
3790 		return -ENOTSUPP;
3791 
3792 	/* The basic idea of this helper is that it's performing the
3793 	 * needed work to either grow or trim an skb, and eBPF program
3794 	 * rewrites the rest via helpers like bpf_skb_store_bytes(),
3795 	 * bpf_lX_csum_replace() and others rather than passing a raw
3796 	 * buffer here. This one is a slow path helper and intended
3797 	 * for replies with control messages.
3798 	 *
3799 	 * Like in bpf_skb_change_proto(), we want to keep this rather
3800 	 * minimal and without protocol specifics so that we are able
3801 	 * to separate concerns as in bpf_skb_store_bytes() should only
3802 	 * be the one responsible for writing buffers.
3803 	 *
3804 	 * It's really expected to be a slow path operation here for
3805 	 * control message replies, so we're implicitly linearizing,
3806 	 * uncloning and drop offloads from the skb by this.
3807 	 */
3808 	ret = __bpf_try_make_writable(skb, skb->len);
3809 	if (!ret) {
3810 		if (new_len > skb->len)
3811 			ret = bpf_skb_grow_rcsum(skb, new_len);
3812 		else if (new_len < skb->len)
3813 			ret = bpf_skb_trim_rcsum(skb, new_len);
3814 		if (!ret && skb_is_gso(skb))
3815 			skb_gso_reset(skb);
3816 	}
3817 	return ret;
3818 }
3819 
BPF_CALL_3(bpf_skb_change_tail,struct sk_buff *,skb,u32,new_len,u64,flags)3820 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3821 	   u64, flags)
3822 {
3823 	int ret = __bpf_skb_change_tail(skb, new_len, flags);
3824 
3825 	bpf_compute_data_pointers(skb);
3826 	return ret;
3827 }
3828 
3829 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3830 	.func		= bpf_skb_change_tail,
3831 	.gpl_only	= false,
3832 	.ret_type	= RET_INTEGER,
3833 	.arg1_type	= ARG_PTR_TO_CTX,
3834 	.arg2_type	= ARG_ANYTHING,
3835 	.arg3_type	= ARG_ANYTHING,
3836 };
3837 
BPF_CALL_3(sk_skb_change_tail,struct sk_buff *,skb,u32,new_len,u64,flags)3838 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3839 	   u64, flags)
3840 {
3841 	return __bpf_skb_change_tail(skb, new_len, flags);
3842 }
3843 
3844 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3845 	.func		= sk_skb_change_tail,
3846 	.gpl_only	= false,
3847 	.ret_type	= RET_INTEGER,
3848 	.arg1_type	= ARG_PTR_TO_CTX,
3849 	.arg2_type	= ARG_ANYTHING,
3850 	.arg3_type	= ARG_ANYTHING,
3851 };
3852 
__bpf_skb_change_head(struct sk_buff * skb,u32 head_room,u64 flags)3853 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3854 					u64 flags)
3855 {
3856 	u32 max_len = BPF_SKB_MAX_LEN;
3857 	u32 new_len = skb->len + head_room;
3858 	int ret;
3859 
3860 	if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3861 		     new_len < skb->len))
3862 		return -EINVAL;
3863 
3864 	ret = skb_cow(skb, head_room);
3865 	if (likely(!ret)) {
3866 		/* Idea for this helper is that we currently only
3867 		 * allow to expand on mac header. This means that
3868 		 * skb->protocol network header, etc, stay as is.
3869 		 * Compared to bpf_skb_change_tail(), we're more
3870 		 * flexible due to not needing to linearize or
3871 		 * reset GSO. Intention for this helper is to be
3872 		 * used by an L3 skb that needs to push mac header
3873 		 * for redirection into L2 device.
3874 		 */
3875 		__skb_push(skb, head_room);
3876 		memset(skb->data, 0, head_room);
3877 		skb_reset_mac_header(skb);
3878 		skb_reset_mac_len(skb);
3879 	}
3880 
3881 	return ret;
3882 }
3883 
BPF_CALL_3(bpf_skb_change_head,struct sk_buff *,skb,u32,head_room,u64,flags)3884 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3885 	   u64, flags)
3886 {
3887 	int ret = __bpf_skb_change_head(skb, head_room, flags);
3888 
3889 	bpf_compute_data_pointers(skb);
3890 	return ret;
3891 }
3892 
3893 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3894 	.func		= bpf_skb_change_head,
3895 	.gpl_only	= false,
3896 	.ret_type	= RET_INTEGER,
3897 	.arg1_type	= ARG_PTR_TO_CTX,
3898 	.arg2_type	= ARG_ANYTHING,
3899 	.arg3_type	= ARG_ANYTHING,
3900 };
3901 
BPF_CALL_3(sk_skb_change_head,struct sk_buff *,skb,u32,head_room,u64,flags)3902 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3903 	   u64, flags)
3904 {
3905 	return __bpf_skb_change_head(skb, head_room, flags);
3906 }
3907 
3908 static const struct bpf_func_proto sk_skb_change_head_proto = {
3909 	.func		= sk_skb_change_head,
3910 	.gpl_only	= false,
3911 	.ret_type	= RET_INTEGER,
3912 	.arg1_type	= ARG_PTR_TO_CTX,
3913 	.arg2_type	= ARG_ANYTHING,
3914 	.arg3_type	= ARG_ANYTHING,
3915 };
3916 
BPF_CALL_1(bpf_xdp_get_buff_len,struct xdp_buff *,xdp)3917 BPF_CALL_1(bpf_xdp_get_buff_len, struct xdp_buff*, xdp)
3918 {
3919 	return xdp_get_buff_len(xdp);
3920 }
3921 
3922 static const struct bpf_func_proto bpf_xdp_get_buff_len_proto = {
3923 	.func		= bpf_xdp_get_buff_len,
3924 	.gpl_only	= false,
3925 	.ret_type	= RET_INTEGER,
3926 	.arg1_type	= ARG_PTR_TO_CTX,
3927 };
3928 
3929 BTF_ID_LIST_SINGLE(bpf_xdp_get_buff_len_bpf_ids, struct, xdp_buff)
3930 
3931 const struct bpf_func_proto bpf_xdp_get_buff_len_trace_proto = {
3932 	.func		= bpf_xdp_get_buff_len,
3933 	.gpl_only	= false,
3934 	.arg1_type	= ARG_PTR_TO_BTF_ID,
3935 	.arg1_btf_id	= &bpf_xdp_get_buff_len_bpf_ids[0],
3936 };
3937 
xdp_get_metalen(const struct xdp_buff * xdp)3938 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3939 {
3940 	return xdp_data_meta_unsupported(xdp) ? 0 :
3941 	       xdp->data - xdp->data_meta;
3942 }
3943 
BPF_CALL_2(bpf_xdp_adjust_head,struct xdp_buff *,xdp,int,offset)3944 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3945 {
3946 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3947 	unsigned long metalen = xdp_get_metalen(xdp);
3948 	void *data_start = xdp_frame_end + metalen;
3949 	void *data = xdp->data + offset;
3950 
3951 	if (unlikely(data < data_start ||
3952 		     data > xdp->data_end - ETH_HLEN))
3953 		return -EINVAL;
3954 
3955 	if (metalen)
3956 		memmove(xdp->data_meta + offset,
3957 			xdp->data_meta, metalen);
3958 	xdp->data_meta += offset;
3959 	xdp->data = data;
3960 
3961 	return 0;
3962 }
3963 
3964 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3965 	.func		= bpf_xdp_adjust_head,
3966 	.gpl_only	= false,
3967 	.ret_type	= RET_INTEGER,
3968 	.arg1_type	= ARG_PTR_TO_CTX,
3969 	.arg2_type	= ARG_ANYTHING,
3970 };
3971 
bpf_xdp_copy_buf(struct xdp_buff * xdp,unsigned long off,void * buf,unsigned long len,bool flush)3972 void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
3973 		      void *buf, unsigned long len, bool flush)
3974 {
3975 	unsigned long ptr_len, ptr_off = 0;
3976 	skb_frag_t *next_frag, *end_frag;
3977 	struct skb_shared_info *sinfo;
3978 	void *src, *dst;
3979 	u8 *ptr_buf;
3980 
3981 	if (likely(xdp->data_end - xdp->data >= off + len)) {
3982 		src = flush ? buf : xdp->data + off;
3983 		dst = flush ? xdp->data + off : buf;
3984 		memcpy(dst, src, len);
3985 		return;
3986 	}
3987 
3988 	sinfo = xdp_get_shared_info_from_buff(xdp);
3989 	end_frag = &sinfo->frags[sinfo->nr_frags];
3990 	next_frag = &sinfo->frags[0];
3991 
3992 	ptr_len = xdp->data_end - xdp->data;
3993 	ptr_buf = xdp->data;
3994 
3995 	while (true) {
3996 		if (off < ptr_off + ptr_len) {
3997 			unsigned long copy_off = off - ptr_off;
3998 			unsigned long copy_len = min(len, ptr_len - copy_off);
3999 
4000 			src = flush ? buf : ptr_buf + copy_off;
4001 			dst = flush ? ptr_buf + copy_off : buf;
4002 			memcpy(dst, src, copy_len);
4003 
4004 			off += copy_len;
4005 			len -= copy_len;
4006 			buf += copy_len;
4007 		}
4008 
4009 		if (!len || next_frag == end_frag)
4010 			break;
4011 
4012 		ptr_off += ptr_len;
4013 		ptr_buf = skb_frag_address(next_frag);
4014 		ptr_len = skb_frag_size(next_frag);
4015 		next_frag++;
4016 	}
4017 }
4018 
bpf_xdp_pointer(struct xdp_buff * xdp,u32 offset,u32 len)4019 void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
4020 {
4021 	u32 size = xdp->data_end - xdp->data;
4022 	struct skb_shared_info *sinfo;
4023 	void *addr = xdp->data;
4024 	int i;
4025 
4026 	if (unlikely(offset > 0xffff || len > 0xffff))
4027 		return ERR_PTR(-EFAULT);
4028 
4029 	if (unlikely(offset + len > xdp_get_buff_len(xdp)))
4030 		return ERR_PTR(-EINVAL);
4031 
4032 	if (likely(offset < size)) /* linear area */
4033 		goto out;
4034 
4035 	sinfo = xdp_get_shared_info_from_buff(xdp);
4036 	offset -= size;
4037 	for (i = 0; i < sinfo->nr_frags; i++) { /* paged area */
4038 		u32 frag_size = skb_frag_size(&sinfo->frags[i]);
4039 
4040 		if  (offset < frag_size) {
4041 			addr = skb_frag_address(&sinfo->frags[i]);
4042 			size = frag_size;
4043 			break;
4044 		}
4045 		offset -= frag_size;
4046 	}
4047 out:
4048 	return offset + len <= size ? addr + offset : NULL;
4049 }
4050 
BPF_CALL_4(bpf_xdp_load_bytes,struct xdp_buff *,xdp,u32,offset,void *,buf,u32,len)4051 BPF_CALL_4(bpf_xdp_load_bytes, struct xdp_buff *, xdp, u32, offset,
4052 	   void *, buf, u32, len)
4053 {
4054 	void *ptr;
4055 
4056 	ptr = bpf_xdp_pointer(xdp, offset, len);
4057 	if (IS_ERR(ptr))
4058 		return PTR_ERR(ptr);
4059 
4060 	if (!ptr)
4061 		bpf_xdp_copy_buf(xdp, offset, buf, len, false);
4062 	else
4063 		memcpy(buf, ptr, len);
4064 
4065 	return 0;
4066 }
4067 
4068 static const struct bpf_func_proto bpf_xdp_load_bytes_proto = {
4069 	.func		= bpf_xdp_load_bytes,
4070 	.gpl_only	= false,
4071 	.ret_type	= RET_INTEGER,
4072 	.arg1_type	= ARG_PTR_TO_CTX,
4073 	.arg2_type	= ARG_ANYTHING,
4074 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
4075 	.arg4_type	= ARG_CONST_SIZE,
4076 };
4077 
__bpf_xdp_load_bytes(struct xdp_buff * xdp,u32 offset,void * buf,u32 len)4078 int __bpf_xdp_load_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
4079 {
4080 	return ____bpf_xdp_load_bytes(xdp, offset, buf, len);
4081 }
4082 
BPF_CALL_4(bpf_xdp_store_bytes,struct xdp_buff *,xdp,u32,offset,void *,buf,u32,len)4083 BPF_CALL_4(bpf_xdp_store_bytes, struct xdp_buff *, xdp, u32, offset,
4084 	   void *, buf, u32, len)
4085 {
4086 	void *ptr;
4087 
4088 	ptr = bpf_xdp_pointer(xdp, offset, len);
4089 	if (IS_ERR(ptr))
4090 		return PTR_ERR(ptr);
4091 
4092 	if (!ptr)
4093 		bpf_xdp_copy_buf(xdp, offset, buf, len, true);
4094 	else
4095 		memcpy(ptr, buf, len);
4096 
4097 	return 0;
4098 }
4099 
4100 static const struct bpf_func_proto bpf_xdp_store_bytes_proto = {
4101 	.func		= bpf_xdp_store_bytes,
4102 	.gpl_only	= false,
4103 	.ret_type	= RET_INTEGER,
4104 	.arg1_type	= ARG_PTR_TO_CTX,
4105 	.arg2_type	= ARG_ANYTHING,
4106 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
4107 	.arg4_type	= ARG_CONST_SIZE,
4108 };
4109 
__bpf_xdp_store_bytes(struct xdp_buff * xdp,u32 offset,void * buf,u32 len)4110 int __bpf_xdp_store_bytes(struct xdp_buff *xdp, u32 offset, void *buf, u32 len)
4111 {
4112 	return ____bpf_xdp_store_bytes(xdp, offset, buf, len);
4113 }
4114 
bpf_xdp_frags_increase_tail(struct xdp_buff * xdp,int offset)4115 static int bpf_xdp_frags_increase_tail(struct xdp_buff *xdp, int offset)
4116 {
4117 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4118 	skb_frag_t *frag = &sinfo->frags[sinfo->nr_frags - 1];
4119 	struct xdp_rxq_info *rxq = xdp->rxq;
4120 	unsigned int tailroom;
4121 
4122 	if (!rxq->frag_size || rxq->frag_size > xdp->frame_sz)
4123 		return -EOPNOTSUPP;
4124 
4125 	tailroom = rxq->frag_size - skb_frag_size(frag) - skb_frag_off(frag);
4126 	if (unlikely(offset > tailroom))
4127 		return -EINVAL;
4128 
4129 	memset(skb_frag_address(frag) + skb_frag_size(frag), 0, offset);
4130 	skb_frag_size_add(frag, offset);
4131 	sinfo->xdp_frags_size += offset;
4132 	if (rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL)
4133 		xsk_buff_get_tail(xdp)->data_end += offset;
4134 
4135 	return 0;
4136 }
4137 
bpf_xdp_shrink_data_zc(struct xdp_buff * xdp,int shrink,enum xdp_mem_type mem_type,bool release)4138 static void bpf_xdp_shrink_data_zc(struct xdp_buff *xdp, int shrink,
4139 				   enum xdp_mem_type mem_type, bool release)
4140 {
4141 	struct xdp_buff *zc_frag = xsk_buff_get_tail(xdp);
4142 
4143 	if (release) {
4144 		xsk_buff_del_tail(zc_frag);
4145 		__xdp_return(0, mem_type, false, zc_frag);
4146 	} else {
4147 		zc_frag->data_end -= shrink;
4148 	}
4149 }
4150 
bpf_xdp_shrink_data(struct xdp_buff * xdp,skb_frag_t * frag,int shrink)4151 static bool bpf_xdp_shrink_data(struct xdp_buff *xdp, skb_frag_t *frag,
4152 				int shrink)
4153 {
4154 	enum xdp_mem_type mem_type = xdp->rxq->mem.type;
4155 	bool release = skb_frag_size(frag) == shrink;
4156 
4157 	if (mem_type == MEM_TYPE_XSK_BUFF_POOL) {
4158 		bpf_xdp_shrink_data_zc(xdp, shrink, mem_type, release);
4159 		goto out;
4160 	}
4161 
4162 	if (release)
4163 		__xdp_return(skb_frag_netmem(frag), mem_type, false, NULL);
4164 
4165 out:
4166 	return release;
4167 }
4168 
bpf_xdp_frags_shrink_tail(struct xdp_buff * xdp,int offset)4169 static int bpf_xdp_frags_shrink_tail(struct xdp_buff *xdp, int offset)
4170 {
4171 	struct skb_shared_info *sinfo = xdp_get_shared_info_from_buff(xdp);
4172 	int i, n_frags_free = 0, len_free = 0;
4173 
4174 	if (unlikely(offset > (int)xdp_get_buff_len(xdp) - ETH_HLEN))
4175 		return -EINVAL;
4176 
4177 	for (i = sinfo->nr_frags - 1; i >= 0 && offset > 0; i--) {
4178 		skb_frag_t *frag = &sinfo->frags[i];
4179 		int shrink = min_t(int, offset, skb_frag_size(frag));
4180 
4181 		len_free += shrink;
4182 		offset -= shrink;
4183 		if (bpf_xdp_shrink_data(xdp, frag, shrink)) {
4184 			n_frags_free++;
4185 		} else {
4186 			skb_frag_size_sub(frag, shrink);
4187 			break;
4188 		}
4189 	}
4190 	sinfo->nr_frags -= n_frags_free;
4191 	sinfo->xdp_frags_size -= len_free;
4192 
4193 	if (unlikely(!sinfo->nr_frags)) {
4194 		xdp_buff_clear_frags_flag(xdp);
4195 		xdp->data_end -= offset;
4196 	}
4197 
4198 	return 0;
4199 }
4200 
BPF_CALL_2(bpf_xdp_adjust_tail,struct xdp_buff *,xdp,int,offset)4201 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
4202 {
4203 	void *data_hard_end = xdp_data_hard_end(xdp); /* use xdp->frame_sz */
4204 	void *data_end = xdp->data_end + offset;
4205 
4206 	if (unlikely(xdp_buff_has_frags(xdp))) { /* non-linear xdp buff */
4207 		if (offset < 0)
4208 			return bpf_xdp_frags_shrink_tail(xdp, -offset);
4209 
4210 		return bpf_xdp_frags_increase_tail(xdp, offset);
4211 	}
4212 
4213 	/* Notice that xdp_data_hard_end have reserved some tailroom */
4214 	if (unlikely(data_end > data_hard_end))
4215 		return -EINVAL;
4216 
4217 	if (unlikely(data_end < xdp->data + ETH_HLEN))
4218 		return -EINVAL;
4219 
4220 	/* Clear memory area on grow, can contain uninit kernel memory */
4221 	if (offset > 0)
4222 		memset(xdp->data_end, 0, offset);
4223 
4224 	xdp->data_end = data_end;
4225 
4226 	return 0;
4227 }
4228 
4229 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
4230 	.func		= bpf_xdp_adjust_tail,
4231 	.gpl_only	= false,
4232 	.ret_type	= RET_INTEGER,
4233 	.arg1_type	= ARG_PTR_TO_CTX,
4234 	.arg2_type	= ARG_ANYTHING,
4235 };
4236 
BPF_CALL_2(bpf_xdp_adjust_meta,struct xdp_buff *,xdp,int,offset)4237 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
4238 {
4239 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
4240 	void *meta = xdp->data_meta + offset;
4241 	unsigned long metalen = xdp->data - meta;
4242 
4243 	if (xdp_data_meta_unsupported(xdp))
4244 		return -ENOTSUPP;
4245 	if (unlikely(meta < xdp_frame_end ||
4246 		     meta > xdp->data))
4247 		return -EINVAL;
4248 	if (unlikely(xdp_metalen_invalid(metalen)))
4249 		return -EACCES;
4250 
4251 	xdp->data_meta = meta;
4252 
4253 	return 0;
4254 }
4255 
4256 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
4257 	.func		= bpf_xdp_adjust_meta,
4258 	.gpl_only	= false,
4259 	.ret_type	= RET_INTEGER,
4260 	.arg1_type	= ARG_PTR_TO_CTX,
4261 	.arg2_type	= ARG_ANYTHING,
4262 };
4263 
4264 /**
4265  * DOC: xdp redirect
4266  *
4267  * XDP_REDIRECT works by a three-step process, implemented in the functions
4268  * below:
4269  *
4270  * 1. The bpf_redirect() and bpf_redirect_map() helpers will lookup the target
4271  *    of the redirect and store it (along with some other metadata) in a per-CPU
4272  *    struct bpf_redirect_info.
4273  *
4274  * 2. When the program returns the XDP_REDIRECT return code, the driver will
4275  *    call xdp_do_redirect() which will use the information in struct
4276  *    bpf_redirect_info to actually enqueue the frame into a map type-specific
4277  *    bulk queue structure.
4278  *
4279  * 3. Before exiting its NAPI poll loop, the driver will call
4280  *    xdp_do_flush(), which will flush all the different bulk queues,
4281  *    thus completing the redirect. Note that xdp_do_flush() must be
4282  *    called before napi_complete_done() in the driver, as the
4283  *    XDP_REDIRECT logic relies on being inside a single NAPI instance
4284  *    through to the xdp_do_flush() call for RCU protection of all
4285  *    in-kernel data structures.
4286  */
4287 /*
4288  * Pointers to the map entries will be kept around for this whole sequence of
4289  * steps, protected by RCU. However, there is no top-level rcu_read_lock() in
4290  * the core code; instead, the RCU protection relies on everything happening
4291  * inside a single NAPI poll sequence, which means it's between a pair of calls
4292  * to local_bh_disable()/local_bh_enable().
4293  *
4294  * The map entries are marked as __rcu and the map code makes sure to
4295  * dereference those pointers with rcu_dereference_check() in a way that works
4296  * for both sections that to hold an rcu_read_lock() and sections that are
4297  * called from NAPI without a separate rcu_read_lock(). The code below does not
4298  * use RCU annotations, but relies on those in the map code.
4299  */
xdp_do_flush(void)4300 void xdp_do_flush(void)
4301 {
4302 	struct list_head *lh_map, *lh_dev, *lh_xsk;
4303 
4304 	bpf_net_ctx_get_all_used_flush_lists(&lh_map, &lh_dev, &lh_xsk);
4305 	if (lh_dev)
4306 		__dev_flush(lh_dev);
4307 	if (lh_map)
4308 		__cpu_map_flush(lh_map);
4309 	if (lh_xsk)
4310 		__xsk_map_flush(lh_xsk);
4311 }
4312 EXPORT_SYMBOL_GPL(xdp_do_flush);
4313 
4314 #if defined(CONFIG_DEBUG_NET) && defined(CONFIG_BPF_SYSCALL)
xdp_do_check_flushed(struct napi_struct * napi)4315 void xdp_do_check_flushed(struct napi_struct *napi)
4316 {
4317 	struct list_head *lh_map, *lh_dev, *lh_xsk;
4318 	bool missed = false;
4319 
4320 	bpf_net_ctx_get_all_used_flush_lists(&lh_map, &lh_dev, &lh_xsk);
4321 	if (lh_dev) {
4322 		__dev_flush(lh_dev);
4323 		missed = true;
4324 	}
4325 	if (lh_map) {
4326 		__cpu_map_flush(lh_map);
4327 		missed = true;
4328 	}
4329 	if (lh_xsk) {
4330 		__xsk_map_flush(lh_xsk);
4331 		missed = true;
4332 	}
4333 
4334 	WARN_ONCE(missed, "Missing xdp_do_flush() invocation after NAPI by %ps\n",
4335 		  napi->poll);
4336 }
4337 #endif
4338 
4339 DEFINE_STATIC_KEY_FALSE(bpf_master_redirect_enabled_key);
4340 EXPORT_SYMBOL_GPL(bpf_master_redirect_enabled_key);
4341 
xdp_master_redirect(struct xdp_buff * xdp)4342 u32 xdp_master_redirect(struct xdp_buff *xdp)
4343 {
4344 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4345 	struct net_device *master, *slave;
4346 
4347 	master = netdev_master_upper_dev_get_rcu(xdp->rxq->dev);
4348 	slave = master->netdev_ops->ndo_xdp_get_xmit_slave(master, xdp);
4349 	if (slave && slave != xdp->rxq->dev) {
4350 		/* The target device is different from the receiving device, so
4351 		 * redirect it to the new device.
4352 		 * Using XDP_REDIRECT gets the correct behaviour from XDP enabled
4353 		 * drivers to unmap the packet from their rx ring.
4354 		 */
4355 		ri->tgt_index = slave->ifindex;
4356 		ri->map_id = INT_MAX;
4357 		ri->map_type = BPF_MAP_TYPE_UNSPEC;
4358 		return XDP_REDIRECT;
4359 	}
4360 	return XDP_TX;
4361 }
4362 EXPORT_SYMBOL_GPL(xdp_master_redirect);
4363 
__xdp_do_redirect_xsk(struct bpf_redirect_info * ri,const struct net_device * dev,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog)4364 static inline int __xdp_do_redirect_xsk(struct bpf_redirect_info *ri,
4365 					const struct net_device *dev,
4366 					struct xdp_buff *xdp,
4367 					const struct bpf_prog *xdp_prog)
4368 {
4369 	enum bpf_map_type map_type = ri->map_type;
4370 	void *fwd = ri->tgt_value;
4371 	u32 map_id = ri->map_id;
4372 	int err;
4373 
4374 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4375 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4376 
4377 	err = __xsk_map_redirect(fwd, xdp);
4378 	if (unlikely(err))
4379 		goto err;
4380 
4381 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4382 	return 0;
4383 err:
4384 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4385 	return err;
4386 }
4387 
4388 static __always_inline int
__xdp_do_redirect_frame(struct bpf_redirect_info * ri,struct net_device * dev,struct xdp_frame * xdpf,const struct bpf_prog * xdp_prog)4389 __xdp_do_redirect_frame(struct bpf_redirect_info *ri, struct net_device *dev,
4390 			struct xdp_frame *xdpf,
4391 			const struct bpf_prog *xdp_prog)
4392 {
4393 	enum bpf_map_type map_type = ri->map_type;
4394 	void *fwd = ri->tgt_value;
4395 	u32 map_id = ri->map_id;
4396 	u32 flags = ri->flags;
4397 	struct bpf_map *map;
4398 	int err;
4399 
4400 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4401 	ri->flags = 0;
4402 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4403 
4404 	if (unlikely(!xdpf)) {
4405 		err = -EOVERFLOW;
4406 		goto err;
4407 	}
4408 
4409 	switch (map_type) {
4410 	case BPF_MAP_TYPE_DEVMAP:
4411 		fallthrough;
4412 	case BPF_MAP_TYPE_DEVMAP_HASH:
4413 		if (unlikely(flags & BPF_F_BROADCAST)) {
4414 			map = READ_ONCE(ri->map);
4415 
4416 			/* The map pointer is cleared when the map is being torn
4417 			 * down by dev_map_free()
4418 			 */
4419 			if (unlikely(!map)) {
4420 				err = -ENOENT;
4421 				break;
4422 			}
4423 
4424 			WRITE_ONCE(ri->map, NULL);
4425 			err = dev_map_enqueue_multi(xdpf, dev, map,
4426 						    flags & BPF_F_EXCLUDE_INGRESS);
4427 		} else {
4428 			err = dev_map_enqueue(fwd, xdpf, dev);
4429 		}
4430 		break;
4431 	case BPF_MAP_TYPE_CPUMAP:
4432 		err = cpu_map_enqueue(fwd, xdpf, dev);
4433 		break;
4434 	case BPF_MAP_TYPE_UNSPEC:
4435 		if (map_id == INT_MAX) {
4436 			fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4437 			if (unlikely(!fwd)) {
4438 				err = -EINVAL;
4439 				break;
4440 			}
4441 			err = dev_xdp_enqueue(fwd, xdpf, dev);
4442 			break;
4443 		}
4444 		fallthrough;
4445 	default:
4446 		err = -EBADRQC;
4447 	}
4448 
4449 	if (unlikely(err))
4450 		goto err;
4451 
4452 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4453 	return 0;
4454 err:
4455 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4456 	return err;
4457 }
4458 
xdp_do_redirect(struct net_device * dev,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog)4459 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
4460 		    const struct bpf_prog *xdp_prog)
4461 {
4462 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4463 	enum bpf_map_type map_type = ri->map_type;
4464 
4465 	if (map_type == BPF_MAP_TYPE_XSKMAP)
4466 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4467 
4468 	return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
4469 				       xdp_prog);
4470 }
4471 EXPORT_SYMBOL_GPL(xdp_do_redirect);
4472 
xdp_do_redirect_frame(struct net_device * dev,struct xdp_buff * xdp,struct xdp_frame * xdpf,const struct bpf_prog * xdp_prog)4473 int xdp_do_redirect_frame(struct net_device *dev, struct xdp_buff *xdp,
4474 			  struct xdp_frame *xdpf,
4475 			  const struct bpf_prog *xdp_prog)
4476 {
4477 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4478 	enum bpf_map_type map_type = ri->map_type;
4479 
4480 	if (map_type == BPF_MAP_TYPE_XSKMAP)
4481 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
4482 
4483 	return __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);
4484 }
4485 EXPORT_SYMBOL_GPL(xdp_do_redirect_frame);
4486 
xdp_do_generic_redirect_map(struct net_device * dev,struct sk_buff * skb,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog,void * fwd,enum bpf_map_type map_type,u32 map_id,u32 flags)4487 static int xdp_do_generic_redirect_map(struct net_device *dev,
4488 				       struct sk_buff *skb,
4489 				       struct xdp_buff *xdp,
4490 				       const struct bpf_prog *xdp_prog,
4491 				       void *fwd, enum bpf_map_type map_type,
4492 				       u32 map_id, u32 flags)
4493 {
4494 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4495 	struct bpf_map *map;
4496 	int err;
4497 
4498 	switch (map_type) {
4499 	case BPF_MAP_TYPE_DEVMAP:
4500 		fallthrough;
4501 	case BPF_MAP_TYPE_DEVMAP_HASH:
4502 		if (unlikely(flags & BPF_F_BROADCAST)) {
4503 			map = READ_ONCE(ri->map);
4504 
4505 			/* The map pointer is cleared when the map is being torn
4506 			 * down by dev_map_free()
4507 			 */
4508 			if (unlikely(!map)) {
4509 				err = -ENOENT;
4510 				break;
4511 			}
4512 
4513 			WRITE_ONCE(ri->map, NULL);
4514 			err = dev_map_redirect_multi(dev, skb, xdp_prog, map,
4515 						     flags & BPF_F_EXCLUDE_INGRESS);
4516 		} else {
4517 			err = dev_map_generic_redirect(fwd, skb, xdp_prog);
4518 		}
4519 		if (unlikely(err))
4520 			goto err;
4521 		break;
4522 	case BPF_MAP_TYPE_XSKMAP:
4523 		err = xsk_generic_rcv(fwd, xdp);
4524 		if (err)
4525 			goto err;
4526 		consume_skb(skb);
4527 		break;
4528 	case BPF_MAP_TYPE_CPUMAP:
4529 		err = cpu_map_generic_redirect(fwd, skb);
4530 		if (unlikely(err))
4531 			goto err;
4532 		break;
4533 	default:
4534 		err = -EBADRQC;
4535 		goto err;
4536 	}
4537 
4538 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index);
4539 	return 0;
4540 err:
4541 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map_type, map_id, ri->tgt_index, err);
4542 	return err;
4543 }
4544 
xdp_do_generic_redirect(struct net_device * dev,struct sk_buff * skb,struct xdp_buff * xdp,const struct bpf_prog * xdp_prog)4545 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
4546 			    struct xdp_buff *xdp,
4547 			    const struct bpf_prog *xdp_prog)
4548 {
4549 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4550 	enum bpf_map_type map_type = ri->map_type;
4551 	void *fwd = ri->tgt_value;
4552 	u32 map_id = ri->map_id;
4553 	u32 flags = ri->flags;
4554 	int err;
4555 
4556 	ri->map_id = 0; /* Valid map id idr range: [1,INT_MAX[ */
4557 	ri->flags = 0;
4558 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4559 
4560 	if (map_type == BPF_MAP_TYPE_UNSPEC && map_id == INT_MAX) {
4561 		fwd = dev_get_by_index_rcu(dev_net(dev), ri->tgt_index);
4562 		if (unlikely(!fwd)) {
4563 			err = -EINVAL;
4564 			goto err;
4565 		}
4566 
4567 		err = xdp_ok_fwd_dev(fwd, skb->len);
4568 		if (unlikely(err))
4569 			goto err;
4570 
4571 		skb->dev = fwd;
4572 		_trace_xdp_redirect(dev, xdp_prog, ri->tgt_index);
4573 		generic_xdp_tx(skb, xdp_prog);
4574 		return 0;
4575 	}
4576 
4577 	return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog, fwd, map_type, map_id, flags);
4578 err:
4579 	_trace_xdp_redirect_err(dev, xdp_prog, ri->tgt_index, err);
4580 	return err;
4581 }
4582 
BPF_CALL_2(bpf_xdp_redirect,u32,ifindex,u64,flags)4583 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
4584 {
4585 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
4586 
4587 	if (unlikely(flags))
4588 		return XDP_ABORTED;
4589 
4590 	/* NB! Map type UNSPEC and map_id == INT_MAX (never generated
4591 	 * by map_idr) is used for ifindex based XDP redirect.
4592 	 */
4593 	ri->tgt_index = ifindex;
4594 	ri->map_id = INT_MAX;
4595 	ri->map_type = BPF_MAP_TYPE_UNSPEC;
4596 
4597 	return XDP_REDIRECT;
4598 }
4599 
4600 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
4601 	.func           = bpf_xdp_redirect,
4602 	.gpl_only       = false,
4603 	.ret_type       = RET_INTEGER,
4604 	.arg1_type      = ARG_ANYTHING,
4605 	.arg2_type      = ARG_ANYTHING,
4606 };
4607 
BPF_CALL_3(bpf_xdp_redirect_map,struct bpf_map *,map,u64,key,u64,flags)4608 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u64, key,
4609 	   u64, flags)
4610 {
4611 	return map->ops->map_redirect(map, key, flags);
4612 }
4613 
4614 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
4615 	.func           = bpf_xdp_redirect_map,
4616 	.gpl_only       = false,
4617 	.ret_type       = RET_INTEGER,
4618 	.arg1_type      = ARG_CONST_MAP_PTR,
4619 	.arg2_type      = ARG_ANYTHING,
4620 	.arg3_type      = ARG_ANYTHING,
4621 };
4622 
bpf_skb_copy(void * dst_buff,const void * skb,unsigned long off,unsigned long len)4623 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
4624 				  unsigned long off, unsigned long len)
4625 {
4626 	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
4627 
4628 	if (unlikely(!ptr))
4629 		return len;
4630 	if (ptr != dst_buff)
4631 		memcpy(dst_buff, ptr, len);
4632 
4633 	return 0;
4634 }
4635 
BPF_CALL_5(bpf_skb_event_output,struct sk_buff *,skb,struct bpf_map *,map,u64,flags,void *,meta,u64,meta_size)4636 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
4637 	   u64, flags, void *, meta, u64, meta_size)
4638 {
4639 	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4640 
4641 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4642 		return -EINVAL;
4643 	if (unlikely(!skb || skb_size > skb->len))
4644 		return -EFAULT;
4645 
4646 	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
4647 				bpf_skb_copy);
4648 }
4649 
4650 static const struct bpf_func_proto bpf_skb_event_output_proto = {
4651 	.func		= bpf_skb_event_output,
4652 	.gpl_only	= true,
4653 	.ret_type	= RET_INTEGER,
4654 	.arg1_type	= ARG_PTR_TO_CTX,
4655 	.arg2_type	= ARG_CONST_MAP_PTR,
4656 	.arg3_type	= ARG_ANYTHING,
4657 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4658 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
4659 };
4660 
4661 BTF_ID_LIST_SINGLE(bpf_skb_output_btf_ids, struct, sk_buff)
4662 
4663 const struct bpf_func_proto bpf_skb_output_proto = {
4664 	.func		= bpf_skb_event_output,
4665 	.gpl_only	= true,
4666 	.ret_type	= RET_INTEGER,
4667 	.arg1_type	= ARG_PTR_TO_BTF_ID,
4668 	.arg1_btf_id	= &bpf_skb_output_btf_ids[0],
4669 	.arg2_type	= ARG_CONST_MAP_PTR,
4670 	.arg3_type	= ARG_ANYTHING,
4671 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4672 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
4673 };
4674 
bpf_tunnel_key_af(u64 flags)4675 static unsigned short bpf_tunnel_key_af(u64 flags)
4676 {
4677 	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
4678 }
4679 
BPF_CALL_4(bpf_skb_get_tunnel_key,struct sk_buff *,skb,struct bpf_tunnel_key *,to,u32,size,u64,flags)4680 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
4681 	   u32, size, u64, flags)
4682 {
4683 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4684 	u8 compat[sizeof(struct bpf_tunnel_key)];
4685 	void *to_orig = to;
4686 	int err;
4687 
4688 	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6 |
4689 					 BPF_F_TUNINFO_FLAGS)))) {
4690 		err = -EINVAL;
4691 		goto err_clear;
4692 	}
4693 	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
4694 		err = -EPROTO;
4695 		goto err_clear;
4696 	}
4697 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4698 		err = -EINVAL;
4699 		switch (size) {
4700 		case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4701 		case offsetof(struct bpf_tunnel_key, tunnel_label):
4702 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
4703 			goto set_compat;
4704 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4705 			/* Fixup deprecated structure layouts here, so we have
4706 			 * a common path later on.
4707 			 */
4708 			if (ip_tunnel_info_af(info) != AF_INET)
4709 				goto err_clear;
4710 set_compat:
4711 			to = (struct bpf_tunnel_key *)compat;
4712 			break;
4713 		default:
4714 			goto err_clear;
4715 		}
4716 	}
4717 
4718 	to->tunnel_id = be64_to_cpu(info->key.tun_id);
4719 	to->tunnel_tos = info->key.tos;
4720 	to->tunnel_ttl = info->key.ttl;
4721 	if (flags & BPF_F_TUNINFO_FLAGS)
4722 		to->tunnel_flags = ip_tunnel_flags_to_be16(info->key.tun_flags);
4723 	else
4724 		to->tunnel_ext = 0;
4725 
4726 	if (flags & BPF_F_TUNINFO_IPV6) {
4727 		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
4728 		       sizeof(to->remote_ipv6));
4729 		memcpy(to->local_ipv6, &info->key.u.ipv6.dst,
4730 		       sizeof(to->local_ipv6));
4731 		to->tunnel_label = be32_to_cpu(info->key.label);
4732 	} else {
4733 		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
4734 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4735 		to->local_ipv4 = be32_to_cpu(info->key.u.ipv4.dst);
4736 		memset(&to->local_ipv6[1], 0, sizeof(__u32) * 3);
4737 		to->tunnel_label = 0;
4738 	}
4739 
4740 	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
4741 		memcpy(to_orig, to, size);
4742 
4743 	return 0;
4744 err_clear:
4745 	memset(to_orig, 0, size);
4746 	return err;
4747 }
4748 
4749 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
4750 	.func		= bpf_skb_get_tunnel_key,
4751 	.gpl_only	= false,
4752 	.ret_type	= RET_INTEGER,
4753 	.arg1_type	= ARG_PTR_TO_CTX,
4754 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
4755 	.arg3_type	= ARG_CONST_SIZE,
4756 	.arg4_type	= ARG_ANYTHING,
4757 };
4758 
BPF_CALL_3(bpf_skb_get_tunnel_opt,struct sk_buff *,skb,u8 *,to,u32,size)4759 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
4760 {
4761 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
4762 	int err;
4763 
4764 	if (unlikely(!info ||
4765 		     !ip_tunnel_is_options_present(info->key.tun_flags))) {
4766 		err = -ENOENT;
4767 		goto err_clear;
4768 	}
4769 	if (unlikely(size < info->options_len)) {
4770 		err = -ENOMEM;
4771 		goto err_clear;
4772 	}
4773 
4774 	ip_tunnel_info_opts_get(to, info);
4775 	if (size > info->options_len)
4776 		memset(to + info->options_len, 0, size - info->options_len);
4777 
4778 	return info->options_len;
4779 err_clear:
4780 	memset(to, 0, size);
4781 	return err;
4782 }
4783 
4784 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
4785 	.func		= bpf_skb_get_tunnel_opt,
4786 	.gpl_only	= false,
4787 	.ret_type	= RET_INTEGER,
4788 	.arg1_type	= ARG_PTR_TO_CTX,
4789 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
4790 	.arg3_type	= ARG_CONST_SIZE,
4791 };
4792 
4793 static struct metadata_dst __percpu *md_dst;
4794 
BPF_CALL_4(bpf_skb_set_tunnel_key,struct sk_buff *,skb,const struct bpf_tunnel_key *,from,u32,size,u64,flags)4795 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
4796 	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
4797 {
4798 	struct metadata_dst *md = this_cpu_ptr(md_dst);
4799 	u8 compat[sizeof(struct bpf_tunnel_key)];
4800 	struct ip_tunnel_info *info;
4801 
4802 	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
4803 			       BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER |
4804 			       BPF_F_NO_TUNNEL_KEY)))
4805 		return -EINVAL;
4806 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
4807 		switch (size) {
4808 		case offsetof(struct bpf_tunnel_key, local_ipv6[0]):
4809 		case offsetof(struct bpf_tunnel_key, tunnel_label):
4810 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
4811 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
4812 			/* Fixup deprecated structure layouts here, so we have
4813 			 * a common path later on.
4814 			 */
4815 			memcpy(compat, from, size);
4816 			memset(compat + size, 0, sizeof(compat) - size);
4817 			from = (const struct bpf_tunnel_key *) compat;
4818 			break;
4819 		default:
4820 			return -EINVAL;
4821 		}
4822 	}
4823 	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
4824 		     from->tunnel_ext))
4825 		return -EINVAL;
4826 
4827 	skb_dst_drop(skb);
4828 	dst_hold((struct dst_entry *) md);
4829 	skb_dst_set(skb, (struct dst_entry *) md);
4830 
4831 	info = &md->u.tun_info;
4832 	memset(info, 0, sizeof(*info));
4833 	info->mode = IP_TUNNEL_INFO_TX;
4834 
4835 	__set_bit(IP_TUNNEL_NOCACHE_BIT, info->key.tun_flags);
4836 	__assign_bit(IP_TUNNEL_DONT_FRAGMENT_BIT, info->key.tun_flags,
4837 		     flags & BPF_F_DONT_FRAGMENT);
4838 	__assign_bit(IP_TUNNEL_CSUM_BIT, info->key.tun_flags,
4839 		     !(flags & BPF_F_ZERO_CSUM_TX));
4840 	__assign_bit(IP_TUNNEL_SEQ_BIT, info->key.tun_flags,
4841 		     flags & BPF_F_SEQ_NUMBER);
4842 	__assign_bit(IP_TUNNEL_KEY_BIT, info->key.tun_flags,
4843 		     !(flags & BPF_F_NO_TUNNEL_KEY));
4844 
4845 	info->key.tun_id = cpu_to_be64(from->tunnel_id);
4846 	info->key.tos = from->tunnel_tos;
4847 	info->key.ttl = from->tunnel_ttl;
4848 
4849 	if (flags & BPF_F_TUNINFO_IPV6) {
4850 		info->mode |= IP_TUNNEL_INFO_IPV6;
4851 		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
4852 		       sizeof(from->remote_ipv6));
4853 		memcpy(&info->key.u.ipv6.src, from->local_ipv6,
4854 		       sizeof(from->local_ipv6));
4855 		info->key.label = cpu_to_be32(from->tunnel_label) &
4856 				  IPV6_FLOWLABEL_MASK;
4857 	} else {
4858 		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
4859 		info->key.u.ipv4.src = cpu_to_be32(from->local_ipv4);
4860 		info->key.flow_flags = FLOWI_FLAG_ANYSRC;
4861 	}
4862 
4863 	return 0;
4864 }
4865 
4866 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
4867 	.func		= bpf_skb_set_tunnel_key,
4868 	.gpl_only	= false,
4869 	.ret_type	= RET_INTEGER,
4870 	.arg1_type	= ARG_PTR_TO_CTX,
4871 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4872 	.arg3_type	= ARG_CONST_SIZE,
4873 	.arg4_type	= ARG_ANYTHING,
4874 };
4875 
BPF_CALL_3(bpf_skb_set_tunnel_opt,struct sk_buff *,skb,const u8 *,from,u32,size)4876 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
4877 	   const u8 *, from, u32, size)
4878 {
4879 	struct ip_tunnel_info *info = skb_tunnel_info(skb);
4880 	const struct metadata_dst *md = this_cpu_ptr(md_dst);
4881 	IP_TUNNEL_DECLARE_FLAGS(present) = { };
4882 
4883 	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
4884 		return -EINVAL;
4885 	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
4886 		return -ENOMEM;
4887 
4888 	ip_tunnel_set_options_present(present);
4889 	ip_tunnel_info_opts_set(info, from, size, present);
4890 
4891 	return 0;
4892 }
4893 
4894 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
4895 	.func		= bpf_skb_set_tunnel_opt,
4896 	.gpl_only	= false,
4897 	.ret_type	= RET_INTEGER,
4898 	.arg1_type	= ARG_PTR_TO_CTX,
4899 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
4900 	.arg3_type	= ARG_CONST_SIZE,
4901 };
4902 
4903 static const struct bpf_func_proto *
bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)4904 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4905 {
4906 	if (!md_dst) {
4907 		struct metadata_dst __percpu *tmp;
4908 
4909 		tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4910 						METADATA_IP_TUNNEL,
4911 						GFP_KERNEL);
4912 		if (!tmp)
4913 			return NULL;
4914 		if (cmpxchg(&md_dst, NULL, tmp))
4915 			metadata_dst_free_percpu(tmp);
4916 	}
4917 
4918 	switch (which) {
4919 	case BPF_FUNC_skb_set_tunnel_key:
4920 		return &bpf_skb_set_tunnel_key_proto;
4921 	case BPF_FUNC_skb_set_tunnel_opt:
4922 		return &bpf_skb_set_tunnel_opt_proto;
4923 	default:
4924 		return NULL;
4925 	}
4926 }
4927 
BPF_CALL_3(bpf_skb_under_cgroup,struct sk_buff *,skb,struct bpf_map *,map,u32,idx)4928 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4929 	   u32, idx)
4930 {
4931 	struct bpf_array *array = container_of(map, struct bpf_array, map);
4932 	struct cgroup *cgrp;
4933 	struct sock *sk;
4934 
4935 	sk = skb_to_full_sk(skb);
4936 	if (!sk || !sk_fullsock(sk))
4937 		return -ENOENT;
4938 	if (unlikely(idx >= array->map.max_entries))
4939 		return -E2BIG;
4940 
4941 	cgrp = READ_ONCE(array->ptrs[idx]);
4942 	if (unlikely(!cgrp))
4943 		return -EAGAIN;
4944 
4945 	return sk_under_cgroup_hierarchy(sk, cgrp);
4946 }
4947 
4948 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4949 	.func		= bpf_skb_under_cgroup,
4950 	.gpl_only	= false,
4951 	.ret_type	= RET_INTEGER,
4952 	.arg1_type	= ARG_PTR_TO_CTX,
4953 	.arg2_type	= ARG_CONST_MAP_PTR,
4954 	.arg3_type	= ARG_ANYTHING,
4955 };
4956 
4957 #ifdef CONFIG_SOCK_CGROUP_DATA
__bpf_sk_cgroup_id(struct sock * sk)4958 static inline u64 __bpf_sk_cgroup_id(struct sock *sk)
4959 {
4960 	struct cgroup *cgrp;
4961 
4962 	sk = sk_to_full_sk(sk);
4963 	if (!sk || !sk_fullsock(sk))
4964 		return 0;
4965 
4966 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4967 	return cgroup_id(cgrp);
4968 }
4969 
BPF_CALL_1(bpf_skb_cgroup_id,const struct sk_buff *,skb)4970 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4971 {
4972 	return __bpf_sk_cgroup_id(skb->sk);
4973 }
4974 
4975 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4976 	.func           = bpf_skb_cgroup_id,
4977 	.gpl_only       = false,
4978 	.ret_type       = RET_INTEGER,
4979 	.arg1_type      = ARG_PTR_TO_CTX,
4980 };
4981 
__bpf_sk_ancestor_cgroup_id(struct sock * sk,int ancestor_level)4982 static inline u64 __bpf_sk_ancestor_cgroup_id(struct sock *sk,
4983 					      int ancestor_level)
4984 {
4985 	struct cgroup *ancestor;
4986 	struct cgroup *cgrp;
4987 
4988 	sk = sk_to_full_sk(sk);
4989 	if (!sk || !sk_fullsock(sk))
4990 		return 0;
4991 
4992 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4993 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
4994 	if (!ancestor)
4995 		return 0;
4996 
4997 	return cgroup_id(ancestor);
4998 }
4999 
BPF_CALL_2(bpf_skb_ancestor_cgroup_id,const struct sk_buff *,skb,int,ancestor_level)5000 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
5001 	   ancestor_level)
5002 {
5003 	return __bpf_sk_ancestor_cgroup_id(skb->sk, ancestor_level);
5004 }
5005 
5006 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
5007 	.func           = bpf_skb_ancestor_cgroup_id,
5008 	.gpl_only       = false,
5009 	.ret_type       = RET_INTEGER,
5010 	.arg1_type      = ARG_PTR_TO_CTX,
5011 	.arg2_type      = ARG_ANYTHING,
5012 };
5013 
BPF_CALL_1(bpf_sk_cgroup_id,struct sock *,sk)5014 BPF_CALL_1(bpf_sk_cgroup_id, struct sock *, sk)
5015 {
5016 	return __bpf_sk_cgroup_id(sk);
5017 }
5018 
5019 static const struct bpf_func_proto bpf_sk_cgroup_id_proto = {
5020 	.func           = bpf_sk_cgroup_id,
5021 	.gpl_only       = false,
5022 	.ret_type       = RET_INTEGER,
5023 	.arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5024 };
5025 
BPF_CALL_2(bpf_sk_ancestor_cgroup_id,struct sock *,sk,int,ancestor_level)5026 BPF_CALL_2(bpf_sk_ancestor_cgroup_id, struct sock *, sk, int, ancestor_level)
5027 {
5028 	return __bpf_sk_ancestor_cgroup_id(sk, ancestor_level);
5029 }
5030 
5031 static const struct bpf_func_proto bpf_sk_ancestor_cgroup_id_proto = {
5032 	.func           = bpf_sk_ancestor_cgroup_id,
5033 	.gpl_only       = false,
5034 	.ret_type       = RET_INTEGER,
5035 	.arg1_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5036 	.arg2_type      = ARG_ANYTHING,
5037 };
5038 #endif
5039 
bpf_xdp_copy(void * dst,const void * ctx,unsigned long off,unsigned long len)5040 static unsigned long bpf_xdp_copy(void *dst, const void *ctx,
5041 				  unsigned long off, unsigned long len)
5042 {
5043 	struct xdp_buff *xdp = (struct xdp_buff *)ctx;
5044 
5045 	bpf_xdp_copy_buf(xdp, off, dst, len, false);
5046 	return 0;
5047 }
5048 
BPF_CALL_5(bpf_xdp_event_output,struct xdp_buff *,xdp,struct bpf_map *,map,u64,flags,void *,meta,u64,meta_size)5049 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
5050 	   u64, flags, void *, meta, u64, meta_size)
5051 {
5052 	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
5053 
5054 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
5055 		return -EINVAL;
5056 
5057 	if (unlikely(!xdp || xdp_size > xdp_get_buff_len(xdp)))
5058 		return -EFAULT;
5059 
5060 	return bpf_event_output(map, flags, meta, meta_size, xdp,
5061 				xdp_size, bpf_xdp_copy);
5062 }
5063 
5064 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
5065 	.func		= bpf_xdp_event_output,
5066 	.gpl_only	= true,
5067 	.ret_type	= RET_INTEGER,
5068 	.arg1_type	= ARG_PTR_TO_CTX,
5069 	.arg2_type	= ARG_CONST_MAP_PTR,
5070 	.arg3_type	= ARG_ANYTHING,
5071 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5072 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
5073 };
5074 
5075 BTF_ID_LIST_SINGLE(bpf_xdp_output_btf_ids, struct, xdp_buff)
5076 
5077 const struct bpf_func_proto bpf_xdp_output_proto = {
5078 	.func		= bpf_xdp_event_output,
5079 	.gpl_only	= true,
5080 	.ret_type	= RET_INTEGER,
5081 	.arg1_type	= ARG_PTR_TO_BTF_ID,
5082 	.arg1_btf_id	= &bpf_xdp_output_btf_ids[0],
5083 	.arg2_type	= ARG_CONST_MAP_PTR,
5084 	.arg3_type	= ARG_ANYTHING,
5085 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5086 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
5087 };
5088 
BPF_CALL_1(bpf_get_socket_cookie,struct sk_buff *,skb)5089 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
5090 {
5091 	return skb->sk ? __sock_gen_cookie(skb->sk) : 0;
5092 }
5093 
5094 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
5095 	.func           = bpf_get_socket_cookie,
5096 	.gpl_only       = false,
5097 	.ret_type       = RET_INTEGER,
5098 	.arg1_type      = ARG_PTR_TO_CTX,
5099 };
5100 
BPF_CALL_1(bpf_get_socket_cookie_sock_addr,struct bpf_sock_addr_kern *,ctx)5101 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5102 {
5103 	return __sock_gen_cookie(ctx->sk);
5104 }
5105 
5106 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
5107 	.func		= bpf_get_socket_cookie_sock_addr,
5108 	.gpl_only	= false,
5109 	.ret_type	= RET_INTEGER,
5110 	.arg1_type	= ARG_PTR_TO_CTX,
5111 };
5112 
BPF_CALL_1(bpf_get_socket_cookie_sock,struct sock *,ctx)5113 BPF_CALL_1(bpf_get_socket_cookie_sock, struct sock *, ctx)
5114 {
5115 	return __sock_gen_cookie(ctx);
5116 }
5117 
5118 static const struct bpf_func_proto bpf_get_socket_cookie_sock_proto = {
5119 	.func		= bpf_get_socket_cookie_sock,
5120 	.gpl_only	= false,
5121 	.ret_type	= RET_INTEGER,
5122 	.arg1_type	= ARG_PTR_TO_CTX,
5123 };
5124 
BPF_CALL_1(bpf_get_socket_ptr_cookie,struct sock *,sk)5125 BPF_CALL_1(bpf_get_socket_ptr_cookie, struct sock *, sk)
5126 {
5127 	return sk ? sock_gen_cookie(sk) : 0;
5128 }
5129 
5130 const struct bpf_func_proto bpf_get_socket_ptr_cookie_proto = {
5131 	.func		= bpf_get_socket_ptr_cookie,
5132 	.gpl_only	= false,
5133 	.ret_type	= RET_INTEGER,
5134 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON | PTR_MAYBE_NULL,
5135 };
5136 
BPF_CALL_1(bpf_get_socket_cookie_sock_ops,struct bpf_sock_ops_kern *,ctx)5137 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5138 {
5139 	return __sock_gen_cookie(ctx->sk);
5140 }
5141 
5142 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
5143 	.func		= bpf_get_socket_cookie_sock_ops,
5144 	.gpl_only	= false,
5145 	.ret_type	= RET_INTEGER,
5146 	.arg1_type	= ARG_PTR_TO_CTX,
5147 };
5148 
__bpf_get_netns_cookie(struct sock * sk)5149 static u64 __bpf_get_netns_cookie(struct sock *sk)
5150 {
5151 	const struct net *net = sk ? sock_net(sk) : &init_net;
5152 
5153 	return net->net_cookie;
5154 }
5155 
BPF_CALL_1(bpf_get_netns_cookie,struct sk_buff *,skb)5156 BPF_CALL_1(bpf_get_netns_cookie, struct sk_buff *, skb)
5157 {
5158 	return __bpf_get_netns_cookie(skb && skb->sk ? skb->sk : NULL);
5159 }
5160 
5161 static const struct bpf_func_proto bpf_get_netns_cookie_proto = {
5162 	.func           = bpf_get_netns_cookie,
5163 	.ret_type       = RET_INTEGER,
5164 	.arg1_type      = ARG_PTR_TO_CTX_OR_NULL,
5165 };
5166 
BPF_CALL_1(bpf_get_netns_cookie_sock,struct sock *,ctx)5167 BPF_CALL_1(bpf_get_netns_cookie_sock, struct sock *, ctx)
5168 {
5169 	return __bpf_get_netns_cookie(ctx);
5170 }
5171 
5172 static const struct bpf_func_proto bpf_get_netns_cookie_sock_proto = {
5173 	.func		= bpf_get_netns_cookie_sock,
5174 	.gpl_only	= false,
5175 	.ret_type	= RET_INTEGER,
5176 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5177 };
5178 
BPF_CALL_1(bpf_get_netns_cookie_sock_addr,struct bpf_sock_addr_kern *,ctx)5179 BPF_CALL_1(bpf_get_netns_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
5180 {
5181 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5182 }
5183 
5184 static const struct bpf_func_proto bpf_get_netns_cookie_sock_addr_proto = {
5185 	.func		= bpf_get_netns_cookie_sock_addr,
5186 	.gpl_only	= false,
5187 	.ret_type	= RET_INTEGER,
5188 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5189 };
5190 
BPF_CALL_1(bpf_get_netns_cookie_sock_ops,struct bpf_sock_ops_kern *,ctx)5191 BPF_CALL_1(bpf_get_netns_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
5192 {
5193 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5194 }
5195 
5196 static const struct bpf_func_proto bpf_get_netns_cookie_sock_ops_proto = {
5197 	.func		= bpf_get_netns_cookie_sock_ops,
5198 	.gpl_only	= false,
5199 	.ret_type	= RET_INTEGER,
5200 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5201 };
5202 
BPF_CALL_1(bpf_get_netns_cookie_sk_msg,struct sk_msg *,ctx)5203 BPF_CALL_1(bpf_get_netns_cookie_sk_msg, struct sk_msg *, ctx)
5204 {
5205 	return __bpf_get_netns_cookie(ctx ? ctx->sk : NULL);
5206 }
5207 
5208 static const struct bpf_func_proto bpf_get_netns_cookie_sk_msg_proto = {
5209 	.func		= bpf_get_netns_cookie_sk_msg,
5210 	.gpl_only	= false,
5211 	.ret_type	= RET_INTEGER,
5212 	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
5213 };
5214 
BPF_CALL_1(bpf_get_socket_uid,struct sk_buff *,skb)5215 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
5216 {
5217 	struct sock *sk = sk_to_full_sk(skb->sk);
5218 	kuid_t kuid;
5219 
5220 	if (!sk || !sk_fullsock(sk))
5221 		return overflowuid;
5222 	kuid = sock_net_uid(sock_net(sk), sk);
5223 	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
5224 }
5225 
5226 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
5227 	.func           = bpf_get_socket_uid,
5228 	.gpl_only       = false,
5229 	.ret_type       = RET_INTEGER,
5230 	.arg1_type      = ARG_PTR_TO_CTX,
5231 };
5232 
sk_bpf_set_get_cb_flags(struct sock * sk,char * optval,bool getopt)5233 static int sk_bpf_set_get_cb_flags(struct sock *sk, char *optval, bool getopt)
5234 {
5235 	u32 sk_bpf_cb_flags;
5236 
5237 	if (getopt) {
5238 		*(u32 *)optval = sk->sk_bpf_cb_flags;
5239 		return 0;
5240 	}
5241 
5242 	sk_bpf_cb_flags = *(u32 *)optval;
5243 
5244 	if (sk_bpf_cb_flags & ~SK_BPF_CB_MASK)
5245 		return -EINVAL;
5246 
5247 	sk->sk_bpf_cb_flags = sk_bpf_cb_flags;
5248 
5249 	return 0;
5250 }
5251 
sol_socket_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5252 static int sol_socket_sockopt(struct sock *sk, int optname,
5253 			      char *optval, int *optlen,
5254 			      bool getopt)
5255 {
5256 	switch (optname) {
5257 	case SO_REUSEADDR:
5258 	case SO_SNDBUF:
5259 	case SO_RCVBUF:
5260 	case SO_KEEPALIVE:
5261 	case SO_PRIORITY:
5262 	case SO_REUSEPORT:
5263 	case SO_RCVLOWAT:
5264 	case SO_MARK:
5265 	case SO_MAX_PACING_RATE:
5266 	case SO_BINDTOIFINDEX:
5267 	case SO_TXREHASH:
5268 	case SK_BPF_CB_FLAGS:
5269 		if (*optlen != sizeof(int))
5270 			return -EINVAL;
5271 		break;
5272 	case SO_BINDTODEVICE:
5273 		break;
5274 	default:
5275 		return -EINVAL;
5276 	}
5277 
5278 	if (optname == SK_BPF_CB_FLAGS)
5279 		return sk_bpf_set_get_cb_flags(sk, optval, getopt);
5280 
5281 	if (getopt) {
5282 		if (optname == SO_BINDTODEVICE)
5283 			return -EINVAL;
5284 		return sk_getsockopt(sk, SOL_SOCKET, optname,
5285 				     KERNEL_SOCKPTR(optval),
5286 				     KERNEL_SOCKPTR(optlen));
5287 	}
5288 
5289 	return sk_setsockopt(sk, SOL_SOCKET, optname,
5290 			     KERNEL_SOCKPTR(optval), *optlen);
5291 }
5292 
bpf_sol_tcp_getsockopt(struct sock * sk,int optname,char * optval,int optlen)5293 static int bpf_sol_tcp_getsockopt(struct sock *sk, int optname,
5294 				  char *optval, int optlen)
5295 {
5296 	if (optlen != sizeof(int))
5297 		return -EINVAL;
5298 
5299 	switch (optname) {
5300 	case TCP_BPF_SOCK_OPS_CB_FLAGS: {
5301 		int cb_flags = tcp_sk(sk)->bpf_sock_ops_cb_flags;
5302 
5303 		memcpy(optval, &cb_flags, optlen);
5304 		break;
5305 	}
5306 	case TCP_BPF_RTO_MIN: {
5307 		int rto_min_us = jiffies_to_usecs(inet_csk(sk)->icsk_rto_min);
5308 
5309 		memcpy(optval, &rto_min_us, optlen);
5310 		break;
5311 	}
5312 	case TCP_BPF_DELACK_MAX: {
5313 		int delack_max_us = jiffies_to_usecs(inet_csk(sk)->icsk_delack_max);
5314 
5315 		memcpy(optval, &delack_max_us, optlen);
5316 		break;
5317 	}
5318 	default:
5319 		return -EINVAL;
5320 	}
5321 
5322 	return 0;
5323 }
5324 
bpf_sol_tcp_setsockopt(struct sock * sk,int optname,char * optval,int optlen)5325 static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
5326 				  char *optval, int optlen)
5327 {
5328 	struct tcp_sock *tp = tcp_sk(sk);
5329 	unsigned long timeout;
5330 	int val;
5331 
5332 	if (optlen != sizeof(int))
5333 		return -EINVAL;
5334 
5335 	val = *(int *)optval;
5336 
5337 	/* Only some options are supported */
5338 	switch (optname) {
5339 	case TCP_BPF_IW:
5340 		if (val <= 0 || tp->data_segs_out > tp->syn_data)
5341 			return -EINVAL;
5342 		tcp_snd_cwnd_set(tp, val);
5343 		break;
5344 	case TCP_BPF_SNDCWND_CLAMP:
5345 		if (val <= 0)
5346 			return -EINVAL;
5347 		tp->snd_cwnd_clamp = val;
5348 		tp->snd_ssthresh = val;
5349 		break;
5350 	case TCP_BPF_DELACK_MAX:
5351 		timeout = usecs_to_jiffies(val);
5352 		if (timeout > TCP_DELACK_MAX ||
5353 		    timeout < TCP_TIMEOUT_MIN)
5354 			return -EINVAL;
5355 		inet_csk(sk)->icsk_delack_max = timeout;
5356 		break;
5357 	case TCP_BPF_RTO_MIN:
5358 		timeout = usecs_to_jiffies(val);
5359 		if (timeout > TCP_RTO_MIN ||
5360 		    timeout < TCP_TIMEOUT_MIN)
5361 			return -EINVAL;
5362 		inet_csk(sk)->icsk_rto_min = timeout;
5363 		break;
5364 	case TCP_BPF_SOCK_OPS_CB_FLAGS:
5365 		if (val & ~(BPF_SOCK_OPS_ALL_CB_FLAGS))
5366 			return -EINVAL;
5367 		tp->bpf_sock_ops_cb_flags = val;
5368 		break;
5369 	default:
5370 		return -EINVAL;
5371 	}
5372 
5373 	return 0;
5374 }
5375 
sol_tcp_sockopt_congestion(struct sock * sk,char * optval,int * optlen,bool getopt)5376 static int sol_tcp_sockopt_congestion(struct sock *sk, char *optval,
5377 				      int *optlen, bool getopt)
5378 {
5379 	struct tcp_sock *tp;
5380 	int ret;
5381 
5382 	if (*optlen < 2)
5383 		return -EINVAL;
5384 
5385 	if (getopt) {
5386 		if (!inet_csk(sk)->icsk_ca_ops)
5387 			return -EINVAL;
5388 		/* BPF expects NULL-terminated tcp-cc string */
5389 		optval[--(*optlen)] = '\0';
5390 		return do_tcp_getsockopt(sk, SOL_TCP, TCP_CONGESTION,
5391 					 KERNEL_SOCKPTR(optval),
5392 					 KERNEL_SOCKPTR(optlen));
5393 	}
5394 
5395 	/* "cdg" is the only cc that alloc a ptr
5396 	 * in inet_csk_ca area.  The bpf-tcp-cc may
5397 	 * overwrite this ptr after switching to cdg.
5398 	 */
5399 	if (*optlen >= sizeof("cdg") - 1 && !strncmp("cdg", optval, *optlen))
5400 		return -ENOTSUPP;
5401 
5402 	/* It stops this looping
5403 	 *
5404 	 * .init => bpf_setsockopt(tcp_cc) => .init =>
5405 	 * bpf_setsockopt(tcp_cc)" => .init => ....
5406 	 *
5407 	 * The second bpf_setsockopt(tcp_cc) is not allowed
5408 	 * in order to break the loop when both .init
5409 	 * are the same bpf prog.
5410 	 *
5411 	 * This applies even the second bpf_setsockopt(tcp_cc)
5412 	 * does not cause a loop.  This limits only the first
5413 	 * '.init' can call bpf_setsockopt(TCP_CONGESTION) to
5414 	 * pick a fallback cc (eg. peer does not support ECN)
5415 	 * and the second '.init' cannot fallback to
5416 	 * another.
5417 	 */
5418 	tp = tcp_sk(sk);
5419 	if (tp->bpf_chg_cc_inprogress)
5420 		return -EBUSY;
5421 
5422 	tp->bpf_chg_cc_inprogress = 1;
5423 	ret = do_tcp_setsockopt(sk, SOL_TCP, TCP_CONGESTION,
5424 				KERNEL_SOCKPTR(optval), *optlen);
5425 	tp->bpf_chg_cc_inprogress = 0;
5426 	return ret;
5427 }
5428 
sol_tcp_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5429 static int sol_tcp_sockopt(struct sock *sk, int optname,
5430 			   char *optval, int *optlen,
5431 			   bool getopt)
5432 {
5433 	if (sk->sk_protocol != IPPROTO_TCP)
5434 		return -EINVAL;
5435 
5436 	switch (optname) {
5437 	case TCP_NODELAY:
5438 	case TCP_MAXSEG:
5439 	case TCP_KEEPIDLE:
5440 	case TCP_KEEPINTVL:
5441 	case TCP_KEEPCNT:
5442 	case TCP_SYNCNT:
5443 	case TCP_WINDOW_CLAMP:
5444 	case TCP_THIN_LINEAR_TIMEOUTS:
5445 	case TCP_USER_TIMEOUT:
5446 	case TCP_NOTSENT_LOWAT:
5447 	case TCP_SAVE_SYN:
5448 	case TCP_RTO_MAX_MS:
5449 		if (*optlen != sizeof(int))
5450 			return -EINVAL;
5451 		break;
5452 	case TCP_CONGESTION:
5453 		return sol_tcp_sockopt_congestion(sk, optval, optlen, getopt);
5454 	case TCP_SAVED_SYN:
5455 		if (*optlen < 1)
5456 			return -EINVAL;
5457 		break;
5458 	default:
5459 		if (getopt)
5460 			return bpf_sol_tcp_getsockopt(sk, optname, optval, *optlen);
5461 		return bpf_sol_tcp_setsockopt(sk, optname, optval, *optlen);
5462 	}
5463 
5464 	if (getopt) {
5465 		if (optname == TCP_SAVED_SYN) {
5466 			struct tcp_sock *tp = tcp_sk(sk);
5467 
5468 			if (!tp->saved_syn ||
5469 			    *optlen > tcp_saved_syn_len(tp->saved_syn))
5470 				return -EINVAL;
5471 			memcpy(optval, tp->saved_syn->data, *optlen);
5472 			/* It cannot free tp->saved_syn here because it
5473 			 * does not know if the user space still needs it.
5474 			 */
5475 			return 0;
5476 		}
5477 
5478 		return do_tcp_getsockopt(sk, SOL_TCP, optname,
5479 					 KERNEL_SOCKPTR(optval),
5480 					 KERNEL_SOCKPTR(optlen));
5481 	}
5482 
5483 	return do_tcp_setsockopt(sk, SOL_TCP, optname,
5484 				 KERNEL_SOCKPTR(optval), *optlen);
5485 }
5486 
sol_ip_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5487 static int sol_ip_sockopt(struct sock *sk, int optname,
5488 			  char *optval, int *optlen,
5489 			  bool getopt)
5490 {
5491 	if (sk->sk_family != AF_INET)
5492 		return -EINVAL;
5493 
5494 	switch (optname) {
5495 	case IP_TOS:
5496 		if (*optlen != sizeof(int))
5497 			return -EINVAL;
5498 		break;
5499 	default:
5500 		return -EINVAL;
5501 	}
5502 
5503 	if (getopt)
5504 		return do_ip_getsockopt(sk, SOL_IP, optname,
5505 					KERNEL_SOCKPTR(optval),
5506 					KERNEL_SOCKPTR(optlen));
5507 
5508 	return do_ip_setsockopt(sk, SOL_IP, optname,
5509 				KERNEL_SOCKPTR(optval), *optlen);
5510 }
5511 
sol_ipv6_sockopt(struct sock * sk,int optname,char * optval,int * optlen,bool getopt)5512 static int sol_ipv6_sockopt(struct sock *sk, int optname,
5513 			    char *optval, int *optlen,
5514 			    bool getopt)
5515 {
5516 	if (sk->sk_family != AF_INET6)
5517 		return -EINVAL;
5518 
5519 	switch (optname) {
5520 	case IPV6_TCLASS:
5521 	case IPV6_AUTOFLOWLABEL:
5522 		if (*optlen != sizeof(int))
5523 			return -EINVAL;
5524 		break;
5525 	default:
5526 		return -EINVAL;
5527 	}
5528 
5529 	if (getopt)
5530 		return ipv6_bpf_stub->ipv6_getsockopt(sk, SOL_IPV6, optname,
5531 						      KERNEL_SOCKPTR(optval),
5532 						      KERNEL_SOCKPTR(optlen));
5533 
5534 	return ipv6_bpf_stub->ipv6_setsockopt(sk, SOL_IPV6, optname,
5535 					      KERNEL_SOCKPTR(optval), *optlen);
5536 }
5537 
__bpf_setsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5538 static int __bpf_setsockopt(struct sock *sk, int level, int optname,
5539 			    char *optval, int optlen)
5540 {
5541 	if (!sk_fullsock(sk))
5542 		return -EINVAL;
5543 
5544 	if (level == SOL_SOCKET)
5545 		return sol_socket_sockopt(sk, optname, optval, &optlen, false);
5546 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5547 		return sol_ip_sockopt(sk, optname, optval, &optlen, false);
5548 	else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5549 		return sol_ipv6_sockopt(sk, optname, optval, &optlen, false);
5550 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5551 		return sol_tcp_sockopt(sk, optname, optval, &optlen, false);
5552 
5553 	return -EINVAL;
5554 }
5555 
is_locked_tcp_sock_ops(struct bpf_sock_ops_kern * bpf_sock)5556 static bool is_locked_tcp_sock_ops(struct bpf_sock_ops_kern *bpf_sock)
5557 {
5558 	return bpf_sock->op <= BPF_SOCK_OPS_WRITE_HDR_OPT_CB;
5559 }
5560 
_bpf_setsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5561 static int _bpf_setsockopt(struct sock *sk, int level, int optname,
5562 			   char *optval, int optlen)
5563 {
5564 	if (sk_fullsock(sk))
5565 		sock_owned_by_me(sk);
5566 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
5567 }
5568 
__bpf_getsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5569 static int __bpf_getsockopt(struct sock *sk, int level, int optname,
5570 			    char *optval, int optlen)
5571 {
5572 	int err, saved_optlen = optlen;
5573 
5574 	if (!sk_fullsock(sk)) {
5575 		err = -EINVAL;
5576 		goto done;
5577 	}
5578 
5579 	if (level == SOL_SOCKET)
5580 		err = sol_socket_sockopt(sk, optname, optval, &optlen, true);
5581 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP)
5582 		err = sol_tcp_sockopt(sk, optname, optval, &optlen, true);
5583 	else if (IS_ENABLED(CONFIG_INET) && level == SOL_IP)
5584 		err = sol_ip_sockopt(sk, optname, optval, &optlen, true);
5585 	else if (IS_ENABLED(CONFIG_IPV6) && level == SOL_IPV6)
5586 		err = sol_ipv6_sockopt(sk, optname, optval, &optlen, true);
5587 	else
5588 		err = -EINVAL;
5589 
5590 done:
5591 	if (err)
5592 		optlen = 0;
5593 	if (optlen < saved_optlen)
5594 		memset(optval + optlen, 0, saved_optlen - optlen);
5595 	return err;
5596 }
5597 
_bpf_getsockopt(struct sock * sk,int level,int optname,char * optval,int optlen)5598 static int _bpf_getsockopt(struct sock *sk, int level, int optname,
5599 			   char *optval, int optlen)
5600 {
5601 	if (sk_fullsock(sk))
5602 		sock_owned_by_me(sk);
5603 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
5604 }
5605 
BPF_CALL_5(bpf_sk_setsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5606 BPF_CALL_5(bpf_sk_setsockopt, struct sock *, sk, int, level,
5607 	   int, optname, char *, optval, int, optlen)
5608 {
5609 	return _bpf_setsockopt(sk, level, optname, optval, optlen);
5610 }
5611 
5612 const struct bpf_func_proto bpf_sk_setsockopt_proto = {
5613 	.func		= bpf_sk_setsockopt,
5614 	.gpl_only	= false,
5615 	.ret_type	= RET_INTEGER,
5616 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5617 	.arg2_type	= ARG_ANYTHING,
5618 	.arg3_type	= ARG_ANYTHING,
5619 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5620 	.arg5_type	= ARG_CONST_SIZE,
5621 };
5622 
BPF_CALL_5(bpf_sk_getsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5623 BPF_CALL_5(bpf_sk_getsockopt, struct sock *, sk, int, level,
5624 	   int, optname, char *, optval, int, optlen)
5625 {
5626 	return _bpf_getsockopt(sk, level, optname, optval, optlen);
5627 }
5628 
5629 const struct bpf_func_proto bpf_sk_getsockopt_proto = {
5630 	.func		= bpf_sk_getsockopt,
5631 	.gpl_only	= false,
5632 	.ret_type	= RET_INTEGER,
5633 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5634 	.arg2_type	= ARG_ANYTHING,
5635 	.arg3_type	= ARG_ANYTHING,
5636 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5637 	.arg5_type	= ARG_CONST_SIZE,
5638 };
5639 
BPF_CALL_5(bpf_unlocked_sk_setsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5640 BPF_CALL_5(bpf_unlocked_sk_setsockopt, struct sock *, sk, int, level,
5641 	   int, optname, char *, optval, int, optlen)
5642 {
5643 	return __bpf_setsockopt(sk, level, optname, optval, optlen);
5644 }
5645 
5646 const struct bpf_func_proto bpf_unlocked_sk_setsockopt_proto = {
5647 	.func		= bpf_unlocked_sk_setsockopt,
5648 	.gpl_only	= false,
5649 	.ret_type	= RET_INTEGER,
5650 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5651 	.arg2_type	= ARG_ANYTHING,
5652 	.arg3_type	= ARG_ANYTHING,
5653 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5654 	.arg5_type	= ARG_CONST_SIZE,
5655 };
5656 
BPF_CALL_5(bpf_unlocked_sk_getsockopt,struct sock *,sk,int,level,int,optname,char *,optval,int,optlen)5657 BPF_CALL_5(bpf_unlocked_sk_getsockopt, struct sock *, sk, int, level,
5658 	   int, optname, char *, optval, int, optlen)
5659 {
5660 	return __bpf_getsockopt(sk, level, optname, optval, optlen);
5661 }
5662 
5663 const struct bpf_func_proto bpf_unlocked_sk_getsockopt_proto = {
5664 	.func		= bpf_unlocked_sk_getsockopt,
5665 	.gpl_only	= false,
5666 	.ret_type	= RET_INTEGER,
5667 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
5668 	.arg2_type	= ARG_ANYTHING,
5669 	.arg3_type	= ARG_ANYTHING,
5670 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5671 	.arg5_type	= ARG_CONST_SIZE,
5672 };
5673 
BPF_CALL_5(bpf_sock_addr_setsockopt,struct bpf_sock_addr_kern *,ctx,int,level,int,optname,char *,optval,int,optlen)5674 BPF_CALL_5(bpf_sock_addr_setsockopt, struct bpf_sock_addr_kern *, ctx,
5675 	   int, level, int, optname, char *, optval, int, optlen)
5676 {
5677 	return _bpf_setsockopt(ctx->sk, level, optname, optval, optlen);
5678 }
5679 
5680 static const struct bpf_func_proto bpf_sock_addr_setsockopt_proto = {
5681 	.func		= bpf_sock_addr_setsockopt,
5682 	.gpl_only	= false,
5683 	.ret_type	= RET_INTEGER,
5684 	.arg1_type	= ARG_PTR_TO_CTX,
5685 	.arg2_type	= ARG_ANYTHING,
5686 	.arg3_type	= ARG_ANYTHING,
5687 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5688 	.arg5_type	= ARG_CONST_SIZE,
5689 };
5690 
BPF_CALL_5(bpf_sock_addr_getsockopt,struct bpf_sock_addr_kern *,ctx,int,level,int,optname,char *,optval,int,optlen)5691 BPF_CALL_5(bpf_sock_addr_getsockopt, struct bpf_sock_addr_kern *, ctx,
5692 	   int, level, int, optname, char *, optval, int, optlen)
5693 {
5694 	return _bpf_getsockopt(ctx->sk, level, optname, optval, optlen);
5695 }
5696 
5697 static const struct bpf_func_proto bpf_sock_addr_getsockopt_proto = {
5698 	.func		= bpf_sock_addr_getsockopt,
5699 	.gpl_only	= false,
5700 	.ret_type	= RET_INTEGER,
5701 	.arg1_type	= ARG_PTR_TO_CTX,
5702 	.arg2_type	= ARG_ANYTHING,
5703 	.arg3_type	= ARG_ANYTHING,
5704 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5705 	.arg5_type	= ARG_CONST_SIZE,
5706 };
5707 
BPF_CALL_5(bpf_sock_ops_setsockopt,struct bpf_sock_ops_kern *,bpf_sock,int,level,int,optname,char *,optval,int,optlen)5708 BPF_CALL_5(bpf_sock_ops_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
5709 	   int, level, int, optname, char *, optval, int, optlen)
5710 {
5711 	if (!is_locked_tcp_sock_ops(bpf_sock))
5712 		return -EOPNOTSUPP;
5713 
5714 	return _bpf_setsockopt(bpf_sock->sk, level, optname, optval, optlen);
5715 }
5716 
5717 static const struct bpf_func_proto bpf_sock_ops_setsockopt_proto = {
5718 	.func		= bpf_sock_ops_setsockopt,
5719 	.gpl_only	= false,
5720 	.ret_type	= RET_INTEGER,
5721 	.arg1_type	= ARG_PTR_TO_CTX,
5722 	.arg2_type	= ARG_ANYTHING,
5723 	.arg3_type	= ARG_ANYTHING,
5724 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5725 	.arg5_type	= ARG_CONST_SIZE,
5726 };
5727 
bpf_sock_ops_get_syn(struct bpf_sock_ops_kern * bpf_sock,int optname,const u8 ** start)5728 static int bpf_sock_ops_get_syn(struct bpf_sock_ops_kern *bpf_sock,
5729 				int optname, const u8 **start)
5730 {
5731 	struct sk_buff *syn_skb = bpf_sock->syn_skb;
5732 	const u8 *hdr_start;
5733 	int ret;
5734 
5735 	if (syn_skb) {
5736 		/* sk is a request_sock here */
5737 
5738 		if (optname == TCP_BPF_SYN) {
5739 			hdr_start = syn_skb->data;
5740 			ret = tcp_hdrlen(syn_skb);
5741 		} else if (optname == TCP_BPF_SYN_IP) {
5742 			hdr_start = skb_network_header(syn_skb);
5743 			ret = skb_network_header_len(syn_skb) +
5744 				tcp_hdrlen(syn_skb);
5745 		} else {
5746 			/* optname == TCP_BPF_SYN_MAC */
5747 			hdr_start = skb_mac_header(syn_skb);
5748 			ret = skb_mac_header_len(syn_skb) +
5749 				skb_network_header_len(syn_skb) +
5750 				tcp_hdrlen(syn_skb);
5751 		}
5752 	} else {
5753 		struct sock *sk = bpf_sock->sk;
5754 		struct saved_syn *saved_syn;
5755 
5756 		if (sk->sk_state == TCP_NEW_SYN_RECV)
5757 			/* synack retransmit. bpf_sock->syn_skb will
5758 			 * not be available.  It has to resort to
5759 			 * saved_syn (if it is saved).
5760 			 */
5761 			saved_syn = inet_reqsk(sk)->saved_syn;
5762 		else
5763 			saved_syn = tcp_sk(sk)->saved_syn;
5764 
5765 		if (!saved_syn)
5766 			return -ENOENT;
5767 
5768 		if (optname == TCP_BPF_SYN) {
5769 			hdr_start = saved_syn->data +
5770 				saved_syn->mac_hdrlen +
5771 				saved_syn->network_hdrlen;
5772 			ret = saved_syn->tcp_hdrlen;
5773 		} else if (optname == TCP_BPF_SYN_IP) {
5774 			hdr_start = saved_syn->data +
5775 				saved_syn->mac_hdrlen;
5776 			ret = saved_syn->network_hdrlen +
5777 				saved_syn->tcp_hdrlen;
5778 		} else {
5779 			/* optname == TCP_BPF_SYN_MAC */
5780 
5781 			/* TCP_SAVE_SYN may not have saved the mac hdr */
5782 			if (!saved_syn->mac_hdrlen)
5783 				return -ENOENT;
5784 
5785 			hdr_start = saved_syn->data;
5786 			ret = saved_syn->mac_hdrlen +
5787 				saved_syn->network_hdrlen +
5788 				saved_syn->tcp_hdrlen;
5789 		}
5790 	}
5791 
5792 	*start = hdr_start;
5793 	return ret;
5794 }
5795 
BPF_CALL_5(bpf_sock_ops_getsockopt,struct bpf_sock_ops_kern *,bpf_sock,int,level,int,optname,char *,optval,int,optlen)5796 BPF_CALL_5(bpf_sock_ops_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
5797 	   int, level, int, optname, char *, optval, int, optlen)
5798 {
5799 	if (!is_locked_tcp_sock_ops(bpf_sock))
5800 		return -EOPNOTSUPP;
5801 
5802 	if (IS_ENABLED(CONFIG_INET) && level == SOL_TCP &&
5803 	    optname >= TCP_BPF_SYN && optname <= TCP_BPF_SYN_MAC) {
5804 		int ret, copy_len = 0;
5805 		const u8 *start;
5806 
5807 		ret = bpf_sock_ops_get_syn(bpf_sock, optname, &start);
5808 		if (ret > 0) {
5809 			copy_len = ret;
5810 			if (optlen < copy_len) {
5811 				copy_len = optlen;
5812 				ret = -ENOSPC;
5813 			}
5814 
5815 			memcpy(optval, start, copy_len);
5816 		}
5817 
5818 		/* Zero out unused buffer at the end */
5819 		memset(optval + copy_len, 0, optlen - copy_len);
5820 
5821 		return ret;
5822 	}
5823 
5824 	return _bpf_getsockopt(bpf_sock->sk, level, optname, optval, optlen);
5825 }
5826 
5827 static const struct bpf_func_proto bpf_sock_ops_getsockopt_proto = {
5828 	.func		= bpf_sock_ops_getsockopt,
5829 	.gpl_only	= false,
5830 	.ret_type	= RET_INTEGER,
5831 	.arg1_type	= ARG_PTR_TO_CTX,
5832 	.arg2_type	= ARG_ANYTHING,
5833 	.arg3_type	= ARG_ANYTHING,
5834 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
5835 	.arg5_type	= ARG_CONST_SIZE,
5836 };
5837 
BPF_CALL_2(bpf_sock_ops_cb_flags_set,struct bpf_sock_ops_kern *,bpf_sock,int,argval)5838 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
5839 	   int, argval)
5840 {
5841 	struct sock *sk = bpf_sock->sk;
5842 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
5843 
5844 	if (!is_locked_tcp_sock_ops(bpf_sock))
5845 		return -EOPNOTSUPP;
5846 
5847 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
5848 		return -EINVAL;
5849 
5850 	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
5851 
5852 	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
5853 }
5854 
5855 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
5856 	.func		= bpf_sock_ops_cb_flags_set,
5857 	.gpl_only	= false,
5858 	.ret_type	= RET_INTEGER,
5859 	.arg1_type	= ARG_PTR_TO_CTX,
5860 	.arg2_type	= ARG_ANYTHING,
5861 };
5862 
5863 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
5864 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
5865 
BPF_CALL_3(bpf_bind,struct bpf_sock_addr_kern *,ctx,struct sockaddr *,addr,int,addr_len)5866 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
5867 	   int, addr_len)
5868 {
5869 #ifdef CONFIG_INET
5870 	struct sock *sk = ctx->sk;
5871 	u32 flags = BIND_FROM_BPF;
5872 	int err;
5873 
5874 	err = -EINVAL;
5875 	if (addr_len < offsetofend(struct sockaddr, sa_family))
5876 		return err;
5877 	if (addr->sa_family == AF_INET) {
5878 		if (addr_len < sizeof(struct sockaddr_in))
5879 			return err;
5880 		if (((struct sockaddr_in *)addr)->sin_port == htons(0))
5881 			flags |= BIND_FORCE_ADDRESS_NO_PORT;
5882 		return __inet_bind(sk, addr, addr_len, flags);
5883 #if IS_ENABLED(CONFIG_IPV6)
5884 	} else if (addr->sa_family == AF_INET6) {
5885 		if (addr_len < SIN6_LEN_RFC2133)
5886 			return err;
5887 		if (((struct sockaddr_in6 *)addr)->sin6_port == htons(0))
5888 			flags |= BIND_FORCE_ADDRESS_NO_PORT;
5889 		/* ipv6_bpf_stub cannot be NULL, since it's called from
5890 		 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
5891 		 */
5892 		return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, flags);
5893 #endif /* CONFIG_IPV6 */
5894 	}
5895 #endif /* CONFIG_INET */
5896 
5897 	return -EAFNOSUPPORT;
5898 }
5899 
5900 static const struct bpf_func_proto bpf_bind_proto = {
5901 	.func		= bpf_bind,
5902 	.gpl_only	= false,
5903 	.ret_type	= RET_INTEGER,
5904 	.arg1_type	= ARG_PTR_TO_CTX,
5905 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
5906 	.arg3_type	= ARG_CONST_SIZE,
5907 };
5908 
5909 #ifdef CONFIG_XFRM
5910 
5911 #if (IS_BUILTIN(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) || \
5912     (IS_MODULE(CONFIG_XFRM_INTERFACE) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
5913 
5914 struct metadata_dst __percpu *xfrm_bpf_md_dst;
5915 EXPORT_SYMBOL_GPL(xfrm_bpf_md_dst);
5916 
5917 #endif
5918 
BPF_CALL_5(bpf_skb_get_xfrm_state,struct sk_buff *,skb,u32,index,struct bpf_xfrm_state *,to,u32,size,u64,flags)5919 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
5920 	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
5921 {
5922 	const struct sec_path *sp = skb_sec_path(skb);
5923 	const struct xfrm_state *x;
5924 
5925 	if (!sp || unlikely(index >= sp->len || flags))
5926 		goto err_clear;
5927 
5928 	x = sp->xvec[index];
5929 
5930 	if (unlikely(size != sizeof(struct bpf_xfrm_state)))
5931 		goto err_clear;
5932 
5933 	to->reqid = x->props.reqid;
5934 	to->spi = x->id.spi;
5935 	to->family = x->props.family;
5936 	to->ext = 0;
5937 
5938 	if (to->family == AF_INET6) {
5939 		memcpy(to->remote_ipv6, x->props.saddr.a6,
5940 		       sizeof(to->remote_ipv6));
5941 	} else {
5942 		to->remote_ipv4 = x->props.saddr.a4;
5943 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
5944 	}
5945 
5946 	return 0;
5947 err_clear:
5948 	memset(to, 0, size);
5949 	return -EINVAL;
5950 }
5951 
5952 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
5953 	.func		= bpf_skb_get_xfrm_state,
5954 	.gpl_only	= false,
5955 	.ret_type	= RET_INTEGER,
5956 	.arg1_type	= ARG_PTR_TO_CTX,
5957 	.arg2_type	= ARG_ANYTHING,
5958 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
5959 	.arg4_type	= ARG_CONST_SIZE,
5960 	.arg5_type	= ARG_ANYTHING,
5961 };
5962 #endif
5963 
5964 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
bpf_fib_set_fwd_params(struct bpf_fib_lookup * params,u32 mtu)5965 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params, u32 mtu)
5966 {
5967 	params->h_vlan_TCI = 0;
5968 	params->h_vlan_proto = 0;
5969 	if (mtu)
5970 		params->mtu_result = mtu; /* union with tot_len */
5971 
5972 	return 0;
5973 }
5974 #endif
5975 
5976 #if IS_ENABLED(CONFIG_INET)
bpf_ipv4_fib_lookup(struct net * net,struct bpf_fib_lookup * params,u32 flags,bool check_mtu)5977 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
5978 			       u32 flags, bool check_mtu)
5979 {
5980 	struct fib_nh_common *nhc;
5981 	struct in_device *in_dev;
5982 	struct neighbour *neigh;
5983 	struct net_device *dev;
5984 	struct fib_result res;
5985 	struct flowi4 fl4;
5986 	u32 mtu = 0;
5987 	int err;
5988 
5989 	dev = dev_get_by_index_rcu(net, params->ifindex);
5990 	if (unlikely(!dev))
5991 		return -ENODEV;
5992 
5993 	/* verify forwarding is enabled on this interface */
5994 	in_dev = __in_dev_get_rcu(dev);
5995 	if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
5996 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
5997 
5998 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
5999 		fl4.flowi4_iif = 1;
6000 		fl4.flowi4_oif = params->ifindex;
6001 	} else {
6002 		fl4.flowi4_iif = params->ifindex;
6003 		fl4.flowi4_oif = 0;
6004 	}
6005 	fl4.flowi4_tos = params->tos & INET_DSCP_MASK;
6006 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
6007 	fl4.flowi4_flags = 0;
6008 
6009 	fl4.flowi4_proto = params->l4_protocol;
6010 	fl4.daddr = params->ipv4_dst;
6011 	fl4.saddr = params->ipv4_src;
6012 	fl4.fl4_sport = params->sport;
6013 	fl4.fl4_dport = params->dport;
6014 	fl4.flowi4_multipath_hash = 0;
6015 
6016 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
6017 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
6018 		struct fib_table *tb;
6019 
6020 		if (flags & BPF_FIB_LOOKUP_TBID) {
6021 			tbid = params->tbid;
6022 			/* zero out for vlan output */
6023 			params->tbid = 0;
6024 		}
6025 
6026 		tb = fib_get_table(net, tbid);
6027 		if (unlikely(!tb))
6028 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6029 
6030 		err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
6031 	} else {
6032 		if (flags & BPF_FIB_LOOKUP_MARK)
6033 			fl4.flowi4_mark = params->mark;
6034 		else
6035 			fl4.flowi4_mark = 0;
6036 		fl4.flowi4_secid = 0;
6037 		fl4.flowi4_tun_key.tun_id = 0;
6038 		fl4.flowi4_uid = sock_net_uid(net, NULL);
6039 
6040 		err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
6041 	}
6042 
6043 	if (err) {
6044 		/* map fib lookup errors to RTN_ type */
6045 		if (err == -EINVAL)
6046 			return BPF_FIB_LKUP_RET_BLACKHOLE;
6047 		if (err == -EHOSTUNREACH)
6048 			return BPF_FIB_LKUP_RET_UNREACHABLE;
6049 		if (err == -EACCES)
6050 			return BPF_FIB_LKUP_RET_PROHIBIT;
6051 
6052 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6053 	}
6054 
6055 	if (res.type != RTN_UNICAST)
6056 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6057 
6058 	if (fib_info_num_path(res.fi) > 1)
6059 		fib_select_path(net, &res, &fl4, NULL);
6060 
6061 	if (check_mtu) {
6062 		mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
6063 		if (params->tot_len > mtu) {
6064 			params->mtu_result = mtu; /* union with tot_len */
6065 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
6066 		}
6067 	}
6068 
6069 	nhc = res.nhc;
6070 
6071 	/* do not handle lwt encaps right now */
6072 	if (nhc->nhc_lwtstate)
6073 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6074 
6075 	dev = nhc->nhc_dev;
6076 
6077 	params->rt_metric = res.fi->fib_priority;
6078 	params->ifindex = dev->ifindex;
6079 
6080 	if (flags & BPF_FIB_LOOKUP_SRC)
6081 		params->ipv4_src = fib_result_prefsrc(net, &res);
6082 
6083 	/* xdp and cls_bpf programs are run in RCU-bh so
6084 	 * rcu_read_lock_bh is not needed here
6085 	 */
6086 	if (likely(nhc->nhc_gw_family != AF_INET6)) {
6087 		if (nhc->nhc_gw_family)
6088 			params->ipv4_dst = nhc->nhc_gw.ipv4;
6089 	} else {
6090 		struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
6091 
6092 		params->family = AF_INET6;
6093 		*dst = nhc->nhc_gw.ipv6;
6094 	}
6095 
6096 	if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6097 		goto set_fwd_params;
6098 
6099 	if (likely(nhc->nhc_gw_family != AF_INET6))
6100 		neigh = __ipv4_neigh_lookup_noref(dev,
6101 						  (__force u32)params->ipv4_dst);
6102 	else
6103 		neigh = __ipv6_neigh_lookup_noref_stub(dev, params->ipv6_dst);
6104 
6105 	if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6106 		return BPF_FIB_LKUP_RET_NO_NEIGH;
6107 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
6108 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6109 
6110 set_fwd_params:
6111 	return bpf_fib_set_fwd_params(params, mtu);
6112 }
6113 #endif
6114 
6115 #if IS_ENABLED(CONFIG_IPV6)
bpf_ipv6_fib_lookup(struct net * net,struct bpf_fib_lookup * params,u32 flags,bool check_mtu)6116 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
6117 			       u32 flags, bool check_mtu)
6118 {
6119 	struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
6120 	struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
6121 	struct fib6_result res = {};
6122 	struct neighbour *neigh;
6123 	struct net_device *dev;
6124 	struct inet6_dev *idev;
6125 	struct flowi6 fl6;
6126 	int strict = 0;
6127 	int oif, err;
6128 	u32 mtu = 0;
6129 
6130 	/* link local addresses are never forwarded */
6131 	if (rt6_need_strict(dst) || rt6_need_strict(src))
6132 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6133 
6134 	dev = dev_get_by_index_rcu(net, params->ifindex);
6135 	if (unlikely(!dev))
6136 		return -ENODEV;
6137 
6138 	idev = __in6_dev_get_safely(dev);
6139 	if (unlikely(!idev || !READ_ONCE(idev->cnf.forwarding)))
6140 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
6141 
6142 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
6143 		fl6.flowi6_iif = 1;
6144 		oif = fl6.flowi6_oif = params->ifindex;
6145 	} else {
6146 		oif = fl6.flowi6_iif = params->ifindex;
6147 		fl6.flowi6_oif = 0;
6148 		strict = RT6_LOOKUP_F_HAS_SADDR;
6149 	}
6150 	fl6.flowlabel = params->flowinfo;
6151 	fl6.flowi6_scope = 0;
6152 	fl6.flowi6_flags = 0;
6153 	fl6.mp_hash = 0;
6154 
6155 	fl6.flowi6_proto = params->l4_protocol;
6156 	fl6.daddr = *dst;
6157 	fl6.saddr = *src;
6158 	fl6.fl6_sport = params->sport;
6159 	fl6.fl6_dport = params->dport;
6160 
6161 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
6162 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
6163 		struct fib6_table *tb;
6164 
6165 		if (flags & BPF_FIB_LOOKUP_TBID) {
6166 			tbid = params->tbid;
6167 			/* zero out for vlan output */
6168 			params->tbid = 0;
6169 		}
6170 
6171 		tb = ipv6_stub->fib6_get_table(net, tbid);
6172 		if (unlikely(!tb))
6173 			return BPF_FIB_LKUP_RET_NOT_FWDED;
6174 
6175 		err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
6176 						   strict);
6177 	} else {
6178 		if (flags & BPF_FIB_LOOKUP_MARK)
6179 			fl6.flowi6_mark = params->mark;
6180 		else
6181 			fl6.flowi6_mark = 0;
6182 		fl6.flowi6_secid = 0;
6183 		fl6.flowi6_tun_key.tun_id = 0;
6184 		fl6.flowi6_uid = sock_net_uid(net, NULL);
6185 
6186 		err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
6187 	}
6188 
6189 	if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
6190 		     res.f6i == net->ipv6.fib6_null_entry))
6191 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6192 
6193 	switch (res.fib6_type) {
6194 	/* only unicast is forwarded */
6195 	case RTN_UNICAST:
6196 		break;
6197 	case RTN_BLACKHOLE:
6198 		return BPF_FIB_LKUP_RET_BLACKHOLE;
6199 	case RTN_UNREACHABLE:
6200 		return BPF_FIB_LKUP_RET_UNREACHABLE;
6201 	case RTN_PROHIBIT:
6202 		return BPF_FIB_LKUP_RET_PROHIBIT;
6203 	default:
6204 		return BPF_FIB_LKUP_RET_NOT_FWDED;
6205 	}
6206 
6207 	ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
6208 				    fl6.flowi6_oif != 0, NULL, strict);
6209 
6210 	if (check_mtu) {
6211 		mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
6212 		if (params->tot_len > mtu) {
6213 			params->mtu_result = mtu; /* union with tot_len */
6214 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
6215 		}
6216 	}
6217 
6218 	if (res.nh->fib_nh_lws)
6219 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
6220 
6221 	if (res.nh->fib_nh_gw_family)
6222 		*dst = res.nh->fib_nh_gw6;
6223 
6224 	dev = res.nh->fib_nh_dev;
6225 	params->rt_metric = res.f6i->fib6_metric;
6226 	params->ifindex = dev->ifindex;
6227 
6228 	if (flags & BPF_FIB_LOOKUP_SRC) {
6229 		if (res.f6i->fib6_prefsrc.plen) {
6230 			*src = res.f6i->fib6_prefsrc.addr;
6231 		} else {
6232 			err = ipv6_bpf_stub->ipv6_dev_get_saddr(net, dev,
6233 								&fl6.daddr, 0,
6234 								src);
6235 			if (err)
6236 				return BPF_FIB_LKUP_RET_NO_SRC_ADDR;
6237 		}
6238 	}
6239 
6240 	if (flags & BPF_FIB_LOOKUP_SKIP_NEIGH)
6241 		goto set_fwd_params;
6242 
6243 	/* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
6244 	 * not needed here.
6245 	 */
6246 	neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
6247 	if (!neigh || !(READ_ONCE(neigh->nud_state) & NUD_VALID))
6248 		return BPF_FIB_LKUP_RET_NO_NEIGH;
6249 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
6250 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
6251 
6252 set_fwd_params:
6253 	return bpf_fib_set_fwd_params(params, mtu);
6254 }
6255 #endif
6256 
6257 #define BPF_FIB_LOOKUP_MASK (BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT | \
6258 			     BPF_FIB_LOOKUP_SKIP_NEIGH | BPF_FIB_LOOKUP_TBID | \
6259 			     BPF_FIB_LOOKUP_SRC | BPF_FIB_LOOKUP_MARK)
6260 
BPF_CALL_4(bpf_xdp_fib_lookup,struct xdp_buff *,ctx,struct bpf_fib_lookup *,params,int,plen,u32,flags)6261 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
6262 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
6263 {
6264 	if (plen < sizeof(*params))
6265 		return -EINVAL;
6266 
6267 	if (flags & ~BPF_FIB_LOOKUP_MASK)
6268 		return -EINVAL;
6269 
6270 	switch (params->family) {
6271 #if IS_ENABLED(CONFIG_INET)
6272 	case AF_INET:
6273 		return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
6274 					   flags, true);
6275 #endif
6276 #if IS_ENABLED(CONFIG_IPV6)
6277 	case AF_INET6:
6278 		return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
6279 					   flags, true);
6280 #endif
6281 	}
6282 	return -EAFNOSUPPORT;
6283 }
6284 
6285 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
6286 	.func		= bpf_xdp_fib_lookup,
6287 	.gpl_only	= true,
6288 	.ret_type	= RET_INTEGER,
6289 	.arg1_type      = ARG_PTR_TO_CTX,
6290 	.arg2_type      = ARG_PTR_TO_MEM,
6291 	.arg3_type      = ARG_CONST_SIZE,
6292 	.arg4_type	= ARG_ANYTHING,
6293 };
6294 
BPF_CALL_4(bpf_skb_fib_lookup,struct sk_buff *,skb,struct bpf_fib_lookup *,params,int,plen,u32,flags)6295 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
6296 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
6297 {
6298 	struct net *net = dev_net(skb->dev);
6299 	int rc = -EAFNOSUPPORT;
6300 	bool check_mtu = false;
6301 
6302 	if (plen < sizeof(*params))
6303 		return -EINVAL;
6304 
6305 	if (flags & ~BPF_FIB_LOOKUP_MASK)
6306 		return -EINVAL;
6307 
6308 	if (params->tot_len)
6309 		check_mtu = true;
6310 
6311 	switch (params->family) {
6312 #if IS_ENABLED(CONFIG_INET)
6313 	case AF_INET:
6314 		rc = bpf_ipv4_fib_lookup(net, params, flags, check_mtu);
6315 		break;
6316 #endif
6317 #if IS_ENABLED(CONFIG_IPV6)
6318 	case AF_INET6:
6319 		rc = bpf_ipv6_fib_lookup(net, params, flags, check_mtu);
6320 		break;
6321 #endif
6322 	}
6323 
6324 	if (rc == BPF_FIB_LKUP_RET_SUCCESS && !check_mtu) {
6325 		struct net_device *dev;
6326 
6327 		/* When tot_len isn't provided by user, check skb
6328 		 * against MTU of FIB lookup resulting net_device
6329 		 */
6330 		dev = dev_get_by_index_rcu(net, params->ifindex);
6331 		if (!is_skb_forwardable(dev, skb))
6332 			rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
6333 
6334 		params->mtu_result = dev->mtu; /* union with tot_len */
6335 	}
6336 
6337 	return rc;
6338 }
6339 
6340 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
6341 	.func		= bpf_skb_fib_lookup,
6342 	.gpl_only	= true,
6343 	.ret_type	= RET_INTEGER,
6344 	.arg1_type      = ARG_PTR_TO_CTX,
6345 	.arg2_type      = ARG_PTR_TO_MEM,
6346 	.arg3_type      = ARG_CONST_SIZE,
6347 	.arg4_type	= ARG_ANYTHING,
6348 };
6349 
__dev_via_ifindex(struct net_device * dev_curr,u32 ifindex)6350 static struct net_device *__dev_via_ifindex(struct net_device *dev_curr,
6351 					    u32 ifindex)
6352 {
6353 	struct net *netns = dev_net(dev_curr);
6354 
6355 	/* Non-redirect use-cases can use ifindex=0 and save ifindex lookup */
6356 	if (ifindex == 0)
6357 		return dev_curr;
6358 
6359 	return dev_get_by_index_rcu(netns, ifindex);
6360 }
6361 
BPF_CALL_5(bpf_skb_check_mtu,struct sk_buff *,skb,u32,ifindex,u32 *,mtu_len,s32,len_diff,u64,flags)6362 BPF_CALL_5(bpf_skb_check_mtu, struct sk_buff *, skb,
6363 	   u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6364 {
6365 	int ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6366 	struct net_device *dev = skb->dev;
6367 	int mtu, dev_len, skb_len;
6368 
6369 	if (unlikely(flags & ~(BPF_MTU_CHK_SEGS)))
6370 		return -EINVAL;
6371 	if (unlikely(flags & BPF_MTU_CHK_SEGS && (len_diff || *mtu_len)))
6372 		return -EINVAL;
6373 
6374 	dev = __dev_via_ifindex(dev, ifindex);
6375 	if (unlikely(!dev))
6376 		return -ENODEV;
6377 
6378 	mtu = READ_ONCE(dev->mtu);
6379 	dev_len = mtu + dev->hard_header_len;
6380 
6381 	/* If set use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6382 	skb_len = *mtu_len ? *mtu_len + dev->hard_header_len : skb->len;
6383 
6384 	skb_len += len_diff; /* minus result pass check */
6385 	if (skb_len <= dev_len) {
6386 		ret = BPF_MTU_CHK_RET_SUCCESS;
6387 		goto out;
6388 	}
6389 	/* At this point, skb->len exceed MTU, but as it include length of all
6390 	 * segments, it can still be below MTU.  The SKB can possibly get
6391 	 * re-segmented in transmit path (see validate_xmit_skb).  Thus, user
6392 	 * must choose if segs are to be MTU checked.
6393 	 */
6394 	if (skb_is_gso(skb)) {
6395 		ret = BPF_MTU_CHK_RET_SUCCESS;
6396 		if (flags & BPF_MTU_CHK_SEGS &&
6397 		    !skb_gso_validate_network_len(skb, mtu))
6398 			ret = BPF_MTU_CHK_RET_SEGS_TOOBIG;
6399 	}
6400 out:
6401 	*mtu_len = mtu;
6402 	return ret;
6403 }
6404 
BPF_CALL_5(bpf_xdp_check_mtu,struct xdp_buff *,xdp,u32,ifindex,u32 *,mtu_len,s32,len_diff,u64,flags)6405 BPF_CALL_5(bpf_xdp_check_mtu, struct xdp_buff *, xdp,
6406 	   u32, ifindex, u32 *, mtu_len, s32, len_diff, u64, flags)
6407 {
6408 	struct net_device *dev = xdp->rxq->dev;
6409 	int xdp_len = xdp->data_end - xdp->data;
6410 	int ret = BPF_MTU_CHK_RET_SUCCESS;
6411 	int mtu, dev_len;
6412 
6413 	/* XDP variant doesn't support multi-buffer segment check (yet) */
6414 	if (unlikely(flags))
6415 		return -EINVAL;
6416 
6417 	dev = __dev_via_ifindex(dev, ifindex);
6418 	if (unlikely(!dev))
6419 		return -ENODEV;
6420 
6421 	mtu = READ_ONCE(dev->mtu);
6422 	dev_len = mtu + dev->hard_header_len;
6423 
6424 	/* Use *mtu_len as input, L3 as iph->tot_len (like fib_lookup) */
6425 	if (*mtu_len)
6426 		xdp_len = *mtu_len + dev->hard_header_len;
6427 
6428 	xdp_len += len_diff; /* minus result pass check */
6429 	if (xdp_len > dev_len)
6430 		ret = BPF_MTU_CHK_RET_FRAG_NEEDED;
6431 
6432 	*mtu_len = mtu;
6433 	return ret;
6434 }
6435 
6436 static const struct bpf_func_proto bpf_skb_check_mtu_proto = {
6437 	.func		= bpf_skb_check_mtu,
6438 	.gpl_only	= true,
6439 	.ret_type	= RET_INTEGER,
6440 	.arg1_type      = ARG_PTR_TO_CTX,
6441 	.arg2_type      = ARG_ANYTHING,
6442 	.arg3_type      = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_WRITE | MEM_ALIGNED,
6443 	.arg3_size	= sizeof(u32),
6444 	.arg4_type      = ARG_ANYTHING,
6445 	.arg5_type      = ARG_ANYTHING,
6446 };
6447 
6448 static const struct bpf_func_proto bpf_xdp_check_mtu_proto = {
6449 	.func		= bpf_xdp_check_mtu,
6450 	.gpl_only	= true,
6451 	.ret_type	= RET_INTEGER,
6452 	.arg1_type      = ARG_PTR_TO_CTX,
6453 	.arg2_type      = ARG_ANYTHING,
6454 	.arg3_type      = ARG_PTR_TO_FIXED_SIZE_MEM | MEM_WRITE | MEM_ALIGNED,
6455 	.arg3_size	= sizeof(u32),
6456 	.arg4_type      = ARG_ANYTHING,
6457 	.arg5_type      = ARG_ANYTHING,
6458 };
6459 
6460 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
bpf_push_seg6_encap(struct sk_buff * skb,u32 type,void * hdr,u32 len)6461 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
6462 {
6463 	int err;
6464 	struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
6465 
6466 	if (!seg6_validate_srh(srh, len, false))
6467 		return -EINVAL;
6468 
6469 	switch (type) {
6470 	case BPF_LWT_ENCAP_SEG6_INLINE:
6471 		if (skb->protocol != htons(ETH_P_IPV6))
6472 			return -EBADMSG;
6473 
6474 		err = seg6_do_srh_inline(skb, srh);
6475 		break;
6476 	case BPF_LWT_ENCAP_SEG6:
6477 		skb_reset_inner_headers(skb);
6478 		skb->encapsulation = 1;
6479 		err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
6480 		break;
6481 	default:
6482 		return -EINVAL;
6483 	}
6484 
6485 	bpf_compute_data_pointers(skb);
6486 	if (err)
6487 		return err;
6488 
6489 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
6490 
6491 	return seg6_lookup_nexthop(skb, NULL, 0);
6492 }
6493 #endif /* CONFIG_IPV6_SEG6_BPF */
6494 
6495 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
bpf_push_ip_encap(struct sk_buff * skb,void * hdr,u32 len,bool ingress)6496 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
6497 			     bool ingress)
6498 {
6499 	return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
6500 }
6501 #endif
6502 
BPF_CALL_4(bpf_lwt_in_push_encap,struct sk_buff *,skb,u32,type,void *,hdr,u32,len)6503 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
6504 	   u32, len)
6505 {
6506 	switch (type) {
6507 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6508 	case BPF_LWT_ENCAP_SEG6:
6509 	case BPF_LWT_ENCAP_SEG6_INLINE:
6510 		return bpf_push_seg6_encap(skb, type, hdr, len);
6511 #endif
6512 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6513 	case BPF_LWT_ENCAP_IP:
6514 		return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
6515 #endif
6516 	default:
6517 		return -EINVAL;
6518 	}
6519 }
6520 
BPF_CALL_4(bpf_lwt_xmit_push_encap,struct sk_buff *,skb,u32,type,void *,hdr,u32,len)6521 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
6522 	   void *, hdr, u32, len)
6523 {
6524 	switch (type) {
6525 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
6526 	case BPF_LWT_ENCAP_IP:
6527 		return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
6528 #endif
6529 	default:
6530 		return -EINVAL;
6531 	}
6532 }
6533 
6534 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
6535 	.func		= bpf_lwt_in_push_encap,
6536 	.gpl_only	= false,
6537 	.ret_type	= RET_INTEGER,
6538 	.arg1_type	= ARG_PTR_TO_CTX,
6539 	.arg2_type	= ARG_ANYTHING,
6540 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6541 	.arg4_type	= ARG_CONST_SIZE
6542 };
6543 
6544 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
6545 	.func		= bpf_lwt_xmit_push_encap,
6546 	.gpl_only	= false,
6547 	.ret_type	= RET_INTEGER,
6548 	.arg1_type	= ARG_PTR_TO_CTX,
6549 	.arg2_type	= ARG_ANYTHING,
6550 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6551 	.arg4_type	= ARG_CONST_SIZE
6552 };
6553 
6554 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
BPF_CALL_4(bpf_lwt_seg6_store_bytes,struct sk_buff *,skb,u32,offset,const void *,from,u32,len)6555 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
6556 	   const void *, from, u32, len)
6557 {
6558 	struct seg6_bpf_srh_state *srh_state =
6559 		this_cpu_ptr(&seg6_bpf_srh_states);
6560 	struct ipv6_sr_hdr *srh = srh_state->srh;
6561 	void *srh_tlvs, *srh_end, *ptr;
6562 	int srhoff = 0;
6563 
6564 	lockdep_assert_held(&srh_state->bh_lock);
6565 	if (srh == NULL)
6566 		return -EINVAL;
6567 
6568 	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
6569 	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
6570 
6571 	ptr = skb->data + offset;
6572 	if (ptr >= srh_tlvs && ptr + len <= srh_end)
6573 		srh_state->valid = false;
6574 	else if (ptr < (void *)&srh->flags ||
6575 		 ptr + len > (void *)&srh->segments)
6576 		return -EFAULT;
6577 
6578 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
6579 		return -EFAULT;
6580 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
6581 		return -EINVAL;
6582 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6583 
6584 	memcpy(skb->data + offset, from, len);
6585 	return 0;
6586 }
6587 
6588 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
6589 	.func		= bpf_lwt_seg6_store_bytes,
6590 	.gpl_only	= false,
6591 	.ret_type	= RET_INTEGER,
6592 	.arg1_type	= ARG_PTR_TO_CTX,
6593 	.arg2_type	= ARG_ANYTHING,
6594 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6595 	.arg4_type	= ARG_CONST_SIZE
6596 };
6597 
bpf_update_srh_state(struct sk_buff * skb)6598 static void bpf_update_srh_state(struct sk_buff *skb)
6599 {
6600 	struct seg6_bpf_srh_state *srh_state =
6601 		this_cpu_ptr(&seg6_bpf_srh_states);
6602 	int srhoff = 0;
6603 
6604 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
6605 		srh_state->srh = NULL;
6606 	} else {
6607 		srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6608 		srh_state->hdrlen = srh_state->srh->hdrlen << 3;
6609 		srh_state->valid = true;
6610 	}
6611 }
6612 
BPF_CALL_4(bpf_lwt_seg6_action,struct sk_buff *,skb,u32,action,void *,param,u32,param_len)6613 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
6614 	   u32, action, void *, param, u32, param_len)
6615 {
6616 	struct seg6_bpf_srh_state *srh_state =
6617 		this_cpu_ptr(&seg6_bpf_srh_states);
6618 	int hdroff = 0;
6619 	int err;
6620 
6621 	lockdep_assert_held(&srh_state->bh_lock);
6622 	switch (action) {
6623 	case SEG6_LOCAL_ACTION_END_X:
6624 		if (!seg6_bpf_has_valid_srh(skb))
6625 			return -EBADMSG;
6626 		if (param_len != sizeof(struct in6_addr))
6627 			return -EINVAL;
6628 		return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
6629 	case SEG6_LOCAL_ACTION_END_T:
6630 		if (!seg6_bpf_has_valid_srh(skb))
6631 			return -EBADMSG;
6632 		if (param_len != sizeof(int))
6633 			return -EINVAL;
6634 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
6635 	case SEG6_LOCAL_ACTION_END_DT6:
6636 		if (!seg6_bpf_has_valid_srh(skb))
6637 			return -EBADMSG;
6638 		if (param_len != sizeof(int))
6639 			return -EINVAL;
6640 
6641 		if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
6642 			return -EBADMSG;
6643 		if (!pskb_pull(skb, hdroff))
6644 			return -EBADMSG;
6645 
6646 		skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
6647 		skb_reset_network_header(skb);
6648 		skb_reset_transport_header(skb);
6649 		skb->encapsulation = 0;
6650 
6651 		bpf_compute_data_pointers(skb);
6652 		bpf_update_srh_state(skb);
6653 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
6654 	case SEG6_LOCAL_ACTION_END_B6:
6655 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
6656 			return -EBADMSG;
6657 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
6658 					  param, param_len);
6659 		if (!err)
6660 			bpf_update_srh_state(skb);
6661 
6662 		return err;
6663 	case SEG6_LOCAL_ACTION_END_B6_ENCAP:
6664 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
6665 			return -EBADMSG;
6666 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
6667 					  param, param_len);
6668 		if (!err)
6669 			bpf_update_srh_state(skb);
6670 
6671 		return err;
6672 	default:
6673 		return -EINVAL;
6674 	}
6675 }
6676 
6677 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
6678 	.func		= bpf_lwt_seg6_action,
6679 	.gpl_only	= false,
6680 	.ret_type	= RET_INTEGER,
6681 	.arg1_type	= ARG_PTR_TO_CTX,
6682 	.arg2_type	= ARG_ANYTHING,
6683 	.arg3_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6684 	.arg4_type	= ARG_CONST_SIZE
6685 };
6686 
BPF_CALL_3(bpf_lwt_seg6_adjust_srh,struct sk_buff *,skb,u32,offset,s32,len)6687 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
6688 	   s32, len)
6689 {
6690 	struct seg6_bpf_srh_state *srh_state =
6691 		this_cpu_ptr(&seg6_bpf_srh_states);
6692 	struct ipv6_sr_hdr *srh = srh_state->srh;
6693 	void *srh_end, *srh_tlvs, *ptr;
6694 	struct ipv6hdr *hdr;
6695 	int srhoff = 0;
6696 	int ret;
6697 
6698 	lockdep_assert_held(&srh_state->bh_lock);
6699 	if (unlikely(srh == NULL))
6700 		return -EINVAL;
6701 
6702 	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
6703 			((srh->first_segment + 1) << 4));
6704 	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
6705 			srh_state->hdrlen);
6706 	ptr = skb->data + offset;
6707 
6708 	if (unlikely(ptr < srh_tlvs || ptr > srh_end))
6709 		return -EFAULT;
6710 	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
6711 		return -EFAULT;
6712 
6713 	if (len > 0) {
6714 		ret = skb_cow_head(skb, len);
6715 		if (unlikely(ret < 0))
6716 			return ret;
6717 
6718 		ret = bpf_skb_net_hdr_push(skb, offset, len);
6719 	} else {
6720 		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
6721 	}
6722 
6723 	bpf_compute_data_pointers(skb);
6724 	if (unlikely(ret < 0))
6725 		return ret;
6726 
6727 	hdr = (struct ipv6hdr *)skb->data;
6728 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
6729 
6730 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
6731 		return -EINVAL;
6732 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
6733 	srh_state->hdrlen += len;
6734 	srh_state->valid = false;
6735 	return 0;
6736 }
6737 
6738 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
6739 	.func		= bpf_lwt_seg6_adjust_srh,
6740 	.gpl_only	= false,
6741 	.ret_type	= RET_INTEGER,
6742 	.arg1_type	= ARG_PTR_TO_CTX,
6743 	.arg2_type	= ARG_ANYTHING,
6744 	.arg3_type	= ARG_ANYTHING,
6745 };
6746 #endif /* CONFIG_IPV6_SEG6_BPF */
6747 
6748 #ifdef CONFIG_INET
sk_lookup(struct net * net,struct bpf_sock_tuple * tuple,int dif,int sdif,u8 family,u8 proto)6749 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
6750 			      int dif, int sdif, u8 family, u8 proto)
6751 {
6752 	struct inet_hashinfo *hinfo = net->ipv4.tcp_death_row.hashinfo;
6753 	bool refcounted = false;
6754 	struct sock *sk = NULL;
6755 
6756 	if (family == AF_INET) {
6757 		__be32 src4 = tuple->ipv4.saddr;
6758 		__be32 dst4 = tuple->ipv4.daddr;
6759 
6760 		if (proto == IPPROTO_TCP)
6761 			sk = __inet_lookup(net, hinfo, NULL, 0,
6762 					   src4, tuple->ipv4.sport,
6763 					   dst4, tuple->ipv4.dport,
6764 					   dif, sdif, &refcounted);
6765 		else
6766 			sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
6767 					       dst4, tuple->ipv4.dport,
6768 					       dif, sdif, net->ipv4.udp_table, NULL);
6769 #if IS_ENABLED(CONFIG_IPV6)
6770 	} else {
6771 		struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
6772 		struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
6773 
6774 		if (proto == IPPROTO_TCP)
6775 			sk = __inet6_lookup(net, hinfo, NULL, 0,
6776 					    src6, tuple->ipv6.sport,
6777 					    dst6, ntohs(tuple->ipv6.dport),
6778 					    dif, sdif, &refcounted);
6779 		else if (likely(ipv6_bpf_stub))
6780 			sk = ipv6_bpf_stub->udp6_lib_lookup(net,
6781 							    src6, tuple->ipv6.sport,
6782 							    dst6, tuple->ipv6.dport,
6783 							    dif, sdif,
6784 							    net->ipv4.udp_table, NULL);
6785 #endif
6786 	}
6787 
6788 	if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
6789 		WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6790 		sk = NULL;
6791 	}
6792 	return sk;
6793 }
6794 
6795 /* bpf_skc_lookup performs the core lookup for different types of sockets,
6796  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
6797  */
6798 static struct sock *
__bpf_skc_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,struct net * caller_net,u32 ifindex,u8 proto,u64 netns_id,u64 flags,int sdif)6799 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6800 		 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
6801 		 u64 flags, int sdif)
6802 {
6803 	struct sock *sk = NULL;
6804 	struct net *net;
6805 	u8 family;
6806 
6807 	if (len == sizeof(tuple->ipv4))
6808 		family = AF_INET;
6809 	else if (len == sizeof(tuple->ipv6))
6810 		family = AF_INET6;
6811 	else
6812 		return NULL;
6813 
6814 	if (unlikely(flags || !((s32)netns_id < 0 || netns_id <= S32_MAX)))
6815 		goto out;
6816 
6817 	if (sdif < 0) {
6818 		if (family == AF_INET)
6819 			sdif = inet_sdif(skb);
6820 		else
6821 			sdif = inet6_sdif(skb);
6822 	}
6823 
6824 	if ((s32)netns_id < 0) {
6825 		net = caller_net;
6826 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
6827 	} else {
6828 		net = get_net_ns_by_id(caller_net, netns_id);
6829 		if (unlikely(!net))
6830 			goto out;
6831 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
6832 		put_net(net);
6833 	}
6834 
6835 out:
6836 	return sk;
6837 }
6838 
6839 static struct sock *
__bpf_sk_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,struct net * caller_net,u32 ifindex,u8 proto,u64 netns_id,u64 flags,int sdif)6840 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6841 		struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
6842 		u64 flags, int sdif)
6843 {
6844 	struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
6845 					   ifindex, proto, netns_id, flags,
6846 					   sdif);
6847 
6848 	if (sk) {
6849 		struct sock *sk2 = sk_to_full_sk(sk);
6850 
6851 		/* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
6852 		 * sock refcnt is decremented to prevent a request_sock leak.
6853 		 */
6854 		if (sk2 != sk) {
6855 			sock_gen_put(sk);
6856 			/* Ensure there is no need to bump sk2 refcnt */
6857 			if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
6858 				WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6859 				return NULL;
6860 			}
6861 			sk = sk2;
6862 		}
6863 	}
6864 
6865 	return sk;
6866 }
6867 
6868 static struct sock *
bpf_skc_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,u8 proto,u64 netns_id,u64 flags)6869 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6870 	       u8 proto, u64 netns_id, u64 flags)
6871 {
6872 	struct net *caller_net;
6873 	int ifindex;
6874 
6875 	if (skb->dev) {
6876 		caller_net = dev_net(skb->dev);
6877 		ifindex = skb->dev->ifindex;
6878 	} else {
6879 		caller_net = sock_net(skb->sk);
6880 		ifindex = 0;
6881 	}
6882 
6883 	return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
6884 				netns_id, flags, -1);
6885 }
6886 
6887 static struct sock *
bpf_sk_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,u8 proto,u64 netns_id,u64 flags)6888 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
6889 	      u8 proto, u64 netns_id, u64 flags)
6890 {
6891 	struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
6892 					 flags);
6893 
6894 	if (sk) {
6895 		struct sock *sk2 = sk_to_full_sk(sk);
6896 
6897 		/* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
6898 		 * sock refcnt is decremented to prevent a request_sock leak.
6899 		 */
6900 		if (sk2 != sk) {
6901 			sock_gen_put(sk);
6902 			/* Ensure there is no need to bump sk2 refcnt */
6903 			if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
6904 				WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
6905 				return NULL;
6906 			}
6907 			sk = sk2;
6908 		}
6909 	}
6910 
6911 	return sk;
6912 }
6913 
BPF_CALL_5(bpf_skc_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6914 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
6915 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6916 {
6917 	return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
6918 					     netns_id, flags);
6919 }
6920 
6921 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
6922 	.func		= bpf_skc_lookup_tcp,
6923 	.gpl_only	= false,
6924 	.pkt_access	= true,
6925 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
6926 	.arg1_type	= ARG_PTR_TO_CTX,
6927 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6928 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6929 	.arg4_type	= ARG_ANYTHING,
6930 	.arg5_type	= ARG_ANYTHING,
6931 };
6932 
BPF_CALL_5(bpf_sk_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6933 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
6934 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6935 {
6936 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
6937 					    netns_id, flags);
6938 }
6939 
6940 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
6941 	.func		= bpf_sk_lookup_tcp,
6942 	.gpl_only	= false,
6943 	.pkt_access	= true,
6944 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
6945 	.arg1_type	= ARG_PTR_TO_CTX,
6946 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6947 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6948 	.arg4_type	= ARG_ANYTHING,
6949 	.arg5_type	= ARG_ANYTHING,
6950 };
6951 
BPF_CALL_5(bpf_sk_lookup_udp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6952 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
6953 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6954 {
6955 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
6956 					    netns_id, flags);
6957 }
6958 
6959 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
6960 	.func		= bpf_sk_lookup_udp,
6961 	.gpl_only	= false,
6962 	.pkt_access	= true,
6963 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
6964 	.arg1_type	= ARG_PTR_TO_CTX,
6965 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6966 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6967 	.arg4_type	= ARG_ANYTHING,
6968 	.arg5_type	= ARG_ANYTHING,
6969 };
6970 
BPF_CALL_5(bpf_tc_skc_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6971 BPF_CALL_5(bpf_tc_skc_lookup_tcp, struct sk_buff *, skb,
6972 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6973 {
6974 	struct net_device *dev = skb->dev;
6975 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
6976 	struct net *caller_net = dev_net(dev);
6977 
6978 	return (unsigned long)__bpf_skc_lookup(skb, tuple, len, caller_net,
6979 					       ifindex, IPPROTO_TCP, netns_id,
6980 					       flags, sdif);
6981 }
6982 
6983 static const struct bpf_func_proto bpf_tc_skc_lookup_tcp_proto = {
6984 	.func		= bpf_tc_skc_lookup_tcp,
6985 	.gpl_only	= false,
6986 	.pkt_access	= true,
6987 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
6988 	.arg1_type	= ARG_PTR_TO_CTX,
6989 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
6990 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
6991 	.arg4_type	= ARG_ANYTHING,
6992 	.arg5_type	= ARG_ANYTHING,
6993 };
6994 
BPF_CALL_5(bpf_tc_sk_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)6995 BPF_CALL_5(bpf_tc_sk_lookup_tcp, struct sk_buff *, skb,
6996 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
6997 {
6998 	struct net_device *dev = skb->dev;
6999 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7000 	struct net *caller_net = dev_net(dev);
7001 
7002 	return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
7003 					      ifindex, IPPROTO_TCP, netns_id,
7004 					      flags, sdif);
7005 }
7006 
7007 static const struct bpf_func_proto bpf_tc_sk_lookup_tcp_proto = {
7008 	.func		= bpf_tc_sk_lookup_tcp,
7009 	.gpl_only	= false,
7010 	.pkt_access	= true,
7011 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7012 	.arg1_type	= ARG_PTR_TO_CTX,
7013 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7014 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7015 	.arg4_type	= ARG_ANYTHING,
7016 	.arg5_type	= ARG_ANYTHING,
7017 };
7018 
BPF_CALL_5(bpf_tc_sk_lookup_udp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)7019 BPF_CALL_5(bpf_tc_sk_lookup_udp, struct sk_buff *, skb,
7020 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7021 {
7022 	struct net_device *dev = skb->dev;
7023 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7024 	struct net *caller_net = dev_net(dev);
7025 
7026 	return (unsigned long)__bpf_sk_lookup(skb, tuple, len, caller_net,
7027 					      ifindex, IPPROTO_UDP, netns_id,
7028 					      flags, sdif);
7029 }
7030 
7031 static const struct bpf_func_proto bpf_tc_sk_lookup_udp_proto = {
7032 	.func		= bpf_tc_sk_lookup_udp,
7033 	.gpl_only	= false,
7034 	.pkt_access	= true,
7035 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7036 	.arg1_type	= ARG_PTR_TO_CTX,
7037 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7038 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7039 	.arg4_type	= ARG_ANYTHING,
7040 	.arg5_type	= ARG_ANYTHING,
7041 };
7042 
BPF_CALL_1(bpf_sk_release,struct sock *,sk)7043 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
7044 {
7045 	if (sk && sk_is_refcounted(sk))
7046 		sock_gen_put(sk);
7047 	return 0;
7048 }
7049 
7050 static const struct bpf_func_proto bpf_sk_release_proto = {
7051 	.func		= bpf_sk_release,
7052 	.gpl_only	= false,
7053 	.ret_type	= RET_INTEGER,
7054 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON | OBJ_RELEASE,
7055 };
7056 
BPF_CALL_5(bpf_xdp_sk_lookup_udp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)7057 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
7058 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7059 {
7060 	struct net_device *dev = ctx->rxq->dev;
7061 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7062 	struct net *caller_net = dev_net(dev);
7063 
7064 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
7065 					      ifindex, IPPROTO_UDP, netns_id,
7066 					      flags, sdif);
7067 }
7068 
7069 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
7070 	.func           = bpf_xdp_sk_lookup_udp,
7071 	.gpl_only       = false,
7072 	.pkt_access     = true,
7073 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7074 	.arg1_type      = ARG_PTR_TO_CTX,
7075 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7076 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7077 	.arg4_type      = ARG_ANYTHING,
7078 	.arg5_type      = ARG_ANYTHING,
7079 };
7080 
BPF_CALL_5(bpf_xdp_skc_lookup_tcp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)7081 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
7082 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7083 {
7084 	struct net_device *dev = ctx->rxq->dev;
7085 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7086 	struct net *caller_net = dev_net(dev);
7087 
7088 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
7089 					       ifindex, IPPROTO_TCP, netns_id,
7090 					       flags, sdif);
7091 }
7092 
7093 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
7094 	.func           = bpf_xdp_skc_lookup_tcp,
7095 	.gpl_only       = false,
7096 	.pkt_access     = true,
7097 	.ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
7098 	.arg1_type      = ARG_PTR_TO_CTX,
7099 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7100 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7101 	.arg4_type      = ARG_ANYTHING,
7102 	.arg5_type      = ARG_ANYTHING,
7103 };
7104 
BPF_CALL_5(bpf_xdp_sk_lookup_tcp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)7105 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
7106 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
7107 {
7108 	struct net_device *dev = ctx->rxq->dev;
7109 	int ifindex = dev->ifindex, sdif = dev_sdif(dev);
7110 	struct net *caller_net = dev_net(dev);
7111 
7112 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
7113 					      ifindex, IPPROTO_TCP, netns_id,
7114 					      flags, sdif);
7115 }
7116 
7117 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
7118 	.func           = bpf_xdp_sk_lookup_tcp,
7119 	.gpl_only       = false,
7120 	.pkt_access     = true,
7121 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
7122 	.arg1_type      = ARG_PTR_TO_CTX,
7123 	.arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
7124 	.arg3_type      = ARG_CONST_SIZE_OR_ZERO,
7125 	.arg4_type      = ARG_ANYTHING,
7126 	.arg5_type      = ARG_ANYTHING,
7127 };
7128 
BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp,struct bpf_sock_addr_kern *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)7129 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7130 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7131 {
7132 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
7133 					       sock_net(ctx->sk), 0,
7134 					       IPPROTO_TCP, netns_id, flags,
7135 					       -1);
7136 }
7137 
7138 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
7139 	.func		= bpf_sock_addr_skc_lookup_tcp,
7140 	.gpl_only	= false,
7141 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
7142 	.arg1_type	= ARG_PTR_TO_CTX,
7143 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7144 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7145 	.arg4_type	= ARG_ANYTHING,
7146 	.arg5_type	= ARG_ANYTHING,
7147 };
7148 
BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp,struct bpf_sock_addr_kern *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)7149 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
7150 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7151 {
7152 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7153 					      sock_net(ctx->sk), 0, IPPROTO_TCP,
7154 					      netns_id, flags, -1);
7155 }
7156 
7157 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
7158 	.func		= bpf_sock_addr_sk_lookup_tcp,
7159 	.gpl_only	= false,
7160 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7161 	.arg1_type	= ARG_PTR_TO_CTX,
7162 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7163 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7164 	.arg4_type	= ARG_ANYTHING,
7165 	.arg5_type	= ARG_ANYTHING,
7166 };
7167 
BPF_CALL_5(bpf_sock_addr_sk_lookup_udp,struct bpf_sock_addr_kern *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)7168 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
7169 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
7170 {
7171 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
7172 					      sock_net(ctx->sk), 0, IPPROTO_UDP,
7173 					      netns_id, flags, -1);
7174 }
7175 
7176 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
7177 	.func		= bpf_sock_addr_sk_lookup_udp,
7178 	.gpl_only	= false,
7179 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7180 	.arg1_type	= ARG_PTR_TO_CTX,
7181 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7182 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7183 	.arg4_type	= ARG_ANYTHING,
7184 	.arg5_type	= ARG_ANYTHING,
7185 };
7186 
bpf_tcp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)7187 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7188 				  struct bpf_insn_access_aux *info)
7189 {
7190 	if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
7191 					  icsk_retransmits))
7192 		return false;
7193 
7194 	if (off % size != 0)
7195 		return false;
7196 
7197 	switch (off) {
7198 	case offsetof(struct bpf_tcp_sock, bytes_received):
7199 	case offsetof(struct bpf_tcp_sock, bytes_acked):
7200 		return size == sizeof(__u64);
7201 	default:
7202 		return size == sizeof(__u32);
7203 	}
7204 }
7205 
bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)7206 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
7207 				    const struct bpf_insn *si,
7208 				    struct bpf_insn *insn_buf,
7209 				    struct bpf_prog *prog, u32 *target_size)
7210 {
7211 	struct bpf_insn *insn = insn_buf;
7212 
7213 #define BPF_TCP_SOCK_GET_COMMON(FIELD)					\
7214 	do {								\
7215 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, FIELD) >	\
7216 			     sizeof_field(struct bpf_tcp_sock, FIELD));	\
7217 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
7218 				      si->dst_reg, si->src_reg,		\
7219 				      offsetof(struct tcp_sock, FIELD)); \
7220 	} while (0)
7221 
7222 #define BPF_INET_SOCK_GET_COMMON(FIELD)					\
7223 	do {								\
7224 		BUILD_BUG_ON(sizeof_field(struct inet_connection_sock,	\
7225 					  FIELD) >			\
7226 			     sizeof_field(struct bpf_tcp_sock, FIELD));	\
7227 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			\
7228 					struct inet_connection_sock,	\
7229 					FIELD),				\
7230 				      si->dst_reg, si->src_reg,		\
7231 				      offsetof(				\
7232 					struct inet_connection_sock,	\
7233 					FIELD));			\
7234 	} while (0)
7235 
7236 	BTF_TYPE_EMIT(struct bpf_tcp_sock);
7237 
7238 	switch (si->off) {
7239 	case offsetof(struct bpf_tcp_sock, rtt_min):
7240 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
7241 			     sizeof(struct minmax));
7242 		BUILD_BUG_ON(sizeof(struct minmax) <
7243 			     sizeof(struct minmax_sample));
7244 
7245 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7246 				      offsetof(struct tcp_sock, rtt_min) +
7247 				      offsetof(struct minmax_sample, v));
7248 		break;
7249 	case offsetof(struct bpf_tcp_sock, snd_cwnd):
7250 		BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
7251 		break;
7252 	case offsetof(struct bpf_tcp_sock, srtt_us):
7253 		BPF_TCP_SOCK_GET_COMMON(srtt_us);
7254 		break;
7255 	case offsetof(struct bpf_tcp_sock, snd_ssthresh):
7256 		BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
7257 		break;
7258 	case offsetof(struct bpf_tcp_sock, rcv_nxt):
7259 		BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
7260 		break;
7261 	case offsetof(struct bpf_tcp_sock, snd_nxt):
7262 		BPF_TCP_SOCK_GET_COMMON(snd_nxt);
7263 		break;
7264 	case offsetof(struct bpf_tcp_sock, snd_una):
7265 		BPF_TCP_SOCK_GET_COMMON(snd_una);
7266 		break;
7267 	case offsetof(struct bpf_tcp_sock, mss_cache):
7268 		BPF_TCP_SOCK_GET_COMMON(mss_cache);
7269 		break;
7270 	case offsetof(struct bpf_tcp_sock, ecn_flags):
7271 		BPF_TCP_SOCK_GET_COMMON(ecn_flags);
7272 		break;
7273 	case offsetof(struct bpf_tcp_sock, rate_delivered):
7274 		BPF_TCP_SOCK_GET_COMMON(rate_delivered);
7275 		break;
7276 	case offsetof(struct bpf_tcp_sock, rate_interval_us):
7277 		BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
7278 		break;
7279 	case offsetof(struct bpf_tcp_sock, packets_out):
7280 		BPF_TCP_SOCK_GET_COMMON(packets_out);
7281 		break;
7282 	case offsetof(struct bpf_tcp_sock, retrans_out):
7283 		BPF_TCP_SOCK_GET_COMMON(retrans_out);
7284 		break;
7285 	case offsetof(struct bpf_tcp_sock, total_retrans):
7286 		BPF_TCP_SOCK_GET_COMMON(total_retrans);
7287 		break;
7288 	case offsetof(struct bpf_tcp_sock, segs_in):
7289 		BPF_TCP_SOCK_GET_COMMON(segs_in);
7290 		break;
7291 	case offsetof(struct bpf_tcp_sock, data_segs_in):
7292 		BPF_TCP_SOCK_GET_COMMON(data_segs_in);
7293 		break;
7294 	case offsetof(struct bpf_tcp_sock, segs_out):
7295 		BPF_TCP_SOCK_GET_COMMON(segs_out);
7296 		break;
7297 	case offsetof(struct bpf_tcp_sock, data_segs_out):
7298 		BPF_TCP_SOCK_GET_COMMON(data_segs_out);
7299 		break;
7300 	case offsetof(struct bpf_tcp_sock, lost_out):
7301 		BPF_TCP_SOCK_GET_COMMON(lost_out);
7302 		break;
7303 	case offsetof(struct bpf_tcp_sock, sacked_out):
7304 		BPF_TCP_SOCK_GET_COMMON(sacked_out);
7305 		break;
7306 	case offsetof(struct bpf_tcp_sock, bytes_received):
7307 		BPF_TCP_SOCK_GET_COMMON(bytes_received);
7308 		break;
7309 	case offsetof(struct bpf_tcp_sock, bytes_acked):
7310 		BPF_TCP_SOCK_GET_COMMON(bytes_acked);
7311 		break;
7312 	case offsetof(struct bpf_tcp_sock, dsack_dups):
7313 		BPF_TCP_SOCK_GET_COMMON(dsack_dups);
7314 		break;
7315 	case offsetof(struct bpf_tcp_sock, delivered):
7316 		BPF_TCP_SOCK_GET_COMMON(delivered);
7317 		break;
7318 	case offsetof(struct bpf_tcp_sock, delivered_ce):
7319 		BPF_TCP_SOCK_GET_COMMON(delivered_ce);
7320 		break;
7321 	case offsetof(struct bpf_tcp_sock, icsk_retransmits):
7322 		BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
7323 		break;
7324 	}
7325 
7326 	return insn - insn_buf;
7327 }
7328 
BPF_CALL_1(bpf_tcp_sock,struct sock *,sk)7329 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
7330 {
7331 	if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
7332 		return (unsigned long)sk;
7333 
7334 	return (unsigned long)NULL;
7335 }
7336 
7337 const struct bpf_func_proto bpf_tcp_sock_proto = {
7338 	.func		= bpf_tcp_sock,
7339 	.gpl_only	= false,
7340 	.ret_type	= RET_PTR_TO_TCP_SOCK_OR_NULL,
7341 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
7342 };
7343 
BPF_CALL_1(bpf_get_listener_sock,struct sock *,sk)7344 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
7345 {
7346 	sk = sk_to_full_sk(sk);
7347 
7348 	if (sk && sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
7349 		return (unsigned long)sk;
7350 
7351 	return (unsigned long)NULL;
7352 }
7353 
7354 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
7355 	.func		= bpf_get_listener_sock,
7356 	.gpl_only	= false,
7357 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
7358 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
7359 };
7360 
BPF_CALL_1(bpf_skb_ecn_set_ce,struct sk_buff *,skb)7361 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
7362 {
7363 	unsigned int iphdr_len;
7364 
7365 	switch (skb_protocol(skb, true)) {
7366 	case cpu_to_be16(ETH_P_IP):
7367 		iphdr_len = sizeof(struct iphdr);
7368 		break;
7369 	case cpu_to_be16(ETH_P_IPV6):
7370 		iphdr_len = sizeof(struct ipv6hdr);
7371 		break;
7372 	default:
7373 		return 0;
7374 	}
7375 
7376 	if (skb_headlen(skb) < iphdr_len)
7377 		return 0;
7378 
7379 	if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
7380 		return 0;
7381 
7382 	return INET_ECN_set_ce(skb);
7383 }
7384 
bpf_xdp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)7385 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
7386 				  struct bpf_insn_access_aux *info)
7387 {
7388 	if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
7389 		return false;
7390 
7391 	if (off % size != 0)
7392 		return false;
7393 
7394 	switch (off) {
7395 	default:
7396 		return size == sizeof(__u32);
7397 	}
7398 }
7399 
bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)7400 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
7401 				    const struct bpf_insn *si,
7402 				    struct bpf_insn *insn_buf,
7403 				    struct bpf_prog *prog, u32 *target_size)
7404 {
7405 	struct bpf_insn *insn = insn_buf;
7406 
7407 #define BPF_XDP_SOCK_GET(FIELD)						\
7408 	do {								\
7409 		BUILD_BUG_ON(sizeof_field(struct xdp_sock, FIELD) >	\
7410 			     sizeof_field(struct bpf_xdp_sock, FIELD));	\
7411 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
7412 				      si->dst_reg, si->src_reg,		\
7413 				      offsetof(struct xdp_sock, FIELD)); \
7414 	} while (0)
7415 
7416 	switch (si->off) {
7417 	case offsetof(struct bpf_xdp_sock, queue_id):
7418 		BPF_XDP_SOCK_GET(queue_id);
7419 		break;
7420 	}
7421 
7422 	return insn - insn_buf;
7423 }
7424 
7425 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
7426 	.func           = bpf_skb_ecn_set_ce,
7427 	.gpl_only       = false,
7428 	.ret_type       = RET_INTEGER,
7429 	.arg1_type      = ARG_PTR_TO_CTX,
7430 };
7431 
BPF_CALL_5(bpf_tcp_check_syncookie,struct sock *,sk,void *,iph,u32,iph_len,struct tcphdr *,th,u32,th_len)7432 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7433 	   struct tcphdr *, th, u32, th_len)
7434 {
7435 #ifdef CONFIG_SYN_COOKIES
7436 	int ret;
7437 
7438 	if (unlikely(!sk || th_len < sizeof(*th)))
7439 		return -EINVAL;
7440 
7441 	/* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
7442 	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
7443 		return -EINVAL;
7444 
7445 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7446 		return -EINVAL;
7447 
7448 	if (!th->ack || th->rst || th->syn)
7449 		return -ENOENT;
7450 
7451 	if (unlikely(iph_len < sizeof(struct iphdr)))
7452 		return -EINVAL;
7453 
7454 	if (tcp_synq_no_recent_overflow(sk))
7455 		return -ENOENT;
7456 
7457 	/* Both struct iphdr and struct ipv6hdr have the version field at the
7458 	 * same offset so we can cast to the shorter header (struct iphdr).
7459 	 */
7460 	switch (((struct iphdr *)iph)->version) {
7461 	case 4:
7462 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7463 			return -EINVAL;
7464 
7465 		ret = __cookie_v4_check((struct iphdr *)iph, th);
7466 		break;
7467 
7468 #if IS_BUILTIN(CONFIG_IPV6)
7469 	case 6:
7470 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7471 			return -EINVAL;
7472 
7473 		if (sk->sk_family != AF_INET6)
7474 			return -EINVAL;
7475 
7476 		ret = __cookie_v6_check((struct ipv6hdr *)iph, th);
7477 		break;
7478 #endif /* CONFIG_IPV6 */
7479 
7480 	default:
7481 		return -EPROTONOSUPPORT;
7482 	}
7483 
7484 	if (ret > 0)
7485 		return 0;
7486 
7487 	return -ENOENT;
7488 #else
7489 	return -ENOTSUPP;
7490 #endif
7491 }
7492 
7493 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
7494 	.func		= bpf_tcp_check_syncookie,
7495 	.gpl_only	= true,
7496 	.pkt_access	= true,
7497 	.ret_type	= RET_INTEGER,
7498 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7499 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7500 	.arg3_type	= ARG_CONST_SIZE,
7501 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7502 	.arg5_type	= ARG_CONST_SIZE,
7503 };
7504 
BPF_CALL_5(bpf_tcp_gen_syncookie,struct sock *,sk,void *,iph,u32,iph_len,struct tcphdr *,th,u32,th_len)7505 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
7506 	   struct tcphdr *, th, u32, th_len)
7507 {
7508 #ifdef CONFIG_SYN_COOKIES
7509 	u32 cookie;
7510 	u16 mss;
7511 
7512 	if (unlikely(!sk || th_len < sizeof(*th) || th_len != th->doff * 4))
7513 		return -EINVAL;
7514 
7515 	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
7516 		return -EINVAL;
7517 
7518 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
7519 		return -ENOENT;
7520 
7521 	if (!th->syn || th->ack || th->fin || th->rst)
7522 		return -EINVAL;
7523 
7524 	if (unlikely(iph_len < sizeof(struct iphdr)))
7525 		return -EINVAL;
7526 
7527 	/* Both struct iphdr and struct ipv6hdr have the version field at the
7528 	 * same offset so we can cast to the shorter header (struct iphdr).
7529 	 */
7530 	switch (((struct iphdr *)iph)->version) {
7531 	case 4:
7532 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
7533 			return -EINVAL;
7534 
7535 		mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
7536 		break;
7537 
7538 #if IS_BUILTIN(CONFIG_IPV6)
7539 	case 6:
7540 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
7541 			return -EINVAL;
7542 
7543 		if (sk->sk_family != AF_INET6)
7544 			return -EINVAL;
7545 
7546 		mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
7547 		break;
7548 #endif /* CONFIG_IPV6 */
7549 
7550 	default:
7551 		return -EPROTONOSUPPORT;
7552 	}
7553 	if (mss == 0)
7554 		return -ENOENT;
7555 
7556 	return cookie | ((u64)mss << 32);
7557 #else
7558 	return -EOPNOTSUPP;
7559 #endif /* CONFIG_SYN_COOKIES */
7560 }
7561 
7562 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
7563 	.func		= bpf_tcp_gen_syncookie,
7564 	.gpl_only	= true, /* __cookie_v*_init_sequence() is GPL */
7565 	.pkt_access	= true,
7566 	.ret_type	= RET_INTEGER,
7567 	.arg1_type	= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7568 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7569 	.arg3_type	= ARG_CONST_SIZE,
7570 	.arg4_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7571 	.arg5_type	= ARG_CONST_SIZE,
7572 };
7573 
BPF_CALL_3(bpf_sk_assign,struct sk_buff *,skb,struct sock *,sk,u64,flags)7574 BPF_CALL_3(bpf_sk_assign, struct sk_buff *, skb, struct sock *, sk, u64, flags)
7575 {
7576 	if (!sk || flags != 0)
7577 		return -EINVAL;
7578 	if (!skb_at_tc_ingress(skb))
7579 		return -EOPNOTSUPP;
7580 	if (unlikely(dev_net(skb->dev) != sock_net(sk)))
7581 		return -ENETUNREACH;
7582 	if (sk_unhashed(sk))
7583 		return -EOPNOTSUPP;
7584 	if (sk_is_refcounted(sk) &&
7585 	    unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
7586 		return -ENOENT;
7587 
7588 	skb_orphan(skb);
7589 	skb->sk = sk;
7590 	skb->destructor = sock_pfree;
7591 
7592 	return 0;
7593 }
7594 
7595 static const struct bpf_func_proto bpf_sk_assign_proto = {
7596 	.func		= bpf_sk_assign,
7597 	.gpl_only	= false,
7598 	.ret_type	= RET_INTEGER,
7599 	.arg1_type      = ARG_PTR_TO_CTX,
7600 	.arg2_type      = ARG_PTR_TO_BTF_ID_SOCK_COMMON,
7601 	.arg3_type	= ARG_ANYTHING,
7602 };
7603 
bpf_search_tcp_opt(const u8 * op,const u8 * opend,u8 search_kind,const u8 * magic,u8 magic_len,bool * eol)7604 static const u8 *bpf_search_tcp_opt(const u8 *op, const u8 *opend,
7605 				    u8 search_kind, const u8 *magic,
7606 				    u8 magic_len, bool *eol)
7607 {
7608 	u8 kind, kind_len;
7609 
7610 	*eol = false;
7611 
7612 	while (op < opend) {
7613 		kind = op[0];
7614 
7615 		if (kind == TCPOPT_EOL) {
7616 			*eol = true;
7617 			return ERR_PTR(-ENOMSG);
7618 		} else if (kind == TCPOPT_NOP) {
7619 			op++;
7620 			continue;
7621 		}
7622 
7623 		if (opend - op < 2 || opend - op < op[1] || op[1] < 2)
7624 			/* Something is wrong in the received header.
7625 			 * Follow the TCP stack's tcp_parse_options()
7626 			 * and just bail here.
7627 			 */
7628 			return ERR_PTR(-EFAULT);
7629 
7630 		kind_len = op[1];
7631 		if (search_kind == kind) {
7632 			if (!magic_len)
7633 				return op;
7634 
7635 			if (magic_len > kind_len - 2)
7636 				return ERR_PTR(-ENOMSG);
7637 
7638 			if (!memcmp(&op[2], magic, magic_len))
7639 				return op;
7640 		}
7641 
7642 		op += kind_len;
7643 	}
7644 
7645 	return ERR_PTR(-ENOMSG);
7646 }
7647 
BPF_CALL_4(bpf_sock_ops_load_hdr_opt,struct bpf_sock_ops_kern *,bpf_sock,void *,search_res,u32,len,u64,flags)7648 BPF_CALL_4(bpf_sock_ops_load_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7649 	   void *, search_res, u32, len, u64, flags)
7650 {
7651 	bool eol, load_syn = flags & BPF_LOAD_HDR_OPT_TCP_SYN;
7652 	const u8 *op, *opend, *magic, *search = search_res;
7653 	u8 search_kind, search_len, copy_len, magic_len;
7654 	int ret;
7655 
7656 	if (!is_locked_tcp_sock_ops(bpf_sock))
7657 		return -EOPNOTSUPP;
7658 
7659 	/* 2 byte is the minimal option len except TCPOPT_NOP and
7660 	 * TCPOPT_EOL which are useless for the bpf prog to learn
7661 	 * and this helper disallow loading them also.
7662 	 */
7663 	if (len < 2 || flags & ~BPF_LOAD_HDR_OPT_TCP_SYN)
7664 		return -EINVAL;
7665 
7666 	search_kind = search[0];
7667 	search_len = search[1];
7668 
7669 	if (search_len > len || search_kind == TCPOPT_NOP ||
7670 	    search_kind == TCPOPT_EOL)
7671 		return -EINVAL;
7672 
7673 	if (search_kind == TCPOPT_EXP || search_kind == 253) {
7674 		/* 16 or 32 bit magic.  +2 for kind and kind length */
7675 		if (search_len != 4 && search_len != 6)
7676 			return -EINVAL;
7677 		magic = &search[2];
7678 		magic_len = search_len - 2;
7679 	} else {
7680 		if (search_len)
7681 			return -EINVAL;
7682 		magic = NULL;
7683 		magic_len = 0;
7684 	}
7685 
7686 	if (load_syn) {
7687 		ret = bpf_sock_ops_get_syn(bpf_sock, TCP_BPF_SYN, &op);
7688 		if (ret < 0)
7689 			return ret;
7690 
7691 		opend = op + ret;
7692 		op += sizeof(struct tcphdr);
7693 	} else {
7694 		if (!bpf_sock->skb ||
7695 		    bpf_sock->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB)
7696 			/* This bpf_sock->op cannot call this helper */
7697 			return -EPERM;
7698 
7699 		opend = bpf_sock->skb_data_end;
7700 		op = bpf_sock->skb->data + sizeof(struct tcphdr);
7701 	}
7702 
7703 	op = bpf_search_tcp_opt(op, opend, search_kind, magic, magic_len,
7704 				&eol);
7705 	if (IS_ERR(op))
7706 		return PTR_ERR(op);
7707 
7708 	copy_len = op[1];
7709 	ret = copy_len;
7710 	if (copy_len > len) {
7711 		ret = -ENOSPC;
7712 		copy_len = len;
7713 	}
7714 
7715 	memcpy(search_res, op, copy_len);
7716 	return ret;
7717 }
7718 
7719 static const struct bpf_func_proto bpf_sock_ops_load_hdr_opt_proto = {
7720 	.func		= bpf_sock_ops_load_hdr_opt,
7721 	.gpl_only	= false,
7722 	.ret_type	= RET_INTEGER,
7723 	.arg1_type	= ARG_PTR_TO_CTX,
7724 	.arg2_type	= ARG_PTR_TO_MEM | MEM_WRITE,
7725 	.arg3_type	= ARG_CONST_SIZE,
7726 	.arg4_type	= ARG_ANYTHING,
7727 };
7728 
BPF_CALL_4(bpf_sock_ops_store_hdr_opt,struct bpf_sock_ops_kern *,bpf_sock,const void *,from,u32,len,u64,flags)7729 BPF_CALL_4(bpf_sock_ops_store_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7730 	   const void *, from, u32, len, u64, flags)
7731 {
7732 	u8 new_kind, new_kind_len, magic_len = 0, *opend;
7733 	const u8 *op, *new_op, *magic = NULL;
7734 	struct sk_buff *skb;
7735 	bool eol;
7736 
7737 	if (bpf_sock->op != BPF_SOCK_OPS_WRITE_HDR_OPT_CB)
7738 		return -EPERM;
7739 
7740 	if (len < 2 || flags)
7741 		return -EINVAL;
7742 
7743 	new_op = from;
7744 	new_kind = new_op[0];
7745 	new_kind_len = new_op[1];
7746 
7747 	if (new_kind_len > len || new_kind == TCPOPT_NOP ||
7748 	    new_kind == TCPOPT_EOL)
7749 		return -EINVAL;
7750 
7751 	if (new_kind_len > bpf_sock->remaining_opt_len)
7752 		return -ENOSPC;
7753 
7754 	/* 253 is another experimental kind */
7755 	if (new_kind == TCPOPT_EXP || new_kind == 253)  {
7756 		if (new_kind_len < 4)
7757 			return -EINVAL;
7758 		/* Match for the 2 byte magic also.
7759 		 * RFC 6994: the magic could be 2 or 4 bytes.
7760 		 * Hence, matching by 2 byte only is on the
7761 		 * conservative side but it is the right
7762 		 * thing to do for the 'search-for-duplication'
7763 		 * purpose.
7764 		 */
7765 		magic = &new_op[2];
7766 		magic_len = 2;
7767 	}
7768 
7769 	/* Check for duplication */
7770 	skb = bpf_sock->skb;
7771 	op = skb->data + sizeof(struct tcphdr);
7772 	opend = bpf_sock->skb_data_end;
7773 
7774 	op = bpf_search_tcp_opt(op, opend, new_kind, magic, magic_len,
7775 				&eol);
7776 	if (!IS_ERR(op))
7777 		return -EEXIST;
7778 
7779 	if (PTR_ERR(op) != -ENOMSG)
7780 		return PTR_ERR(op);
7781 
7782 	if (eol)
7783 		/* The option has been ended.  Treat it as no more
7784 		 * header option can be written.
7785 		 */
7786 		return -ENOSPC;
7787 
7788 	/* No duplication found.  Store the header option. */
7789 	memcpy(opend, from, new_kind_len);
7790 
7791 	bpf_sock->remaining_opt_len -= new_kind_len;
7792 	bpf_sock->skb_data_end += new_kind_len;
7793 
7794 	return 0;
7795 }
7796 
7797 static const struct bpf_func_proto bpf_sock_ops_store_hdr_opt_proto = {
7798 	.func		= bpf_sock_ops_store_hdr_opt,
7799 	.gpl_only	= false,
7800 	.ret_type	= RET_INTEGER,
7801 	.arg1_type	= ARG_PTR_TO_CTX,
7802 	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7803 	.arg3_type	= ARG_CONST_SIZE,
7804 	.arg4_type	= ARG_ANYTHING,
7805 };
7806 
BPF_CALL_3(bpf_sock_ops_reserve_hdr_opt,struct bpf_sock_ops_kern *,bpf_sock,u32,len,u64,flags)7807 BPF_CALL_3(bpf_sock_ops_reserve_hdr_opt, struct bpf_sock_ops_kern *, bpf_sock,
7808 	   u32, len, u64, flags)
7809 {
7810 	if (bpf_sock->op != BPF_SOCK_OPS_HDR_OPT_LEN_CB)
7811 		return -EPERM;
7812 
7813 	if (flags || len < 2)
7814 		return -EINVAL;
7815 
7816 	if (len > bpf_sock->remaining_opt_len)
7817 		return -ENOSPC;
7818 
7819 	bpf_sock->remaining_opt_len -= len;
7820 
7821 	return 0;
7822 }
7823 
7824 static const struct bpf_func_proto bpf_sock_ops_reserve_hdr_opt_proto = {
7825 	.func		= bpf_sock_ops_reserve_hdr_opt,
7826 	.gpl_only	= false,
7827 	.ret_type	= RET_INTEGER,
7828 	.arg1_type	= ARG_PTR_TO_CTX,
7829 	.arg2_type	= ARG_ANYTHING,
7830 	.arg3_type	= ARG_ANYTHING,
7831 };
7832 
BPF_CALL_3(bpf_skb_set_tstamp,struct sk_buff *,skb,u64,tstamp,u32,tstamp_type)7833 BPF_CALL_3(bpf_skb_set_tstamp, struct sk_buff *, skb,
7834 	   u64, tstamp, u32, tstamp_type)
7835 {
7836 	/* skb_clear_delivery_time() is done for inet protocol */
7837 	if (skb->protocol != htons(ETH_P_IP) &&
7838 	    skb->protocol != htons(ETH_P_IPV6))
7839 		return -EOPNOTSUPP;
7840 
7841 	switch (tstamp_type) {
7842 	case BPF_SKB_CLOCK_REALTIME:
7843 		skb->tstamp = tstamp;
7844 		skb->tstamp_type = SKB_CLOCK_REALTIME;
7845 		break;
7846 	case BPF_SKB_CLOCK_MONOTONIC:
7847 		if (!tstamp)
7848 			return -EINVAL;
7849 		skb->tstamp = tstamp;
7850 		skb->tstamp_type = SKB_CLOCK_MONOTONIC;
7851 		break;
7852 	case BPF_SKB_CLOCK_TAI:
7853 		if (!tstamp)
7854 			return -EINVAL;
7855 		skb->tstamp = tstamp;
7856 		skb->tstamp_type = SKB_CLOCK_TAI;
7857 		break;
7858 	default:
7859 		return -EINVAL;
7860 	}
7861 
7862 	return 0;
7863 }
7864 
7865 static const struct bpf_func_proto bpf_skb_set_tstamp_proto = {
7866 	.func           = bpf_skb_set_tstamp,
7867 	.gpl_only       = false,
7868 	.ret_type       = RET_INTEGER,
7869 	.arg1_type      = ARG_PTR_TO_CTX,
7870 	.arg2_type      = ARG_ANYTHING,
7871 	.arg3_type      = ARG_ANYTHING,
7872 };
7873 
7874 #ifdef CONFIG_SYN_COOKIES
BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv4,struct iphdr *,iph,struct tcphdr *,th,u32,th_len)7875 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv4, struct iphdr *, iph,
7876 	   struct tcphdr *, th, u32, th_len)
7877 {
7878 	u32 cookie;
7879 	u16 mss;
7880 
7881 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
7882 		return -EINVAL;
7883 
7884 	mss = tcp_parse_mss_option(th, 0) ?: TCP_MSS_DEFAULT;
7885 	cookie = __cookie_v4_init_sequence(iph, th, &mss);
7886 
7887 	return cookie | ((u64)mss << 32);
7888 }
7889 
7890 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv4_proto = {
7891 	.func		= bpf_tcp_raw_gen_syncookie_ipv4,
7892 	.gpl_only	= true, /* __cookie_v4_init_sequence() is GPL */
7893 	.pkt_access	= true,
7894 	.ret_type	= RET_INTEGER,
7895 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7896 	.arg1_size	= sizeof(struct iphdr),
7897 	.arg2_type	= ARG_PTR_TO_MEM,
7898 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7899 };
7900 
BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv6,struct ipv6hdr *,iph,struct tcphdr *,th,u32,th_len)7901 BPF_CALL_3(bpf_tcp_raw_gen_syncookie_ipv6, struct ipv6hdr *, iph,
7902 	   struct tcphdr *, th, u32, th_len)
7903 {
7904 #if IS_BUILTIN(CONFIG_IPV6)
7905 	const u16 mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) -
7906 		sizeof(struct ipv6hdr);
7907 	u32 cookie;
7908 	u16 mss;
7909 
7910 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
7911 		return -EINVAL;
7912 
7913 	mss = tcp_parse_mss_option(th, 0) ?: mss_clamp;
7914 	cookie = __cookie_v6_init_sequence(iph, th, &mss);
7915 
7916 	return cookie | ((u64)mss << 32);
7917 #else
7918 	return -EPROTONOSUPPORT;
7919 #endif
7920 }
7921 
7922 static const struct bpf_func_proto bpf_tcp_raw_gen_syncookie_ipv6_proto = {
7923 	.func		= bpf_tcp_raw_gen_syncookie_ipv6,
7924 	.gpl_only	= true, /* __cookie_v6_init_sequence() is GPL */
7925 	.pkt_access	= true,
7926 	.ret_type	= RET_INTEGER,
7927 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7928 	.arg1_size	= sizeof(struct ipv6hdr),
7929 	.arg2_type	= ARG_PTR_TO_MEM,
7930 	.arg3_type	= ARG_CONST_SIZE_OR_ZERO,
7931 };
7932 
BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv4,struct iphdr *,iph,struct tcphdr *,th)7933 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv4, struct iphdr *, iph,
7934 	   struct tcphdr *, th)
7935 {
7936 	if (__cookie_v4_check(iph, th) > 0)
7937 		return 0;
7938 
7939 	return -EACCES;
7940 }
7941 
7942 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv4_proto = {
7943 	.func		= bpf_tcp_raw_check_syncookie_ipv4,
7944 	.gpl_only	= true, /* __cookie_v4_check is GPL */
7945 	.pkt_access	= true,
7946 	.ret_type	= RET_INTEGER,
7947 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7948 	.arg1_size	= sizeof(struct iphdr),
7949 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7950 	.arg2_size	= sizeof(struct tcphdr),
7951 };
7952 
BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv6,struct ipv6hdr *,iph,struct tcphdr *,th)7953 BPF_CALL_2(bpf_tcp_raw_check_syncookie_ipv6, struct ipv6hdr *, iph,
7954 	   struct tcphdr *, th)
7955 {
7956 #if IS_BUILTIN(CONFIG_IPV6)
7957 	if (__cookie_v6_check(iph, th) > 0)
7958 		return 0;
7959 
7960 	return -EACCES;
7961 #else
7962 	return -EPROTONOSUPPORT;
7963 #endif
7964 }
7965 
7966 static const struct bpf_func_proto bpf_tcp_raw_check_syncookie_ipv6_proto = {
7967 	.func		= bpf_tcp_raw_check_syncookie_ipv6,
7968 	.gpl_only	= true, /* __cookie_v6_check is GPL */
7969 	.pkt_access	= true,
7970 	.ret_type	= RET_INTEGER,
7971 	.arg1_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7972 	.arg1_size	= sizeof(struct ipv6hdr),
7973 	.arg2_type	= ARG_PTR_TO_FIXED_SIZE_MEM,
7974 	.arg2_size	= sizeof(struct tcphdr),
7975 };
7976 #endif /* CONFIG_SYN_COOKIES */
7977 
7978 #endif /* CONFIG_INET */
7979 
bpf_helper_changes_pkt_data(enum bpf_func_id func_id)7980 bool bpf_helper_changes_pkt_data(enum bpf_func_id func_id)
7981 {
7982 	switch (func_id) {
7983 	case BPF_FUNC_clone_redirect:
7984 	case BPF_FUNC_l3_csum_replace:
7985 	case BPF_FUNC_l4_csum_replace:
7986 	case BPF_FUNC_lwt_push_encap:
7987 	case BPF_FUNC_lwt_seg6_action:
7988 	case BPF_FUNC_lwt_seg6_adjust_srh:
7989 	case BPF_FUNC_lwt_seg6_store_bytes:
7990 	case BPF_FUNC_msg_pop_data:
7991 	case BPF_FUNC_msg_pull_data:
7992 	case BPF_FUNC_msg_push_data:
7993 	case BPF_FUNC_skb_adjust_room:
7994 	case BPF_FUNC_skb_change_head:
7995 	case BPF_FUNC_skb_change_proto:
7996 	case BPF_FUNC_skb_change_tail:
7997 	case BPF_FUNC_skb_pull_data:
7998 	case BPF_FUNC_skb_store_bytes:
7999 	case BPF_FUNC_skb_vlan_pop:
8000 	case BPF_FUNC_skb_vlan_push:
8001 	case BPF_FUNC_store_hdr_opt:
8002 	case BPF_FUNC_xdp_adjust_head:
8003 	case BPF_FUNC_xdp_adjust_meta:
8004 	case BPF_FUNC_xdp_adjust_tail:
8005 	/* tail-called program could call any of the above */
8006 	case BPF_FUNC_tail_call:
8007 		return true;
8008 	default:
8009 		return false;
8010 	}
8011 }
8012 
8013 const struct bpf_func_proto bpf_event_output_data_proto __weak;
8014 const struct bpf_func_proto bpf_sk_storage_get_cg_sock_proto __weak;
8015 
8016 static const struct bpf_func_proto *
sock_filter_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8017 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8018 {
8019 	const struct bpf_func_proto *func_proto;
8020 
8021 	func_proto = cgroup_common_func_proto(func_id, prog);
8022 	if (func_proto)
8023 		return func_proto;
8024 
8025 	func_proto = cgroup_current_func_proto(func_id, prog);
8026 	if (func_proto)
8027 		return func_proto;
8028 
8029 	switch (func_id) {
8030 	case BPF_FUNC_get_socket_cookie:
8031 		return &bpf_get_socket_cookie_sock_proto;
8032 	case BPF_FUNC_get_netns_cookie:
8033 		return &bpf_get_netns_cookie_sock_proto;
8034 	case BPF_FUNC_perf_event_output:
8035 		return &bpf_event_output_data_proto;
8036 	case BPF_FUNC_sk_storage_get:
8037 		return &bpf_sk_storage_get_cg_sock_proto;
8038 	case BPF_FUNC_ktime_get_coarse_ns:
8039 		return &bpf_ktime_get_coarse_ns_proto;
8040 	default:
8041 		return bpf_base_func_proto(func_id, prog);
8042 	}
8043 }
8044 
8045 static const struct bpf_func_proto *
sock_addr_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8046 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8047 {
8048 	const struct bpf_func_proto *func_proto;
8049 
8050 	func_proto = cgroup_common_func_proto(func_id, prog);
8051 	if (func_proto)
8052 		return func_proto;
8053 
8054 	func_proto = cgroup_current_func_proto(func_id, prog);
8055 	if (func_proto)
8056 		return func_proto;
8057 
8058 	switch (func_id) {
8059 	case BPF_FUNC_bind:
8060 		switch (prog->expected_attach_type) {
8061 		case BPF_CGROUP_INET4_CONNECT:
8062 		case BPF_CGROUP_INET6_CONNECT:
8063 			return &bpf_bind_proto;
8064 		default:
8065 			return NULL;
8066 		}
8067 	case BPF_FUNC_get_socket_cookie:
8068 		return &bpf_get_socket_cookie_sock_addr_proto;
8069 	case BPF_FUNC_get_netns_cookie:
8070 		return &bpf_get_netns_cookie_sock_addr_proto;
8071 	case BPF_FUNC_perf_event_output:
8072 		return &bpf_event_output_data_proto;
8073 #ifdef CONFIG_INET
8074 	case BPF_FUNC_sk_lookup_tcp:
8075 		return &bpf_sock_addr_sk_lookup_tcp_proto;
8076 	case BPF_FUNC_sk_lookup_udp:
8077 		return &bpf_sock_addr_sk_lookup_udp_proto;
8078 	case BPF_FUNC_sk_release:
8079 		return &bpf_sk_release_proto;
8080 	case BPF_FUNC_skc_lookup_tcp:
8081 		return &bpf_sock_addr_skc_lookup_tcp_proto;
8082 #endif /* CONFIG_INET */
8083 	case BPF_FUNC_sk_storage_get:
8084 		return &bpf_sk_storage_get_proto;
8085 	case BPF_FUNC_sk_storage_delete:
8086 		return &bpf_sk_storage_delete_proto;
8087 	case BPF_FUNC_setsockopt:
8088 		switch (prog->expected_attach_type) {
8089 		case BPF_CGROUP_INET4_BIND:
8090 		case BPF_CGROUP_INET6_BIND:
8091 		case BPF_CGROUP_INET4_CONNECT:
8092 		case BPF_CGROUP_INET6_CONNECT:
8093 		case BPF_CGROUP_UNIX_CONNECT:
8094 		case BPF_CGROUP_UDP4_RECVMSG:
8095 		case BPF_CGROUP_UDP6_RECVMSG:
8096 		case BPF_CGROUP_UNIX_RECVMSG:
8097 		case BPF_CGROUP_UDP4_SENDMSG:
8098 		case BPF_CGROUP_UDP6_SENDMSG:
8099 		case BPF_CGROUP_UNIX_SENDMSG:
8100 		case BPF_CGROUP_INET4_GETPEERNAME:
8101 		case BPF_CGROUP_INET6_GETPEERNAME:
8102 		case BPF_CGROUP_UNIX_GETPEERNAME:
8103 		case BPF_CGROUP_INET4_GETSOCKNAME:
8104 		case BPF_CGROUP_INET6_GETSOCKNAME:
8105 		case BPF_CGROUP_UNIX_GETSOCKNAME:
8106 			return &bpf_sock_addr_setsockopt_proto;
8107 		default:
8108 			return NULL;
8109 		}
8110 	case BPF_FUNC_getsockopt:
8111 		switch (prog->expected_attach_type) {
8112 		case BPF_CGROUP_INET4_BIND:
8113 		case BPF_CGROUP_INET6_BIND:
8114 		case BPF_CGROUP_INET4_CONNECT:
8115 		case BPF_CGROUP_INET6_CONNECT:
8116 		case BPF_CGROUP_UNIX_CONNECT:
8117 		case BPF_CGROUP_UDP4_RECVMSG:
8118 		case BPF_CGROUP_UDP6_RECVMSG:
8119 		case BPF_CGROUP_UNIX_RECVMSG:
8120 		case BPF_CGROUP_UDP4_SENDMSG:
8121 		case BPF_CGROUP_UDP6_SENDMSG:
8122 		case BPF_CGROUP_UNIX_SENDMSG:
8123 		case BPF_CGROUP_INET4_GETPEERNAME:
8124 		case BPF_CGROUP_INET6_GETPEERNAME:
8125 		case BPF_CGROUP_UNIX_GETPEERNAME:
8126 		case BPF_CGROUP_INET4_GETSOCKNAME:
8127 		case BPF_CGROUP_INET6_GETSOCKNAME:
8128 		case BPF_CGROUP_UNIX_GETSOCKNAME:
8129 			return &bpf_sock_addr_getsockopt_proto;
8130 		default:
8131 			return NULL;
8132 		}
8133 	default:
8134 		return bpf_sk_base_func_proto(func_id, prog);
8135 	}
8136 }
8137 
8138 static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8139 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8140 {
8141 	switch (func_id) {
8142 	case BPF_FUNC_skb_load_bytes:
8143 		return &bpf_skb_load_bytes_proto;
8144 	case BPF_FUNC_skb_load_bytes_relative:
8145 		return &bpf_skb_load_bytes_relative_proto;
8146 	case BPF_FUNC_get_socket_cookie:
8147 		return &bpf_get_socket_cookie_proto;
8148 	case BPF_FUNC_get_netns_cookie:
8149 		return &bpf_get_netns_cookie_proto;
8150 	case BPF_FUNC_get_socket_uid:
8151 		return &bpf_get_socket_uid_proto;
8152 	case BPF_FUNC_perf_event_output:
8153 		return &bpf_skb_event_output_proto;
8154 	default:
8155 		return bpf_sk_base_func_proto(func_id, prog);
8156 	}
8157 }
8158 
8159 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
8160 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
8161 
8162 static const struct bpf_func_proto *
cg_skb_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8163 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8164 {
8165 	const struct bpf_func_proto *func_proto;
8166 
8167 	func_proto = cgroup_common_func_proto(func_id, prog);
8168 	if (func_proto)
8169 		return func_proto;
8170 
8171 	switch (func_id) {
8172 	case BPF_FUNC_sk_fullsock:
8173 		return &bpf_sk_fullsock_proto;
8174 	case BPF_FUNC_sk_storage_get:
8175 		return &bpf_sk_storage_get_proto;
8176 	case BPF_FUNC_sk_storage_delete:
8177 		return &bpf_sk_storage_delete_proto;
8178 	case BPF_FUNC_perf_event_output:
8179 		return &bpf_skb_event_output_proto;
8180 #ifdef CONFIG_SOCK_CGROUP_DATA
8181 	case BPF_FUNC_skb_cgroup_id:
8182 		return &bpf_skb_cgroup_id_proto;
8183 	case BPF_FUNC_skb_ancestor_cgroup_id:
8184 		return &bpf_skb_ancestor_cgroup_id_proto;
8185 	case BPF_FUNC_sk_cgroup_id:
8186 		return &bpf_sk_cgroup_id_proto;
8187 	case BPF_FUNC_sk_ancestor_cgroup_id:
8188 		return &bpf_sk_ancestor_cgroup_id_proto;
8189 #endif
8190 #ifdef CONFIG_INET
8191 	case BPF_FUNC_sk_lookup_tcp:
8192 		return &bpf_sk_lookup_tcp_proto;
8193 	case BPF_FUNC_sk_lookup_udp:
8194 		return &bpf_sk_lookup_udp_proto;
8195 	case BPF_FUNC_sk_release:
8196 		return &bpf_sk_release_proto;
8197 	case BPF_FUNC_skc_lookup_tcp:
8198 		return &bpf_skc_lookup_tcp_proto;
8199 	case BPF_FUNC_tcp_sock:
8200 		return &bpf_tcp_sock_proto;
8201 	case BPF_FUNC_get_listener_sock:
8202 		return &bpf_get_listener_sock_proto;
8203 	case BPF_FUNC_skb_ecn_set_ce:
8204 		return &bpf_skb_ecn_set_ce_proto;
8205 #endif
8206 	default:
8207 		return sk_filter_func_proto(func_id, prog);
8208 	}
8209 }
8210 
8211 static const struct bpf_func_proto *
tc_cls_act_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8212 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8213 {
8214 	switch (func_id) {
8215 	case BPF_FUNC_skb_store_bytes:
8216 		return &bpf_skb_store_bytes_proto;
8217 	case BPF_FUNC_skb_load_bytes:
8218 		return &bpf_skb_load_bytes_proto;
8219 	case BPF_FUNC_skb_load_bytes_relative:
8220 		return &bpf_skb_load_bytes_relative_proto;
8221 	case BPF_FUNC_skb_pull_data:
8222 		return &bpf_skb_pull_data_proto;
8223 	case BPF_FUNC_csum_diff:
8224 		return &bpf_csum_diff_proto;
8225 	case BPF_FUNC_csum_update:
8226 		return &bpf_csum_update_proto;
8227 	case BPF_FUNC_csum_level:
8228 		return &bpf_csum_level_proto;
8229 	case BPF_FUNC_l3_csum_replace:
8230 		return &bpf_l3_csum_replace_proto;
8231 	case BPF_FUNC_l4_csum_replace:
8232 		return &bpf_l4_csum_replace_proto;
8233 	case BPF_FUNC_clone_redirect:
8234 		return &bpf_clone_redirect_proto;
8235 	case BPF_FUNC_get_cgroup_classid:
8236 		return &bpf_get_cgroup_classid_proto;
8237 	case BPF_FUNC_skb_vlan_push:
8238 		return &bpf_skb_vlan_push_proto;
8239 	case BPF_FUNC_skb_vlan_pop:
8240 		return &bpf_skb_vlan_pop_proto;
8241 	case BPF_FUNC_skb_change_proto:
8242 		return &bpf_skb_change_proto_proto;
8243 	case BPF_FUNC_skb_change_type:
8244 		return &bpf_skb_change_type_proto;
8245 	case BPF_FUNC_skb_adjust_room:
8246 		return &bpf_skb_adjust_room_proto;
8247 	case BPF_FUNC_skb_change_tail:
8248 		return &bpf_skb_change_tail_proto;
8249 	case BPF_FUNC_skb_change_head:
8250 		return &bpf_skb_change_head_proto;
8251 	case BPF_FUNC_skb_get_tunnel_key:
8252 		return &bpf_skb_get_tunnel_key_proto;
8253 	case BPF_FUNC_skb_set_tunnel_key:
8254 		return bpf_get_skb_set_tunnel_proto(func_id);
8255 	case BPF_FUNC_skb_get_tunnel_opt:
8256 		return &bpf_skb_get_tunnel_opt_proto;
8257 	case BPF_FUNC_skb_set_tunnel_opt:
8258 		return bpf_get_skb_set_tunnel_proto(func_id);
8259 	case BPF_FUNC_redirect:
8260 		return &bpf_redirect_proto;
8261 	case BPF_FUNC_redirect_neigh:
8262 		return &bpf_redirect_neigh_proto;
8263 	case BPF_FUNC_redirect_peer:
8264 		return &bpf_redirect_peer_proto;
8265 	case BPF_FUNC_get_route_realm:
8266 		return &bpf_get_route_realm_proto;
8267 	case BPF_FUNC_get_hash_recalc:
8268 		return &bpf_get_hash_recalc_proto;
8269 	case BPF_FUNC_set_hash_invalid:
8270 		return &bpf_set_hash_invalid_proto;
8271 	case BPF_FUNC_set_hash:
8272 		return &bpf_set_hash_proto;
8273 	case BPF_FUNC_perf_event_output:
8274 		return &bpf_skb_event_output_proto;
8275 	case BPF_FUNC_get_smp_processor_id:
8276 		return &bpf_get_smp_processor_id_proto;
8277 	case BPF_FUNC_skb_under_cgroup:
8278 		return &bpf_skb_under_cgroup_proto;
8279 	case BPF_FUNC_get_socket_cookie:
8280 		return &bpf_get_socket_cookie_proto;
8281 	case BPF_FUNC_get_netns_cookie:
8282 		return &bpf_get_netns_cookie_proto;
8283 	case BPF_FUNC_get_socket_uid:
8284 		return &bpf_get_socket_uid_proto;
8285 	case BPF_FUNC_fib_lookup:
8286 		return &bpf_skb_fib_lookup_proto;
8287 	case BPF_FUNC_check_mtu:
8288 		return &bpf_skb_check_mtu_proto;
8289 	case BPF_FUNC_sk_fullsock:
8290 		return &bpf_sk_fullsock_proto;
8291 	case BPF_FUNC_sk_storage_get:
8292 		return &bpf_sk_storage_get_proto;
8293 	case BPF_FUNC_sk_storage_delete:
8294 		return &bpf_sk_storage_delete_proto;
8295 #ifdef CONFIG_XFRM
8296 	case BPF_FUNC_skb_get_xfrm_state:
8297 		return &bpf_skb_get_xfrm_state_proto;
8298 #endif
8299 #ifdef CONFIG_CGROUP_NET_CLASSID
8300 	case BPF_FUNC_skb_cgroup_classid:
8301 		return &bpf_skb_cgroup_classid_proto;
8302 #endif
8303 #ifdef CONFIG_SOCK_CGROUP_DATA
8304 	case BPF_FUNC_skb_cgroup_id:
8305 		return &bpf_skb_cgroup_id_proto;
8306 	case BPF_FUNC_skb_ancestor_cgroup_id:
8307 		return &bpf_skb_ancestor_cgroup_id_proto;
8308 #endif
8309 #ifdef CONFIG_INET
8310 	case BPF_FUNC_sk_lookup_tcp:
8311 		return &bpf_tc_sk_lookup_tcp_proto;
8312 	case BPF_FUNC_sk_lookup_udp:
8313 		return &bpf_tc_sk_lookup_udp_proto;
8314 	case BPF_FUNC_sk_release:
8315 		return &bpf_sk_release_proto;
8316 	case BPF_FUNC_tcp_sock:
8317 		return &bpf_tcp_sock_proto;
8318 	case BPF_FUNC_get_listener_sock:
8319 		return &bpf_get_listener_sock_proto;
8320 	case BPF_FUNC_skc_lookup_tcp:
8321 		return &bpf_tc_skc_lookup_tcp_proto;
8322 	case BPF_FUNC_tcp_check_syncookie:
8323 		return &bpf_tcp_check_syncookie_proto;
8324 	case BPF_FUNC_skb_ecn_set_ce:
8325 		return &bpf_skb_ecn_set_ce_proto;
8326 	case BPF_FUNC_tcp_gen_syncookie:
8327 		return &bpf_tcp_gen_syncookie_proto;
8328 	case BPF_FUNC_sk_assign:
8329 		return &bpf_sk_assign_proto;
8330 	case BPF_FUNC_skb_set_tstamp:
8331 		return &bpf_skb_set_tstamp_proto;
8332 #ifdef CONFIG_SYN_COOKIES
8333 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8334 		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8335 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8336 		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8337 	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8338 		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8339 	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8340 		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8341 #endif
8342 #endif
8343 	default:
8344 		return bpf_sk_base_func_proto(func_id, prog);
8345 	}
8346 }
8347 
8348 static const struct bpf_func_proto *
xdp_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8349 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8350 {
8351 	switch (func_id) {
8352 	case BPF_FUNC_perf_event_output:
8353 		return &bpf_xdp_event_output_proto;
8354 	case BPF_FUNC_get_smp_processor_id:
8355 		return &bpf_get_smp_processor_id_proto;
8356 	case BPF_FUNC_csum_diff:
8357 		return &bpf_csum_diff_proto;
8358 	case BPF_FUNC_xdp_adjust_head:
8359 		return &bpf_xdp_adjust_head_proto;
8360 	case BPF_FUNC_xdp_adjust_meta:
8361 		return &bpf_xdp_adjust_meta_proto;
8362 	case BPF_FUNC_redirect:
8363 		return &bpf_xdp_redirect_proto;
8364 	case BPF_FUNC_redirect_map:
8365 		return &bpf_xdp_redirect_map_proto;
8366 	case BPF_FUNC_xdp_adjust_tail:
8367 		return &bpf_xdp_adjust_tail_proto;
8368 	case BPF_FUNC_xdp_get_buff_len:
8369 		return &bpf_xdp_get_buff_len_proto;
8370 	case BPF_FUNC_xdp_load_bytes:
8371 		return &bpf_xdp_load_bytes_proto;
8372 	case BPF_FUNC_xdp_store_bytes:
8373 		return &bpf_xdp_store_bytes_proto;
8374 	case BPF_FUNC_fib_lookup:
8375 		return &bpf_xdp_fib_lookup_proto;
8376 	case BPF_FUNC_check_mtu:
8377 		return &bpf_xdp_check_mtu_proto;
8378 #ifdef CONFIG_INET
8379 	case BPF_FUNC_sk_lookup_udp:
8380 		return &bpf_xdp_sk_lookup_udp_proto;
8381 	case BPF_FUNC_sk_lookup_tcp:
8382 		return &bpf_xdp_sk_lookup_tcp_proto;
8383 	case BPF_FUNC_sk_release:
8384 		return &bpf_sk_release_proto;
8385 	case BPF_FUNC_skc_lookup_tcp:
8386 		return &bpf_xdp_skc_lookup_tcp_proto;
8387 	case BPF_FUNC_tcp_check_syncookie:
8388 		return &bpf_tcp_check_syncookie_proto;
8389 	case BPF_FUNC_tcp_gen_syncookie:
8390 		return &bpf_tcp_gen_syncookie_proto;
8391 #ifdef CONFIG_SYN_COOKIES
8392 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv4:
8393 		return &bpf_tcp_raw_gen_syncookie_ipv4_proto;
8394 	case BPF_FUNC_tcp_raw_gen_syncookie_ipv6:
8395 		return &bpf_tcp_raw_gen_syncookie_ipv6_proto;
8396 	case BPF_FUNC_tcp_raw_check_syncookie_ipv4:
8397 		return &bpf_tcp_raw_check_syncookie_ipv4_proto;
8398 	case BPF_FUNC_tcp_raw_check_syncookie_ipv6:
8399 		return &bpf_tcp_raw_check_syncookie_ipv6_proto;
8400 #endif
8401 #endif
8402 	default:
8403 		return bpf_sk_base_func_proto(func_id, prog);
8404 	}
8405 
8406 #if IS_MODULE(CONFIG_NF_CONNTRACK) && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)
8407 	/* The nf_conn___init type is used in the NF_CONNTRACK kfuncs. The
8408 	 * kfuncs are defined in two different modules, and we want to be able
8409 	 * to use them interchangeably with the same BTF type ID. Because modules
8410 	 * can't de-duplicate BTF IDs between each other, we need the type to be
8411 	 * referenced in the vmlinux BTF or the verifier will get confused about
8412 	 * the different types. So we add this dummy type reference which will
8413 	 * be included in vmlinux BTF, allowing both modules to refer to the
8414 	 * same type ID.
8415 	 */
8416 	BTF_TYPE_EMIT(struct nf_conn___init);
8417 #endif
8418 }
8419 
8420 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
8421 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
8422 
8423 static const struct bpf_func_proto *
sock_ops_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8424 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8425 {
8426 	const struct bpf_func_proto *func_proto;
8427 
8428 	func_proto = cgroup_common_func_proto(func_id, prog);
8429 	if (func_proto)
8430 		return func_proto;
8431 
8432 	switch (func_id) {
8433 	case BPF_FUNC_setsockopt:
8434 		return &bpf_sock_ops_setsockopt_proto;
8435 	case BPF_FUNC_getsockopt:
8436 		return &bpf_sock_ops_getsockopt_proto;
8437 	case BPF_FUNC_sock_ops_cb_flags_set:
8438 		return &bpf_sock_ops_cb_flags_set_proto;
8439 	case BPF_FUNC_sock_map_update:
8440 		return &bpf_sock_map_update_proto;
8441 	case BPF_FUNC_sock_hash_update:
8442 		return &bpf_sock_hash_update_proto;
8443 	case BPF_FUNC_get_socket_cookie:
8444 		return &bpf_get_socket_cookie_sock_ops_proto;
8445 	case BPF_FUNC_perf_event_output:
8446 		return &bpf_event_output_data_proto;
8447 	case BPF_FUNC_sk_storage_get:
8448 		return &bpf_sk_storage_get_proto;
8449 	case BPF_FUNC_sk_storage_delete:
8450 		return &bpf_sk_storage_delete_proto;
8451 	case BPF_FUNC_get_netns_cookie:
8452 		return &bpf_get_netns_cookie_sock_ops_proto;
8453 #ifdef CONFIG_INET
8454 	case BPF_FUNC_load_hdr_opt:
8455 		return &bpf_sock_ops_load_hdr_opt_proto;
8456 	case BPF_FUNC_store_hdr_opt:
8457 		return &bpf_sock_ops_store_hdr_opt_proto;
8458 	case BPF_FUNC_reserve_hdr_opt:
8459 		return &bpf_sock_ops_reserve_hdr_opt_proto;
8460 	case BPF_FUNC_tcp_sock:
8461 		return &bpf_tcp_sock_proto;
8462 #endif /* CONFIG_INET */
8463 	default:
8464 		return bpf_sk_base_func_proto(func_id, prog);
8465 	}
8466 }
8467 
8468 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
8469 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
8470 
8471 static const struct bpf_func_proto *
sk_msg_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8472 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8473 {
8474 	switch (func_id) {
8475 	case BPF_FUNC_msg_redirect_map:
8476 		return &bpf_msg_redirect_map_proto;
8477 	case BPF_FUNC_msg_redirect_hash:
8478 		return &bpf_msg_redirect_hash_proto;
8479 	case BPF_FUNC_msg_apply_bytes:
8480 		return &bpf_msg_apply_bytes_proto;
8481 	case BPF_FUNC_msg_cork_bytes:
8482 		return &bpf_msg_cork_bytes_proto;
8483 	case BPF_FUNC_msg_pull_data:
8484 		return &bpf_msg_pull_data_proto;
8485 	case BPF_FUNC_msg_push_data:
8486 		return &bpf_msg_push_data_proto;
8487 	case BPF_FUNC_msg_pop_data:
8488 		return &bpf_msg_pop_data_proto;
8489 	case BPF_FUNC_perf_event_output:
8490 		return &bpf_event_output_data_proto;
8491 	case BPF_FUNC_get_current_uid_gid:
8492 		return &bpf_get_current_uid_gid_proto;
8493 	case BPF_FUNC_sk_storage_get:
8494 		return &bpf_sk_storage_get_proto;
8495 	case BPF_FUNC_sk_storage_delete:
8496 		return &bpf_sk_storage_delete_proto;
8497 	case BPF_FUNC_get_netns_cookie:
8498 		return &bpf_get_netns_cookie_sk_msg_proto;
8499 #ifdef CONFIG_CGROUP_NET_CLASSID
8500 	case BPF_FUNC_get_cgroup_classid:
8501 		return &bpf_get_cgroup_classid_curr_proto;
8502 #endif
8503 	default:
8504 		return bpf_sk_base_func_proto(func_id, prog);
8505 	}
8506 }
8507 
8508 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
8509 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
8510 
8511 static const struct bpf_func_proto *
sk_skb_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8512 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8513 {
8514 	switch (func_id) {
8515 	case BPF_FUNC_skb_store_bytes:
8516 		return &bpf_skb_store_bytes_proto;
8517 	case BPF_FUNC_skb_load_bytes:
8518 		return &bpf_skb_load_bytes_proto;
8519 	case BPF_FUNC_skb_pull_data:
8520 		return &sk_skb_pull_data_proto;
8521 	case BPF_FUNC_skb_change_tail:
8522 		return &sk_skb_change_tail_proto;
8523 	case BPF_FUNC_skb_change_head:
8524 		return &sk_skb_change_head_proto;
8525 	case BPF_FUNC_skb_adjust_room:
8526 		return &sk_skb_adjust_room_proto;
8527 	case BPF_FUNC_get_socket_cookie:
8528 		return &bpf_get_socket_cookie_proto;
8529 	case BPF_FUNC_get_socket_uid:
8530 		return &bpf_get_socket_uid_proto;
8531 	case BPF_FUNC_sk_redirect_map:
8532 		return &bpf_sk_redirect_map_proto;
8533 	case BPF_FUNC_sk_redirect_hash:
8534 		return &bpf_sk_redirect_hash_proto;
8535 	case BPF_FUNC_perf_event_output:
8536 		return &bpf_skb_event_output_proto;
8537 #ifdef CONFIG_INET
8538 	case BPF_FUNC_sk_lookup_tcp:
8539 		return &bpf_sk_lookup_tcp_proto;
8540 	case BPF_FUNC_sk_lookup_udp:
8541 		return &bpf_sk_lookup_udp_proto;
8542 	case BPF_FUNC_sk_release:
8543 		return &bpf_sk_release_proto;
8544 	case BPF_FUNC_skc_lookup_tcp:
8545 		return &bpf_skc_lookup_tcp_proto;
8546 #endif
8547 	default:
8548 		return bpf_sk_base_func_proto(func_id, prog);
8549 	}
8550 }
8551 
8552 static const struct bpf_func_proto *
flow_dissector_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8553 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8554 {
8555 	switch (func_id) {
8556 	case BPF_FUNC_skb_load_bytes:
8557 		return &bpf_flow_dissector_load_bytes_proto;
8558 	default:
8559 		return bpf_sk_base_func_proto(func_id, prog);
8560 	}
8561 }
8562 
8563 static const struct bpf_func_proto *
lwt_out_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8564 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8565 {
8566 	switch (func_id) {
8567 	case BPF_FUNC_skb_load_bytes:
8568 		return &bpf_skb_load_bytes_proto;
8569 	case BPF_FUNC_skb_pull_data:
8570 		return &bpf_skb_pull_data_proto;
8571 	case BPF_FUNC_csum_diff:
8572 		return &bpf_csum_diff_proto;
8573 	case BPF_FUNC_get_cgroup_classid:
8574 		return &bpf_get_cgroup_classid_proto;
8575 	case BPF_FUNC_get_route_realm:
8576 		return &bpf_get_route_realm_proto;
8577 	case BPF_FUNC_get_hash_recalc:
8578 		return &bpf_get_hash_recalc_proto;
8579 	case BPF_FUNC_perf_event_output:
8580 		return &bpf_skb_event_output_proto;
8581 	case BPF_FUNC_get_smp_processor_id:
8582 		return &bpf_get_smp_processor_id_proto;
8583 	case BPF_FUNC_skb_under_cgroup:
8584 		return &bpf_skb_under_cgroup_proto;
8585 	default:
8586 		return bpf_sk_base_func_proto(func_id, prog);
8587 	}
8588 }
8589 
8590 static const struct bpf_func_proto *
lwt_in_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8591 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8592 {
8593 	switch (func_id) {
8594 	case BPF_FUNC_lwt_push_encap:
8595 		return &bpf_lwt_in_push_encap_proto;
8596 	default:
8597 		return lwt_out_func_proto(func_id, prog);
8598 	}
8599 }
8600 
8601 static const struct bpf_func_proto *
lwt_xmit_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8602 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8603 {
8604 	switch (func_id) {
8605 	case BPF_FUNC_skb_get_tunnel_key:
8606 		return &bpf_skb_get_tunnel_key_proto;
8607 	case BPF_FUNC_skb_set_tunnel_key:
8608 		return bpf_get_skb_set_tunnel_proto(func_id);
8609 	case BPF_FUNC_skb_get_tunnel_opt:
8610 		return &bpf_skb_get_tunnel_opt_proto;
8611 	case BPF_FUNC_skb_set_tunnel_opt:
8612 		return bpf_get_skb_set_tunnel_proto(func_id);
8613 	case BPF_FUNC_redirect:
8614 		return &bpf_redirect_proto;
8615 	case BPF_FUNC_clone_redirect:
8616 		return &bpf_clone_redirect_proto;
8617 	case BPF_FUNC_skb_change_tail:
8618 		return &bpf_skb_change_tail_proto;
8619 	case BPF_FUNC_skb_change_head:
8620 		return &bpf_skb_change_head_proto;
8621 	case BPF_FUNC_skb_store_bytes:
8622 		return &bpf_skb_store_bytes_proto;
8623 	case BPF_FUNC_csum_update:
8624 		return &bpf_csum_update_proto;
8625 	case BPF_FUNC_csum_level:
8626 		return &bpf_csum_level_proto;
8627 	case BPF_FUNC_l3_csum_replace:
8628 		return &bpf_l3_csum_replace_proto;
8629 	case BPF_FUNC_l4_csum_replace:
8630 		return &bpf_l4_csum_replace_proto;
8631 	case BPF_FUNC_set_hash_invalid:
8632 		return &bpf_set_hash_invalid_proto;
8633 	case BPF_FUNC_lwt_push_encap:
8634 		return &bpf_lwt_xmit_push_encap_proto;
8635 	default:
8636 		return lwt_out_func_proto(func_id, prog);
8637 	}
8638 }
8639 
8640 static const struct bpf_func_proto *
lwt_seg6local_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8641 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
8642 {
8643 	switch (func_id) {
8644 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
8645 	case BPF_FUNC_lwt_seg6_store_bytes:
8646 		return &bpf_lwt_seg6_store_bytes_proto;
8647 	case BPF_FUNC_lwt_seg6_action:
8648 		return &bpf_lwt_seg6_action_proto;
8649 	case BPF_FUNC_lwt_seg6_adjust_srh:
8650 		return &bpf_lwt_seg6_adjust_srh_proto;
8651 #endif
8652 	default:
8653 		return lwt_out_func_proto(func_id, prog);
8654 	}
8655 }
8656 
bpf_skb_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)8657 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
8658 				    const struct bpf_prog *prog,
8659 				    struct bpf_insn_access_aux *info)
8660 {
8661 	const int size_default = sizeof(__u32);
8662 
8663 	if (off < 0 || off >= sizeof(struct __sk_buff))
8664 		return false;
8665 
8666 	/* The verifier guarantees that size > 0. */
8667 	if (off % size != 0)
8668 		return false;
8669 
8670 	switch (off) {
8671 	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8672 		if (off + size > offsetofend(struct __sk_buff, cb[4]))
8673 			return false;
8674 		break;
8675 	case bpf_ctx_range(struct __sk_buff, data):
8676 	case bpf_ctx_range(struct __sk_buff, data_meta):
8677 	case bpf_ctx_range(struct __sk_buff, data_end):
8678 		if (info->is_ldsx || size != size_default)
8679 			return false;
8680 		break;
8681 	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
8682 	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
8683 	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
8684 	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
8685 		if (size != size_default)
8686 			return false;
8687 		break;
8688 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
8689 		return false;
8690 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
8691 		if (type == BPF_WRITE || size != sizeof(__u64))
8692 			return false;
8693 		break;
8694 	case bpf_ctx_range(struct __sk_buff, tstamp):
8695 		if (size != sizeof(__u64))
8696 			return false;
8697 		break;
8698 	case offsetof(struct __sk_buff, sk):
8699 		if (type == BPF_WRITE || size != sizeof(__u64))
8700 			return false;
8701 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
8702 		break;
8703 	case offsetof(struct __sk_buff, tstamp_type):
8704 		return false;
8705 	case offsetofend(struct __sk_buff, tstamp_type) ... offsetof(struct __sk_buff, hwtstamp) - 1:
8706 		/* Explicitly prohibit access to padding in __sk_buff. */
8707 		return false;
8708 	default:
8709 		/* Only narrow read access allowed for now. */
8710 		if (type == BPF_WRITE) {
8711 			if (size != size_default)
8712 				return false;
8713 		} else {
8714 			bpf_ctx_record_field_size(info, size_default);
8715 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
8716 				return false;
8717 		}
8718 	}
8719 
8720 	return true;
8721 }
8722 
sk_filter_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)8723 static bool sk_filter_is_valid_access(int off, int size,
8724 				      enum bpf_access_type type,
8725 				      const struct bpf_prog *prog,
8726 				      struct bpf_insn_access_aux *info)
8727 {
8728 	switch (off) {
8729 	case bpf_ctx_range(struct __sk_buff, tc_classid):
8730 	case bpf_ctx_range(struct __sk_buff, data):
8731 	case bpf_ctx_range(struct __sk_buff, data_meta):
8732 	case bpf_ctx_range(struct __sk_buff, data_end):
8733 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8734 	case bpf_ctx_range(struct __sk_buff, tstamp):
8735 	case bpf_ctx_range(struct __sk_buff, wire_len):
8736 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
8737 		return false;
8738 	}
8739 
8740 	if (type == BPF_WRITE) {
8741 		switch (off) {
8742 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8743 			break;
8744 		default:
8745 			return false;
8746 		}
8747 	}
8748 
8749 	return bpf_skb_is_valid_access(off, size, type, prog, info);
8750 }
8751 
cg_skb_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)8752 static bool cg_skb_is_valid_access(int off, int size,
8753 				   enum bpf_access_type type,
8754 				   const struct bpf_prog *prog,
8755 				   struct bpf_insn_access_aux *info)
8756 {
8757 	switch (off) {
8758 	case bpf_ctx_range(struct __sk_buff, tc_classid):
8759 	case bpf_ctx_range(struct __sk_buff, data_meta):
8760 	case bpf_ctx_range(struct __sk_buff, wire_len):
8761 		return false;
8762 	case bpf_ctx_range(struct __sk_buff, data):
8763 	case bpf_ctx_range(struct __sk_buff, data_end):
8764 		if (!bpf_token_capable(prog->aux->token, CAP_BPF))
8765 			return false;
8766 		break;
8767 	}
8768 
8769 	if (type == BPF_WRITE) {
8770 		switch (off) {
8771 		case bpf_ctx_range(struct __sk_buff, mark):
8772 		case bpf_ctx_range(struct __sk_buff, priority):
8773 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8774 			break;
8775 		case bpf_ctx_range(struct __sk_buff, tstamp):
8776 			if (!bpf_token_capable(prog->aux->token, CAP_BPF))
8777 				return false;
8778 			break;
8779 		default:
8780 			return false;
8781 		}
8782 	}
8783 
8784 	switch (off) {
8785 	case bpf_ctx_range(struct __sk_buff, data):
8786 		info->reg_type = PTR_TO_PACKET;
8787 		break;
8788 	case bpf_ctx_range(struct __sk_buff, data_end):
8789 		info->reg_type = PTR_TO_PACKET_END;
8790 		break;
8791 	}
8792 
8793 	return bpf_skb_is_valid_access(off, size, type, prog, info);
8794 }
8795 
lwt_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)8796 static bool lwt_is_valid_access(int off, int size,
8797 				enum bpf_access_type type,
8798 				const struct bpf_prog *prog,
8799 				struct bpf_insn_access_aux *info)
8800 {
8801 	switch (off) {
8802 	case bpf_ctx_range(struct __sk_buff, tc_classid):
8803 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
8804 	case bpf_ctx_range(struct __sk_buff, data_meta):
8805 	case bpf_ctx_range(struct __sk_buff, tstamp):
8806 	case bpf_ctx_range(struct __sk_buff, wire_len):
8807 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
8808 		return false;
8809 	}
8810 
8811 	if (type == BPF_WRITE) {
8812 		switch (off) {
8813 		case bpf_ctx_range(struct __sk_buff, mark):
8814 		case bpf_ctx_range(struct __sk_buff, priority):
8815 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
8816 			break;
8817 		default:
8818 			return false;
8819 		}
8820 	}
8821 
8822 	switch (off) {
8823 	case bpf_ctx_range(struct __sk_buff, data):
8824 		info->reg_type = PTR_TO_PACKET;
8825 		break;
8826 	case bpf_ctx_range(struct __sk_buff, data_end):
8827 		info->reg_type = PTR_TO_PACKET_END;
8828 		break;
8829 	}
8830 
8831 	return bpf_skb_is_valid_access(off, size, type, prog, info);
8832 }
8833 
8834 /* Attach type specific accesses */
__sock_filter_check_attach_type(int off,enum bpf_access_type access_type,enum bpf_attach_type attach_type)8835 static bool __sock_filter_check_attach_type(int off,
8836 					    enum bpf_access_type access_type,
8837 					    enum bpf_attach_type attach_type)
8838 {
8839 	switch (off) {
8840 	case offsetof(struct bpf_sock, bound_dev_if):
8841 	case offsetof(struct bpf_sock, mark):
8842 	case offsetof(struct bpf_sock, priority):
8843 		switch (attach_type) {
8844 		case BPF_CGROUP_INET_SOCK_CREATE:
8845 		case BPF_CGROUP_INET_SOCK_RELEASE:
8846 			goto full_access;
8847 		default:
8848 			return false;
8849 		}
8850 	case bpf_ctx_range(struct bpf_sock, src_ip4):
8851 		switch (attach_type) {
8852 		case BPF_CGROUP_INET4_POST_BIND:
8853 			goto read_only;
8854 		default:
8855 			return false;
8856 		}
8857 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
8858 		switch (attach_type) {
8859 		case BPF_CGROUP_INET6_POST_BIND:
8860 			goto read_only;
8861 		default:
8862 			return false;
8863 		}
8864 	case bpf_ctx_range(struct bpf_sock, src_port):
8865 		switch (attach_type) {
8866 		case BPF_CGROUP_INET4_POST_BIND:
8867 		case BPF_CGROUP_INET6_POST_BIND:
8868 			goto read_only;
8869 		default:
8870 			return false;
8871 		}
8872 	}
8873 read_only:
8874 	return access_type == BPF_READ;
8875 full_access:
8876 	return true;
8877 }
8878 
bpf_sock_common_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)8879 bool bpf_sock_common_is_valid_access(int off, int size,
8880 				     enum bpf_access_type type,
8881 				     struct bpf_insn_access_aux *info)
8882 {
8883 	switch (off) {
8884 	case bpf_ctx_range_till(struct bpf_sock, type, priority):
8885 		return false;
8886 	default:
8887 		return bpf_sock_is_valid_access(off, size, type, info);
8888 	}
8889 }
8890 
bpf_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)8891 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
8892 			      struct bpf_insn_access_aux *info)
8893 {
8894 	const int size_default = sizeof(__u32);
8895 	int field_size;
8896 
8897 	if (off < 0 || off >= sizeof(struct bpf_sock))
8898 		return false;
8899 	if (off % size != 0)
8900 		return false;
8901 
8902 	switch (off) {
8903 	case offsetof(struct bpf_sock, state):
8904 	case offsetof(struct bpf_sock, family):
8905 	case offsetof(struct bpf_sock, type):
8906 	case offsetof(struct bpf_sock, protocol):
8907 	case offsetof(struct bpf_sock, src_port):
8908 	case offsetof(struct bpf_sock, rx_queue_mapping):
8909 	case bpf_ctx_range(struct bpf_sock, src_ip4):
8910 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
8911 	case bpf_ctx_range(struct bpf_sock, dst_ip4):
8912 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
8913 		bpf_ctx_record_field_size(info, size_default);
8914 		return bpf_ctx_narrow_access_ok(off, size, size_default);
8915 	case bpf_ctx_range(struct bpf_sock, dst_port):
8916 		field_size = size == size_default ?
8917 			size_default : sizeof_field(struct bpf_sock, dst_port);
8918 		bpf_ctx_record_field_size(info, field_size);
8919 		return bpf_ctx_narrow_access_ok(off, size, field_size);
8920 	case offsetofend(struct bpf_sock, dst_port) ...
8921 	     offsetof(struct bpf_sock, dst_ip4) - 1:
8922 		return false;
8923 	}
8924 
8925 	return size == size_default;
8926 }
8927 
sock_filter_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)8928 static bool sock_filter_is_valid_access(int off, int size,
8929 					enum bpf_access_type type,
8930 					const struct bpf_prog *prog,
8931 					struct bpf_insn_access_aux *info)
8932 {
8933 	if (!bpf_sock_is_valid_access(off, size, type, info))
8934 		return false;
8935 	return __sock_filter_check_attach_type(off, type,
8936 					       prog->expected_attach_type);
8937 }
8938 
bpf_noop_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)8939 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
8940 			     const struct bpf_prog *prog)
8941 {
8942 	/* Neither direct read nor direct write requires any preliminary
8943 	 * action.
8944 	 */
8945 	return 0;
8946 }
8947 
bpf_unclone_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog,int drop_verdict)8948 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
8949 				const struct bpf_prog *prog, int drop_verdict)
8950 {
8951 	struct bpf_insn *insn = insn_buf;
8952 
8953 	if (!direct_write)
8954 		return 0;
8955 
8956 	/* if (!skb->cloned)
8957 	 *       goto start;
8958 	 *
8959 	 * (Fast-path, otherwise approximation that we might be
8960 	 *  a clone, do the rest in helper.)
8961 	 */
8962 	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET);
8963 	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
8964 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
8965 
8966 	/* ret = bpf_skb_pull_data(skb, 0); */
8967 	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
8968 	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
8969 	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
8970 			       BPF_FUNC_skb_pull_data);
8971 	/* if (!ret)
8972 	 *      goto restore;
8973 	 * return TC_ACT_SHOT;
8974 	 */
8975 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
8976 	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
8977 	*insn++ = BPF_EXIT_INSN();
8978 
8979 	/* restore: */
8980 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
8981 	/* start: */
8982 	*insn++ = prog->insnsi[0];
8983 
8984 	return insn - insn_buf;
8985 }
8986 
bpf_gen_ld_abs(const struct bpf_insn * orig,struct bpf_insn * insn_buf)8987 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
8988 			  struct bpf_insn *insn_buf)
8989 {
8990 	bool indirect = BPF_MODE(orig->code) == BPF_IND;
8991 	struct bpf_insn *insn = insn_buf;
8992 
8993 	if (!indirect) {
8994 		*insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
8995 	} else {
8996 		*insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
8997 		if (orig->imm)
8998 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
8999 	}
9000 	/* We're guaranteed here that CTX is in R6. */
9001 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
9002 
9003 	switch (BPF_SIZE(orig->code)) {
9004 	case BPF_B:
9005 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
9006 		break;
9007 	case BPF_H:
9008 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
9009 		break;
9010 	case BPF_W:
9011 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
9012 		break;
9013 	}
9014 
9015 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
9016 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
9017 	*insn++ = BPF_EXIT_INSN();
9018 
9019 	return insn - insn_buf;
9020 }
9021 
tc_cls_act_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)9022 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
9023 			       const struct bpf_prog *prog)
9024 {
9025 	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
9026 }
9027 
tc_cls_act_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9028 static bool tc_cls_act_is_valid_access(int off, int size,
9029 				       enum bpf_access_type type,
9030 				       const struct bpf_prog *prog,
9031 				       struct bpf_insn_access_aux *info)
9032 {
9033 	if (type == BPF_WRITE) {
9034 		switch (off) {
9035 		case bpf_ctx_range(struct __sk_buff, mark):
9036 		case bpf_ctx_range(struct __sk_buff, tc_index):
9037 		case bpf_ctx_range(struct __sk_buff, priority):
9038 		case bpf_ctx_range(struct __sk_buff, tc_classid):
9039 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
9040 		case bpf_ctx_range(struct __sk_buff, tstamp):
9041 		case bpf_ctx_range(struct __sk_buff, queue_mapping):
9042 			break;
9043 		default:
9044 			return false;
9045 		}
9046 	}
9047 
9048 	switch (off) {
9049 	case bpf_ctx_range(struct __sk_buff, data):
9050 		info->reg_type = PTR_TO_PACKET;
9051 		break;
9052 	case bpf_ctx_range(struct __sk_buff, data_meta):
9053 		info->reg_type = PTR_TO_PACKET_META;
9054 		break;
9055 	case bpf_ctx_range(struct __sk_buff, data_end):
9056 		info->reg_type = PTR_TO_PACKET_END;
9057 		break;
9058 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
9059 		return false;
9060 	case offsetof(struct __sk_buff, tstamp_type):
9061 		/* The convert_ctx_access() on reading and writing
9062 		 * __sk_buff->tstamp depends on whether the bpf prog
9063 		 * has used __sk_buff->tstamp_type or not.
9064 		 * Thus, we need to set prog->tstamp_type_access
9065 		 * earlier during is_valid_access() here.
9066 		 */
9067 		((struct bpf_prog *)prog)->tstamp_type_access = 1;
9068 		return size == sizeof(__u8);
9069 	}
9070 
9071 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9072 }
9073 
9074 DEFINE_MUTEX(nf_conn_btf_access_lock);
9075 EXPORT_SYMBOL_GPL(nf_conn_btf_access_lock);
9076 
9077 int (*nfct_btf_struct_access)(struct bpf_verifier_log *log,
9078 			      const struct bpf_reg_state *reg,
9079 			      int off, int size);
9080 EXPORT_SYMBOL_GPL(nfct_btf_struct_access);
9081 
tc_cls_act_btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size)9082 static int tc_cls_act_btf_struct_access(struct bpf_verifier_log *log,
9083 					const struct bpf_reg_state *reg,
9084 					int off, int size)
9085 {
9086 	int ret = -EACCES;
9087 
9088 	mutex_lock(&nf_conn_btf_access_lock);
9089 	if (nfct_btf_struct_access)
9090 		ret = nfct_btf_struct_access(log, reg, off, size);
9091 	mutex_unlock(&nf_conn_btf_access_lock);
9092 
9093 	return ret;
9094 }
9095 
__is_valid_xdp_access(int off,int size)9096 static bool __is_valid_xdp_access(int off, int size)
9097 {
9098 	if (off < 0 || off >= sizeof(struct xdp_md))
9099 		return false;
9100 	if (off % size != 0)
9101 		return false;
9102 	if (size != sizeof(__u32))
9103 		return false;
9104 
9105 	return true;
9106 }
9107 
xdp_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9108 static bool xdp_is_valid_access(int off, int size,
9109 				enum bpf_access_type type,
9110 				const struct bpf_prog *prog,
9111 				struct bpf_insn_access_aux *info)
9112 {
9113 	if (prog->expected_attach_type != BPF_XDP_DEVMAP) {
9114 		switch (off) {
9115 		case offsetof(struct xdp_md, egress_ifindex):
9116 			return false;
9117 		}
9118 	}
9119 
9120 	if (type == BPF_WRITE) {
9121 		if (bpf_prog_is_offloaded(prog->aux)) {
9122 			switch (off) {
9123 			case offsetof(struct xdp_md, rx_queue_index):
9124 				return __is_valid_xdp_access(off, size);
9125 			}
9126 		}
9127 		return false;
9128 	} else {
9129 		switch (off) {
9130 		case offsetof(struct xdp_md, data_meta):
9131 		case offsetof(struct xdp_md, data):
9132 		case offsetof(struct xdp_md, data_end):
9133 			if (info->is_ldsx)
9134 				return false;
9135 		}
9136 	}
9137 
9138 	switch (off) {
9139 	case offsetof(struct xdp_md, data):
9140 		info->reg_type = PTR_TO_PACKET;
9141 		break;
9142 	case offsetof(struct xdp_md, data_meta):
9143 		info->reg_type = PTR_TO_PACKET_META;
9144 		break;
9145 	case offsetof(struct xdp_md, data_end):
9146 		info->reg_type = PTR_TO_PACKET_END;
9147 		break;
9148 	}
9149 
9150 	return __is_valid_xdp_access(off, size);
9151 }
9152 
bpf_warn_invalid_xdp_action(const struct net_device * dev,const struct bpf_prog * prog,u32 act)9153 void bpf_warn_invalid_xdp_action(const struct net_device *dev,
9154 				 const struct bpf_prog *prog, u32 act)
9155 {
9156 	const u32 act_max = XDP_REDIRECT;
9157 
9158 	pr_warn_once("%s XDP return value %u on prog %s (id %d) dev %s, expect packet loss!\n",
9159 		     act > act_max ? "Illegal" : "Driver unsupported",
9160 		     act, prog->aux->name, prog->aux->id, dev ? dev->name : "N/A");
9161 }
9162 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
9163 
xdp_btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size)9164 static int xdp_btf_struct_access(struct bpf_verifier_log *log,
9165 				 const struct bpf_reg_state *reg,
9166 				 int off, int size)
9167 {
9168 	int ret = -EACCES;
9169 
9170 	mutex_lock(&nf_conn_btf_access_lock);
9171 	if (nfct_btf_struct_access)
9172 		ret = nfct_btf_struct_access(log, reg, off, size);
9173 	mutex_unlock(&nf_conn_btf_access_lock);
9174 
9175 	return ret;
9176 }
9177 
sock_addr_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9178 static bool sock_addr_is_valid_access(int off, int size,
9179 				      enum bpf_access_type type,
9180 				      const struct bpf_prog *prog,
9181 				      struct bpf_insn_access_aux *info)
9182 {
9183 	const int size_default = sizeof(__u32);
9184 
9185 	if (off < 0 || off >= sizeof(struct bpf_sock_addr))
9186 		return false;
9187 	if (off % size != 0)
9188 		return false;
9189 
9190 	/* Disallow access to fields not belonging to the attach type's address
9191 	 * family.
9192 	 */
9193 	switch (off) {
9194 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
9195 		switch (prog->expected_attach_type) {
9196 		case BPF_CGROUP_INET4_BIND:
9197 		case BPF_CGROUP_INET4_CONNECT:
9198 		case BPF_CGROUP_INET4_GETPEERNAME:
9199 		case BPF_CGROUP_INET4_GETSOCKNAME:
9200 		case BPF_CGROUP_UDP4_SENDMSG:
9201 		case BPF_CGROUP_UDP4_RECVMSG:
9202 			break;
9203 		default:
9204 			return false;
9205 		}
9206 		break;
9207 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
9208 		switch (prog->expected_attach_type) {
9209 		case BPF_CGROUP_INET6_BIND:
9210 		case BPF_CGROUP_INET6_CONNECT:
9211 		case BPF_CGROUP_INET6_GETPEERNAME:
9212 		case BPF_CGROUP_INET6_GETSOCKNAME:
9213 		case BPF_CGROUP_UDP6_SENDMSG:
9214 		case BPF_CGROUP_UDP6_RECVMSG:
9215 			break;
9216 		default:
9217 			return false;
9218 		}
9219 		break;
9220 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
9221 		switch (prog->expected_attach_type) {
9222 		case BPF_CGROUP_UDP4_SENDMSG:
9223 			break;
9224 		default:
9225 			return false;
9226 		}
9227 		break;
9228 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
9229 				msg_src_ip6[3]):
9230 		switch (prog->expected_attach_type) {
9231 		case BPF_CGROUP_UDP6_SENDMSG:
9232 			break;
9233 		default:
9234 			return false;
9235 		}
9236 		break;
9237 	}
9238 
9239 	switch (off) {
9240 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
9241 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
9242 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
9243 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
9244 				msg_src_ip6[3]):
9245 	case bpf_ctx_range(struct bpf_sock_addr, user_port):
9246 		if (type == BPF_READ) {
9247 			bpf_ctx_record_field_size(info, size_default);
9248 
9249 			if (bpf_ctx_wide_access_ok(off, size,
9250 						   struct bpf_sock_addr,
9251 						   user_ip6))
9252 				return true;
9253 
9254 			if (bpf_ctx_wide_access_ok(off, size,
9255 						   struct bpf_sock_addr,
9256 						   msg_src_ip6))
9257 				return true;
9258 
9259 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
9260 				return false;
9261 		} else {
9262 			if (bpf_ctx_wide_access_ok(off, size,
9263 						   struct bpf_sock_addr,
9264 						   user_ip6))
9265 				return true;
9266 
9267 			if (bpf_ctx_wide_access_ok(off, size,
9268 						   struct bpf_sock_addr,
9269 						   msg_src_ip6))
9270 				return true;
9271 
9272 			if (size != size_default)
9273 				return false;
9274 		}
9275 		break;
9276 	case offsetof(struct bpf_sock_addr, sk):
9277 		if (type != BPF_READ)
9278 			return false;
9279 		if (size != sizeof(__u64))
9280 			return false;
9281 		info->reg_type = PTR_TO_SOCKET;
9282 		break;
9283 	default:
9284 		if (type == BPF_READ) {
9285 			if (size != size_default)
9286 				return false;
9287 		} else {
9288 			return false;
9289 		}
9290 	}
9291 
9292 	return true;
9293 }
9294 
sock_ops_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9295 static bool sock_ops_is_valid_access(int off, int size,
9296 				     enum bpf_access_type type,
9297 				     const struct bpf_prog *prog,
9298 				     struct bpf_insn_access_aux *info)
9299 {
9300 	const int size_default = sizeof(__u32);
9301 
9302 	if (off < 0 || off >= sizeof(struct bpf_sock_ops))
9303 		return false;
9304 
9305 	/* The verifier guarantees that size > 0. */
9306 	if (off % size != 0)
9307 		return false;
9308 
9309 	if (type == BPF_WRITE) {
9310 		switch (off) {
9311 		case offsetof(struct bpf_sock_ops, reply):
9312 		case offsetof(struct bpf_sock_ops, sk_txhash):
9313 			if (size != size_default)
9314 				return false;
9315 			break;
9316 		default:
9317 			return false;
9318 		}
9319 	} else {
9320 		switch (off) {
9321 		case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
9322 					bytes_acked):
9323 			if (size != sizeof(__u64))
9324 				return false;
9325 			break;
9326 		case offsetof(struct bpf_sock_ops, sk):
9327 			if (size != sizeof(__u64))
9328 				return false;
9329 			info->reg_type = PTR_TO_SOCKET_OR_NULL;
9330 			break;
9331 		case offsetof(struct bpf_sock_ops, skb_data):
9332 			if (size != sizeof(__u64))
9333 				return false;
9334 			info->reg_type = PTR_TO_PACKET;
9335 			break;
9336 		case offsetof(struct bpf_sock_ops, skb_data_end):
9337 			if (size != sizeof(__u64))
9338 				return false;
9339 			info->reg_type = PTR_TO_PACKET_END;
9340 			break;
9341 		case offsetof(struct bpf_sock_ops, skb_tcp_flags):
9342 			bpf_ctx_record_field_size(info, size_default);
9343 			return bpf_ctx_narrow_access_ok(off, size,
9344 							size_default);
9345 		case offsetof(struct bpf_sock_ops, skb_hwtstamp):
9346 			if (size != sizeof(__u64))
9347 				return false;
9348 			break;
9349 		default:
9350 			if (size != size_default)
9351 				return false;
9352 			break;
9353 		}
9354 	}
9355 
9356 	return true;
9357 }
9358 
sk_skb_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)9359 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
9360 			   const struct bpf_prog *prog)
9361 {
9362 	return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
9363 }
9364 
sk_skb_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9365 static bool sk_skb_is_valid_access(int off, int size,
9366 				   enum bpf_access_type type,
9367 				   const struct bpf_prog *prog,
9368 				   struct bpf_insn_access_aux *info)
9369 {
9370 	switch (off) {
9371 	case bpf_ctx_range(struct __sk_buff, tc_classid):
9372 	case bpf_ctx_range(struct __sk_buff, data_meta):
9373 	case bpf_ctx_range(struct __sk_buff, tstamp):
9374 	case bpf_ctx_range(struct __sk_buff, wire_len):
9375 	case bpf_ctx_range(struct __sk_buff, hwtstamp):
9376 		return false;
9377 	}
9378 
9379 	if (type == BPF_WRITE) {
9380 		switch (off) {
9381 		case bpf_ctx_range(struct __sk_buff, tc_index):
9382 		case bpf_ctx_range(struct __sk_buff, priority):
9383 			break;
9384 		default:
9385 			return false;
9386 		}
9387 	}
9388 
9389 	switch (off) {
9390 	case bpf_ctx_range(struct __sk_buff, mark):
9391 		return false;
9392 	case bpf_ctx_range(struct __sk_buff, data):
9393 		info->reg_type = PTR_TO_PACKET;
9394 		break;
9395 	case bpf_ctx_range(struct __sk_buff, data_end):
9396 		info->reg_type = PTR_TO_PACKET_END;
9397 		break;
9398 	}
9399 
9400 	return bpf_skb_is_valid_access(off, size, type, prog, info);
9401 }
9402 
sk_msg_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9403 static bool sk_msg_is_valid_access(int off, int size,
9404 				   enum bpf_access_type type,
9405 				   const struct bpf_prog *prog,
9406 				   struct bpf_insn_access_aux *info)
9407 {
9408 	if (type == BPF_WRITE)
9409 		return false;
9410 
9411 	if (off % size != 0)
9412 		return false;
9413 
9414 	switch (off) {
9415 	case offsetof(struct sk_msg_md, data):
9416 		info->reg_type = PTR_TO_PACKET;
9417 		if (size != sizeof(__u64))
9418 			return false;
9419 		break;
9420 	case offsetof(struct sk_msg_md, data_end):
9421 		info->reg_type = PTR_TO_PACKET_END;
9422 		if (size != sizeof(__u64))
9423 			return false;
9424 		break;
9425 	case offsetof(struct sk_msg_md, sk):
9426 		if (size != sizeof(__u64))
9427 			return false;
9428 		info->reg_type = PTR_TO_SOCKET;
9429 		break;
9430 	case bpf_ctx_range(struct sk_msg_md, family):
9431 	case bpf_ctx_range(struct sk_msg_md, remote_ip4):
9432 	case bpf_ctx_range(struct sk_msg_md, local_ip4):
9433 	case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
9434 	case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
9435 	case bpf_ctx_range(struct sk_msg_md, remote_port):
9436 	case bpf_ctx_range(struct sk_msg_md, local_port):
9437 	case bpf_ctx_range(struct sk_msg_md, size):
9438 		if (size != sizeof(__u32))
9439 			return false;
9440 		break;
9441 	default:
9442 		return false;
9443 	}
9444 	return true;
9445 }
9446 
flow_dissector_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)9447 static bool flow_dissector_is_valid_access(int off, int size,
9448 					   enum bpf_access_type type,
9449 					   const struct bpf_prog *prog,
9450 					   struct bpf_insn_access_aux *info)
9451 {
9452 	const int size_default = sizeof(__u32);
9453 
9454 	if (off < 0 || off >= sizeof(struct __sk_buff))
9455 		return false;
9456 
9457 	if (type == BPF_WRITE)
9458 		return false;
9459 
9460 	switch (off) {
9461 	case bpf_ctx_range(struct __sk_buff, data):
9462 		if (info->is_ldsx || size != size_default)
9463 			return false;
9464 		info->reg_type = PTR_TO_PACKET;
9465 		return true;
9466 	case bpf_ctx_range(struct __sk_buff, data_end):
9467 		if (info->is_ldsx || size != size_default)
9468 			return false;
9469 		info->reg_type = PTR_TO_PACKET_END;
9470 		return true;
9471 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
9472 		if (size != sizeof(__u64))
9473 			return false;
9474 		info->reg_type = PTR_TO_FLOW_KEYS;
9475 		return true;
9476 	default:
9477 		return false;
9478 	}
9479 }
9480 
flow_dissector_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)9481 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
9482 					     const struct bpf_insn *si,
9483 					     struct bpf_insn *insn_buf,
9484 					     struct bpf_prog *prog,
9485 					     u32 *target_size)
9486 
9487 {
9488 	struct bpf_insn *insn = insn_buf;
9489 
9490 	switch (si->off) {
9491 	case offsetof(struct __sk_buff, data):
9492 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
9493 				      si->dst_reg, si->src_reg,
9494 				      offsetof(struct bpf_flow_dissector, data));
9495 		break;
9496 
9497 	case offsetof(struct __sk_buff, data_end):
9498 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
9499 				      si->dst_reg, si->src_reg,
9500 				      offsetof(struct bpf_flow_dissector, data_end));
9501 		break;
9502 
9503 	case offsetof(struct __sk_buff, flow_keys):
9504 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
9505 				      si->dst_reg, si->src_reg,
9506 				      offsetof(struct bpf_flow_dissector, flow_keys));
9507 		break;
9508 	}
9509 
9510 	return insn - insn_buf;
9511 }
9512 
bpf_convert_tstamp_type_read(const struct bpf_insn * si,struct bpf_insn * insn)9513 static struct bpf_insn *bpf_convert_tstamp_type_read(const struct bpf_insn *si,
9514 						     struct bpf_insn *insn)
9515 {
9516 	__u8 value_reg = si->dst_reg;
9517 	__u8 skb_reg = si->src_reg;
9518 	BUILD_BUG_ON(__SKB_CLOCK_MAX != (int)BPF_SKB_CLOCK_TAI);
9519 	BUILD_BUG_ON(SKB_CLOCK_REALTIME != (int)BPF_SKB_CLOCK_REALTIME);
9520 	BUILD_BUG_ON(SKB_CLOCK_MONOTONIC != (int)BPF_SKB_CLOCK_MONOTONIC);
9521 	BUILD_BUG_ON(SKB_CLOCK_TAI != (int)BPF_SKB_CLOCK_TAI);
9522 	*insn++ = BPF_LDX_MEM(BPF_B, value_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
9523 	*insn++ = BPF_ALU32_IMM(BPF_AND, value_reg, SKB_TSTAMP_TYPE_MASK);
9524 #ifdef __BIG_ENDIAN_BITFIELD
9525 	*insn++ = BPF_ALU32_IMM(BPF_RSH, value_reg, SKB_TSTAMP_TYPE_RSHIFT);
9526 #else
9527 	BUILD_BUG_ON(!(SKB_TSTAMP_TYPE_MASK & 0x1));
9528 #endif
9529 
9530 	return insn;
9531 }
9532 
bpf_convert_shinfo_access(__u8 dst_reg,__u8 skb_reg,struct bpf_insn * insn)9533 static struct bpf_insn *bpf_convert_shinfo_access(__u8 dst_reg, __u8 skb_reg,
9534 						  struct bpf_insn *insn)
9535 {
9536 	/* si->dst_reg = skb_shinfo(SKB); */
9537 #ifdef NET_SKBUFF_DATA_USES_OFFSET
9538 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
9539 			      BPF_REG_AX, skb_reg,
9540 			      offsetof(struct sk_buff, end));
9541 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
9542 			      dst_reg, skb_reg,
9543 			      offsetof(struct sk_buff, head));
9544 	*insn++ = BPF_ALU64_REG(BPF_ADD, dst_reg, BPF_REG_AX);
9545 #else
9546 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
9547 			      dst_reg, skb_reg,
9548 			      offsetof(struct sk_buff, end));
9549 #endif
9550 
9551 	return insn;
9552 }
9553 
bpf_convert_tstamp_read(const struct bpf_prog * prog,const struct bpf_insn * si,struct bpf_insn * insn)9554 static struct bpf_insn *bpf_convert_tstamp_read(const struct bpf_prog *prog,
9555 						const struct bpf_insn *si,
9556 						struct bpf_insn *insn)
9557 {
9558 	__u8 value_reg = si->dst_reg;
9559 	__u8 skb_reg = si->src_reg;
9560 
9561 #ifdef CONFIG_NET_XGRESS
9562 	/* If the tstamp_type is read,
9563 	 * the bpf prog is aware the tstamp could have delivery time.
9564 	 * Thus, read skb->tstamp as is if tstamp_type_access is true.
9565 	 */
9566 	if (!prog->tstamp_type_access) {
9567 		/* AX is needed because src_reg and dst_reg could be the same */
9568 		__u8 tmp_reg = BPF_REG_AX;
9569 
9570 		*insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
9571 		/* check if ingress mask bits is set */
9572 		*insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, TC_AT_INGRESS_MASK, 1);
9573 		*insn++ = BPF_JMP_A(4);
9574 		*insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, SKB_TSTAMP_TYPE_MASK, 1);
9575 		*insn++ = BPF_JMP_A(2);
9576 		/* skb->tc_at_ingress && skb->tstamp_type,
9577 		 * read 0 as the (rcv) timestamp.
9578 		 */
9579 		*insn++ = BPF_MOV64_IMM(value_reg, 0);
9580 		*insn++ = BPF_JMP_A(1);
9581 	}
9582 #endif
9583 
9584 	*insn++ = BPF_LDX_MEM(BPF_DW, value_reg, skb_reg,
9585 			      offsetof(struct sk_buff, tstamp));
9586 	return insn;
9587 }
9588 
bpf_convert_tstamp_write(const struct bpf_prog * prog,const struct bpf_insn * si,struct bpf_insn * insn)9589 static struct bpf_insn *bpf_convert_tstamp_write(const struct bpf_prog *prog,
9590 						 const struct bpf_insn *si,
9591 						 struct bpf_insn *insn)
9592 {
9593 	__u8 value_reg = si->src_reg;
9594 	__u8 skb_reg = si->dst_reg;
9595 
9596 #ifdef CONFIG_NET_XGRESS
9597 	/* If the tstamp_type is read,
9598 	 * the bpf prog is aware the tstamp could have delivery time.
9599 	 * Thus, write skb->tstamp as is if tstamp_type_access is true.
9600 	 * Otherwise, writing at ingress will have to clear the
9601 	 * skb->tstamp_type bit also.
9602 	 */
9603 	if (!prog->tstamp_type_access) {
9604 		__u8 tmp_reg = BPF_REG_AX;
9605 
9606 		*insn++ = BPF_LDX_MEM(BPF_B, tmp_reg, skb_reg, SKB_BF_MONO_TC_OFFSET);
9607 		/* Writing __sk_buff->tstamp as ingress, goto <clear> */
9608 		*insn++ = BPF_JMP32_IMM(BPF_JSET, tmp_reg, TC_AT_INGRESS_MASK, 1);
9609 		/* goto <store> */
9610 		*insn++ = BPF_JMP_A(2);
9611 		/* <clear>: skb->tstamp_type */
9612 		*insn++ = BPF_ALU32_IMM(BPF_AND, tmp_reg, ~SKB_TSTAMP_TYPE_MASK);
9613 		*insn++ = BPF_STX_MEM(BPF_B, skb_reg, tmp_reg, SKB_BF_MONO_TC_OFFSET);
9614 	}
9615 #endif
9616 
9617 	/* <store>: skb->tstamp = tstamp */
9618 	*insn++ = BPF_RAW_INSN(BPF_CLASS(si->code) | BPF_DW | BPF_MEM,
9619 			       skb_reg, value_reg, offsetof(struct sk_buff, tstamp), si->imm);
9620 	return insn;
9621 }
9622 
9623 #define BPF_EMIT_STORE(size, si, off)					\
9624 	BPF_RAW_INSN(BPF_CLASS((si)->code) | (size) | BPF_MEM,		\
9625 		     (si)->dst_reg, (si)->src_reg, (off), (si)->imm)
9626 
bpf_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)9627 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
9628 				  const struct bpf_insn *si,
9629 				  struct bpf_insn *insn_buf,
9630 				  struct bpf_prog *prog, u32 *target_size)
9631 {
9632 	struct bpf_insn *insn = insn_buf;
9633 	int off;
9634 
9635 	switch (si->off) {
9636 	case offsetof(struct __sk_buff, len):
9637 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9638 				      bpf_target_off(struct sk_buff, len, 4,
9639 						     target_size));
9640 		break;
9641 
9642 	case offsetof(struct __sk_buff, protocol):
9643 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9644 				      bpf_target_off(struct sk_buff, protocol, 2,
9645 						     target_size));
9646 		break;
9647 
9648 	case offsetof(struct __sk_buff, vlan_proto):
9649 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9650 				      bpf_target_off(struct sk_buff, vlan_proto, 2,
9651 						     target_size));
9652 		break;
9653 
9654 	case offsetof(struct __sk_buff, priority):
9655 		if (type == BPF_WRITE)
9656 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
9657 						 bpf_target_off(struct sk_buff, priority, 4,
9658 								target_size));
9659 		else
9660 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9661 					      bpf_target_off(struct sk_buff, priority, 4,
9662 							     target_size));
9663 		break;
9664 
9665 	case offsetof(struct __sk_buff, ingress_ifindex):
9666 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9667 				      bpf_target_off(struct sk_buff, skb_iif, 4,
9668 						     target_size));
9669 		break;
9670 
9671 	case offsetof(struct __sk_buff, ifindex):
9672 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
9673 				      si->dst_reg, si->src_reg,
9674 				      offsetof(struct sk_buff, dev));
9675 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
9676 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9677 				      bpf_target_off(struct net_device, ifindex, 4,
9678 						     target_size));
9679 		break;
9680 
9681 	case offsetof(struct __sk_buff, hash):
9682 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9683 				      bpf_target_off(struct sk_buff, hash, 4,
9684 						     target_size));
9685 		break;
9686 
9687 	case offsetof(struct __sk_buff, mark):
9688 		if (type == BPF_WRITE)
9689 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
9690 						 bpf_target_off(struct sk_buff, mark, 4,
9691 								target_size));
9692 		else
9693 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9694 					      bpf_target_off(struct sk_buff, mark, 4,
9695 							     target_size));
9696 		break;
9697 
9698 	case offsetof(struct __sk_buff, pkt_type):
9699 		*target_size = 1;
9700 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
9701 				      PKT_TYPE_OFFSET);
9702 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
9703 #ifdef __BIG_ENDIAN_BITFIELD
9704 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
9705 #endif
9706 		break;
9707 
9708 	case offsetof(struct __sk_buff, queue_mapping):
9709 		if (type == BPF_WRITE) {
9710 			u32 offset = bpf_target_off(struct sk_buff, queue_mapping, 2, target_size);
9711 
9712 			if (BPF_CLASS(si->code) == BPF_ST && si->imm >= NO_QUEUE_MAPPING) {
9713 				*insn++ = BPF_JMP_A(0); /* noop */
9714 				break;
9715 			}
9716 
9717 			if (BPF_CLASS(si->code) == BPF_STX)
9718 				*insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
9719 			*insn++ = BPF_EMIT_STORE(BPF_H, si, offset);
9720 		} else {
9721 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9722 					      bpf_target_off(struct sk_buff,
9723 							     queue_mapping,
9724 							     2, target_size));
9725 		}
9726 		break;
9727 
9728 	case offsetof(struct __sk_buff, vlan_present):
9729 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9730 				      bpf_target_off(struct sk_buff,
9731 						     vlan_all, 4, target_size));
9732 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
9733 		*insn++ = BPF_ALU32_IMM(BPF_MOV, si->dst_reg, 1);
9734 		break;
9735 
9736 	case offsetof(struct __sk_buff, vlan_tci):
9737 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9738 				      bpf_target_off(struct sk_buff, vlan_tci, 2,
9739 						     target_size));
9740 		break;
9741 
9742 	case offsetof(struct __sk_buff, cb[0]) ...
9743 	     offsetofend(struct __sk_buff, cb[4]) - 1:
9744 		BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, data) < 20);
9745 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
9746 			      offsetof(struct qdisc_skb_cb, data)) %
9747 			     sizeof(__u64));
9748 
9749 		prog->cb_access = 1;
9750 		off  = si->off;
9751 		off -= offsetof(struct __sk_buff, cb[0]);
9752 		off += offsetof(struct sk_buff, cb);
9753 		off += offsetof(struct qdisc_skb_cb, data);
9754 		if (type == BPF_WRITE)
9755 			*insn++ = BPF_EMIT_STORE(BPF_SIZE(si->code), si, off);
9756 		else
9757 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
9758 					      si->src_reg, off);
9759 		break;
9760 
9761 	case offsetof(struct __sk_buff, tc_classid):
9762 		BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, tc_classid) != 2);
9763 
9764 		off  = si->off;
9765 		off -= offsetof(struct __sk_buff, tc_classid);
9766 		off += offsetof(struct sk_buff, cb);
9767 		off += offsetof(struct qdisc_skb_cb, tc_classid);
9768 		*target_size = 2;
9769 		if (type == BPF_WRITE)
9770 			*insn++ = BPF_EMIT_STORE(BPF_H, si, off);
9771 		else
9772 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
9773 					      si->src_reg, off);
9774 		break;
9775 
9776 	case offsetof(struct __sk_buff, data):
9777 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
9778 				      si->dst_reg, si->src_reg,
9779 				      offsetof(struct sk_buff, data));
9780 		break;
9781 
9782 	case offsetof(struct __sk_buff, data_meta):
9783 		off  = si->off;
9784 		off -= offsetof(struct __sk_buff, data_meta);
9785 		off += offsetof(struct sk_buff, cb);
9786 		off += offsetof(struct bpf_skb_data_end, data_meta);
9787 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
9788 				      si->src_reg, off);
9789 		break;
9790 
9791 	case offsetof(struct __sk_buff, data_end):
9792 		off  = si->off;
9793 		off -= offsetof(struct __sk_buff, data_end);
9794 		off += offsetof(struct sk_buff, cb);
9795 		off += offsetof(struct bpf_skb_data_end, data_end);
9796 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
9797 				      si->src_reg, off);
9798 		break;
9799 
9800 	case offsetof(struct __sk_buff, tc_index):
9801 #ifdef CONFIG_NET_SCHED
9802 		if (type == BPF_WRITE)
9803 			*insn++ = BPF_EMIT_STORE(BPF_H, si,
9804 						 bpf_target_off(struct sk_buff, tc_index, 2,
9805 								target_size));
9806 		else
9807 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
9808 					      bpf_target_off(struct sk_buff, tc_index, 2,
9809 							     target_size));
9810 #else
9811 		*target_size = 2;
9812 		if (type == BPF_WRITE)
9813 			*insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
9814 		else
9815 			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
9816 #endif
9817 		break;
9818 
9819 	case offsetof(struct __sk_buff, napi_id):
9820 #if defined(CONFIG_NET_RX_BUSY_POLL)
9821 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
9822 				      bpf_target_off(struct sk_buff, napi_id, 4,
9823 						     target_size));
9824 		*insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
9825 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
9826 #else
9827 		*target_size = 4;
9828 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
9829 #endif
9830 		break;
9831 	case offsetof(struct __sk_buff, family):
9832 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
9833 
9834 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9835 				      si->dst_reg, si->src_reg,
9836 				      offsetof(struct sk_buff, sk));
9837 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
9838 				      bpf_target_off(struct sock_common,
9839 						     skc_family,
9840 						     2, target_size));
9841 		break;
9842 	case offsetof(struct __sk_buff, remote_ip4):
9843 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
9844 
9845 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9846 				      si->dst_reg, si->src_reg,
9847 				      offsetof(struct sk_buff, sk));
9848 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9849 				      bpf_target_off(struct sock_common,
9850 						     skc_daddr,
9851 						     4, target_size));
9852 		break;
9853 	case offsetof(struct __sk_buff, local_ip4):
9854 		BUILD_BUG_ON(sizeof_field(struct sock_common,
9855 					  skc_rcv_saddr) != 4);
9856 
9857 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9858 				      si->dst_reg, si->src_reg,
9859 				      offsetof(struct sk_buff, sk));
9860 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9861 				      bpf_target_off(struct sock_common,
9862 						     skc_rcv_saddr,
9863 						     4, target_size));
9864 		break;
9865 	case offsetof(struct __sk_buff, remote_ip6[0]) ...
9866 	     offsetof(struct __sk_buff, remote_ip6[3]):
9867 #if IS_ENABLED(CONFIG_IPV6)
9868 		BUILD_BUG_ON(sizeof_field(struct sock_common,
9869 					  skc_v6_daddr.s6_addr32[0]) != 4);
9870 
9871 		off = si->off;
9872 		off -= offsetof(struct __sk_buff, remote_ip6[0]);
9873 
9874 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9875 				      si->dst_reg, si->src_reg,
9876 				      offsetof(struct sk_buff, sk));
9877 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9878 				      offsetof(struct sock_common,
9879 					       skc_v6_daddr.s6_addr32[0]) +
9880 				      off);
9881 #else
9882 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
9883 #endif
9884 		break;
9885 	case offsetof(struct __sk_buff, local_ip6[0]) ...
9886 	     offsetof(struct __sk_buff, local_ip6[3]):
9887 #if IS_ENABLED(CONFIG_IPV6)
9888 		BUILD_BUG_ON(sizeof_field(struct sock_common,
9889 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
9890 
9891 		off = si->off;
9892 		off -= offsetof(struct __sk_buff, local_ip6[0]);
9893 
9894 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9895 				      si->dst_reg, si->src_reg,
9896 				      offsetof(struct sk_buff, sk));
9897 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
9898 				      offsetof(struct sock_common,
9899 					       skc_v6_rcv_saddr.s6_addr32[0]) +
9900 				      off);
9901 #else
9902 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
9903 #endif
9904 		break;
9905 
9906 	case offsetof(struct __sk_buff, remote_port):
9907 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
9908 
9909 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9910 				      si->dst_reg, si->src_reg,
9911 				      offsetof(struct sk_buff, sk));
9912 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
9913 				      bpf_target_off(struct sock_common,
9914 						     skc_dport,
9915 						     2, target_size));
9916 #ifndef __BIG_ENDIAN_BITFIELD
9917 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
9918 #endif
9919 		break;
9920 
9921 	case offsetof(struct __sk_buff, local_port):
9922 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
9923 
9924 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9925 				      si->dst_reg, si->src_reg,
9926 				      offsetof(struct sk_buff, sk));
9927 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
9928 				      bpf_target_off(struct sock_common,
9929 						     skc_num, 2, target_size));
9930 		break;
9931 
9932 	case offsetof(struct __sk_buff, tstamp):
9933 		BUILD_BUG_ON(sizeof_field(struct sk_buff, tstamp) != 8);
9934 
9935 		if (type == BPF_WRITE)
9936 			insn = bpf_convert_tstamp_write(prog, si, insn);
9937 		else
9938 			insn = bpf_convert_tstamp_read(prog, si, insn);
9939 		break;
9940 
9941 	case offsetof(struct __sk_buff, tstamp_type):
9942 		insn = bpf_convert_tstamp_type_read(si, insn);
9943 		break;
9944 
9945 	case offsetof(struct __sk_buff, gso_segs):
9946 		insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
9947 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
9948 				      si->dst_reg, si->dst_reg,
9949 				      bpf_target_off(struct skb_shared_info,
9950 						     gso_segs, 2,
9951 						     target_size));
9952 		break;
9953 	case offsetof(struct __sk_buff, gso_size):
9954 		insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
9955 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_size),
9956 				      si->dst_reg, si->dst_reg,
9957 				      bpf_target_off(struct skb_shared_info,
9958 						     gso_size, 2,
9959 						     target_size));
9960 		break;
9961 	case offsetof(struct __sk_buff, wire_len):
9962 		BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, pkt_len) != 4);
9963 
9964 		off = si->off;
9965 		off -= offsetof(struct __sk_buff, wire_len);
9966 		off += offsetof(struct sk_buff, cb);
9967 		off += offsetof(struct qdisc_skb_cb, pkt_len);
9968 		*target_size = 4;
9969 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
9970 		break;
9971 
9972 	case offsetof(struct __sk_buff, sk):
9973 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
9974 				      si->dst_reg, si->src_reg,
9975 				      offsetof(struct sk_buff, sk));
9976 		break;
9977 	case offsetof(struct __sk_buff, hwtstamp):
9978 		BUILD_BUG_ON(sizeof_field(struct skb_shared_hwtstamps, hwtstamp) != 8);
9979 		BUILD_BUG_ON(offsetof(struct skb_shared_hwtstamps, hwtstamp) != 0);
9980 
9981 		insn = bpf_convert_shinfo_access(si->dst_reg, si->src_reg, insn);
9982 		*insn++ = BPF_LDX_MEM(BPF_DW,
9983 				      si->dst_reg, si->dst_reg,
9984 				      bpf_target_off(struct skb_shared_info,
9985 						     hwtstamps, 8,
9986 						     target_size));
9987 		break;
9988 	}
9989 
9990 	return insn - insn_buf;
9991 }
9992 
bpf_sock_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)9993 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
9994 				const struct bpf_insn *si,
9995 				struct bpf_insn *insn_buf,
9996 				struct bpf_prog *prog, u32 *target_size)
9997 {
9998 	struct bpf_insn *insn = insn_buf;
9999 	int off;
10000 
10001 	switch (si->off) {
10002 	case offsetof(struct bpf_sock, bound_dev_if):
10003 		BUILD_BUG_ON(sizeof_field(struct sock, sk_bound_dev_if) != 4);
10004 
10005 		if (type == BPF_WRITE)
10006 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10007 						 offsetof(struct sock, sk_bound_dev_if));
10008 		else
10009 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10010 				      offsetof(struct sock, sk_bound_dev_if));
10011 		break;
10012 
10013 	case offsetof(struct bpf_sock, mark):
10014 		BUILD_BUG_ON(sizeof_field(struct sock, sk_mark) != 4);
10015 
10016 		if (type == BPF_WRITE)
10017 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10018 						 offsetof(struct sock, sk_mark));
10019 		else
10020 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10021 				      offsetof(struct sock, sk_mark));
10022 		break;
10023 
10024 	case offsetof(struct bpf_sock, priority):
10025 		BUILD_BUG_ON(sizeof_field(struct sock, sk_priority) != 4);
10026 
10027 		if (type == BPF_WRITE)
10028 			*insn++ = BPF_EMIT_STORE(BPF_W, si,
10029 						 offsetof(struct sock, sk_priority));
10030 		else
10031 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10032 				      offsetof(struct sock, sk_priority));
10033 		break;
10034 
10035 	case offsetof(struct bpf_sock, family):
10036 		*insn++ = BPF_LDX_MEM(
10037 			BPF_FIELD_SIZEOF(struct sock_common, skc_family),
10038 			si->dst_reg, si->src_reg,
10039 			bpf_target_off(struct sock_common,
10040 				       skc_family,
10041 				       sizeof_field(struct sock_common,
10042 						    skc_family),
10043 				       target_size));
10044 		break;
10045 
10046 	case offsetof(struct bpf_sock, type):
10047 		*insn++ = BPF_LDX_MEM(
10048 			BPF_FIELD_SIZEOF(struct sock, sk_type),
10049 			si->dst_reg, si->src_reg,
10050 			bpf_target_off(struct sock, sk_type,
10051 				       sizeof_field(struct sock, sk_type),
10052 				       target_size));
10053 		break;
10054 
10055 	case offsetof(struct bpf_sock, protocol):
10056 		*insn++ = BPF_LDX_MEM(
10057 			BPF_FIELD_SIZEOF(struct sock, sk_protocol),
10058 			si->dst_reg, si->src_reg,
10059 			bpf_target_off(struct sock, sk_protocol,
10060 				       sizeof_field(struct sock, sk_protocol),
10061 				       target_size));
10062 		break;
10063 
10064 	case offsetof(struct bpf_sock, src_ip4):
10065 		*insn++ = BPF_LDX_MEM(
10066 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10067 			bpf_target_off(struct sock_common, skc_rcv_saddr,
10068 				       sizeof_field(struct sock_common,
10069 						    skc_rcv_saddr),
10070 				       target_size));
10071 		break;
10072 
10073 	case offsetof(struct bpf_sock, dst_ip4):
10074 		*insn++ = BPF_LDX_MEM(
10075 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10076 			bpf_target_off(struct sock_common, skc_daddr,
10077 				       sizeof_field(struct sock_common,
10078 						    skc_daddr),
10079 				       target_size));
10080 		break;
10081 
10082 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
10083 #if IS_ENABLED(CONFIG_IPV6)
10084 		off = si->off;
10085 		off -= offsetof(struct bpf_sock, src_ip6[0]);
10086 		*insn++ = BPF_LDX_MEM(
10087 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10088 			bpf_target_off(
10089 				struct sock_common,
10090 				skc_v6_rcv_saddr.s6_addr32[0],
10091 				sizeof_field(struct sock_common,
10092 					     skc_v6_rcv_saddr.s6_addr32[0]),
10093 				target_size) + off);
10094 #else
10095 		(void)off;
10096 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10097 #endif
10098 		break;
10099 
10100 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
10101 #if IS_ENABLED(CONFIG_IPV6)
10102 		off = si->off;
10103 		off -= offsetof(struct bpf_sock, dst_ip6[0]);
10104 		*insn++ = BPF_LDX_MEM(
10105 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
10106 			bpf_target_off(struct sock_common,
10107 				       skc_v6_daddr.s6_addr32[0],
10108 				       sizeof_field(struct sock_common,
10109 						    skc_v6_daddr.s6_addr32[0]),
10110 				       target_size) + off);
10111 #else
10112 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10113 		*target_size = 4;
10114 #endif
10115 		break;
10116 
10117 	case offsetof(struct bpf_sock, src_port):
10118 		*insn++ = BPF_LDX_MEM(
10119 			BPF_FIELD_SIZEOF(struct sock_common, skc_num),
10120 			si->dst_reg, si->src_reg,
10121 			bpf_target_off(struct sock_common, skc_num,
10122 				       sizeof_field(struct sock_common,
10123 						    skc_num),
10124 				       target_size));
10125 		break;
10126 
10127 	case offsetof(struct bpf_sock, dst_port):
10128 		*insn++ = BPF_LDX_MEM(
10129 			BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
10130 			si->dst_reg, si->src_reg,
10131 			bpf_target_off(struct sock_common, skc_dport,
10132 				       sizeof_field(struct sock_common,
10133 						    skc_dport),
10134 				       target_size));
10135 		break;
10136 
10137 	case offsetof(struct bpf_sock, state):
10138 		*insn++ = BPF_LDX_MEM(
10139 			BPF_FIELD_SIZEOF(struct sock_common, skc_state),
10140 			si->dst_reg, si->src_reg,
10141 			bpf_target_off(struct sock_common, skc_state,
10142 				       sizeof_field(struct sock_common,
10143 						    skc_state),
10144 				       target_size));
10145 		break;
10146 	case offsetof(struct bpf_sock, rx_queue_mapping):
10147 #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
10148 		*insn++ = BPF_LDX_MEM(
10149 			BPF_FIELD_SIZEOF(struct sock, sk_rx_queue_mapping),
10150 			si->dst_reg, si->src_reg,
10151 			bpf_target_off(struct sock, sk_rx_queue_mapping,
10152 				       sizeof_field(struct sock,
10153 						    sk_rx_queue_mapping),
10154 				       target_size));
10155 		*insn++ = BPF_JMP_IMM(BPF_JNE, si->dst_reg, NO_QUEUE_MAPPING,
10156 				      1);
10157 		*insn++ = BPF_MOV64_IMM(si->dst_reg, -1);
10158 #else
10159 		*insn++ = BPF_MOV64_IMM(si->dst_reg, -1);
10160 		*target_size = 2;
10161 #endif
10162 		break;
10163 	}
10164 
10165 	return insn - insn_buf;
10166 }
10167 
tc_cls_act_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)10168 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
10169 					 const struct bpf_insn *si,
10170 					 struct bpf_insn *insn_buf,
10171 					 struct bpf_prog *prog, u32 *target_size)
10172 {
10173 	struct bpf_insn *insn = insn_buf;
10174 
10175 	switch (si->off) {
10176 	case offsetof(struct __sk_buff, ifindex):
10177 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
10178 				      si->dst_reg, si->src_reg,
10179 				      offsetof(struct sk_buff, dev));
10180 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10181 				      bpf_target_off(struct net_device, ifindex, 4,
10182 						     target_size));
10183 		break;
10184 	default:
10185 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
10186 					      target_size);
10187 	}
10188 
10189 	return insn - insn_buf;
10190 }
10191 
xdp_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)10192 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
10193 				  const struct bpf_insn *si,
10194 				  struct bpf_insn *insn_buf,
10195 				  struct bpf_prog *prog, u32 *target_size)
10196 {
10197 	struct bpf_insn *insn = insn_buf;
10198 
10199 	switch (si->off) {
10200 	case offsetof(struct xdp_md, data):
10201 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
10202 				      si->dst_reg, si->src_reg,
10203 				      offsetof(struct xdp_buff, data));
10204 		break;
10205 	case offsetof(struct xdp_md, data_meta):
10206 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
10207 				      si->dst_reg, si->src_reg,
10208 				      offsetof(struct xdp_buff, data_meta));
10209 		break;
10210 	case offsetof(struct xdp_md, data_end):
10211 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
10212 				      si->dst_reg, si->src_reg,
10213 				      offsetof(struct xdp_buff, data_end));
10214 		break;
10215 	case offsetof(struct xdp_md, ingress_ifindex):
10216 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
10217 				      si->dst_reg, si->src_reg,
10218 				      offsetof(struct xdp_buff, rxq));
10219 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
10220 				      si->dst_reg, si->dst_reg,
10221 				      offsetof(struct xdp_rxq_info, dev));
10222 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10223 				      offsetof(struct net_device, ifindex));
10224 		break;
10225 	case offsetof(struct xdp_md, rx_queue_index):
10226 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
10227 				      si->dst_reg, si->src_reg,
10228 				      offsetof(struct xdp_buff, rxq));
10229 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10230 				      offsetof(struct xdp_rxq_info,
10231 					       queue_index));
10232 		break;
10233 	case offsetof(struct xdp_md, egress_ifindex):
10234 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, txq),
10235 				      si->dst_reg, si->src_reg,
10236 				      offsetof(struct xdp_buff, txq));
10237 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_txq_info, dev),
10238 				      si->dst_reg, si->dst_reg,
10239 				      offsetof(struct xdp_txq_info, dev));
10240 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10241 				      offsetof(struct net_device, ifindex));
10242 		break;
10243 	}
10244 
10245 	return insn - insn_buf;
10246 }
10247 
10248 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
10249  * context Structure, F is Field in context structure that contains a pointer
10250  * to Nested Structure of type NS that has the field NF.
10251  *
10252  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
10253  * sure that SIZE is not greater than actual size of S.F.NF.
10254  *
10255  * If offset OFF is provided, the load happens from that offset relative to
10256  * offset of NF.
10257  */
10258 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)	       \
10259 	do {								       \
10260 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
10261 				      si->src_reg, offsetof(S, F));	       \
10262 		*insn++ = BPF_LDX_MEM(					       \
10263 			SIZE, si->dst_reg, si->dst_reg,			       \
10264 			bpf_target_off(NS, NF, sizeof_field(NS, NF),	       \
10265 				       target_size)			       \
10266 				+ OFF);					       \
10267 	} while (0)
10268 
10269 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)			       \
10270 	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,		       \
10271 					     BPF_FIELD_SIZEOF(NS, NF), 0)
10272 
10273 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
10274  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
10275  *
10276  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
10277  * "register" since two registers available in convert_ctx_access are not
10278  * enough: we can't override neither SRC, since it contains value to store, nor
10279  * DST since it contains pointer to context that may be used by later
10280  * instructions. But we need a temporary place to save pointer to nested
10281  * structure whose field we want to store to.
10282  */
10283 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE, OFF, TF)	       \
10284 	do {								       \
10285 		int tmp_reg = BPF_REG_9;				       \
10286 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
10287 			--tmp_reg;					       \
10288 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
10289 			--tmp_reg;					       \
10290 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,	       \
10291 				      offsetof(S, TF));			       \
10292 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,	       \
10293 				      si->dst_reg, offsetof(S, F));	       \
10294 		*insn++ = BPF_RAW_INSN(SIZE | BPF_MEM | BPF_CLASS(si->code),   \
10295 				       tmp_reg, si->src_reg,		       \
10296 			bpf_target_off(NS, NF, sizeof_field(NS, NF),	       \
10297 				       target_size)			       \
10298 				       + OFF,				       \
10299 				       si->imm);			       \
10300 		*insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,	       \
10301 				      offsetof(S, TF));			       \
10302 	} while (0)
10303 
10304 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
10305 						      TF)		       \
10306 	do {								       \
10307 		if (type == BPF_WRITE) {				       \
10308 			SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE,   \
10309 							 OFF, TF);	       \
10310 		} else {						       \
10311 			SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(		       \
10312 				S, NS, F, NF, SIZE, OFF);  \
10313 		}							       \
10314 	} while (0)
10315 
sock_addr_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)10316 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
10317 					const struct bpf_insn *si,
10318 					struct bpf_insn *insn_buf,
10319 					struct bpf_prog *prog, u32 *target_size)
10320 {
10321 	int off, port_size = sizeof_field(struct sockaddr_in6, sin6_port);
10322 	struct bpf_insn *insn = insn_buf;
10323 
10324 	switch (si->off) {
10325 	case offsetof(struct bpf_sock_addr, user_family):
10326 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10327 					    struct sockaddr, uaddr, sa_family);
10328 		break;
10329 
10330 	case offsetof(struct bpf_sock_addr, user_ip4):
10331 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10332 			struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
10333 			sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
10334 		break;
10335 
10336 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
10337 		off = si->off;
10338 		off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
10339 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10340 			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
10341 			sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
10342 			tmp_reg);
10343 		break;
10344 
10345 	case offsetof(struct bpf_sock_addr, user_port):
10346 		/* To get port we need to know sa_family first and then treat
10347 		 * sockaddr as either sockaddr_in or sockaddr_in6.
10348 		 * Though we can simplify since port field has same offset and
10349 		 * size in both structures.
10350 		 * Here we check this invariant and use just one of the
10351 		 * structures if it's true.
10352 		 */
10353 		BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
10354 			     offsetof(struct sockaddr_in6, sin6_port));
10355 		BUILD_BUG_ON(sizeof_field(struct sockaddr_in, sin_port) !=
10356 			     sizeof_field(struct sockaddr_in6, sin6_port));
10357 		/* Account for sin6_port being smaller than user_port. */
10358 		port_size = min(port_size, BPF_LDST_BYTES(si));
10359 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10360 			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
10361 			sin6_port, bytes_to_bpf_size(port_size), 0, tmp_reg);
10362 		break;
10363 
10364 	case offsetof(struct bpf_sock_addr, family):
10365 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10366 					    struct sock, sk, sk_family);
10367 		break;
10368 
10369 	case offsetof(struct bpf_sock_addr, type):
10370 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10371 					    struct sock, sk, sk_type);
10372 		break;
10373 
10374 	case offsetof(struct bpf_sock_addr, protocol):
10375 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
10376 					    struct sock, sk, sk_protocol);
10377 		break;
10378 
10379 	case offsetof(struct bpf_sock_addr, msg_src_ip4):
10380 		/* Treat t_ctx as struct in_addr for msg_src_ip4. */
10381 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10382 			struct bpf_sock_addr_kern, struct in_addr, t_ctx,
10383 			s_addr, BPF_SIZE(si->code), 0, tmp_reg);
10384 		break;
10385 
10386 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
10387 				msg_src_ip6[3]):
10388 		off = si->off;
10389 		off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
10390 		/* Treat t_ctx as struct in6_addr for msg_src_ip6. */
10391 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
10392 			struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
10393 			s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
10394 		break;
10395 	case offsetof(struct bpf_sock_addr, sk):
10396 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_addr_kern, sk),
10397 				      si->dst_reg, si->src_reg,
10398 				      offsetof(struct bpf_sock_addr_kern, sk));
10399 		break;
10400 	}
10401 
10402 	return insn - insn_buf;
10403 }
10404 
sock_ops_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)10405 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
10406 				       const struct bpf_insn *si,
10407 				       struct bpf_insn *insn_buf,
10408 				       struct bpf_prog *prog,
10409 				       u32 *target_size)
10410 {
10411 	struct bpf_insn *insn = insn_buf;
10412 	int off;
10413 
10414 /* Helper macro for adding read access to tcp_sock or sock fields. */
10415 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
10416 	do {								      \
10417 		int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 2;     \
10418 		BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >		      \
10419 			     sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
10420 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10421 			reg--;						      \
10422 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10423 			reg--;						      \
10424 		if (si->dst_reg == si->src_reg) {			      \
10425 			*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,	      \
10426 					  offsetof(struct bpf_sock_ops_kern,  \
10427 					  temp));			      \
10428 			fullsock_reg = reg;				      \
10429 			jmp += 2;					      \
10430 		}							      \
10431 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10432 						struct bpf_sock_ops_kern,     \
10433 						is_locked_tcp_sock),	      \
10434 				      fullsock_reg, si->src_reg,	      \
10435 				      offsetof(struct bpf_sock_ops_kern,      \
10436 					       is_locked_tcp_sock));	      \
10437 		*insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);	      \
10438 		if (si->dst_reg == si->src_reg)				      \
10439 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10440 				      offsetof(struct bpf_sock_ops_kern,      \
10441 				      temp));				      \
10442 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10443 						struct bpf_sock_ops_kern, sk),\
10444 				      si->dst_reg, si->src_reg,		      \
10445 				      offsetof(struct bpf_sock_ops_kern, sk));\
10446 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,		      \
10447 						       OBJ_FIELD),	      \
10448 				      si->dst_reg, si->dst_reg,		      \
10449 				      offsetof(OBJ, OBJ_FIELD));	      \
10450 		if (si->dst_reg == si->src_reg)	{			      \
10451 			*insn++ = BPF_JMP_A(1);				      \
10452 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10453 				      offsetof(struct bpf_sock_ops_kern,      \
10454 				      temp));				      \
10455 		}							      \
10456 	} while (0)
10457 
10458 #define SOCK_OPS_GET_SK()							      \
10459 	do {								      \
10460 		int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 1;     \
10461 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10462 			reg--;						      \
10463 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10464 			reg--;						      \
10465 		if (si->dst_reg == si->src_reg) {			      \
10466 			*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,	      \
10467 					  offsetof(struct bpf_sock_ops_kern,  \
10468 					  temp));			      \
10469 			fullsock_reg = reg;				      \
10470 			jmp += 2;					      \
10471 		}							      \
10472 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10473 						struct bpf_sock_ops_kern,     \
10474 						is_fullsock),		      \
10475 				      fullsock_reg, si->src_reg,	      \
10476 				      offsetof(struct bpf_sock_ops_kern,      \
10477 					       is_fullsock));		      \
10478 		*insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);	      \
10479 		if (si->dst_reg == si->src_reg)				      \
10480 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10481 				      offsetof(struct bpf_sock_ops_kern,      \
10482 				      temp));				      \
10483 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10484 						struct bpf_sock_ops_kern, sk),\
10485 				      si->dst_reg, si->src_reg,		      \
10486 				      offsetof(struct bpf_sock_ops_kern, sk));\
10487 		if (si->dst_reg == si->src_reg)	{			      \
10488 			*insn++ = BPF_JMP_A(1);				      \
10489 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
10490 				      offsetof(struct bpf_sock_ops_kern,      \
10491 				      temp));				      \
10492 		}							      \
10493 	} while (0)
10494 
10495 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
10496 		SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
10497 
10498 /* Helper macro for adding write access to tcp_sock or sock fields.
10499  * The macro is called with two registers, dst_reg which contains a pointer
10500  * to ctx (context) and src_reg which contains the value that should be
10501  * stored. However, we need an additional register since we cannot overwrite
10502  * dst_reg because it may be used later in the program.
10503  * Instead we "borrow" one of the other register. We first save its value
10504  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
10505  * it at the end of the macro.
10506  */
10507 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
10508 	do {								      \
10509 		int reg = BPF_REG_9;					      \
10510 		BUILD_BUG_ON(sizeof_field(OBJ, OBJ_FIELD) >		      \
10511 			     sizeof_field(struct bpf_sock_ops, BPF_FIELD));   \
10512 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10513 			reg--;						      \
10514 		if (si->dst_reg == reg || si->src_reg == reg)		      \
10515 			reg--;						      \
10516 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,		      \
10517 				      offsetof(struct bpf_sock_ops_kern,      \
10518 					       temp));			      \
10519 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10520 						struct bpf_sock_ops_kern,     \
10521 						is_locked_tcp_sock),	      \
10522 				      reg, si->dst_reg,			      \
10523 				      offsetof(struct bpf_sock_ops_kern,      \
10524 					       is_locked_tcp_sock));	      \
10525 		*insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);		      \
10526 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
10527 						struct bpf_sock_ops_kern, sk),\
10528 				      reg, si->dst_reg,			      \
10529 				      offsetof(struct bpf_sock_ops_kern, sk));\
10530 		*insn++ = BPF_RAW_INSN(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD) |     \
10531 				       BPF_MEM | BPF_CLASS(si->code),	      \
10532 				       reg, si->src_reg,		      \
10533 				       offsetof(OBJ, OBJ_FIELD),	      \
10534 				       si->imm);			      \
10535 		*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,		      \
10536 				      offsetof(struct bpf_sock_ops_kern,      \
10537 					       temp));			      \
10538 	} while (0)
10539 
10540 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)	      \
10541 	do {								      \
10542 		if (TYPE == BPF_WRITE)					      \
10543 			SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
10544 		else							      \
10545 			SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
10546 	} while (0)
10547 
10548 	switch (si->off) {
10549 	case offsetof(struct bpf_sock_ops, op):
10550 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10551 						       op),
10552 				      si->dst_reg, si->src_reg,
10553 				      offsetof(struct bpf_sock_ops_kern, op));
10554 		break;
10555 
10556 	case offsetof(struct bpf_sock_ops, replylong[0]) ...
10557 	     offsetof(struct bpf_sock_ops, replylong[3]):
10558 		BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, reply) !=
10559 			     sizeof_field(struct bpf_sock_ops_kern, reply));
10560 		BUILD_BUG_ON(sizeof_field(struct bpf_sock_ops, replylong) !=
10561 			     sizeof_field(struct bpf_sock_ops_kern, replylong));
10562 		off = si->off;
10563 		off -= offsetof(struct bpf_sock_ops, replylong[0]);
10564 		off += offsetof(struct bpf_sock_ops_kern, replylong[0]);
10565 		if (type == BPF_WRITE)
10566 			*insn++ = BPF_EMIT_STORE(BPF_W, si, off);
10567 		else
10568 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
10569 					      off);
10570 		break;
10571 
10572 	case offsetof(struct bpf_sock_ops, family):
10573 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
10574 
10575 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10576 					      struct bpf_sock_ops_kern, sk),
10577 				      si->dst_reg, si->src_reg,
10578 				      offsetof(struct bpf_sock_ops_kern, sk));
10579 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10580 				      offsetof(struct sock_common, skc_family));
10581 		break;
10582 
10583 	case offsetof(struct bpf_sock_ops, remote_ip4):
10584 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
10585 
10586 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10587 						struct bpf_sock_ops_kern, sk),
10588 				      si->dst_reg, si->src_reg,
10589 				      offsetof(struct bpf_sock_ops_kern, sk));
10590 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10591 				      offsetof(struct sock_common, skc_daddr));
10592 		break;
10593 
10594 	case offsetof(struct bpf_sock_ops, local_ip4):
10595 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10596 					  skc_rcv_saddr) != 4);
10597 
10598 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10599 					      struct bpf_sock_ops_kern, sk),
10600 				      si->dst_reg, si->src_reg,
10601 				      offsetof(struct bpf_sock_ops_kern, sk));
10602 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10603 				      offsetof(struct sock_common,
10604 					       skc_rcv_saddr));
10605 		break;
10606 
10607 	case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
10608 	     offsetof(struct bpf_sock_ops, remote_ip6[3]):
10609 #if IS_ENABLED(CONFIG_IPV6)
10610 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10611 					  skc_v6_daddr.s6_addr32[0]) != 4);
10612 
10613 		off = si->off;
10614 		off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
10615 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10616 						struct bpf_sock_ops_kern, sk),
10617 				      si->dst_reg, si->src_reg,
10618 				      offsetof(struct bpf_sock_ops_kern, sk));
10619 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10620 				      offsetof(struct sock_common,
10621 					       skc_v6_daddr.s6_addr32[0]) +
10622 				      off);
10623 #else
10624 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10625 #endif
10626 		break;
10627 
10628 	case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
10629 	     offsetof(struct bpf_sock_ops, local_ip6[3]):
10630 #if IS_ENABLED(CONFIG_IPV6)
10631 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10632 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
10633 
10634 		off = si->off;
10635 		off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
10636 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10637 						struct bpf_sock_ops_kern, sk),
10638 				      si->dst_reg, si->src_reg,
10639 				      offsetof(struct bpf_sock_ops_kern, sk));
10640 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10641 				      offsetof(struct sock_common,
10642 					       skc_v6_rcv_saddr.s6_addr32[0]) +
10643 				      off);
10644 #else
10645 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
10646 #endif
10647 		break;
10648 
10649 	case offsetof(struct bpf_sock_ops, remote_port):
10650 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
10651 
10652 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10653 						struct bpf_sock_ops_kern, sk),
10654 				      si->dst_reg, si->src_reg,
10655 				      offsetof(struct bpf_sock_ops_kern, sk));
10656 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10657 				      offsetof(struct sock_common, skc_dport));
10658 #ifndef __BIG_ENDIAN_BITFIELD
10659 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
10660 #endif
10661 		break;
10662 
10663 	case offsetof(struct bpf_sock_ops, local_port):
10664 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
10665 
10666 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10667 						struct bpf_sock_ops_kern, sk),
10668 				      si->dst_reg, si->src_reg,
10669 				      offsetof(struct bpf_sock_ops_kern, sk));
10670 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10671 				      offsetof(struct sock_common, skc_num));
10672 		break;
10673 
10674 	case offsetof(struct bpf_sock_ops, is_fullsock):
10675 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10676 						struct bpf_sock_ops_kern,
10677 						is_fullsock),
10678 				      si->dst_reg, si->src_reg,
10679 				      offsetof(struct bpf_sock_ops_kern,
10680 					       is_fullsock));
10681 		break;
10682 
10683 	case offsetof(struct bpf_sock_ops, state):
10684 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_state) != 1);
10685 
10686 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10687 						struct bpf_sock_ops_kern, sk),
10688 				      si->dst_reg, si->src_reg,
10689 				      offsetof(struct bpf_sock_ops_kern, sk));
10690 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
10691 				      offsetof(struct sock_common, skc_state));
10692 		break;
10693 
10694 	case offsetof(struct bpf_sock_ops, rtt_min):
10695 		BUILD_BUG_ON(sizeof_field(struct tcp_sock, rtt_min) !=
10696 			     sizeof(struct minmax));
10697 		BUILD_BUG_ON(sizeof(struct minmax) <
10698 			     sizeof(struct minmax_sample));
10699 
10700 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10701 						struct bpf_sock_ops_kern, sk),
10702 				      si->dst_reg, si->src_reg,
10703 				      offsetof(struct bpf_sock_ops_kern, sk));
10704 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10705 				      offsetof(struct tcp_sock, rtt_min) +
10706 				      sizeof_field(struct minmax_sample, t));
10707 		break;
10708 
10709 	case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
10710 		SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
10711 				   struct tcp_sock);
10712 		break;
10713 
10714 	case offsetof(struct bpf_sock_ops, sk_txhash):
10715 		SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
10716 					  struct sock, type);
10717 		break;
10718 	case offsetof(struct bpf_sock_ops, snd_cwnd):
10719 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_cwnd);
10720 		break;
10721 	case offsetof(struct bpf_sock_ops, srtt_us):
10722 		SOCK_OPS_GET_TCP_SOCK_FIELD(srtt_us);
10723 		break;
10724 	case offsetof(struct bpf_sock_ops, snd_ssthresh):
10725 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_ssthresh);
10726 		break;
10727 	case offsetof(struct bpf_sock_ops, rcv_nxt):
10728 		SOCK_OPS_GET_TCP_SOCK_FIELD(rcv_nxt);
10729 		break;
10730 	case offsetof(struct bpf_sock_ops, snd_nxt):
10731 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_nxt);
10732 		break;
10733 	case offsetof(struct bpf_sock_ops, snd_una):
10734 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_una);
10735 		break;
10736 	case offsetof(struct bpf_sock_ops, mss_cache):
10737 		SOCK_OPS_GET_TCP_SOCK_FIELD(mss_cache);
10738 		break;
10739 	case offsetof(struct bpf_sock_ops, ecn_flags):
10740 		SOCK_OPS_GET_TCP_SOCK_FIELD(ecn_flags);
10741 		break;
10742 	case offsetof(struct bpf_sock_ops, rate_delivered):
10743 		SOCK_OPS_GET_TCP_SOCK_FIELD(rate_delivered);
10744 		break;
10745 	case offsetof(struct bpf_sock_ops, rate_interval_us):
10746 		SOCK_OPS_GET_TCP_SOCK_FIELD(rate_interval_us);
10747 		break;
10748 	case offsetof(struct bpf_sock_ops, packets_out):
10749 		SOCK_OPS_GET_TCP_SOCK_FIELD(packets_out);
10750 		break;
10751 	case offsetof(struct bpf_sock_ops, retrans_out):
10752 		SOCK_OPS_GET_TCP_SOCK_FIELD(retrans_out);
10753 		break;
10754 	case offsetof(struct bpf_sock_ops, total_retrans):
10755 		SOCK_OPS_GET_TCP_SOCK_FIELD(total_retrans);
10756 		break;
10757 	case offsetof(struct bpf_sock_ops, segs_in):
10758 		SOCK_OPS_GET_TCP_SOCK_FIELD(segs_in);
10759 		break;
10760 	case offsetof(struct bpf_sock_ops, data_segs_in):
10761 		SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_in);
10762 		break;
10763 	case offsetof(struct bpf_sock_ops, segs_out):
10764 		SOCK_OPS_GET_TCP_SOCK_FIELD(segs_out);
10765 		break;
10766 	case offsetof(struct bpf_sock_ops, data_segs_out):
10767 		SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_out);
10768 		break;
10769 	case offsetof(struct bpf_sock_ops, lost_out):
10770 		SOCK_OPS_GET_TCP_SOCK_FIELD(lost_out);
10771 		break;
10772 	case offsetof(struct bpf_sock_ops, sacked_out):
10773 		SOCK_OPS_GET_TCP_SOCK_FIELD(sacked_out);
10774 		break;
10775 	case offsetof(struct bpf_sock_ops, bytes_received):
10776 		SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_received);
10777 		break;
10778 	case offsetof(struct bpf_sock_ops, bytes_acked):
10779 		SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_acked);
10780 		break;
10781 	case offsetof(struct bpf_sock_ops, sk):
10782 		SOCK_OPS_GET_SK();
10783 		break;
10784 	case offsetof(struct bpf_sock_ops, skb_data_end):
10785 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10786 						       skb_data_end),
10787 				      si->dst_reg, si->src_reg,
10788 				      offsetof(struct bpf_sock_ops_kern,
10789 					       skb_data_end));
10790 		break;
10791 	case offsetof(struct bpf_sock_ops, skb_data):
10792 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10793 						       skb),
10794 				      si->dst_reg, si->src_reg,
10795 				      offsetof(struct bpf_sock_ops_kern,
10796 					       skb));
10797 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10798 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
10799 				      si->dst_reg, si->dst_reg,
10800 				      offsetof(struct sk_buff, data));
10801 		break;
10802 	case offsetof(struct bpf_sock_ops, skb_len):
10803 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10804 						       skb),
10805 				      si->dst_reg, si->src_reg,
10806 				      offsetof(struct bpf_sock_ops_kern,
10807 					       skb));
10808 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10809 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, len),
10810 				      si->dst_reg, si->dst_reg,
10811 				      offsetof(struct sk_buff, len));
10812 		break;
10813 	case offsetof(struct bpf_sock_ops, skb_tcp_flags):
10814 		off = offsetof(struct sk_buff, cb);
10815 		off += offsetof(struct tcp_skb_cb, tcp_flags);
10816 		*target_size = sizeof_field(struct tcp_skb_cb, tcp_flags);
10817 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10818 						       skb),
10819 				      si->dst_reg, si->src_reg,
10820 				      offsetof(struct bpf_sock_ops_kern,
10821 					       skb));
10822 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
10823 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_skb_cb,
10824 						       tcp_flags),
10825 				      si->dst_reg, si->dst_reg, off);
10826 		break;
10827 	case offsetof(struct bpf_sock_ops, skb_hwtstamp): {
10828 		struct bpf_insn *jmp_on_null_skb;
10829 
10830 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_ops_kern,
10831 						       skb),
10832 				      si->dst_reg, si->src_reg,
10833 				      offsetof(struct bpf_sock_ops_kern,
10834 					       skb));
10835 		/* Reserve one insn to test skb == NULL */
10836 		jmp_on_null_skb = insn++;
10837 		insn = bpf_convert_shinfo_access(si->dst_reg, si->dst_reg, insn);
10838 		*insn++ = BPF_LDX_MEM(BPF_DW, si->dst_reg, si->dst_reg,
10839 				      bpf_target_off(struct skb_shared_info,
10840 						     hwtstamps, 8,
10841 						     target_size));
10842 		*jmp_on_null_skb = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0,
10843 					       insn - jmp_on_null_skb - 1);
10844 		break;
10845 	}
10846 	}
10847 	return insn - insn_buf;
10848 }
10849 
10850 /* data_end = skb->data + skb_headlen() */
bpf_convert_data_end_access(const struct bpf_insn * si,struct bpf_insn * insn)10851 static struct bpf_insn *bpf_convert_data_end_access(const struct bpf_insn *si,
10852 						    struct bpf_insn *insn)
10853 {
10854 	int reg;
10855 	int temp_reg_off = offsetof(struct sk_buff, cb) +
10856 			   offsetof(struct sk_skb_cb, temp_reg);
10857 
10858 	if (si->src_reg == si->dst_reg) {
10859 		/* We need an extra register, choose and save a register. */
10860 		reg = BPF_REG_9;
10861 		if (si->src_reg == reg || si->dst_reg == reg)
10862 			reg--;
10863 		if (si->src_reg == reg || si->dst_reg == reg)
10864 			reg--;
10865 		*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg, temp_reg_off);
10866 	} else {
10867 		reg = si->dst_reg;
10868 	}
10869 
10870 	/* reg = skb->data */
10871 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
10872 			      reg, si->src_reg,
10873 			      offsetof(struct sk_buff, data));
10874 	/* AX = skb->len */
10875 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, len),
10876 			      BPF_REG_AX, si->src_reg,
10877 			      offsetof(struct sk_buff, len));
10878 	/* reg = skb->data + skb->len */
10879 	*insn++ = BPF_ALU64_REG(BPF_ADD, reg, BPF_REG_AX);
10880 	/* AX = skb->data_len */
10881 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data_len),
10882 			      BPF_REG_AX, si->src_reg,
10883 			      offsetof(struct sk_buff, data_len));
10884 
10885 	/* reg = skb->data + skb->len - skb->data_len */
10886 	*insn++ = BPF_ALU64_REG(BPF_SUB, reg, BPF_REG_AX);
10887 
10888 	if (si->src_reg == si->dst_reg) {
10889 		/* Restore the saved register */
10890 		*insn++ = BPF_MOV64_REG(BPF_REG_AX, si->src_reg);
10891 		*insn++ = BPF_MOV64_REG(si->dst_reg, reg);
10892 		*insn++ = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_AX, temp_reg_off);
10893 	}
10894 
10895 	return insn;
10896 }
10897 
sk_skb_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)10898 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
10899 				     const struct bpf_insn *si,
10900 				     struct bpf_insn *insn_buf,
10901 				     struct bpf_prog *prog, u32 *target_size)
10902 {
10903 	struct bpf_insn *insn = insn_buf;
10904 	int off;
10905 
10906 	switch (si->off) {
10907 	case offsetof(struct __sk_buff, data_end):
10908 		insn = bpf_convert_data_end_access(si, insn);
10909 		break;
10910 	case offsetof(struct __sk_buff, cb[0]) ...
10911 	     offsetofend(struct __sk_buff, cb[4]) - 1:
10912 		BUILD_BUG_ON(sizeof_field(struct sk_skb_cb, data) < 20);
10913 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
10914 			      offsetof(struct sk_skb_cb, data)) %
10915 			     sizeof(__u64));
10916 
10917 		prog->cb_access = 1;
10918 		off  = si->off;
10919 		off -= offsetof(struct __sk_buff, cb[0]);
10920 		off += offsetof(struct sk_buff, cb);
10921 		off += offsetof(struct sk_skb_cb, data);
10922 		if (type == BPF_WRITE)
10923 			*insn++ = BPF_EMIT_STORE(BPF_SIZE(si->code), si, off);
10924 		else
10925 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
10926 					      si->src_reg, off);
10927 		break;
10928 
10929 
10930 	default:
10931 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
10932 					      target_size);
10933 	}
10934 
10935 	return insn - insn_buf;
10936 }
10937 
sk_msg_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)10938 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
10939 				     const struct bpf_insn *si,
10940 				     struct bpf_insn *insn_buf,
10941 				     struct bpf_prog *prog, u32 *target_size)
10942 {
10943 	struct bpf_insn *insn = insn_buf;
10944 #if IS_ENABLED(CONFIG_IPV6)
10945 	int off;
10946 #endif
10947 
10948 	/* convert ctx uses the fact sg element is first in struct */
10949 	BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
10950 
10951 	switch (si->off) {
10952 	case offsetof(struct sk_msg_md, data):
10953 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
10954 				      si->dst_reg, si->src_reg,
10955 				      offsetof(struct sk_msg, data));
10956 		break;
10957 	case offsetof(struct sk_msg_md, data_end):
10958 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
10959 				      si->dst_reg, si->src_reg,
10960 				      offsetof(struct sk_msg, data_end));
10961 		break;
10962 	case offsetof(struct sk_msg_md, family):
10963 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);
10964 
10965 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10966 					      struct sk_msg, sk),
10967 				      si->dst_reg, si->src_reg,
10968 				      offsetof(struct sk_msg, sk));
10969 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
10970 				      offsetof(struct sock_common, skc_family));
10971 		break;
10972 
10973 	case offsetof(struct sk_msg_md, remote_ip4):
10974 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);
10975 
10976 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10977 						struct sk_msg, sk),
10978 				      si->dst_reg, si->src_reg,
10979 				      offsetof(struct sk_msg, sk));
10980 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10981 				      offsetof(struct sock_common, skc_daddr));
10982 		break;
10983 
10984 	case offsetof(struct sk_msg_md, local_ip4):
10985 		BUILD_BUG_ON(sizeof_field(struct sock_common,
10986 					  skc_rcv_saddr) != 4);
10987 
10988 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
10989 					      struct sk_msg, sk),
10990 				      si->dst_reg, si->src_reg,
10991 				      offsetof(struct sk_msg, sk));
10992 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
10993 				      offsetof(struct sock_common,
10994 					       skc_rcv_saddr));
10995 		break;
10996 
10997 	case offsetof(struct sk_msg_md, remote_ip6[0]) ...
10998 	     offsetof(struct sk_msg_md, remote_ip6[3]):
10999 #if IS_ENABLED(CONFIG_IPV6)
11000 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11001 					  skc_v6_daddr.s6_addr32[0]) != 4);
11002 
11003 		off = si->off;
11004 		off -= offsetof(struct sk_msg_md, remote_ip6[0]);
11005 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11006 						struct sk_msg, sk),
11007 				      si->dst_reg, si->src_reg,
11008 				      offsetof(struct sk_msg, sk));
11009 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11010 				      offsetof(struct sock_common,
11011 					       skc_v6_daddr.s6_addr32[0]) +
11012 				      off);
11013 #else
11014 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11015 #endif
11016 		break;
11017 
11018 	case offsetof(struct sk_msg_md, local_ip6[0]) ...
11019 	     offsetof(struct sk_msg_md, local_ip6[3]):
11020 #if IS_ENABLED(CONFIG_IPV6)
11021 		BUILD_BUG_ON(sizeof_field(struct sock_common,
11022 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
11023 
11024 		off = si->off;
11025 		off -= offsetof(struct sk_msg_md, local_ip6[0]);
11026 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11027 						struct sk_msg, sk),
11028 				      si->dst_reg, si->src_reg,
11029 				      offsetof(struct sk_msg, sk));
11030 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
11031 				      offsetof(struct sock_common,
11032 					       skc_v6_rcv_saddr.s6_addr32[0]) +
11033 				      off);
11034 #else
11035 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11036 #endif
11037 		break;
11038 
11039 	case offsetof(struct sk_msg_md, remote_port):
11040 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);
11041 
11042 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11043 						struct sk_msg, sk),
11044 				      si->dst_reg, si->src_reg,
11045 				      offsetof(struct sk_msg, sk));
11046 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11047 				      offsetof(struct sock_common, skc_dport));
11048 #ifndef __BIG_ENDIAN_BITFIELD
11049 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
11050 #endif
11051 		break;
11052 
11053 	case offsetof(struct sk_msg_md, local_port):
11054 		BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);
11055 
11056 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
11057 						struct sk_msg, sk),
11058 				      si->dst_reg, si->src_reg,
11059 				      offsetof(struct sk_msg, sk));
11060 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
11061 				      offsetof(struct sock_common, skc_num));
11062 		break;
11063 
11064 	case offsetof(struct sk_msg_md, size):
11065 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
11066 				      si->dst_reg, si->src_reg,
11067 				      offsetof(struct sk_msg_sg, size));
11068 		break;
11069 
11070 	case offsetof(struct sk_msg_md, sk):
11071 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, sk),
11072 				      si->dst_reg, si->src_reg,
11073 				      offsetof(struct sk_msg, sk));
11074 		break;
11075 	}
11076 
11077 	return insn - insn_buf;
11078 }
11079 
11080 const struct bpf_verifier_ops sk_filter_verifier_ops = {
11081 	.get_func_proto		= sk_filter_func_proto,
11082 	.is_valid_access	= sk_filter_is_valid_access,
11083 	.convert_ctx_access	= bpf_convert_ctx_access,
11084 	.gen_ld_abs		= bpf_gen_ld_abs,
11085 };
11086 
11087 const struct bpf_prog_ops sk_filter_prog_ops = {
11088 	.test_run		= bpf_prog_test_run_skb,
11089 };
11090 
11091 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
11092 	.get_func_proto		= tc_cls_act_func_proto,
11093 	.is_valid_access	= tc_cls_act_is_valid_access,
11094 	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
11095 	.gen_prologue		= tc_cls_act_prologue,
11096 	.gen_ld_abs		= bpf_gen_ld_abs,
11097 	.btf_struct_access	= tc_cls_act_btf_struct_access,
11098 };
11099 
11100 const struct bpf_prog_ops tc_cls_act_prog_ops = {
11101 	.test_run		= bpf_prog_test_run_skb,
11102 };
11103 
11104 const struct bpf_verifier_ops xdp_verifier_ops = {
11105 	.get_func_proto		= xdp_func_proto,
11106 	.is_valid_access	= xdp_is_valid_access,
11107 	.convert_ctx_access	= xdp_convert_ctx_access,
11108 	.gen_prologue		= bpf_noop_prologue,
11109 	.btf_struct_access	= xdp_btf_struct_access,
11110 };
11111 
11112 const struct bpf_prog_ops xdp_prog_ops = {
11113 	.test_run		= bpf_prog_test_run_xdp,
11114 };
11115 
11116 const struct bpf_verifier_ops cg_skb_verifier_ops = {
11117 	.get_func_proto		= cg_skb_func_proto,
11118 	.is_valid_access	= cg_skb_is_valid_access,
11119 	.convert_ctx_access	= bpf_convert_ctx_access,
11120 };
11121 
11122 const struct bpf_prog_ops cg_skb_prog_ops = {
11123 	.test_run		= bpf_prog_test_run_skb,
11124 };
11125 
11126 const struct bpf_verifier_ops lwt_in_verifier_ops = {
11127 	.get_func_proto		= lwt_in_func_proto,
11128 	.is_valid_access	= lwt_is_valid_access,
11129 	.convert_ctx_access	= bpf_convert_ctx_access,
11130 };
11131 
11132 const struct bpf_prog_ops lwt_in_prog_ops = {
11133 	.test_run		= bpf_prog_test_run_skb,
11134 };
11135 
11136 const struct bpf_verifier_ops lwt_out_verifier_ops = {
11137 	.get_func_proto		= lwt_out_func_proto,
11138 	.is_valid_access	= lwt_is_valid_access,
11139 	.convert_ctx_access	= bpf_convert_ctx_access,
11140 };
11141 
11142 const struct bpf_prog_ops lwt_out_prog_ops = {
11143 	.test_run		= bpf_prog_test_run_skb,
11144 };
11145 
11146 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
11147 	.get_func_proto		= lwt_xmit_func_proto,
11148 	.is_valid_access	= lwt_is_valid_access,
11149 	.convert_ctx_access	= bpf_convert_ctx_access,
11150 	.gen_prologue		= tc_cls_act_prologue,
11151 };
11152 
11153 const struct bpf_prog_ops lwt_xmit_prog_ops = {
11154 	.test_run		= bpf_prog_test_run_skb,
11155 };
11156 
11157 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
11158 	.get_func_proto		= lwt_seg6local_func_proto,
11159 	.is_valid_access	= lwt_is_valid_access,
11160 	.convert_ctx_access	= bpf_convert_ctx_access,
11161 };
11162 
11163 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
11164 };
11165 
11166 const struct bpf_verifier_ops cg_sock_verifier_ops = {
11167 	.get_func_proto		= sock_filter_func_proto,
11168 	.is_valid_access	= sock_filter_is_valid_access,
11169 	.convert_ctx_access	= bpf_sock_convert_ctx_access,
11170 };
11171 
11172 const struct bpf_prog_ops cg_sock_prog_ops = {
11173 };
11174 
11175 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
11176 	.get_func_proto		= sock_addr_func_proto,
11177 	.is_valid_access	= sock_addr_is_valid_access,
11178 	.convert_ctx_access	= sock_addr_convert_ctx_access,
11179 };
11180 
11181 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
11182 };
11183 
11184 const struct bpf_verifier_ops sock_ops_verifier_ops = {
11185 	.get_func_proto		= sock_ops_func_proto,
11186 	.is_valid_access	= sock_ops_is_valid_access,
11187 	.convert_ctx_access	= sock_ops_convert_ctx_access,
11188 };
11189 
11190 const struct bpf_prog_ops sock_ops_prog_ops = {
11191 };
11192 
11193 const struct bpf_verifier_ops sk_skb_verifier_ops = {
11194 	.get_func_proto		= sk_skb_func_proto,
11195 	.is_valid_access	= sk_skb_is_valid_access,
11196 	.convert_ctx_access	= sk_skb_convert_ctx_access,
11197 	.gen_prologue		= sk_skb_prologue,
11198 };
11199 
11200 const struct bpf_prog_ops sk_skb_prog_ops = {
11201 };
11202 
11203 const struct bpf_verifier_ops sk_msg_verifier_ops = {
11204 	.get_func_proto		= sk_msg_func_proto,
11205 	.is_valid_access	= sk_msg_is_valid_access,
11206 	.convert_ctx_access	= sk_msg_convert_ctx_access,
11207 	.gen_prologue		= bpf_noop_prologue,
11208 };
11209 
11210 const struct bpf_prog_ops sk_msg_prog_ops = {
11211 };
11212 
11213 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
11214 	.get_func_proto		= flow_dissector_func_proto,
11215 	.is_valid_access	= flow_dissector_is_valid_access,
11216 	.convert_ctx_access	= flow_dissector_convert_ctx_access,
11217 };
11218 
11219 const struct bpf_prog_ops flow_dissector_prog_ops = {
11220 	.test_run		= bpf_prog_test_run_flow_dissector,
11221 };
11222 
sk_detach_filter(struct sock * sk)11223 int sk_detach_filter(struct sock *sk)
11224 {
11225 	int ret = -ENOENT;
11226 	struct sk_filter *filter;
11227 
11228 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
11229 		return -EPERM;
11230 
11231 	filter = rcu_dereference_protected(sk->sk_filter,
11232 					   lockdep_sock_is_held(sk));
11233 	if (filter) {
11234 		RCU_INIT_POINTER(sk->sk_filter, NULL);
11235 		sk_filter_uncharge(sk, filter);
11236 		ret = 0;
11237 	}
11238 
11239 	return ret;
11240 }
11241 EXPORT_SYMBOL_GPL(sk_detach_filter);
11242 
sk_get_filter(struct sock * sk,sockptr_t optval,unsigned int len)11243 int sk_get_filter(struct sock *sk, sockptr_t optval, unsigned int len)
11244 {
11245 	struct sock_fprog_kern *fprog;
11246 	struct sk_filter *filter;
11247 	int ret = 0;
11248 
11249 	sockopt_lock_sock(sk);
11250 	filter = rcu_dereference_protected(sk->sk_filter,
11251 					   lockdep_sock_is_held(sk));
11252 	if (!filter)
11253 		goto out;
11254 
11255 	/* We're copying the filter that has been originally attached,
11256 	 * so no conversion/decode needed anymore. eBPF programs that
11257 	 * have no original program cannot be dumped through this.
11258 	 */
11259 	ret = -EACCES;
11260 	fprog = filter->prog->orig_prog;
11261 	if (!fprog)
11262 		goto out;
11263 
11264 	ret = fprog->len;
11265 	if (!len)
11266 		/* User space only enquires number of filter blocks. */
11267 		goto out;
11268 
11269 	ret = -EINVAL;
11270 	if (len < fprog->len)
11271 		goto out;
11272 
11273 	ret = -EFAULT;
11274 	if (copy_to_sockptr(optval, fprog->filter, bpf_classic_proglen(fprog)))
11275 		goto out;
11276 
11277 	/* Instead of bytes, the API requests to return the number
11278 	 * of filter blocks.
11279 	 */
11280 	ret = fprog->len;
11281 out:
11282 	sockopt_release_sock(sk);
11283 	return ret;
11284 }
11285 
11286 #ifdef CONFIG_INET
bpf_init_reuseport_kern(struct sk_reuseport_kern * reuse_kern,struct sock_reuseport * reuse,struct sock * sk,struct sk_buff * skb,struct sock * migrating_sk,u32 hash)11287 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
11288 				    struct sock_reuseport *reuse,
11289 				    struct sock *sk, struct sk_buff *skb,
11290 				    struct sock *migrating_sk,
11291 				    u32 hash)
11292 {
11293 	reuse_kern->skb = skb;
11294 	reuse_kern->sk = sk;
11295 	reuse_kern->selected_sk = NULL;
11296 	reuse_kern->migrating_sk = migrating_sk;
11297 	reuse_kern->data_end = skb->data + skb_headlen(skb);
11298 	reuse_kern->hash = hash;
11299 	reuse_kern->reuseport_id = reuse->reuseport_id;
11300 	reuse_kern->bind_inany = reuse->bind_inany;
11301 }
11302 
bpf_run_sk_reuseport(struct sock_reuseport * reuse,struct sock * sk,struct bpf_prog * prog,struct sk_buff * skb,struct sock * migrating_sk,u32 hash)11303 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
11304 				  struct bpf_prog *prog, struct sk_buff *skb,
11305 				  struct sock *migrating_sk,
11306 				  u32 hash)
11307 {
11308 	struct sk_reuseport_kern reuse_kern;
11309 	enum sk_action action;
11310 
11311 	bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, migrating_sk, hash);
11312 	action = bpf_prog_run(prog, &reuse_kern);
11313 
11314 	if (action == SK_PASS)
11315 		return reuse_kern.selected_sk;
11316 	else
11317 		return ERR_PTR(-ECONNREFUSED);
11318 }
11319 
BPF_CALL_4(sk_select_reuseport,struct sk_reuseport_kern *,reuse_kern,struct bpf_map *,map,void *,key,u32,flags)11320 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
11321 	   struct bpf_map *, map, void *, key, u32, flags)
11322 {
11323 	bool is_sockarray = map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY;
11324 	struct sock_reuseport *reuse;
11325 	struct sock *selected_sk;
11326 	int err;
11327 
11328 	selected_sk = map->ops->map_lookup_elem(map, key);
11329 	if (!selected_sk)
11330 		return -ENOENT;
11331 
11332 	reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
11333 	if (!reuse) {
11334 		/* reuseport_array has only sk with non NULL sk_reuseport_cb.
11335 		 * The only (!reuse) case here is - the sk has already been
11336 		 * unhashed (e.g. by close()), so treat it as -ENOENT.
11337 		 *
11338 		 * Other maps (e.g. sock_map) do not provide this guarantee and
11339 		 * the sk may never be in the reuseport group to begin with.
11340 		 */
11341 		err = is_sockarray ? -ENOENT : -EINVAL;
11342 		goto error;
11343 	}
11344 
11345 	if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
11346 		struct sock *sk = reuse_kern->sk;
11347 
11348 		if (sk->sk_protocol != selected_sk->sk_protocol) {
11349 			err = -EPROTOTYPE;
11350 		} else if (sk->sk_family != selected_sk->sk_family) {
11351 			err = -EAFNOSUPPORT;
11352 		} else {
11353 			/* Catch all. Likely bound to a different sockaddr. */
11354 			err = -EBADFD;
11355 		}
11356 		goto error;
11357 	}
11358 
11359 	reuse_kern->selected_sk = selected_sk;
11360 
11361 	return 0;
11362 error:
11363 	/* Lookup in sock_map can return TCP ESTABLISHED sockets. */
11364 	if (sk_is_refcounted(selected_sk))
11365 		sock_put(selected_sk);
11366 
11367 	return err;
11368 }
11369 
11370 static const struct bpf_func_proto sk_select_reuseport_proto = {
11371 	.func           = sk_select_reuseport,
11372 	.gpl_only       = false,
11373 	.ret_type       = RET_INTEGER,
11374 	.arg1_type	= ARG_PTR_TO_CTX,
11375 	.arg2_type      = ARG_CONST_MAP_PTR,
11376 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
11377 	.arg4_type	= ARG_ANYTHING,
11378 };
11379 
BPF_CALL_4(sk_reuseport_load_bytes,const struct sk_reuseport_kern *,reuse_kern,u32,offset,void *,to,u32,len)11380 BPF_CALL_4(sk_reuseport_load_bytes,
11381 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11382 	   void *, to, u32, len)
11383 {
11384 	return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
11385 }
11386 
11387 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
11388 	.func		= sk_reuseport_load_bytes,
11389 	.gpl_only	= false,
11390 	.ret_type	= RET_INTEGER,
11391 	.arg1_type	= ARG_PTR_TO_CTX,
11392 	.arg2_type	= ARG_ANYTHING,
11393 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
11394 	.arg4_type	= ARG_CONST_SIZE,
11395 };
11396 
BPF_CALL_5(sk_reuseport_load_bytes_relative,const struct sk_reuseport_kern *,reuse_kern,u32,offset,void *,to,u32,len,u32,start_header)11397 BPF_CALL_5(sk_reuseport_load_bytes_relative,
11398 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
11399 	   void *, to, u32, len, u32, start_header)
11400 {
11401 	return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
11402 					       len, start_header);
11403 }
11404 
11405 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
11406 	.func		= sk_reuseport_load_bytes_relative,
11407 	.gpl_only	= false,
11408 	.ret_type	= RET_INTEGER,
11409 	.arg1_type	= ARG_PTR_TO_CTX,
11410 	.arg2_type	= ARG_ANYTHING,
11411 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
11412 	.arg4_type	= ARG_CONST_SIZE,
11413 	.arg5_type	= ARG_ANYTHING,
11414 };
11415 
11416 static const struct bpf_func_proto *
sk_reuseport_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)11417 sk_reuseport_func_proto(enum bpf_func_id func_id,
11418 			const struct bpf_prog *prog)
11419 {
11420 	switch (func_id) {
11421 	case BPF_FUNC_sk_select_reuseport:
11422 		return &sk_select_reuseport_proto;
11423 	case BPF_FUNC_skb_load_bytes:
11424 		return &sk_reuseport_load_bytes_proto;
11425 	case BPF_FUNC_skb_load_bytes_relative:
11426 		return &sk_reuseport_load_bytes_relative_proto;
11427 	case BPF_FUNC_get_socket_cookie:
11428 		return &bpf_get_socket_ptr_cookie_proto;
11429 	case BPF_FUNC_ktime_get_coarse_ns:
11430 		return &bpf_ktime_get_coarse_ns_proto;
11431 	default:
11432 		return bpf_base_func_proto(func_id, prog);
11433 	}
11434 }
11435 
11436 static bool
sk_reuseport_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)11437 sk_reuseport_is_valid_access(int off, int size,
11438 			     enum bpf_access_type type,
11439 			     const struct bpf_prog *prog,
11440 			     struct bpf_insn_access_aux *info)
11441 {
11442 	const u32 size_default = sizeof(__u32);
11443 
11444 	if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
11445 	    off % size || type != BPF_READ)
11446 		return false;
11447 
11448 	switch (off) {
11449 	case offsetof(struct sk_reuseport_md, data):
11450 		info->reg_type = PTR_TO_PACKET;
11451 		return size == sizeof(__u64);
11452 
11453 	case offsetof(struct sk_reuseport_md, data_end):
11454 		info->reg_type = PTR_TO_PACKET_END;
11455 		return size == sizeof(__u64);
11456 
11457 	case offsetof(struct sk_reuseport_md, hash):
11458 		return size == size_default;
11459 
11460 	case offsetof(struct sk_reuseport_md, sk):
11461 		info->reg_type = PTR_TO_SOCKET;
11462 		return size == sizeof(__u64);
11463 
11464 	case offsetof(struct sk_reuseport_md, migrating_sk):
11465 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
11466 		return size == sizeof(__u64);
11467 
11468 	/* Fields that allow narrowing */
11469 	case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
11470 		if (size < sizeof_field(struct sk_buff, protocol))
11471 			return false;
11472 		fallthrough;
11473 	case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
11474 	case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
11475 	case bpf_ctx_range(struct sk_reuseport_md, len):
11476 		bpf_ctx_record_field_size(info, size_default);
11477 		return bpf_ctx_narrow_access_ok(off, size, size_default);
11478 
11479 	default:
11480 		return false;
11481 	}
11482 }
11483 
11484 #define SK_REUSEPORT_LOAD_FIELD(F) ({					\
11485 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
11486 			      si->dst_reg, si->src_reg,			\
11487 			      bpf_target_off(struct sk_reuseport_kern, F, \
11488 					     sizeof_field(struct sk_reuseport_kern, F), \
11489 					     target_size));		\
11490 	})
11491 
11492 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)				\
11493 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
11494 				    struct sk_buff,			\
11495 				    skb,				\
11496 				    SKB_FIELD)
11497 
11498 #define SK_REUSEPORT_LOAD_SK_FIELD(SK_FIELD)				\
11499 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
11500 				    struct sock,			\
11501 				    sk,					\
11502 				    SK_FIELD)
11503 
sk_reuseport_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)11504 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
11505 					   const struct bpf_insn *si,
11506 					   struct bpf_insn *insn_buf,
11507 					   struct bpf_prog *prog,
11508 					   u32 *target_size)
11509 {
11510 	struct bpf_insn *insn = insn_buf;
11511 
11512 	switch (si->off) {
11513 	case offsetof(struct sk_reuseport_md, data):
11514 		SK_REUSEPORT_LOAD_SKB_FIELD(data);
11515 		break;
11516 
11517 	case offsetof(struct sk_reuseport_md, len):
11518 		SK_REUSEPORT_LOAD_SKB_FIELD(len);
11519 		break;
11520 
11521 	case offsetof(struct sk_reuseport_md, eth_protocol):
11522 		SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
11523 		break;
11524 
11525 	case offsetof(struct sk_reuseport_md, ip_protocol):
11526 		SK_REUSEPORT_LOAD_SK_FIELD(sk_protocol);
11527 		break;
11528 
11529 	case offsetof(struct sk_reuseport_md, data_end):
11530 		SK_REUSEPORT_LOAD_FIELD(data_end);
11531 		break;
11532 
11533 	case offsetof(struct sk_reuseport_md, hash):
11534 		SK_REUSEPORT_LOAD_FIELD(hash);
11535 		break;
11536 
11537 	case offsetof(struct sk_reuseport_md, bind_inany):
11538 		SK_REUSEPORT_LOAD_FIELD(bind_inany);
11539 		break;
11540 
11541 	case offsetof(struct sk_reuseport_md, sk):
11542 		SK_REUSEPORT_LOAD_FIELD(sk);
11543 		break;
11544 
11545 	case offsetof(struct sk_reuseport_md, migrating_sk):
11546 		SK_REUSEPORT_LOAD_FIELD(migrating_sk);
11547 		break;
11548 	}
11549 
11550 	return insn - insn_buf;
11551 }
11552 
11553 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
11554 	.get_func_proto		= sk_reuseport_func_proto,
11555 	.is_valid_access	= sk_reuseport_is_valid_access,
11556 	.convert_ctx_access	= sk_reuseport_convert_ctx_access,
11557 };
11558 
11559 const struct bpf_prog_ops sk_reuseport_prog_ops = {
11560 };
11561 
11562 DEFINE_STATIC_KEY_FALSE(bpf_sk_lookup_enabled);
11563 EXPORT_SYMBOL(bpf_sk_lookup_enabled);
11564 
BPF_CALL_3(bpf_sk_lookup_assign,struct bpf_sk_lookup_kern *,ctx,struct sock *,sk,u64,flags)11565 BPF_CALL_3(bpf_sk_lookup_assign, struct bpf_sk_lookup_kern *, ctx,
11566 	   struct sock *, sk, u64, flags)
11567 {
11568 	if (unlikely(flags & ~(BPF_SK_LOOKUP_F_REPLACE |
11569 			       BPF_SK_LOOKUP_F_NO_REUSEPORT)))
11570 		return -EINVAL;
11571 	if (unlikely(sk && sk_is_refcounted(sk)))
11572 		return -ESOCKTNOSUPPORT; /* reject non-RCU freed sockets */
11573 	if (unlikely(sk && sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN))
11574 		return -ESOCKTNOSUPPORT; /* only accept TCP socket in LISTEN */
11575 	if (unlikely(sk && sk_is_udp(sk) && sk->sk_state != TCP_CLOSE))
11576 		return -ESOCKTNOSUPPORT; /* only accept UDP socket in CLOSE */
11577 
11578 	/* Check if socket is suitable for packet L3/L4 protocol */
11579 	if (sk && sk->sk_protocol != ctx->protocol)
11580 		return -EPROTOTYPE;
11581 	if (sk && sk->sk_family != ctx->family &&
11582 	    (sk->sk_family == AF_INET || ipv6_only_sock(sk)))
11583 		return -EAFNOSUPPORT;
11584 
11585 	if (ctx->selected_sk && !(flags & BPF_SK_LOOKUP_F_REPLACE))
11586 		return -EEXIST;
11587 
11588 	/* Select socket as lookup result */
11589 	ctx->selected_sk = sk;
11590 	ctx->no_reuseport = flags & BPF_SK_LOOKUP_F_NO_REUSEPORT;
11591 	return 0;
11592 }
11593 
11594 static const struct bpf_func_proto bpf_sk_lookup_assign_proto = {
11595 	.func		= bpf_sk_lookup_assign,
11596 	.gpl_only	= false,
11597 	.ret_type	= RET_INTEGER,
11598 	.arg1_type	= ARG_PTR_TO_CTX,
11599 	.arg2_type	= ARG_PTR_TO_SOCKET_OR_NULL,
11600 	.arg3_type	= ARG_ANYTHING,
11601 };
11602 
11603 static const struct bpf_func_proto *
sk_lookup_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)11604 sk_lookup_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
11605 {
11606 	switch (func_id) {
11607 	case BPF_FUNC_perf_event_output:
11608 		return &bpf_event_output_data_proto;
11609 	case BPF_FUNC_sk_assign:
11610 		return &bpf_sk_lookup_assign_proto;
11611 	case BPF_FUNC_sk_release:
11612 		return &bpf_sk_release_proto;
11613 	default:
11614 		return bpf_sk_base_func_proto(func_id, prog);
11615 	}
11616 }
11617 
sk_lookup_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)11618 static bool sk_lookup_is_valid_access(int off, int size,
11619 				      enum bpf_access_type type,
11620 				      const struct bpf_prog *prog,
11621 				      struct bpf_insn_access_aux *info)
11622 {
11623 	if (off < 0 || off >= sizeof(struct bpf_sk_lookup))
11624 		return false;
11625 	if (off % size != 0)
11626 		return false;
11627 	if (type != BPF_READ)
11628 		return false;
11629 
11630 	switch (off) {
11631 	case offsetof(struct bpf_sk_lookup, sk):
11632 		info->reg_type = PTR_TO_SOCKET_OR_NULL;
11633 		return size == sizeof(__u64);
11634 
11635 	case bpf_ctx_range(struct bpf_sk_lookup, family):
11636 	case bpf_ctx_range(struct bpf_sk_lookup, protocol):
11637 	case bpf_ctx_range(struct bpf_sk_lookup, remote_ip4):
11638 	case bpf_ctx_range(struct bpf_sk_lookup, local_ip4):
11639 	case bpf_ctx_range_till(struct bpf_sk_lookup, remote_ip6[0], remote_ip6[3]):
11640 	case bpf_ctx_range_till(struct bpf_sk_lookup, local_ip6[0], local_ip6[3]):
11641 	case bpf_ctx_range(struct bpf_sk_lookup, local_port):
11642 	case bpf_ctx_range(struct bpf_sk_lookup, ingress_ifindex):
11643 		bpf_ctx_record_field_size(info, sizeof(__u32));
11644 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__u32));
11645 
11646 	case bpf_ctx_range(struct bpf_sk_lookup, remote_port):
11647 		/* Allow 4-byte access to 2-byte field for backward compatibility */
11648 		if (size == sizeof(__u32))
11649 			return true;
11650 		bpf_ctx_record_field_size(info, sizeof(__be16));
11651 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__be16));
11652 
11653 	case offsetofend(struct bpf_sk_lookup, remote_port) ...
11654 	     offsetof(struct bpf_sk_lookup, local_ip4) - 1:
11655 		/* Allow access to zero padding for backward compatibility */
11656 		bpf_ctx_record_field_size(info, sizeof(__u16));
11657 		return bpf_ctx_narrow_access_ok(off, size, sizeof(__u16));
11658 
11659 	default:
11660 		return false;
11661 	}
11662 }
11663 
sk_lookup_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)11664 static u32 sk_lookup_convert_ctx_access(enum bpf_access_type type,
11665 					const struct bpf_insn *si,
11666 					struct bpf_insn *insn_buf,
11667 					struct bpf_prog *prog,
11668 					u32 *target_size)
11669 {
11670 	struct bpf_insn *insn = insn_buf;
11671 
11672 	switch (si->off) {
11673 	case offsetof(struct bpf_sk_lookup, sk):
11674 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11675 				      offsetof(struct bpf_sk_lookup_kern, selected_sk));
11676 		break;
11677 
11678 	case offsetof(struct bpf_sk_lookup, family):
11679 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11680 				      bpf_target_off(struct bpf_sk_lookup_kern,
11681 						     family, 2, target_size));
11682 		break;
11683 
11684 	case offsetof(struct bpf_sk_lookup, protocol):
11685 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11686 				      bpf_target_off(struct bpf_sk_lookup_kern,
11687 						     protocol, 2, target_size));
11688 		break;
11689 
11690 	case offsetof(struct bpf_sk_lookup, remote_ip4):
11691 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11692 				      bpf_target_off(struct bpf_sk_lookup_kern,
11693 						     v4.saddr, 4, target_size));
11694 		break;
11695 
11696 	case offsetof(struct bpf_sk_lookup, local_ip4):
11697 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11698 				      bpf_target_off(struct bpf_sk_lookup_kern,
11699 						     v4.daddr, 4, target_size));
11700 		break;
11701 
11702 	case bpf_ctx_range_till(struct bpf_sk_lookup,
11703 				remote_ip6[0], remote_ip6[3]): {
11704 #if IS_ENABLED(CONFIG_IPV6)
11705 		int off = si->off;
11706 
11707 		off -= offsetof(struct bpf_sk_lookup, remote_ip6[0]);
11708 		off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
11709 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11710 				      offsetof(struct bpf_sk_lookup_kern, v6.saddr));
11711 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11712 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
11713 #else
11714 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11715 #endif
11716 		break;
11717 	}
11718 	case bpf_ctx_range_till(struct bpf_sk_lookup,
11719 				local_ip6[0], local_ip6[3]): {
11720 #if IS_ENABLED(CONFIG_IPV6)
11721 		int off = si->off;
11722 
11723 		off -= offsetof(struct bpf_sk_lookup, local_ip6[0]);
11724 		off += bpf_target_off(struct in6_addr, s6_addr32[0], 4, target_size);
11725 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg, si->src_reg,
11726 				      offsetof(struct bpf_sk_lookup_kern, v6.daddr));
11727 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
11728 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg, off);
11729 #else
11730 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11731 #endif
11732 		break;
11733 	}
11734 	case offsetof(struct bpf_sk_lookup, remote_port):
11735 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11736 				      bpf_target_off(struct bpf_sk_lookup_kern,
11737 						     sport, 2, target_size));
11738 		break;
11739 
11740 	case offsetofend(struct bpf_sk_lookup, remote_port):
11741 		*target_size = 2;
11742 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
11743 		break;
11744 
11745 	case offsetof(struct bpf_sk_lookup, local_port):
11746 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
11747 				      bpf_target_off(struct bpf_sk_lookup_kern,
11748 						     dport, 2, target_size));
11749 		break;
11750 
11751 	case offsetof(struct bpf_sk_lookup, ingress_ifindex):
11752 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
11753 				      bpf_target_off(struct bpf_sk_lookup_kern,
11754 						     ingress_ifindex, 4, target_size));
11755 		break;
11756 	}
11757 
11758 	return insn - insn_buf;
11759 }
11760 
11761 const struct bpf_prog_ops sk_lookup_prog_ops = {
11762 	.test_run = bpf_prog_test_run_sk_lookup,
11763 };
11764 
11765 const struct bpf_verifier_ops sk_lookup_verifier_ops = {
11766 	.get_func_proto		= sk_lookup_func_proto,
11767 	.is_valid_access	= sk_lookup_is_valid_access,
11768 	.convert_ctx_access	= sk_lookup_convert_ctx_access,
11769 };
11770 
11771 #endif /* CONFIG_INET */
11772 
DEFINE_BPF_DISPATCHER(xdp)11773 DEFINE_BPF_DISPATCHER(xdp)
11774 
11775 void bpf_prog_change_xdp(struct bpf_prog *prev_prog, struct bpf_prog *prog)
11776 {
11777 	bpf_dispatcher_change_prog(BPF_DISPATCHER_PTR(xdp), prev_prog, prog);
11778 }
11779 
BTF_ID_LIST_GLOBAL(btf_sock_ids,MAX_BTF_SOCK_TYPE)11780 BTF_ID_LIST_GLOBAL(btf_sock_ids, MAX_BTF_SOCK_TYPE)
11781 #define BTF_SOCK_TYPE(name, type) BTF_ID(struct, type)
11782 BTF_SOCK_TYPE_xxx
11783 #undef BTF_SOCK_TYPE
11784 
11785 BPF_CALL_1(bpf_skc_to_tcp6_sock, struct sock *, sk)
11786 {
11787 	/* tcp6_sock type is not generated in dwarf and hence btf,
11788 	 * trigger an explicit type generation here.
11789 	 */
11790 	BTF_TYPE_EMIT(struct tcp6_sock);
11791 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP &&
11792 	    sk->sk_family == AF_INET6)
11793 		return (unsigned long)sk;
11794 
11795 	return (unsigned long)NULL;
11796 }
11797 
11798 const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto = {
11799 	.func			= bpf_skc_to_tcp6_sock,
11800 	.gpl_only		= false,
11801 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11802 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11803 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP6],
11804 };
11805 
BPF_CALL_1(bpf_skc_to_tcp_sock,struct sock *,sk)11806 BPF_CALL_1(bpf_skc_to_tcp_sock, struct sock *, sk)
11807 {
11808 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
11809 		return (unsigned long)sk;
11810 
11811 	return (unsigned long)NULL;
11812 }
11813 
11814 const struct bpf_func_proto bpf_skc_to_tcp_sock_proto = {
11815 	.func			= bpf_skc_to_tcp_sock,
11816 	.gpl_only		= false,
11817 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11818 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11819 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP],
11820 };
11821 
BPF_CALL_1(bpf_skc_to_tcp_timewait_sock,struct sock *,sk)11822 BPF_CALL_1(bpf_skc_to_tcp_timewait_sock, struct sock *, sk)
11823 {
11824 	/* BTF types for tcp_timewait_sock and inet_timewait_sock are not
11825 	 * generated if CONFIG_INET=n. Trigger an explicit generation here.
11826 	 */
11827 	BTF_TYPE_EMIT(struct inet_timewait_sock);
11828 	BTF_TYPE_EMIT(struct tcp_timewait_sock);
11829 
11830 #ifdef CONFIG_INET
11831 	if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_TIME_WAIT)
11832 		return (unsigned long)sk;
11833 #endif
11834 
11835 #if IS_BUILTIN(CONFIG_IPV6)
11836 	if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_TIME_WAIT)
11837 		return (unsigned long)sk;
11838 #endif
11839 
11840 	return (unsigned long)NULL;
11841 }
11842 
11843 const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto = {
11844 	.func			= bpf_skc_to_tcp_timewait_sock,
11845 	.gpl_only		= false,
11846 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11847 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11848 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP_TW],
11849 };
11850 
BPF_CALL_1(bpf_skc_to_tcp_request_sock,struct sock *,sk)11851 BPF_CALL_1(bpf_skc_to_tcp_request_sock, struct sock *, sk)
11852 {
11853 #ifdef CONFIG_INET
11854 	if (sk && sk->sk_prot == &tcp_prot && sk->sk_state == TCP_NEW_SYN_RECV)
11855 		return (unsigned long)sk;
11856 #endif
11857 
11858 #if IS_BUILTIN(CONFIG_IPV6)
11859 	if (sk && sk->sk_prot == &tcpv6_prot && sk->sk_state == TCP_NEW_SYN_RECV)
11860 		return (unsigned long)sk;
11861 #endif
11862 
11863 	return (unsigned long)NULL;
11864 }
11865 
11866 const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto = {
11867 	.func			= bpf_skc_to_tcp_request_sock,
11868 	.gpl_only		= false,
11869 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11870 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11871 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_TCP_REQ],
11872 };
11873 
BPF_CALL_1(bpf_skc_to_udp6_sock,struct sock *,sk)11874 BPF_CALL_1(bpf_skc_to_udp6_sock, struct sock *, sk)
11875 {
11876 	/* udp6_sock type is not generated in dwarf and hence btf,
11877 	 * trigger an explicit type generation here.
11878 	 */
11879 	BTF_TYPE_EMIT(struct udp6_sock);
11880 	if (sk && sk_fullsock(sk) && sk->sk_protocol == IPPROTO_UDP &&
11881 	    sk->sk_type == SOCK_DGRAM && sk->sk_family == AF_INET6)
11882 		return (unsigned long)sk;
11883 
11884 	return (unsigned long)NULL;
11885 }
11886 
11887 const struct bpf_func_proto bpf_skc_to_udp6_sock_proto = {
11888 	.func			= bpf_skc_to_udp6_sock,
11889 	.gpl_only		= false,
11890 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11891 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11892 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_UDP6],
11893 };
11894 
BPF_CALL_1(bpf_skc_to_unix_sock,struct sock *,sk)11895 BPF_CALL_1(bpf_skc_to_unix_sock, struct sock *, sk)
11896 {
11897 	/* unix_sock type is not generated in dwarf and hence btf,
11898 	 * trigger an explicit type generation here.
11899 	 */
11900 	BTF_TYPE_EMIT(struct unix_sock);
11901 	if (sk && sk_fullsock(sk) && sk->sk_family == AF_UNIX)
11902 		return (unsigned long)sk;
11903 
11904 	return (unsigned long)NULL;
11905 }
11906 
11907 const struct bpf_func_proto bpf_skc_to_unix_sock_proto = {
11908 	.func			= bpf_skc_to_unix_sock,
11909 	.gpl_only		= false,
11910 	.ret_type		= RET_PTR_TO_BTF_ID_OR_NULL,
11911 	.arg1_type		= ARG_PTR_TO_BTF_ID_SOCK_COMMON,
11912 	.ret_btf_id		= &btf_sock_ids[BTF_SOCK_TYPE_UNIX],
11913 };
11914 
BPF_CALL_1(bpf_skc_to_mptcp_sock,struct sock *,sk)11915 BPF_CALL_1(bpf_skc_to_mptcp_sock, struct sock *, sk)
11916 {
11917 	BTF_TYPE_EMIT(struct mptcp_sock);
11918 	return (unsigned long)bpf_mptcp_sock_from_subflow(sk);
11919 }
11920 
11921 const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto = {
11922 	.func		= bpf_skc_to_mptcp_sock,
11923 	.gpl_only	= false,
11924 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
11925 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
11926 	.ret_btf_id	= &btf_sock_ids[BTF_SOCK_TYPE_MPTCP],
11927 };
11928 
BPF_CALL_1(bpf_sock_from_file,struct file *,file)11929 BPF_CALL_1(bpf_sock_from_file, struct file *, file)
11930 {
11931 	return (unsigned long)sock_from_file(file);
11932 }
11933 
11934 BTF_ID_LIST(bpf_sock_from_file_btf_ids)
11935 BTF_ID(struct, socket)
11936 BTF_ID(struct, file)
11937 
11938 const struct bpf_func_proto bpf_sock_from_file_proto = {
11939 	.func		= bpf_sock_from_file,
11940 	.gpl_only	= false,
11941 	.ret_type	= RET_PTR_TO_BTF_ID_OR_NULL,
11942 	.ret_btf_id	= &bpf_sock_from_file_btf_ids[0],
11943 	.arg1_type	= ARG_PTR_TO_BTF_ID,
11944 	.arg1_btf_id	= &bpf_sock_from_file_btf_ids[1],
11945 };
11946 
11947 static const struct bpf_func_proto *
bpf_sk_base_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)11948 bpf_sk_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
11949 {
11950 	const struct bpf_func_proto *func;
11951 
11952 	switch (func_id) {
11953 	case BPF_FUNC_skc_to_tcp6_sock:
11954 		func = &bpf_skc_to_tcp6_sock_proto;
11955 		break;
11956 	case BPF_FUNC_skc_to_tcp_sock:
11957 		func = &bpf_skc_to_tcp_sock_proto;
11958 		break;
11959 	case BPF_FUNC_skc_to_tcp_timewait_sock:
11960 		func = &bpf_skc_to_tcp_timewait_sock_proto;
11961 		break;
11962 	case BPF_FUNC_skc_to_tcp_request_sock:
11963 		func = &bpf_skc_to_tcp_request_sock_proto;
11964 		break;
11965 	case BPF_FUNC_skc_to_udp6_sock:
11966 		func = &bpf_skc_to_udp6_sock_proto;
11967 		break;
11968 	case BPF_FUNC_skc_to_unix_sock:
11969 		func = &bpf_skc_to_unix_sock_proto;
11970 		break;
11971 	case BPF_FUNC_skc_to_mptcp_sock:
11972 		func = &bpf_skc_to_mptcp_sock_proto;
11973 		break;
11974 	case BPF_FUNC_ktime_get_coarse_ns:
11975 		return &bpf_ktime_get_coarse_ns_proto;
11976 	default:
11977 		return bpf_base_func_proto(func_id, prog);
11978 	}
11979 
11980 	if (!bpf_token_capable(prog->aux->token, CAP_PERFMON))
11981 		return NULL;
11982 
11983 	return func;
11984 }
11985 
11986 __bpf_kfunc_start_defs();
bpf_dynptr_from_skb(struct __sk_buff * s,u64 flags,struct bpf_dynptr * ptr__uninit)11987 __bpf_kfunc int bpf_dynptr_from_skb(struct __sk_buff *s, u64 flags,
11988 				    struct bpf_dynptr *ptr__uninit)
11989 {
11990 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
11991 	struct sk_buff *skb = (struct sk_buff *)s;
11992 
11993 	if (flags) {
11994 		bpf_dynptr_set_null(ptr);
11995 		return -EINVAL;
11996 	}
11997 
11998 	bpf_dynptr_init(ptr, skb, BPF_DYNPTR_TYPE_SKB, 0, skb->len);
11999 
12000 	return 0;
12001 }
12002 
bpf_dynptr_from_xdp(struct xdp_md * x,u64 flags,struct bpf_dynptr * ptr__uninit)12003 __bpf_kfunc int bpf_dynptr_from_xdp(struct xdp_md *x, u64 flags,
12004 				    struct bpf_dynptr *ptr__uninit)
12005 {
12006 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12007 	struct xdp_buff *xdp = (struct xdp_buff *)x;
12008 
12009 	if (flags) {
12010 		bpf_dynptr_set_null(ptr);
12011 		return -EINVAL;
12012 	}
12013 
12014 	bpf_dynptr_init(ptr, xdp, BPF_DYNPTR_TYPE_XDP, 0, xdp_get_buff_len(xdp));
12015 
12016 	return 0;
12017 }
12018 
bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern * sa_kern,const u8 * sun_path,u32 sun_path__sz)12019 __bpf_kfunc int bpf_sock_addr_set_sun_path(struct bpf_sock_addr_kern *sa_kern,
12020 					   const u8 *sun_path, u32 sun_path__sz)
12021 {
12022 	struct sockaddr_un *un;
12023 
12024 	if (sa_kern->sk->sk_family != AF_UNIX)
12025 		return -EINVAL;
12026 
12027 	/* We do not allow changing the address to unnamed or larger than the
12028 	 * maximum allowed address size for a unix sockaddr.
12029 	 */
12030 	if (sun_path__sz == 0 || sun_path__sz > UNIX_PATH_MAX)
12031 		return -EINVAL;
12032 
12033 	un = (struct sockaddr_un *)sa_kern->uaddr;
12034 	memcpy(un->sun_path, sun_path, sun_path__sz);
12035 	sa_kern->uaddrlen = offsetof(struct sockaddr_un, sun_path) + sun_path__sz;
12036 
12037 	return 0;
12038 }
12039 
bpf_sk_assign_tcp_reqsk(struct __sk_buff * s,struct sock * sk,struct bpf_tcp_req_attrs * attrs,int attrs__sz)12040 __bpf_kfunc int bpf_sk_assign_tcp_reqsk(struct __sk_buff *s, struct sock *sk,
12041 					struct bpf_tcp_req_attrs *attrs, int attrs__sz)
12042 {
12043 #if IS_ENABLED(CONFIG_SYN_COOKIES)
12044 	struct sk_buff *skb = (struct sk_buff *)s;
12045 	const struct request_sock_ops *ops;
12046 	struct inet_request_sock *ireq;
12047 	struct tcp_request_sock *treq;
12048 	struct request_sock *req;
12049 	struct net *net;
12050 	__u16 min_mss;
12051 	u32 tsoff = 0;
12052 
12053 	if (attrs__sz != sizeof(*attrs) ||
12054 	    attrs->reserved[0] || attrs->reserved[1] || attrs->reserved[2])
12055 		return -EINVAL;
12056 
12057 	if (!skb_at_tc_ingress(skb))
12058 		return -EINVAL;
12059 
12060 	net = dev_net(skb->dev);
12061 	if (net != sock_net(sk))
12062 		return -ENETUNREACH;
12063 
12064 	switch (skb->protocol) {
12065 	case htons(ETH_P_IP):
12066 		ops = &tcp_request_sock_ops;
12067 		min_mss = 536;
12068 		break;
12069 #if IS_BUILTIN(CONFIG_IPV6)
12070 	case htons(ETH_P_IPV6):
12071 		ops = &tcp6_request_sock_ops;
12072 		min_mss = IPV6_MIN_MTU - 60;
12073 		break;
12074 #endif
12075 	default:
12076 		return -EINVAL;
12077 	}
12078 
12079 	if (sk->sk_type != SOCK_STREAM || sk->sk_state != TCP_LISTEN ||
12080 	    sk_is_mptcp(sk))
12081 		return -EINVAL;
12082 
12083 	if (attrs->mss < min_mss)
12084 		return -EINVAL;
12085 
12086 	if (attrs->wscale_ok) {
12087 		if (!READ_ONCE(net->ipv4.sysctl_tcp_window_scaling))
12088 			return -EINVAL;
12089 
12090 		if (attrs->snd_wscale > TCP_MAX_WSCALE ||
12091 		    attrs->rcv_wscale > TCP_MAX_WSCALE)
12092 			return -EINVAL;
12093 	}
12094 
12095 	if (attrs->sack_ok && !READ_ONCE(net->ipv4.sysctl_tcp_sack))
12096 		return -EINVAL;
12097 
12098 	if (attrs->tstamp_ok) {
12099 		if (!READ_ONCE(net->ipv4.sysctl_tcp_timestamps))
12100 			return -EINVAL;
12101 
12102 		tsoff = attrs->rcv_tsecr - tcp_ns_to_ts(attrs->usec_ts_ok, tcp_clock_ns());
12103 	}
12104 
12105 	req = inet_reqsk_alloc(ops, sk, false);
12106 	if (!req)
12107 		return -ENOMEM;
12108 
12109 	ireq = inet_rsk(req);
12110 	treq = tcp_rsk(req);
12111 
12112 	req->rsk_listener = sk;
12113 	req->syncookie = 1;
12114 	req->mss = attrs->mss;
12115 	req->ts_recent = attrs->rcv_tsval;
12116 
12117 	ireq->snd_wscale = attrs->snd_wscale;
12118 	ireq->rcv_wscale = attrs->rcv_wscale;
12119 	ireq->tstamp_ok	= !!attrs->tstamp_ok;
12120 	ireq->sack_ok = !!attrs->sack_ok;
12121 	ireq->wscale_ok = !!attrs->wscale_ok;
12122 	ireq->ecn_ok = !!attrs->ecn_ok;
12123 
12124 	treq->req_usec_ts = !!attrs->usec_ts_ok;
12125 	treq->ts_off = tsoff;
12126 
12127 	skb_orphan(skb);
12128 	skb->sk = req_to_sk(req);
12129 	skb->destructor = sock_pfree;
12130 
12131 	return 0;
12132 #else
12133 	return -EOPNOTSUPP;
12134 #endif
12135 }
12136 
bpf_sock_ops_enable_tx_tstamp(struct bpf_sock_ops_kern * skops,u64 flags)12137 __bpf_kfunc int bpf_sock_ops_enable_tx_tstamp(struct bpf_sock_ops_kern *skops,
12138 					      u64 flags)
12139 {
12140 	struct sk_buff *skb;
12141 
12142 	if (skops->op != BPF_SOCK_OPS_TSTAMP_SENDMSG_CB)
12143 		return -EOPNOTSUPP;
12144 
12145 	if (flags)
12146 		return -EINVAL;
12147 
12148 	skb = skops->skb;
12149 	skb_shinfo(skb)->tx_flags |= SKBTX_BPF;
12150 	TCP_SKB_CB(skb)->txstamp_ack |= TSTAMP_ACK_BPF;
12151 	skb_shinfo(skb)->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1;
12152 
12153 	return 0;
12154 }
12155 
12156 __bpf_kfunc_end_defs();
12157 
bpf_dynptr_from_skb_rdonly(struct __sk_buff * skb,u64 flags,struct bpf_dynptr * ptr__uninit)12158 int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
12159 			       struct bpf_dynptr *ptr__uninit)
12160 {
12161 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)ptr__uninit;
12162 	int err;
12163 
12164 	err = bpf_dynptr_from_skb(skb, flags, ptr__uninit);
12165 	if (err)
12166 		return err;
12167 
12168 	bpf_dynptr_set_rdonly(ptr);
12169 
12170 	return 0;
12171 }
12172 
12173 BTF_KFUNCS_START(bpf_kfunc_check_set_skb)
12174 BTF_ID_FLAGS(func, bpf_dynptr_from_skb, KF_TRUSTED_ARGS)
12175 BTF_KFUNCS_END(bpf_kfunc_check_set_skb)
12176 
12177 BTF_KFUNCS_START(bpf_kfunc_check_set_xdp)
12178 BTF_ID_FLAGS(func, bpf_dynptr_from_xdp)
12179 BTF_KFUNCS_END(bpf_kfunc_check_set_xdp)
12180 
12181 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_addr)
12182 BTF_ID_FLAGS(func, bpf_sock_addr_set_sun_path)
12183 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_addr)
12184 
12185 BTF_KFUNCS_START(bpf_kfunc_check_set_tcp_reqsk)
12186 BTF_ID_FLAGS(func, bpf_sk_assign_tcp_reqsk, KF_TRUSTED_ARGS)
12187 BTF_KFUNCS_END(bpf_kfunc_check_set_tcp_reqsk)
12188 
12189 BTF_KFUNCS_START(bpf_kfunc_check_set_sock_ops)
12190 BTF_ID_FLAGS(func, bpf_sock_ops_enable_tx_tstamp, KF_TRUSTED_ARGS)
12191 BTF_KFUNCS_END(bpf_kfunc_check_set_sock_ops)
12192 
12193 static const struct btf_kfunc_id_set bpf_kfunc_set_skb = {
12194 	.owner = THIS_MODULE,
12195 	.set = &bpf_kfunc_check_set_skb,
12196 };
12197 
12198 static const struct btf_kfunc_id_set bpf_kfunc_set_xdp = {
12199 	.owner = THIS_MODULE,
12200 	.set = &bpf_kfunc_check_set_xdp,
12201 };
12202 
12203 static const struct btf_kfunc_id_set bpf_kfunc_set_sock_addr = {
12204 	.owner = THIS_MODULE,
12205 	.set = &bpf_kfunc_check_set_sock_addr,
12206 };
12207 
12208 static const struct btf_kfunc_id_set bpf_kfunc_set_tcp_reqsk = {
12209 	.owner = THIS_MODULE,
12210 	.set = &bpf_kfunc_check_set_tcp_reqsk,
12211 };
12212 
12213 static const struct btf_kfunc_id_set bpf_kfunc_set_sock_ops = {
12214 	.owner = THIS_MODULE,
12215 	.set = &bpf_kfunc_check_set_sock_ops,
12216 };
12217 
bpf_kfunc_init(void)12218 static int __init bpf_kfunc_init(void)
12219 {
12220 	int ret;
12221 
12222 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_skb);
12223 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_ACT, &bpf_kfunc_set_skb);
12224 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SK_SKB, &bpf_kfunc_set_skb);
12225 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SOCKET_FILTER, &bpf_kfunc_set_skb);
12226 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SKB, &bpf_kfunc_set_skb);
12227 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_OUT, &bpf_kfunc_set_skb);
12228 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_IN, &bpf_kfunc_set_skb);
12229 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_XMIT, &bpf_kfunc_set_skb);
12230 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_LWT_SEG6LOCAL, &bpf_kfunc_set_skb);
12231 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_NETFILTER, &bpf_kfunc_set_skb);
12232 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_kfunc_set_skb);
12233 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &bpf_kfunc_set_xdp);
12234 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
12235 					       &bpf_kfunc_set_sock_addr);
12236 	ret = ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SCHED_CLS, &bpf_kfunc_set_tcp_reqsk);
12237 	return ret ?: register_btf_kfunc_id_set(BPF_PROG_TYPE_SOCK_OPS, &bpf_kfunc_set_sock_ops);
12238 }
12239 late_initcall(bpf_kfunc_init);
12240 
12241 __bpf_kfunc_start_defs();
12242 
12243 /* bpf_sock_destroy: Destroy the given socket with ECONNABORTED error code.
12244  *
12245  * The function expects a non-NULL pointer to a socket, and invokes the
12246  * protocol specific socket destroy handlers.
12247  *
12248  * The helper can only be called from BPF contexts that have acquired the socket
12249  * locks.
12250  *
12251  * Parameters:
12252  * @sock: Pointer to socket to be destroyed
12253  *
12254  * Return:
12255  * On error, may return EPROTONOSUPPORT, EINVAL.
12256  * EPROTONOSUPPORT if protocol specific destroy handler is not supported.
12257  * 0 otherwise
12258  */
bpf_sock_destroy(struct sock_common * sock)12259 __bpf_kfunc int bpf_sock_destroy(struct sock_common *sock)
12260 {
12261 	struct sock *sk = (struct sock *)sock;
12262 
12263 	/* The locking semantics that allow for synchronous execution of the
12264 	 * destroy handlers are only supported for TCP and UDP.
12265 	 * Supporting protocols will need to acquire sock lock in the BPF context
12266 	 * prior to invoking this kfunc.
12267 	 */
12268 	if (!sk->sk_prot->diag_destroy || (sk->sk_protocol != IPPROTO_TCP &&
12269 					   sk->sk_protocol != IPPROTO_UDP))
12270 		return -EOPNOTSUPP;
12271 
12272 	return sk->sk_prot->diag_destroy(sk, ECONNABORTED);
12273 }
12274 
12275 __bpf_kfunc_end_defs();
12276 
12277 BTF_KFUNCS_START(bpf_sk_iter_kfunc_ids)
BTF_ID_FLAGS(func,bpf_sock_destroy,KF_TRUSTED_ARGS)12278 BTF_ID_FLAGS(func, bpf_sock_destroy, KF_TRUSTED_ARGS)
12279 BTF_KFUNCS_END(bpf_sk_iter_kfunc_ids)
12280 
12281 static int tracing_iter_filter(const struct bpf_prog *prog, u32 kfunc_id)
12282 {
12283 	if (btf_id_set8_contains(&bpf_sk_iter_kfunc_ids, kfunc_id) &&
12284 	    prog->expected_attach_type != BPF_TRACE_ITER)
12285 		return -EACCES;
12286 	return 0;
12287 }
12288 
12289 static const struct btf_kfunc_id_set bpf_sk_iter_kfunc_set = {
12290 	.owner = THIS_MODULE,
12291 	.set   = &bpf_sk_iter_kfunc_ids,
12292 	.filter = tracing_iter_filter,
12293 };
12294 
init_subsystem(void)12295 static int init_subsystem(void)
12296 {
12297 	return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_sk_iter_kfunc_set);
12298 }
12299 late_initcall(init_subsystem);
12300