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