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