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