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