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