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