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