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