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