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