• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/module.h>
21 #include <linux/types.h>
22 #include <linux/mm.h>
23 #include <linux/fcntl.h>
24 #include <linux/socket.h>
25 #include <linux/sock_diag.h>
26 #include <linux/in.h>
27 #include <linux/inet.h>
28 #include <linux/netdevice.h>
29 #include <linux/if_packet.h>
30 #include <linux/if_arp.h>
31 #include <linux/gfp.h>
32 #include <net/inet_common.h>
33 #include <net/ip.h>
34 #include <net/protocol.h>
35 #include <net/netlink.h>
36 #include <linux/skbuff.h>
37 #include <linux/skmsg.h>
38 #include <net/sock.h>
39 #include <net/flow_dissector.h>
40 #include <linux/errno.h>
41 #include <linux/timer.h>
42 #include <linux/uaccess.h>
43 #include <asm/unaligned.h>
44 #include <asm/cmpxchg.h>
45 #include <linux/filter.h>
46 #include <linux/ratelimit.h>
47 #include <linux/seccomp.h>
48 #include <linux/if_vlan.h>
49 #include <linux/bpf.h>
50 #include <net/sch_generic.h>
51 #include <net/cls_cgroup.h>
52 #include <net/dst_metadata.h>
53 #include <net/dst.h>
54 #include <net/sock_reuseport.h>
55 #include <net/busy_poll.h>
56 #include <net/tcp.h>
57 #include <net/xfrm.h>
58 #include <net/udp.h>
59 #include <linux/bpf_trace.h>
60 #include <net/xdp_sock.h>
61 #include <linux/inetdevice.h>
62 #include <net/inet_hashtables.h>
63 #include <net/inet6_hashtables.h>
64 #include <net/ip_fib.h>
65 #include <net/nexthop.h>
66 #include <net/flow.h>
67 #include <net/arp.h>
68 #include <net/ipv6.h>
69 #include <net/net_namespace.h>
70 #include <linux/seg6_local.h>
71 #include <net/seg6.h>
72 #include <net/seg6_local.h>
73 #include <net/lwtunnel.h>
74 #include <net/ipv6_stubs.h>
75 #include <net/bpf_sk_storage.h>
76 
77 /**
78  *	sk_filter_trim_cap - run a packet through a socket filter
79  *	@sk: sock associated with &sk_buff
80  *	@skb: buffer to filter
81  *	@cap: limit on how short the eBPF program may trim the packet
82  *
83  * Run the eBPF program and then cut skb->data to correct size returned by
84  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
85  * than pkt_len we keep whole skb->data. This is the socket level
86  * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
87  * be accepted or -EPERM if the packet should be tossed.
88  *
89  */
sk_filter_trim_cap(struct sock * sk,struct sk_buff * skb,unsigned int cap)90 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
91 {
92 	int err;
93 	struct sk_filter *filter;
94 
95 	/*
96 	 * If the skb was allocated from pfmemalloc reserves, only
97 	 * allow SOCK_MEMALLOC sockets to use it as this socket is
98 	 * helping free memory
99 	 */
100 	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
101 		NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
102 		return -ENOMEM;
103 	}
104 	err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
105 	if (err)
106 		return err;
107 
108 	err = security_sock_rcv_skb(sk, skb);
109 	if (err)
110 		return err;
111 
112 	rcu_read_lock();
113 	filter = rcu_dereference(sk->sk_filter);
114 	if (filter) {
115 		struct sock *save_sk = skb->sk;
116 		unsigned int pkt_len;
117 
118 		skb->sk = sk;
119 		pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
120 		skb->sk = save_sk;
121 		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
122 	}
123 	rcu_read_unlock();
124 
125 	return err;
126 }
127 EXPORT_SYMBOL(sk_filter_trim_cap);
128 
BPF_CALL_1(bpf_skb_get_pay_offset,struct sk_buff *,skb)129 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
130 {
131 	return skb_get_poff(skb);
132 }
133 
BPF_CALL_3(bpf_skb_get_nlattr,struct sk_buff *,skb,u32,a,u32,x)134 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
135 {
136 	struct nlattr *nla;
137 
138 	if (skb_is_nonlinear(skb))
139 		return 0;
140 
141 	if (skb->len < sizeof(struct nlattr))
142 		return 0;
143 
144 	if (a > skb->len - sizeof(struct nlattr))
145 		return 0;
146 
147 	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
148 	if (nla)
149 		return (void *) nla - (void *) skb->data;
150 
151 	return 0;
152 }
153 
BPF_CALL_3(bpf_skb_get_nlattr_nest,struct sk_buff *,skb,u32,a,u32,x)154 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
155 {
156 	struct nlattr *nla;
157 
158 	if (skb_is_nonlinear(skb))
159 		return 0;
160 
161 	if (skb->len < sizeof(struct nlattr))
162 		return 0;
163 
164 	if (a > skb->len - sizeof(struct nlattr))
165 		return 0;
166 
167 	nla = (struct nlattr *) &skb->data[a];
168 	if (nla->nla_len > skb->len - a)
169 		return 0;
170 
171 	nla = nla_find_nested(nla, x);
172 	if (nla)
173 		return (void *) nla - (void *) skb->data;
174 
175 	return 0;
176 }
177 
BPF_CALL_4(bpf_skb_load_helper_8,const struct sk_buff *,skb,const void *,data,int,headlen,int,offset)178 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
179 	   data, int, headlen, int, offset)
180 {
181 	u8 tmp, *ptr;
182 	const int len = sizeof(tmp);
183 
184 	if (offset >= 0) {
185 		if (headlen - offset >= len)
186 			return *(u8 *)(data + offset);
187 		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
188 			return tmp;
189 	} else {
190 		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
191 		if (likely(ptr))
192 			return *(u8 *)ptr;
193 	}
194 
195 	return -EFAULT;
196 }
197 
BPF_CALL_2(bpf_skb_load_helper_8_no_cache,const struct sk_buff *,skb,int,offset)198 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
199 	   int, offset)
200 {
201 	return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
202 					 offset);
203 }
204 
BPF_CALL_4(bpf_skb_load_helper_16,const struct sk_buff *,skb,const void *,data,int,headlen,int,offset)205 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
206 	   data, int, headlen, int, offset)
207 {
208 	u16 tmp, *ptr;
209 	const int len = sizeof(tmp);
210 
211 	if (offset >= 0) {
212 		if (headlen - offset >= len)
213 			return get_unaligned_be16(data + offset);
214 		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
215 			return be16_to_cpu(tmp);
216 	} else {
217 		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
218 		if (likely(ptr))
219 			return get_unaligned_be16(ptr);
220 	}
221 
222 	return -EFAULT;
223 }
224 
BPF_CALL_2(bpf_skb_load_helper_16_no_cache,const struct sk_buff *,skb,int,offset)225 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
226 	   int, offset)
227 {
228 	return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
229 					  offset);
230 }
231 
BPF_CALL_4(bpf_skb_load_helper_32,const struct sk_buff *,skb,const void *,data,int,headlen,int,offset)232 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
233 	   data, int, headlen, int, offset)
234 {
235 	u32 tmp, *ptr;
236 	const int len = sizeof(tmp);
237 
238 	if (likely(offset >= 0)) {
239 		if (headlen - offset >= len)
240 			return get_unaligned_be32(data + offset);
241 		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
242 			return be32_to_cpu(tmp);
243 	} else {
244 		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
245 		if (likely(ptr))
246 			return get_unaligned_be32(ptr);
247 	}
248 
249 	return -EFAULT;
250 }
251 
BPF_CALL_2(bpf_skb_load_helper_32_no_cache,const struct sk_buff *,skb,int,offset)252 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
253 	   int, offset)
254 {
255 	return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
256 					  offset);
257 }
258 
BPF_CALL_0(bpf_get_raw_cpu_id)259 BPF_CALL_0(bpf_get_raw_cpu_id)
260 {
261 	return raw_smp_processor_id();
262 }
263 
264 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
265 	.func		= bpf_get_raw_cpu_id,
266 	.gpl_only	= false,
267 	.ret_type	= RET_INTEGER,
268 };
269 
convert_skb_access(int skb_field,int dst_reg,int src_reg,struct bpf_insn * insn_buf)270 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
271 			      struct bpf_insn *insn_buf)
272 {
273 	struct bpf_insn *insn = insn_buf;
274 
275 	switch (skb_field) {
276 	case SKF_AD_MARK:
277 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
278 
279 		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
280 				      offsetof(struct sk_buff, mark));
281 		break;
282 
283 	case SKF_AD_PKTTYPE:
284 		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
285 		*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
286 #ifdef __BIG_ENDIAN_BITFIELD
287 		*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
288 #endif
289 		break;
290 
291 	case SKF_AD_QUEUE:
292 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
293 
294 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
295 				      offsetof(struct sk_buff, queue_mapping));
296 		break;
297 
298 	case SKF_AD_VLAN_TAG:
299 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
300 
301 		/* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
302 		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
303 				      offsetof(struct sk_buff, vlan_tci));
304 		break;
305 	case SKF_AD_VLAN_TAG_PRESENT:
306 		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_VLAN_PRESENT_OFFSET());
307 		if (PKT_VLAN_PRESENT_BIT)
308 			*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, PKT_VLAN_PRESENT_BIT);
309 		if (PKT_VLAN_PRESENT_BIT < 7)
310 			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
311 		break;
312 	}
313 
314 	return insn - insn_buf;
315 }
316 
convert_bpf_extensions(struct sock_filter * fp,struct bpf_insn ** insnp)317 static bool convert_bpf_extensions(struct sock_filter *fp,
318 				   struct bpf_insn **insnp)
319 {
320 	struct bpf_insn *insn = *insnp;
321 	u32 cnt;
322 
323 	switch (fp->k) {
324 	case SKF_AD_OFF + SKF_AD_PROTOCOL:
325 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
326 
327 		/* A = *(u16 *) (CTX + offsetof(protocol)) */
328 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
329 				      offsetof(struct sk_buff, protocol));
330 		/* A = ntohs(A) [emitting a nop or swap16] */
331 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
332 		break;
333 
334 	case SKF_AD_OFF + SKF_AD_PKTTYPE:
335 		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
336 		insn += cnt - 1;
337 		break;
338 
339 	case SKF_AD_OFF + SKF_AD_IFINDEX:
340 	case SKF_AD_OFF + SKF_AD_HATYPE:
341 		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
342 		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
343 
344 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
345 				      BPF_REG_TMP, BPF_REG_CTX,
346 				      offsetof(struct sk_buff, dev));
347 		/* if (tmp != 0) goto pc + 1 */
348 		*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
349 		*insn++ = BPF_EXIT_INSN();
350 		if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
351 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
352 					    offsetof(struct net_device, ifindex));
353 		else
354 			*insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
355 					    offsetof(struct net_device, type));
356 		break;
357 
358 	case SKF_AD_OFF + SKF_AD_MARK:
359 		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
360 		insn += cnt - 1;
361 		break;
362 
363 	case SKF_AD_OFF + SKF_AD_RXHASH:
364 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
365 
366 		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
367 				    offsetof(struct sk_buff, hash));
368 		break;
369 
370 	case SKF_AD_OFF + SKF_AD_QUEUE:
371 		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
372 		insn += cnt - 1;
373 		break;
374 
375 	case SKF_AD_OFF + SKF_AD_VLAN_TAG:
376 		cnt = convert_skb_access(SKF_AD_VLAN_TAG,
377 					 BPF_REG_A, BPF_REG_CTX, insn);
378 		insn += cnt - 1;
379 		break;
380 
381 	case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
382 		cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
383 					 BPF_REG_A, BPF_REG_CTX, insn);
384 		insn += cnt - 1;
385 		break;
386 
387 	case SKF_AD_OFF + SKF_AD_VLAN_TPID:
388 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
389 
390 		/* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
391 		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
392 				      offsetof(struct sk_buff, vlan_proto));
393 		/* A = ntohs(A) [emitting a nop or swap16] */
394 		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
395 		break;
396 
397 	case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
398 	case SKF_AD_OFF + SKF_AD_NLATTR:
399 	case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
400 	case SKF_AD_OFF + SKF_AD_CPU:
401 	case SKF_AD_OFF + SKF_AD_RANDOM:
402 		/* arg1 = CTX */
403 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
404 		/* arg2 = A */
405 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
406 		/* arg3 = X */
407 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
408 		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
409 		switch (fp->k) {
410 		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
411 			*insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
412 			break;
413 		case SKF_AD_OFF + SKF_AD_NLATTR:
414 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
415 			break;
416 		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
417 			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
418 			break;
419 		case SKF_AD_OFF + SKF_AD_CPU:
420 			*insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
421 			break;
422 		case SKF_AD_OFF + SKF_AD_RANDOM:
423 			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
424 			bpf_user_rnd_init_once();
425 			break;
426 		}
427 		break;
428 
429 	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
430 		/* A ^= X */
431 		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
432 		break;
433 
434 	default:
435 		/* This is just a dummy call to avoid letting the compiler
436 		 * evict __bpf_call_base() as an optimization. Placed here
437 		 * where no-one bothers.
438 		 */
439 		BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
440 		return false;
441 	}
442 
443 	*insnp = insn;
444 	return true;
445 }
446 
convert_bpf_ld_abs(struct sock_filter * fp,struct bpf_insn ** insnp)447 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
448 {
449 	const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
450 	int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
451 	bool endian = BPF_SIZE(fp->code) == BPF_H ||
452 		      BPF_SIZE(fp->code) == BPF_W;
453 	bool indirect = BPF_MODE(fp->code) == BPF_IND;
454 	const int ip_align = NET_IP_ALIGN;
455 	struct bpf_insn *insn = *insnp;
456 	int offset = fp->k;
457 
458 	if (!indirect &&
459 	    ((unaligned_ok && offset >= 0) ||
460 	     (!unaligned_ok && offset >= 0 &&
461 	      offset + ip_align >= 0 &&
462 	      offset + ip_align % size == 0))) {
463 		bool ldx_off_ok = offset <= S16_MAX;
464 
465 		*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
466 		if (offset)
467 			*insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
468 		*insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
469 				      size, 2 + endian + (!ldx_off_ok * 2));
470 		if (ldx_off_ok) {
471 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
472 					      BPF_REG_D, offset);
473 		} else {
474 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
475 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
476 			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
477 					      BPF_REG_TMP, 0);
478 		}
479 		if (endian)
480 			*insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
481 		*insn++ = BPF_JMP_A(8);
482 	}
483 
484 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
485 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
486 	*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
487 	if (!indirect) {
488 		*insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
489 	} else {
490 		*insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
491 		if (fp->k)
492 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
493 	}
494 
495 	switch (BPF_SIZE(fp->code)) {
496 	case BPF_B:
497 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
498 		break;
499 	case BPF_H:
500 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
501 		break;
502 	case BPF_W:
503 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
504 		break;
505 	default:
506 		return false;
507 	}
508 
509 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
510 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
511 	*insn   = BPF_EXIT_INSN();
512 
513 	*insnp = insn;
514 	return true;
515 }
516 
517 /**
518  *	bpf_convert_filter - convert filter program
519  *	@prog: the user passed filter program
520  *	@len: the length of the user passed filter program
521  *	@new_prog: allocated 'struct bpf_prog' or NULL
522  *	@new_len: pointer to store length of converted program
523  *	@seen_ld_abs: bool whether we've seen ld_abs/ind
524  *
525  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
526  * style extended BPF (eBPF).
527  * Conversion workflow:
528  *
529  * 1) First pass for calculating the new program length:
530  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
531  *
532  * 2) 2nd pass to remap in two passes: 1st pass finds new
533  *    jump offsets, 2nd pass remapping:
534  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
535  */
bpf_convert_filter(struct sock_filter * prog,int len,struct bpf_prog * new_prog,int * new_len,bool * seen_ld_abs)536 static int bpf_convert_filter(struct sock_filter *prog, int len,
537 			      struct bpf_prog *new_prog, int *new_len,
538 			      bool *seen_ld_abs)
539 {
540 	int new_flen = 0, pass = 0, target, i, stack_off;
541 	struct bpf_insn *new_insn, *first_insn = NULL;
542 	struct sock_filter *fp;
543 	int *addrs = NULL;
544 	u8 bpf_src;
545 
546 	BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
547 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
548 
549 	if (len <= 0 || len > BPF_MAXINSNS)
550 		return -EINVAL;
551 
552 	if (new_prog) {
553 		first_insn = new_prog->insnsi;
554 		addrs = kcalloc(len, sizeof(*addrs),
555 				GFP_KERNEL | __GFP_NOWARN);
556 		if (!addrs)
557 			return -ENOMEM;
558 	}
559 
560 do_pass:
561 	new_insn = first_insn;
562 	fp = prog;
563 
564 	/* Classic BPF related prologue emission. */
565 	if (new_prog) {
566 		/* Classic BPF expects A and X to be reset first. These need
567 		 * to be guaranteed to be the first two instructions.
568 		 */
569 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
570 		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
571 
572 		/* All programs must keep CTX in callee saved BPF_REG_CTX.
573 		 * In eBPF case it's done by the compiler, here we need to
574 		 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
575 		 */
576 		*new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
577 		if (*seen_ld_abs) {
578 			/* For packet access in classic BPF, cache skb->data
579 			 * in callee-saved BPF R8 and skb->len - skb->data_len
580 			 * (headlen) in BPF R9. Since classic BPF is read-only
581 			 * on CTX, we only need to cache it once.
582 			 */
583 			*new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
584 						  BPF_REG_D, BPF_REG_CTX,
585 						  offsetof(struct sk_buff, data));
586 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
587 						  offsetof(struct sk_buff, len));
588 			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
589 						  offsetof(struct sk_buff, data_len));
590 			*new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
591 		}
592 	} else {
593 		new_insn += 3;
594 	}
595 
596 	for (i = 0; i < len; fp++, i++) {
597 		struct bpf_insn tmp_insns[32] = { };
598 		struct bpf_insn *insn = tmp_insns;
599 
600 		if (addrs)
601 			addrs[i] = new_insn - first_insn;
602 
603 		switch (fp->code) {
604 		/* All arithmetic insns and skb loads map as-is. */
605 		case BPF_ALU | BPF_ADD | BPF_X:
606 		case BPF_ALU | BPF_ADD | BPF_K:
607 		case BPF_ALU | BPF_SUB | BPF_X:
608 		case BPF_ALU | BPF_SUB | BPF_K:
609 		case BPF_ALU | BPF_AND | BPF_X:
610 		case BPF_ALU | BPF_AND | BPF_K:
611 		case BPF_ALU | BPF_OR | BPF_X:
612 		case BPF_ALU | BPF_OR | BPF_K:
613 		case BPF_ALU | BPF_LSH | BPF_X:
614 		case BPF_ALU | BPF_LSH | BPF_K:
615 		case BPF_ALU | BPF_RSH | BPF_X:
616 		case BPF_ALU | BPF_RSH | BPF_K:
617 		case BPF_ALU | BPF_XOR | BPF_X:
618 		case BPF_ALU | BPF_XOR | BPF_K:
619 		case BPF_ALU | BPF_MUL | BPF_X:
620 		case BPF_ALU | BPF_MUL | BPF_K:
621 		case BPF_ALU | BPF_DIV | BPF_X:
622 		case BPF_ALU | BPF_DIV | BPF_K:
623 		case BPF_ALU | BPF_MOD | BPF_X:
624 		case BPF_ALU | BPF_MOD | BPF_K:
625 		case BPF_ALU | BPF_NEG:
626 		case BPF_LD | BPF_ABS | BPF_W:
627 		case BPF_LD | BPF_ABS | BPF_H:
628 		case BPF_LD | BPF_ABS | BPF_B:
629 		case BPF_LD | BPF_IND | BPF_W:
630 		case BPF_LD | BPF_IND | BPF_H:
631 		case BPF_LD | BPF_IND | BPF_B:
632 			/* Check for overloaded BPF extension and
633 			 * directly convert it if found, otherwise
634 			 * just move on with mapping.
635 			 */
636 			if (BPF_CLASS(fp->code) == BPF_LD &&
637 			    BPF_MODE(fp->code) == BPF_ABS &&
638 			    convert_bpf_extensions(fp, &insn))
639 				break;
640 			if (BPF_CLASS(fp->code) == BPF_LD &&
641 			    convert_bpf_ld_abs(fp, &insn)) {
642 				*seen_ld_abs = true;
643 				break;
644 			}
645 
646 			if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
647 			    fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
648 				*insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
649 				/* Error with exception code on div/mod by 0.
650 				 * For cBPF programs, this was always return 0.
651 				 */
652 				*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
653 				*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
654 				*insn++ = BPF_EXIT_INSN();
655 			}
656 
657 			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
658 			break;
659 
660 		/* Jump transformation cannot use BPF block macros
661 		 * everywhere as offset calculation and target updates
662 		 * require a bit more work than the rest, i.e. jump
663 		 * opcodes map as-is, but offsets need adjustment.
664 		 */
665 
666 #define BPF_EMIT_JMP							\
667 	do {								\
668 		const s32 off_min = S16_MIN, off_max = S16_MAX;		\
669 		s32 off;						\
670 									\
671 		if (target >= len || target < 0)			\
672 			goto err;					\
673 		off = addrs ? addrs[target] - addrs[i] - 1 : 0;		\
674 		/* Adjust pc relative offset for 2nd or 3rd insn. */	\
675 		off -= insn - tmp_insns;				\
676 		/* Reject anything not fitting into insn->off. */	\
677 		if (off < off_min || off > off_max)			\
678 			goto err;					\
679 		insn->off = off;					\
680 	} while (0)
681 
682 		case BPF_JMP | BPF_JA:
683 			target = i + fp->k + 1;
684 			insn->code = fp->code;
685 			BPF_EMIT_JMP;
686 			break;
687 
688 		case BPF_JMP | BPF_JEQ | BPF_K:
689 		case BPF_JMP | BPF_JEQ | BPF_X:
690 		case BPF_JMP | BPF_JSET | BPF_K:
691 		case BPF_JMP | BPF_JSET | BPF_X:
692 		case BPF_JMP | BPF_JGT | BPF_K:
693 		case BPF_JMP | BPF_JGT | BPF_X:
694 		case BPF_JMP | BPF_JGE | BPF_K:
695 		case BPF_JMP | BPF_JGE | BPF_X:
696 			if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
697 				/* BPF immediates are signed, zero extend
698 				 * immediate into tmp register and use it
699 				 * in compare insn.
700 				 */
701 				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
702 
703 				insn->dst_reg = BPF_REG_A;
704 				insn->src_reg = BPF_REG_TMP;
705 				bpf_src = BPF_X;
706 			} else {
707 				insn->dst_reg = BPF_REG_A;
708 				insn->imm = fp->k;
709 				bpf_src = BPF_SRC(fp->code);
710 				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
711 			}
712 
713 			/* Common case where 'jump_false' is next insn. */
714 			if (fp->jf == 0) {
715 				insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
716 				target = i + fp->jt + 1;
717 				BPF_EMIT_JMP;
718 				break;
719 			}
720 
721 			/* Convert some jumps when 'jump_true' is next insn. */
722 			if (fp->jt == 0) {
723 				switch (BPF_OP(fp->code)) {
724 				case BPF_JEQ:
725 					insn->code = BPF_JMP | BPF_JNE | bpf_src;
726 					break;
727 				case BPF_JGT:
728 					insn->code = BPF_JMP | BPF_JLE | bpf_src;
729 					break;
730 				case BPF_JGE:
731 					insn->code = BPF_JMP | BPF_JLT | bpf_src;
732 					break;
733 				default:
734 					goto jmp_rest;
735 				}
736 
737 				target = i + fp->jf + 1;
738 				BPF_EMIT_JMP;
739 				break;
740 			}
741 jmp_rest:
742 			/* Other jumps are mapped into two insns: Jxx and JA. */
743 			target = i + fp->jt + 1;
744 			insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
745 			BPF_EMIT_JMP;
746 			insn++;
747 
748 			insn->code = BPF_JMP | BPF_JA;
749 			target = i + fp->jf + 1;
750 			BPF_EMIT_JMP;
751 			break;
752 
753 		/* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
754 		case BPF_LDX | BPF_MSH | BPF_B: {
755 			struct sock_filter tmp = {
756 				.code	= BPF_LD | BPF_ABS | BPF_B,
757 				.k	= fp->k,
758 			};
759 
760 			*seen_ld_abs = true;
761 
762 			/* X = A */
763 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
764 			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
765 			convert_bpf_ld_abs(&tmp, &insn);
766 			insn++;
767 			/* A &= 0xf */
768 			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
769 			/* A <<= 2 */
770 			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
771 			/* tmp = X */
772 			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
773 			/* X = A */
774 			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
775 			/* A = tmp */
776 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
777 			break;
778 		}
779 		/* RET_K is remaped into 2 insns. RET_A case doesn't need an
780 		 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
781 		 */
782 		case BPF_RET | BPF_A:
783 		case BPF_RET | BPF_K:
784 			if (BPF_RVAL(fp->code) == BPF_K)
785 				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
786 							0, fp->k);
787 			*insn = BPF_EXIT_INSN();
788 			break;
789 
790 		/* Store to stack. */
791 		case BPF_ST:
792 		case BPF_STX:
793 			stack_off = fp->k * 4  + 4;
794 			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
795 					    BPF_ST ? BPF_REG_A : BPF_REG_X,
796 					    -stack_off);
797 			/* check_load_and_stores() verifies that classic BPF can
798 			 * load from stack only after write, so tracking
799 			 * stack_depth for ST|STX insns is enough
800 			 */
801 			if (new_prog && new_prog->aux->stack_depth < stack_off)
802 				new_prog->aux->stack_depth = stack_off;
803 			break;
804 
805 		/* Load from stack. */
806 		case BPF_LD | BPF_MEM:
807 		case BPF_LDX | BPF_MEM:
808 			stack_off = fp->k * 4  + 4;
809 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
810 					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
811 					    -stack_off);
812 			break;
813 
814 		/* A = K or X = K */
815 		case BPF_LD | BPF_IMM:
816 		case BPF_LDX | BPF_IMM:
817 			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
818 					      BPF_REG_A : BPF_REG_X, fp->k);
819 			break;
820 
821 		/* X = A */
822 		case BPF_MISC | BPF_TAX:
823 			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
824 			break;
825 
826 		/* A = X */
827 		case BPF_MISC | BPF_TXA:
828 			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
829 			break;
830 
831 		/* A = skb->len or X = skb->len */
832 		case BPF_LD | BPF_W | BPF_LEN:
833 		case BPF_LDX | BPF_W | BPF_LEN:
834 			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
835 					    BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
836 					    offsetof(struct sk_buff, len));
837 			break;
838 
839 		/* Access seccomp_data fields. */
840 		case BPF_LDX | BPF_ABS | BPF_W:
841 			/* A = *(u32 *) (ctx + K) */
842 			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
843 			break;
844 
845 		/* Unknown instruction. */
846 		default:
847 			goto err;
848 		}
849 
850 		insn++;
851 		if (new_prog)
852 			memcpy(new_insn, tmp_insns,
853 			       sizeof(*insn) * (insn - tmp_insns));
854 		new_insn += insn - tmp_insns;
855 	}
856 
857 	if (!new_prog) {
858 		/* Only calculating new length. */
859 		*new_len = new_insn - first_insn;
860 		if (*seen_ld_abs)
861 			*new_len += 4; /* Prologue bits. */
862 		return 0;
863 	}
864 
865 	pass++;
866 	if (new_flen != new_insn - first_insn) {
867 		new_flen = new_insn - first_insn;
868 		if (pass > 2)
869 			goto err;
870 		goto do_pass;
871 	}
872 
873 	kfree(addrs);
874 	BUG_ON(*new_len != new_flen);
875 	return 0;
876 err:
877 	kfree(addrs);
878 	return -EINVAL;
879 }
880 
881 /* Security:
882  *
883  * As we dont want to clear mem[] array for each packet going through
884  * __bpf_prog_run(), we check that filter loaded by user never try to read
885  * a cell if not previously written, and we check all branches to be sure
886  * a malicious user doesn't try to abuse us.
887  */
check_load_and_stores(const struct sock_filter * filter,int flen)888 static int check_load_and_stores(const struct sock_filter *filter, int flen)
889 {
890 	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
891 	int pc, ret = 0;
892 
893 	BUILD_BUG_ON(BPF_MEMWORDS > 16);
894 
895 	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
896 	if (!masks)
897 		return -ENOMEM;
898 
899 	memset(masks, 0xff, flen * sizeof(*masks));
900 
901 	for (pc = 0; pc < flen; pc++) {
902 		memvalid &= masks[pc];
903 
904 		switch (filter[pc].code) {
905 		case BPF_ST:
906 		case BPF_STX:
907 			memvalid |= (1 << filter[pc].k);
908 			break;
909 		case BPF_LD | BPF_MEM:
910 		case BPF_LDX | BPF_MEM:
911 			if (!(memvalid & (1 << filter[pc].k))) {
912 				ret = -EINVAL;
913 				goto error;
914 			}
915 			break;
916 		case BPF_JMP | BPF_JA:
917 			/* A jump must set masks on target */
918 			masks[pc + 1 + filter[pc].k] &= memvalid;
919 			memvalid = ~0;
920 			break;
921 		case BPF_JMP | BPF_JEQ | BPF_K:
922 		case BPF_JMP | BPF_JEQ | BPF_X:
923 		case BPF_JMP | BPF_JGE | BPF_K:
924 		case BPF_JMP | BPF_JGE | BPF_X:
925 		case BPF_JMP | BPF_JGT | BPF_K:
926 		case BPF_JMP | BPF_JGT | BPF_X:
927 		case BPF_JMP | BPF_JSET | BPF_K:
928 		case BPF_JMP | BPF_JSET | BPF_X:
929 			/* A jump must set masks on targets */
930 			masks[pc + 1 + filter[pc].jt] &= memvalid;
931 			masks[pc + 1 + filter[pc].jf] &= memvalid;
932 			memvalid = ~0;
933 			break;
934 		}
935 	}
936 error:
937 	kfree(masks);
938 	return ret;
939 }
940 
chk_code_allowed(u16 code_to_probe)941 static bool chk_code_allowed(u16 code_to_probe)
942 {
943 	static const bool codes[] = {
944 		/* 32 bit ALU operations */
945 		[BPF_ALU | BPF_ADD | BPF_K] = true,
946 		[BPF_ALU | BPF_ADD | BPF_X] = true,
947 		[BPF_ALU | BPF_SUB | BPF_K] = true,
948 		[BPF_ALU | BPF_SUB | BPF_X] = true,
949 		[BPF_ALU | BPF_MUL | BPF_K] = true,
950 		[BPF_ALU | BPF_MUL | BPF_X] = true,
951 		[BPF_ALU | BPF_DIV | BPF_K] = true,
952 		[BPF_ALU | BPF_DIV | BPF_X] = true,
953 		[BPF_ALU | BPF_MOD | BPF_K] = true,
954 		[BPF_ALU | BPF_MOD | BPF_X] = true,
955 		[BPF_ALU | BPF_AND | BPF_K] = true,
956 		[BPF_ALU | BPF_AND | BPF_X] = true,
957 		[BPF_ALU | BPF_OR | BPF_K] = true,
958 		[BPF_ALU | BPF_OR | BPF_X] = true,
959 		[BPF_ALU | BPF_XOR | BPF_K] = true,
960 		[BPF_ALU | BPF_XOR | BPF_X] = true,
961 		[BPF_ALU | BPF_LSH | BPF_K] = true,
962 		[BPF_ALU | BPF_LSH | BPF_X] = true,
963 		[BPF_ALU | BPF_RSH | BPF_K] = true,
964 		[BPF_ALU | BPF_RSH | BPF_X] = true,
965 		[BPF_ALU | BPF_NEG] = true,
966 		/* Load instructions */
967 		[BPF_LD | BPF_W | BPF_ABS] = true,
968 		[BPF_LD | BPF_H | BPF_ABS] = true,
969 		[BPF_LD | BPF_B | BPF_ABS] = true,
970 		[BPF_LD | BPF_W | BPF_LEN] = true,
971 		[BPF_LD | BPF_W | BPF_IND] = true,
972 		[BPF_LD | BPF_H | BPF_IND] = true,
973 		[BPF_LD | BPF_B | BPF_IND] = true,
974 		[BPF_LD | BPF_IMM] = true,
975 		[BPF_LD | BPF_MEM] = true,
976 		[BPF_LDX | BPF_W | BPF_LEN] = true,
977 		[BPF_LDX | BPF_B | BPF_MSH] = true,
978 		[BPF_LDX | BPF_IMM] = true,
979 		[BPF_LDX | BPF_MEM] = true,
980 		/* Store instructions */
981 		[BPF_ST] = true,
982 		[BPF_STX] = true,
983 		/* Misc instructions */
984 		[BPF_MISC | BPF_TAX] = true,
985 		[BPF_MISC | BPF_TXA] = true,
986 		/* Return instructions */
987 		[BPF_RET | BPF_K] = true,
988 		[BPF_RET | BPF_A] = true,
989 		/* Jump instructions */
990 		[BPF_JMP | BPF_JA] = true,
991 		[BPF_JMP | BPF_JEQ | BPF_K] = true,
992 		[BPF_JMP | BPF_JEQ | BPF_X] = true,
993 		[BPF_JMP | BPF_JGE | BPF_K] = true,
994 		[BPF_JMP | BPF_JGE | BPF_X] = true,
995 		[BPF_JMP | BPF_JGT | BPF_K] = true,
996 		[BPF_JMP | BPF_JGT | BPF_X] = true,
997 		[BPF_JMP | BPF_JSET | BPF_K] = true,
998 		[BPF_JMP | BPF_JSET | BPF_X] = true,
999 	};
1000 
1001 	if (code_to_probe >= ARRAY_SIZE(codes))
1002 		return false;
1003 
1004 	return codes[code_to_probe];
1005 }
1006 
bpf_check_basics_ok(const struct sock_filter * filter,unsigned int flen)1007 static bool bpf_check_basics_ok(const struct sock_filter *filter,
1008 				unsigned int flen)
1009 {
1010 	if (filter == NULL)
1011 		return false;
1012 	if (flen == 0 || flen > BPF_MAXINSNS)
1013 		return false;
1014 
1015 	return true;
1016 }
1017 
1018 /**
1019  *	bpf_check_classic - verify socket filter code
1020  *	@filter: filter to verify
1021  *	@flen: length of filter
1022  *
1023  * Check the user's filter code. If we let some ugly
1024  * filter code slip through kaboom! The filter must contain
1025  * no references or jumps that are out of range, no illegal
1026  * instructions, and must end with a RET instruction.
1027  *
1028  * All jumps are forward as they are not signed.
1029  *
1030  * Returns 0 if the rule set is legal or -EINVAL if not.
1031  */
bpf_check_classic(const struct sock_filter * filter,unsigned int flen)1032 static int bpf_check_classic(const struct sock_filter *filter,
1033 			     unsigned int flen)
1034 {
1035 	bool anc_found;
1036 	int pc;
1037 
1038 	/* Check the filter code now */
1039 	for (pc = 0; pc < flen; pc++) {
1040 		const struct sock_filter *ftest = &filter[pc];
1041 
1042 		/* May we actually operate on this code? */
1043 		if (!chk_code_allowed(ftest->code))
1044 			return -EINVAL;
1045 
1046 		/* Some instructions need special checks */
1047 		switch (ftest->code) {
1048 		case BPF_ALU | BPF_DIV | BPF_K:
1049 		case BPF_ALU | BPF_MOD | BPF_K:
1050 			/* Check for division by zero */
1051 			if (ftest->k == 0)
1052 				return -EINVAL;
1053 			break;
1054 		case BPF_ALU | BPF_LSH | BPF_K:
1055 		case BPF_ALU | BPF_RSH | BPF_K:
1056 			if (ftest->k >= 32)
1057 				return -EINVAL;
1058 			break;
1059 		case BPF_LD | BPF_MEM:
1060 		case BPF_LDX | BPF_MEM:
1061 		case BPF_ST:
1062 		case BPF_STX:
1063 			/* Check for invalid memory addresses */
1064 			if (ftest->k >= BPF_MEMWORDS)
1065 				return -EINVAL;
1066 			break;
1067 		case BPF_JMP | BPF_JA:
1068 			/* Note, the large ftest->k might cause loops.
1069 			 * Compare this with conditional jumps below,
1070 			 * where offsets are limited. --ANK (981016)
1071 			 */
1072 			if (ftest->k >= (unsigned int)(flen - pc - 1))
1073 				return -EINVAL;
1074 			break;
1075 		case BPF_JMP | BPF_JEQ | BPF_K:
1076 		case BPF_JMP | BPF_JEQ | BPF_X:
1077 		case BPF_JMP | BPF_JGE | BPF_K:
1078 		case BPF_JMP | BPF_JGE | BPF_X:
1079 		case BPF_JMP | BPF_JGT | BPF_K:
1080 		case BPF_JMP | BPF_JGT | BPF_X:
1081 		case BPF_JMP | BPF_JSET | BPF_K:
1082 		case BPF_JMP | BPF_JSET | BPF_X:
1083 			/* Both conditionals must be safe */
1084 			if (pc + ftest->jt + 1 >= flen ||
1085 			    pc + ftest->jf + 1 >= flen)
1086 				return -EINVAL;
1087 			break;
1088 		case BPF_LD | BPF_W | BPF_ABS:
1089 		case BPF_LD | BPF_H | BPF_ABS:
1090 		case BPF_LD | BPF_B | BPF_ABS:
1091 			anc_found = false;
1092 			if (bpf_anc_helper(ftest) & BPF_ANC)
1093 				anc_found = true;
1094 			/* Ancillary operation unknown or unsupported */
1095 			if (anc_found == false && ftest->k >= SKF_AD_OFF)
1096 				return -EINVAL;
1097 		}
1098 	}
1099 
1100 	/* Last instruction must be a RET code */
1101 	switch (filter[flen - 1].code) {
1102 	case BPF_RET | BPF_K:
1103 	case BPF_RET | BPF_A:
1104 		return check_load_and_stores(filter, flen);
1105 	}
1106 
1107 	return -EINVAL;
1108 }
1109 
bpf_prog_store_orig_filter(struct bpf_prog * fp,const struct sock_fprog * fprog)1110 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1111 				      const struct sock_fprog *fprog)
1112 {
1113 	unsigned int fsize = bpf_classic_proglen(fprog);
1114 	struct sock_fprog_kern *fkprog;
1115 
1116 	fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1117 	if (!fp->orig_prog)
1118 		return -ENOMEM;
1119 
1120 	fkprog = fp->orig_prog;
1121 	fkprog->len = fprog->len;
1122 
1123 	fkprog->filter = kmemdup(fp->insns, fsize,
1124 				 GFP_KERNEL | __GFP_NOWARN);
1125 	if (!fkprog->filter) {
1126 		kfree(fp->orig_prog);
1127 		return -ENOMEM;
1128 	}
1129 
1130 	return 0;
1131 }
1132 
bpf_release_orig_filter(struct bpf_prog * fp)1133 static void bpf_release_orig_filter(struct bpf_prog *fp)
1134 {
1135 	struct sock_fprog_kern *fprog = fp->orig_prog;
1136 
1137 	if (fprog) {
1138 		kfree(fprog->filter);
1139 		kfree(fprog);
1140 	}
1141 }
1142 
__bpf_prog_release(struct bpf_prog * prog)1143 static void __bpf_prog_release(struct bpf_prog *prog)
1144 {
1145 	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1146 		bpf_prog_put(prog);
1147 	} else {
1148 		bpf_release_orig_filter(prog);
1149 		bpf_prog_free(prog);
1150 	}
1151 }
1152 
__sk_filter_release(struct sk_filter * fp)1153 static void __sk_filter_release(struct sk_filter *fp)
1154 {
1155 	__bpf_prog_release(fp->prog);
1156 	kfree(fp);
1157 }
1158 
1159 /**
1160  * 	sk_filter_release_rcu - Release a socket filter by rcu_head
1161  *	@rcu: rcu_head that contains the sk_filter to free
1162  */
sk_filter_release_rcu(struct rcu_head * rcu)1163 static void sk_filter_release_rcu(struct rcu_head *rcu)
1164 {
1165 	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1166 
1167 	__sk_filter_release(fp);
1168 }
1169 
1170 /**
1171  *	sk_filter_release - release a socket filter
1172  *	@fp: filter to remove
1173  *
1174  *	Remove a filter from a socket and release its resources.
1175  */
sk_filter_release(struct sk_filter * fp)1176 static void sk_filter_release(struct sk_filter *fp)
1177 {
1178 	if (refcount_dec_and_test(&fp->refcnt))
1179 		call_rcu(&fp->rcu, sk_filter_release_rcu);
1180 }
1181 
sk_filter_uncharge(struct sock * sk,struct sk_filter * fp)1182 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1183 {
1184 	u32 filter_size = bpf_prog_size(fp->prog->len);
1185 
1186 	atomic_sub(filter_size, &sk->sk_omem_alloc);
1187 	sk_filter_release(fp);
1188 }
1189 
1190 /* try to charge the socket memory if there is space available
1191  * return true on success
1192  */
__sk_filter_charge(struct sock * sk,struct sk_filter * fp)1193 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1194 {
1195 	u32 filter_size = bpf_prog_size(fp->prog->len);
1196 
1197 	/* same check as in sock_kmalloc() */
1198 	if (filter_size <= sysctl_optmem_max &&
1199 	    atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
1200 		atomic_add(filter_size, &sk->sk_omem_alloc);
1201 		return true;
1202 	}
1203 	return false;
1204 }
1205 
sk_filter_charge(struct sock * sk,struct sk_filter * fp)1206 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1207 {
1208 	if (!refcount_inc_not_zero(&fp->refcnt))
1209 		return false;
1210 
1211 	if (!__sk_filter_charge(sk, fp)) {
1212 		sk_filter_release(fp);
1213 		return false;
1214 	}
1215 	return true;
1216 }
1217 
bpf_migrate_filter(struct bpf_prog * fp)1218 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1219 {
1220 	struct sock_filter *old_prog;
1221 	struct bpf_prog *old_fp;
1222 	int err, new_len, old_len = fp->len;
1223 	bool seen_ld_abs = false;
1224 
1225 	/* We are free to overwrite insns et al right here as it
1226 	 * won't be used at this point in time anymore internally
1227 	 * after the migration to the internal BPF instruction
1228 	 * representation.
1229 	 */
1230 	BUILD_BUG_ON(sizeof(struct sock_filter) !=
1231 		     sizeof(struct bpf_insn));
1232 
1233 	/* Conversion cannot happen on overlapping memory areas,
1234 	 * so we need to keep the user BPF around until the 2nd
1235 	 * pass. At this time, the user BPF is stored in fp->insns.
1236 	 */
1237 	old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1238 			   GFP_KERNEL | __GFP_NOWARN);
1239 	if (!old_prog) {
1240 		err = -ENOMEM;
1241 		goto out_err;
1242 	}
1243 
1244 	/* 1st pass: calculate the new program length. */
1245 	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1246 				 &seen_ld_abs);
1247 	if (err)
1248 		goto out_err_free;
1249 
1250 	/* Expand fp for appending the new filter representation. */
1251 	old_fp = fp;
1252 	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1253 	if (!fp) {
1254 		/* The old_fp is still around in case we couldn't
1255 		 * allocate new memory, so uncharge on that one.
1256 		 */
1257 		fp = old_fp;
1258 		err = -ENOMEM;
1259 		goto out_err_free;
1260 	}
1261 
1262 	fp->len = new_len;
1263 
1264 	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1265 	err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1266 				 &seen_ld_abs);
1267 	if (err)
1268 		/* 2nd bpf_convert_filter() can fail only if it fails
1269 		 * to allocate memory, remapping must succeed. Note,
1270 		 * that at this time old_fp has already been released
1271 		 * by krealloc().
1272 		 */
1273 		goto out_err_free;
1274 
1275 	fp = bpf_prog_select_runtime(fp, &err);
1276 	if (err)
1277 		goto out_err_free;
1278 
1279 	kfree(old_prog);
1280 	return fp;
1281 
1282 out_err_free:
1283 	kfree(old_prog);
1284 out_err:
1285 	__bpf_prog_release(fp);
1286 	return ERR_PTR(err);
1287 }
1288 
bpf_prepare_filter(struct bpf_prog * fp,bpf_aux_classic_check_t trans)1289 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1290 					   bpf_aux_classic_check_t trans)
1291 {
1292 	int err;
1293 
1294 	fp->bpf_func = NULL;
1295 	fp->jited = 0;
1296 
1297 	err = bpf_check_classic(fp->insns, fp->len);
1298 	if (err) {
1299 		__bpf_prog_release(fp);
1300 		return ERR_PTR(err);
1301 	}
1302 
1303 	/* There might be additional checks and transformations
1304 	 * needed on classic filters, f.e. in case of seccomp.
1305 	 */
1306 	if (trans) {
1307 		err = trans(fp->insns, fp->len);
1308 		if (err) {
1309 			__bpf_prog_release(fp);
1310 			return ERR_PTR(err);
1311 		}
1312 	}
1313 
1314 	/* Probe if we can JIT compile the filter and if so, do
1315 	 * the compilation of the filter.
1316 	 */
1317 	bpf_jit_compile(fp);
1318 
1319 	/* JIT compiler couldn't process this filter, so do the
1320 	 * internal BPF translation for the optimized interpreter.
1321 	 */
1322 	if (!fp->jited)
1323 		fp = bpf_migrate_filter(fp);
1324 
1325 	return fp;
1326 }
1327 
1328 /**
1329  *	bpf_prog_create - create an unattached filter
1330  *	@pfp: the unattached filter that is created
1331  *	@fprog: the filter program
1332  *
1333  * Create a filter independent of any socket. We first run some
1334  * sanity checks on it to make sure it does not explode on us later.
1335  * If an error occurs or there is insufficient memory for the filter
1336  * a negative errno code is returned. On success the return is zero.
1337  */
bpf_prog_create(struct bpf_prog ** pfp,struct sock_fprog_kern * fprog)1338 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1339 {
1340 	unsigned int fsize = bpf_classic_proglen(fprog);
1341 	struct bpf_prog *fp;
1342 
1343 	/* Make sure new filter is there and in the right amounts. */
1344 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1345 		return -EINVAL;
1346 
1347 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1348 	if (!fp)
1349 		return -ENOMEM;
1350 
1351 	memcpy(fp->insns, fprog->filter, fsize);
1352 
1353 	fp->len = fprog->len;
1354 	/* Since unattached filters are not copied back to user
1355 	 * space through sk_get_filter(), we do not need to hold
1356 	 * a copy here, and can spare us the work.
1357 	 */
1358 	fp->orig_prog = NULL;
1359 
1360 	/* bpf_prepare_filter() already takes care of freeing
1361 	 * memory in case something goes wrong.
1362 	 */
1363 	fp = bpf_prepare_filter(fp, NULL);
1364 	if (IS_ERR(fp))
1365 		return PTR_ERR(fp);
1366 
1367 	*pfp = fp;
1368 	return 0;
1369 }
1370 EXPORT_SYMBOL_GPL(bpf_prog_create);
1371 
1372 /**
1373  *	bpf_prog_create_from_user - create an unattached filter from user buffer
1374  *	@pfp: the unattached filter that is created
1375  *	@fprog: the filter program
1376  *	@trans: post-classic verifier transformation handler
1377  *	@save_orig: save classic BPF program
1378  *
1379  * This function effectively does the same as bpf_prog_create(), only
1380  * that it builds up its insns buffer from user space provided buffer.
1381  * It also allows for passing a bpf_aux_classic_check_t handler.
1382  */
bpf_prog_create_from_user(struct bpf_prog ** pfp,struct sock_fprog * fprog,bpf_aux_classic_check_t trans,bool save_orig)1383 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1384 			      bpf_aux_classic_check_t trans, bool save_orig)
1385 {
1386 	unsigned int fsize = bpf_classic_proglen(fprog);
1387 	struct bpf_prog *fp;
1388 	int err;
1389 
1390 	/* Make sure new filter is there and in the right amounts. */
1391 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1392 		return -EINVAL;
1393 
1394 	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1395 	if (!fp)
1396 		return -ENOMEM;
1397 
1398 	if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1399 		__bpf_prog_free(fp);
1400 		return -EFAULT;
1401 	}
1402 
1403 	fp->len = fprog->len;
1404 	fp->orig_prog = NULL;
1405 
1406 	if (save_orig) {
1407 		err = bpf_prog_store_orig_filter(fp, fprog);
1408 		if (err) {
1409 			__bpf_prog_free(fp);
1410 			return -ENOMEM;
1411 		}
1412 	}
1413 
1414 	/* bpf_prepare_filter() already takes care of freeing
1415 	 * memory in case something goes wrong.
1416 	 */
1417 	fp = bpf_prepare_filter(fp, trans);
1418 	if (IS_ERR(fp))
1419 		return PTR_ERR(fp);
1420 
1421 	*pfp = fp;
1422 	return 0;
1423 }
1424 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1425 
bpf_prog_destroy(struct bpf_prog * fp)1426 void bpf_prog_destroy(struct bpf_prog *fp)
1427 {
1428 	__bpf_prog_release(fp);
1429 }
1430 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1431 
__sk_attach_prog(struct bpf_prog * prog,struct sock * sk)1432 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1433 {
1434 	struct sk_filter *fp, *old_fp;
1435 
1436 	fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1437 	if (!fp)
1438 		return -ENOMEM;
1439 
1440 	fp->prog = prog;
1441 
1442 	if (!__sk_filter_charge(sk, fp)) {
1443 		kfree(fp);
1444 		return -ENOMEM;
1445 	}
1446 	refcount_set(&fp->refcnt, 1);
1447 
1448 	old_fp = rcu_dereference_protected(sk->sk_filter,
1449 					   lockdep_sock_is_held(sk));
1450 	rcu_assign_pointer(sk->sk_filter, fp);
1451 
1452 	if (old_fp)
1453 		sk_filter_uncharge(sk, old_fp);
1454 
1455 	return 0;
1456 }
1457 
1458 static
__get_filter(struct sock_fprog * fprog,struct sock * sk)1459 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1460 {
1461 	unsigned int fsize = bpf_classic_proglen(fprog);
1462 	struct bpf_prog *prog;
1463 	int err;
1464 
1465 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1466 		return ERR_PTR(-EPERM);
1467 
1468 	/* Make sure new filter is there and in the right amounts. */
1469 	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1470 		return ERR_PTR(-EINVAL);
1471 
1472 	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1473 	if (!prog)
1474 		return ERR_PTR(-ENOMEM);
1475 
1476 	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1477 		__bpf_prog_free(prog);
1478 		return ERR_PTR(-EINVAL);
1479 	}
1480 
1481 	prog->len = fprog->len;
1482 
1483 	err = bpf_prog_store_orig_filter(prog, fprog);
1484 	if (err) {
1485 		__bpf_prog_free(prog);
1486 		return ERR_PTR(-ENOMEM);
1487 	}
1488 
1489 	/* bpf_prepare_filter() already takes care of freeing
1490 	 * memory in case something goes wrong.
1491 	 */
1492 	return bpf_prepare_filter(prog, NULL);
1493 }
1494 
1495 /**
1496  *	sk_attach_filter - attach a socket filter
1497  *	@fprog: the filter program
1498  *	@sk: the socket to use
1499  *
1500  * Attach the user's filter code. We first run some sanity checks on
1501  * it to make sure it does not explode on us later. If an error
1502  * occurs or there is insufficient memory for the filter a negative
1503  * errno code is returned. On success the return is zero.
1504  */
sk_attach_filter(struct sock_fprog * fprog,struct sock * sk)1505 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1506 {
1507 	struct bpf_prog *prog = __get_filter(fprog, sk);
1508 	int err;
1509 
1510 	if (IS_ERR(prog))
1511 		return PTR_ERR(prog);
1512 
1513 	err = __sk_attach_prog(prog, sk);
1514 	if (err < 0) {
1515 		__bpf_prog_release(prog);
1516 		return err;
1517 	}
1518 
1519 	return 0;
1520 }
1521 EXPORT_SYMBOL_GPL(sk_attach_filter);
1522 
sk_reuseport_attach_filter(struct sock_fprog * fprog,struct sock * sk)1523 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1524 {
1525 	struct bpf_prog *prog = __get_filter(fprog, sk);
1526 	int err;
1527 
1528 	if (IS_ERR(prog))
1529 		return PTR_ERR(prog);
1530 
1531 	if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1532 		err = -ENOMEM;
1533 	else
1534 		err = reuseport_attach_prog(sk, prog);
1535 
1536 	if (err)
1537 		__bpf_prog_release(prog);
1538 
1539 	return err;
1540 }
1541 
__get_bpf(u32 ufd,struct sock * sk)1542 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1543 {
1544 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1545 		return ERR_PTR(-EPERM);
1546 
1547 	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1548 }
1549 
sk_attach_bpf(u32 ufd,struct sock * sk)1550 int sk_attach_bpf(u32 ufd, struct sock *sk)
1551 {
1552 	struct bpf_prog *prog = __get_bpf(ufd, sk);
1553 	int err;
1554 
1555 	if (IS_ERR(prog))
1556 		return PTR_ERR(prog);
1557 
1558 	err = __sk_attach_prog(prog, sk);
1559 	if (err < 0) {
1560 		bpf_prog_put(prog);
1561 		return err;
1562 	}
1563 
1564 	return 0;
1565 }
1566 
sk_reuseport_attach_bpf(u32 ufd,struct sock * sk)1567 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1568 {
1569 	struct bpf_prog *prog;
1570 	int err;
1571 
1572 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1573 		return -EPERM;
1574 
1575 	prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1576 	if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL)
1577 		prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1578 	if (IS_ERR(prog))
1579 		return PTR_ERR(prog);
1580 
1581 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1582 		/* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1583 		 * bpf prog (e.g. sockmap).  It depends on the
1584 		 * limitation imposed by bpf_prog_load().
1585 		 * Hence, sysctl_optmem_max is not checked.
1586 		 */
1587 		if ((sk->sk_type != SOCK_STREAM &&
1588 		     sk->sk_type != SOCK_DGRAM) ||
1589 		    (sk->sk_protocol != IPPROTO_UDP &&
1590 		     sk->sk_protocol != IPPROTO_TCP) ||
1591 		    (sk->sk_family != AF_INET &&
1592 		     sk->sk_family != AF_INET6)) {
1593 			err = -ENOTSUPP;
1594 			goto err_prog_put;
1595 		}
1596 	} else {
1597 		/* BPF_PROG_TYPE_SOCKET_FILTER */
1598 		if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
1599 			err = -ENOMEM;
1600 			goto err_prog_put;
1601 		}
1602 	}
1603 
1604 	err = reuseport_attach_prog(sk, prog);
1605 err_prog_put:
1606 	if (err)
1607 		bpf_prog_put(prog);
1608 
1609 	return err;
1610 }
1611 
sk_reuseport_prog_free(struct bpf_prog * prog)1612 void sk_reuseport_prog_free(struct bpf_prog *prog)
1613 {
1614 	if (!prog)
1615 		return;
1616 
1617 	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1618 		bpf_prog_put(prog);
1619 	else
1620 		bpf_prog_destroy(prog);
1621 }
1622 
1623 struct bpf_scratchpad {
1624 	union {
1625 		__be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1626 		u8     buff[MAX_BPF_STACK];
1627 	};
1628 };
1629 
1630 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1631 
__bpf_try_make_writable(struct sk_buff * skb,unsigned int write_len)1632 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1633 					  unsigned int write_len)
1634 {
1635 	return skb_ensure_writable(skb, write_len);
1636 }
1637 
bpf_try_make_writable(struct sk_buff * skb,unsigned int write_len)1638 static inline int bpf_try_make_writable(struct sk_buff *skb,
1639 					unsigned int write_len)
1640 {
1641 	int err = __bpf_try_make_writable(skb, write_len);
1642 
1643 	bpf_compute_data_pointers(skb);
1644 	return err;
1645 }
1646 
bpf_try_make_head_writable(struct sk_buff * skb)1647 static int bpf_try_make_head_writable(struct sk_buff *skb)
1648 {
1649 	return bpf_try_make_writable(skb, skb_headlen(skb));
1650 }
1651 
bpf_push_mac_rcsum(struct sk_buff * skb)1652 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1653 {
1654 	if (skb_at_tc_ingress(skb))
1655 		skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1656 }
1657 
bpf_pull_mac_rcsum(struct sk_buff * skb)1658 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1659 {
1660 	if (skb_at_tc_ingress(skb))
1661 		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1662 }
1663 
BPF_CALL_5(bpf_skb_store_bytes,struct sk_buff *,skb,u32,offset,const void *,from,u32,len,u64,flags)1664 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1665 	   const void *, from, u32, len, u64, flags)
1666 {
1667 	void *ptr;
1668 
1669 	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1670 		return -EINVAL;
1671 	if (unlikely(offset > INT_MAX))
1672 		return -EFAULT;
1673 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
1674 		return -EFAULT;
1675 
1676 	ptr = skb->data + offset;
1677 	if (flags & BPF_F_RECOMPUTE_CSUM)
1678 		__skb_postpull_rcsum(skb, ptr, len, offset);
1679 
1680 	memcpy(ptr, from, len);
1681 
1682 	if (flags & BPF_F_RECOMPUTE_CSUM)
1683 		__skb_postpush_rcsum(skb, ptr, len, offset);
1684 	if (flags & BPF_F_INVALIDATE_HASH)
1685 		skb_clear_hash(skb);
1686 
1687 	return 0;
1688 }
1689 
1690 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1691 	.func		= bpf_skb_store_bytes,
1692 	.gpl_only	= false,
1693 	.ret_type	= RET_INTEGER,
1694 	.arg1_type	= ARG_PTR_TO_CTX,
1695 	.arg2_type	= ARG_ANYTHING,
1696 	.arg3_type	= ARG_PTR_TO_MEM,
1697 	.arg4_type	= ARG_CONST_SIZE,
1698 	.arg5_type	= ARG_ANYTHING,
1699 };
1700 
BPF_CALL_4(bpf_skb_load_bytes,const struct sk_buff *,skb,u32,offset,void *,to,u32,len)1701 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1702 	   void *, to, u32, len)
1703 {
1704 	void *ptr;
1705 
1706 	if (unlikely(offset > INT_MAX))
1707 		goto err_clear;
1708 
1709 	ptr = skb_header_pointer(skb, offset, len, to);
1710 	if (unlikely(!ptr))
1711 		goto err_clear;
1712 	if (ptr != to)
1713 		memcpy(to, ptr, len);
1714 
1715 	return 0;
1716 err_clear:
1717 	memset(to, 0, len);
1718 	return -EFAULT;
1719 }
1720 
1721 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1722 	.func		= bpf_skb_load_bytes,
1723 	.gpl_only	= false,
1724 	.ret_type	= RET_INTEGER,
1725 	.arg1_type	= ARG_PTR_TO_CTX,
1726 	.arg2_type	= ARG_ANYTHING,
1727 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1728 	.arg4_type	= ARG_CONST_SIZE,
1729 };
1730 
BPF_CALL_4(bpf_flow_dissector_load_bytes,const struct bpf_flow_dissector *,ctx,u32,offset,void *,to,u32,len)1731 BPF_CALL_4(bpf_flow_dissector_load_bytes,
1732 	   const struct bpf_flow_dissector *, ctx, u32, offset,
1733 	   void *, to, u32, len)
1734 {
1735 	void *ptr;
1736 
1737 	if (unlikely(offset > 0xffff))
1738 		goto err_clear;
1739 
1740 	if (unlikely(!ctx->skb))
1741 		goto err_clear;
1742 
1743 	ptr = skb_header_pointer(ctx->skb, offset, len, to);
1744 	if (unlikely(!ptr))
1745 		goto err_clear;
1746 	if (ptr != to)
1747 		memcpy(to, ptr, len);
1748 
1749 	return 0;
1750 err_clear:
1751 	memset(to, 0, len);
1752 	return -EFAULT;
1753 }
1754 
1755 static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1756 	.func		= bpf_flow_dissector_load_bytes,
1757 	.gpl_only	= false,
1758 	.ret_type	= RET_INTEGER,
1759 	.arg1_type	= ARG_PTR_TO_CTX,
1760 	.arg2_type	= ARG_ANYTHING,
1761 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1762 	.arg4_type	= ARG_CONST_SIZE,
1763 };
1764 
BPF_CALL_5(bpf_skb_load_bytes_relative,const struct sk_buff *,skb,u32,offset,void *,to,u32,len,u32,start_header)1765 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1766 	   u32, offset, void *, to, u32, len, u32, start_header)
1767 {
1768 	u8 *end = skb_tail_pointer(skb);
1769 	u8 *start, *ptr;
1770 
1771 	if (unlikely(offset > 0xffff))
1772 		goto err_clear;
1773 
1774 	switch (start_header) {
1775 	case BPF_HDR_START_MAC:
1776 		if (unlikely(!skb_mac_header_was_set(skb)))
1777 			goto err_clear;
1778 		start = skb_mac_header(skb);
1779 		break;
1780 	case BPF_HDR_START_NET:
1781 		start = skb_network_header(skb);
1782 		break;
1783 	default:
1784 		goto err_clear;
1785 	}
1786 
1787 	ptr = start + offset;
1788 
1789 	if (likely(ptr + len <= end)) {
1790 		memcpy(to, ptr, len);
1791 		return 0;
1792 	}
1793 
1794 err_clear:
1795 	memset(to, 0, len);
1796 	return -EFAULT;
1797 }
1798 
1799 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1800 	.func		= bpf_skb_load_bytes_relative,
1801 	.gpl_only	= false,
1802 	.ret_type	= RET_INTEGER,
1803 	.arg1_type	= ARG_PTR_TO_CTX,
1804 	.arg2_type	= ARG_ANYTHING,
1805 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
1806 	.arg4_type	= ARG_CONST_SIZE,
1807 	.arg5_type	= ARG_ANYTHING,
1808 };
1809 
BPF_CALL_2(bpf_skb_pull_data,struct sk_buff *,skb,u32,len)1810 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1811 {
1812 	/* Idea is the following: should the needed direct read/write
1813 	 * test fail during runtime, we can pull in more data and redo
1814 	 * again, since implicitly, we invalidate previous checks here.
1815 	 *
1816 	 * Or, since we know how much we need to make read/writeable,
1817 	 * this can be done once at the program beginning for direct
1818 	 * access case. By this we overcome limitations of only current
1819 	 * headroom being accessible.
1820 	 */
1821 	return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1822 }
1823 
1824 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1825 	.func		= bpf_skb_pull_data,
1826 	.gpl_only	= false,
1827 	.ret_type	= RET_INTEGER,
1828 	.arg1_type	= ARG_PTR_TO_CTX,
1829 	.arg2_type	= ARG_ANYTHING,
1830 };
1831 
BPF_CALL_1(bpf_sk_fullsock,struct sock *,sk)1832 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1833 {
1834 	return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1835 }
1836 
1837 static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1838 	.func		= bpf_sk_fullsock,
1839 	.gpl_only	= false,
1840 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
1841 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
1842 };
1843 
sk_skb_try_make_writable(struct sk_buff * skb,unsigned int write_len)1844 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1845 					   unsigned int write_len)
1846 {
1847 	int err = __bpf_try_make_writable(skb, write_len);
1848 
1849 	bpf_compute_data_end_sk_skb(skb);
1850 	return err;
1851 }
1852 
BPF_CALL_2(sk_skb_pull_data,struct sk_buff *,skb,u32,len)1853 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1854 {
1855 	/* Idea is the following: should the needed direct read/write
1856 	 * test fail during runtime, we can pull in more data and redo
1857 	 * again, since implicitly, we invalidate previous checks here.
1858 	 *
1859 	 * Or, since we know how much we need to make read/writeable,
1860 	 * this can be done once at the program beginning for direct
1861 	 * access case. By this we overcome limitations of only current
1862 	 * headroom being accessible.
1863 	 */
1864 	return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1865 }
1866 
1867 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1868 	.func		= sk_skb_pull_data,
1869 	.gpl_only	= false,
1870 	.ret_type	= RET_INTEGER,
1871 	.arg1_type	= ARG_PTR_TO_CTX,
1872 	.arg2_type	= ARG_ANYTHING,
1873 };
1874 
BPF_CALL_5(bpf_l3_csum_replace,struct sk_buff *,skb,u32,offset,u64,from,u64,to,u64,flags)1875 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1876 	   u64, from, u64, to, u64, flags)
1877 {
1878 	__sum16 *ptr;
1879 
1880 	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1881 		return -EINVAL;
1882 	if (unlikely(offset > 0xffff || offset & 1))
1883 		return -EFAULT;
1884 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1885 		return -EFAULT;
1886 
1887 	ptr = (__sum16 *)(skb->data + offset);
1888 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1889 	case 0:
1890 		if (unlikely(from != 0))
1891 			return -EINVAL;
1892 
1893 		csum_replace_by_diff(ptr, to);
1894 		break;
1895 	case 2:
1896 		csum_replace2(ptr, from, to);
1897 		break;
1898 	case 4:
1899 		csum_replace4(ptr, from, to);
1900 		break;
1901 	default:
1902 		return -EINVAL;
1903 	}
1904 
1905 	return 0;
1906 }
1907 
1908 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1909 	.func		= bpf_l3_csum_replace,
1910 	.gpl_only	= false,
1911 	.ret_type	= RET_INTEGER,
1912 	.arg1_type	= ARG_PTR_TO_CTX,
1913 	.arg2_type	= ARG_ANYTHING,
1914 	.arg3_type	= ARG_ANYTHING,
1915 	.arg4_type	= ARG_ANYTHING,
1916 	.arg5_type	= ARG_ANYTHING,
1917 };
1918 
BPF_CALL_5(bpf_l4_csum_replace,struct sk_buff *,skb,u32,offset,u64,from,u64,to,u64,flags)1919 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1920 	   u64, from, u64, to, u64, flags)
1921 {
1922 	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1923 	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1924 	bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1925 	__sum16 *ptr;
1926 
1927 	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1928 			       BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1929 		return -EINVAL;
1930 	if (unlikely(offset > 0xffff || offset & 1))
1931 		return -EFAULT;
1932 	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1933 		return -EFAULT;
1934 
1935 	ptr = (__sum16 *)(skb->data + offset);
1936 	if (is_mmzero && !do_mforce && !*ptr)
1937 		return 0;
1938 
1939 	switch (flags & BPF_F_HDR_FIELD_MASK) {
1940 	case 0:
1941 		if (unlikely(from != 0))
1942 			return -EINVAL;
1943 
1944 		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1945 		break;
1946 	case 2:
1947 		inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1948 		break;
1949 	case 4:
1950 		inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1951 		break;
1952 	default:
1953 		return -EINVAL;
1954 	}
1955 
1956 	if (is_mmzero && !*ptr)
1957 		*ptr = CSUM_MANGLED_0;
1958 	return 0;
1959 }
1960 
1961 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1962 	.func		= bpf_l4_csum_replace,
1963 	.gpl_only	= false,
1964 	.ret_type	= RET_INTEGER,
1965 	.arg1_type	= ARG_PTR_TO_CTX,
1966 	.arg2_type	= ARG_ANYTHING,
1967 	.arg3_type	= ARG_ANYTHING,
1968 	.arg4_type	= ARG_ANYTHING,
1969 	.arg5_type	= ARG_ANYTHING,
1970 };
1971 
BPF_CALL_5(bpf_csum_diff,__be32 *,from,u32,from_size,__be32 *,to,u32,to_size,__wsum,seed)1972 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1973 	   __be32 *, to, u32, to_size, __wsum, seed)
1974 {
1975 	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1976 	u32 diff_size = from_size + to_size;
1977 	int i, j = 0;
1978 
1979 	/* This is quite flexible, some examples:
1980 	 *
1981 	 * from_size == 0, to_size > 0,  seed := csum --> pushing data
1982 	 * from_size > 0,  to_size == 0, seed := csum --> pulling data
1983 	 * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1984 	 *
1985 	 * Even for diffing, from_size and to_size don't need to be equal.
1986 	 */
1987 	if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1988 		     diff_size > sizeof(sp->diff)))
1989 		return -EINVAL;
1990 
1991 	for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1992 		sp->diff[j] = ~from[i];
1993 	for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1994 		sp->diff[j] = to[i];
1995 
1996 	return csum_partial(sp->diff, diff_size, seed);
1997 }
1998 
1999 static const struct bpf_func_proto bpf_csum_diff_proto = {
2000 	.func		= bpf_csum_diff,
2001 	.gpl_only	= false,
2002 	.pkt_access	= true,
2003 	.ret_type	= RET_INTEGER,
2004 	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL,
2005 	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
2006 	.arg3_type	= ARG_PTR_TO_MEM_OR_NULL,
2007 	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
2008 	.arg5_type	= ARG_ANYTHING,
2009 };
2010 
BPF_CALL_2(bpf_csum_update,struct sk_buff *,skb,__wsum,csum)2011 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
2012 {
2013 	/* The interface is to be used in combination with bpf_csum_diff()
2014 	 * for direct packet writes. csum rotation for alignment as well
2015 	 * as emulating csum_sub() can be done from the eBPF program.
2016 	 */
2017 	if (skb->ip_summed == CHECKSUM_COMPLETE)
2018 		return (skb->csum = csum_add(skb->csum, csum));
2019 
2020 	return -ENOTSUPP;
2021 }
2022 
2023 static const struct bpf_func_proto bpf_csum_update_proto = {
2024 	.func		= bpf_csum_update,
2025 	.gpl_only	= false,
2026 	.ret_type	= RET_INTEGER,
2027 	.arg1_type	= ARG_PTR_TO_CTX,
2028 	.arg2_type	= ARG_ANYTHING,
2029 };
2030 
__bpf_rx_skb(struct net_device * dev,struct sk_buff * skb)2031 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2032 {
2033 	return dev_forward_skb(dev, skb);
2034 }
2035 
__bpf_rx_skb_no_mac(struct net_device * dev,struct sk_buff * skb)2036 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2037 				      struct sk_buff *skb)
2038 {
2039 	int ret = ____dev_forward_skb(dev, skb);
2040 
2041 	if (likely(!ret)) {
2042 		skb->dev = dev;
2043 		ret = netif_rx(skb);
2044 	}
2045 
2046 	return ret;
2047 }
2048 
__bpf_tx_skb(struct net_device * dev,struct sk_buff * skb)2049 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2050 {
2051 	int ret;
2052 
2053 	if (dev_xmit_recursion()) {
2054 		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2055 		kfree_skb(skb);
2056 		return -ENETDOWN;
2057 	}
2058 
2059 	skb->dev = dev;
2060 	skb->tstamp = 0;
2061 
2062 	dev_xmit_recursion_inc();
2063 	ret = dev_queue_xmit(skb);
2064 	dev_xmit_recursion_dec();
2065 
2066 	return ret;
2067 }
2068 
__bpf_redirect_no_mac(struct sk_buff * skb,struct net_device * dev,u32 flags)2069 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2070 				 u32 flags)
2071 {
2072 	unsigned int mlen = skb_network_offset(skb);
2073 
2074 	if (unlikely(skb->len <= mlen)) {
2075 		kfree_skb(skb);
2076 		return -ERANGE;
2077 	}
2078 
2079 	if (mlen) {
2080 		__skb_pull(skb, mlen);
2081 		if (unlikely(!skb->len)) {
2082 			kfree_skb(skb);
2083 			return -ERANGE;
2084 		}
2085 
2086 		/* At ingress, the mac header has already been pulled once.
2087 		 * At egress, skb_pospull_rcsum has to be done in case that
2088 		 * the skb is originated from ingress (i.e. a forwarded skb)
2089 		 * to ensure that rcsum starts at net header.
2090 		 */
2091 		if (!skb_at_tc_ingress(skb))
2092 			skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2093 	}
2094 	skb_pop_mac_header(skb);
2095 	skb_reset_mac_len(skb);
2096 	return flags & BPF_F_INGRESS ?
2097 	       __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2098 }
2099 
__bpf_redirect_common(struct sk_buff * skb,struct net_device * dev,u32 flags)2100 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2101 				 u32 flags)
2102 {
2103 	/* Verify that a link layer header is carried */
2104 	if (unlikely(skb->mac_header >= skb->network_header || skb->len == 0)) {
2105 		kfree_skb(skb);
2106 		return -ERANGE;
2107 	}
2108 
2109 	bpf_push_mac_rcsum(skb);
2110 	return flags & BPF_F_INGRESS ?
2111 	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2112 }
2113 
__bpf_redirect(struct sk_buff * skb,struct net_device * dev,u32 flags)2114 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2115 			  u32 flags)
2116 {
2117 	if (dev_is_mac_header_xmit(dev))
2118 		return __bpf_redirect_common(skb, dev, flags);
2119 	else
2120 		return __bpf_redirect_no_mac(skb, dev, flags);
2121 }
2122 
BPF_CALL_3(bpf_clone_redirect,struct sk_buff *,skb,u32,ifindex,u64,flags)2123 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2124 {
2125 	struct net_device *dev;
2126 	struct sk_buff *clone;
2127 	int ret;
2128 
2129 	if (unlikely(flags & ~(BPF_F_INGRESS)))
2130 		return -EINVAL;
2131 
2132 	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2133 	if (unlikely(!dev))
2134 		return -EINVAL;
2135 
2136 	clone = skb_clone(skb, GFP_ATOMIC);
2137 	if (unlikely(!clone))
2138 		return -ENOMEM;
2139 
2140 	/* For direct write, we need to keep the invariant that the skbs
2141 	 * we're dealing with need to be uncloned. Should uncloning fail
2142 	 * here, we need to free the just generated clone to unclone once
2143 	 * again.
2144 	 */
2145 	ret = bpf_try_make_head_writable(skb);
2146 	if (unlikely(ret)) {
2147 		kfree_skb(clone);
2148 		return -ENOMEM;
2149 	}
2150 
2151 	return __bpf_redirect(clone, dev, flags);
2152 }
2153 
2154 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2155 	.func           = bpf_clone_redirect,
2156 	.gpl_only       = false,
2157 	.ret_type       = RET_INTEGER,
2158 	.arg1_type      = ARG_PTR_TO_CTX,
2159 	.arg2_type      = ARG_ANYTHING,
2160 	.arg3_type      = ARG_ANYTHING,
2161 };
2162 
2163 DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2164 EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2165 
BPF_CALL_2(bpf_redirect,u32,ifindex,u64,flags)2166 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2167 {
2168 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2169 
2170 	if (unlikely(flags & ~(BPF_F_INGRESS)))
2171 		return TC_ACT_SHOT;
2172 
2173 	ri->flags = flags;
2174 	ri->tgt_index = ifindex;
2175 
2176 	return TC_ACT_REDIRECT;
2177 }
2178 
skb_do_redirect(struct sk_buff * skb)2179 int skb_do_redirect(struct sk_buff *skb)
2180 {
2181 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2182 	struct net_device *dev;
2183 
2184 	dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->tgt_index);
2185 	ri->tgt_index = 0;
2186 	if (unlikely(!dev)) {
2187 		kfree_skb(skb);
2188 		return -EINVAL;
2189 	}
2190 
2191 	return __bpf_redirect(skb, dev, ri->flags);
2192 }
2193 
2194 static const struct bpf_func_proto bpf_redirect_proto = {
2195 	.func           = bpf_redirect,
2196 	.gpl_only       = false,
2197 	.ret_type       = RET_INTEGER,
2198 	.arg1_type      = ARG_ANYTHING,
2199 	.arg2_type      = ARG_ANYTHING,
2200 };
2201 
BPF_CALL_2(bpf_msg_apply_bytes,struct sk_msg *,msg,u32,bytes)2202 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2203 {
2204 	msg->apply_bytes = bytes;
2205 	return 0;
2206 }
2207 
2208 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2209 	.func           = bpf_msg_apply_bytes,
2210 	.gpl_only       = false,
2211 	.ret_type       = RET_INTEGER,
2212 	.arg1_type	= ARG_PTR_TO_CTX,
2213 	.arg2_type      = ARG_ANYTHING,
2214 };
2215 
BPF_CALL_2(bpf_msg_cork_bytes,struct sk_msg *,msg,u32,bytes)2216 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2217 {
2218 	msg->cork_bytes = bytes;
2219 	return 0;
2220 }
2221 
sk_msg_reset_curr(struct sk_msg * msg)2222 static void sk_msg_reset_curr(struct sk_msg *msg)
2223 {
2224 	u32 i = msg->sg.start;
2225 	u32 len = 0;
2226 
2227 	do {
2228 		len += sk_msg_elem(msg, i)->length;
2229 		sk_msg_iter_var_next(i);
2230 		if (len >= msg->sg.size)
2231 			break;
2232 	} while (i != msg->sg.end);
2233 
2234 	msg->sg.curr = i;
2235 	msg->sg.copybreak = 0;
2236 }
2237 
2238 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2239 	.func           = bpf_msg_cork_bytes,
2240 	.gpl_only       = false,
2241 	.ret_type       = RET_INTEGER,
2242 	.arg1_type	= ARG_PTR_TO_CTX,
2243 	.arg2_type      = ARG_ANYTHING,
2244 };
2245 
BPF_CALL_4(bpf_msg_pull_data,struct sk_msg *,msg,u32,start,u32,end,u64,flags)2246 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2247 	   u32, end, u64, flags)
2248 {
2249 	u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2250 	u32 first_sge, last_sge, i, shift, bytes_sg_total;
2251 	struct scatterlist *sge;
2252 	u8 *raw, *to, *from;
2253 	struct page *page;
2254 
2255 	if (unlikely(flags || end <= start))
2256 		return -EINVAL;
2257 
2258 	/* First find the starting scatterlist element */
2259 	i = msg->sg.start;
2260 	do {
2261 		offset += len;
2262 		len = sk_msg_elem(msg, i)->length;
2263 		if (start < offset + len)
2264 			break;
2265 		sk_msg_iter_var_next(i);
2266 	} while (i != msg->sg.end);
2267 
2268 	if (unlikely(start >= offset + len))
2269 		return -EINVAL;
2270 
2271 	first_sge = i;
2272 	/* The start may point into the sg element so we need to also
2273 	 * account for the headroom.
2274 	 */
2275 	bytes_sg_total = start - offset + bytes;
2276 	if (!msg->sg.copy[i] && bytes_sg_total <= len)
2277 		goto out;
2278 
2279 	/* At this point we need to linearize multiple scatterlist
2280 	 * elements or a single shared page. Either way we need to
2281 	 * copy into a linear buffer exclusively owned by BPF. Then
2282 	 * place the buffer in the scatterlist and fixup the original
2283 	 * entries by removing the entries now in the linear buffer
2284 	 * and shifting the remaining entries. For now we do not try
2285 	 * to copy partial entries to avoid complexity of running out
2286 	 * of sg_entry slots. The downside is reading a single byte
2287 	 * will copy the entire sg entry.
2288 	 */
2289 	do {
2290 		copy += sk_msg_elem(msg, i)->length;
2291 		sk_msg_iter_var_next(i);
2292 		if (bytes_sg_total <= copy)
2293 			break;
2294 	} while (i != msg->sg.end);
2295 	last_sge = i;
2296 
2297 	if (unlikely(bytes_sg_total > copy))
2298 		return -EINVAL;
2299 
2300 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2301 			   get_order(copy));
2302 	if (unlikely(!page))
2303 		return -ENOMEM;
2304 
2305 	raw = page_address(page);
2306 	i = first_sge;
2307 	do {
2308 		sge = sk_msg_elem(msg, i);
2309 		from = sg_virt(sge);
2310 		len = sge->length;
2311 		to = raw + poffset;
2312 
2313 		memcpy(to, from, len);
2314 		poffset += len;
2315 		sge->length = 0;
2316 		put_page(sg_page(sge));
2317 
2318 		sk_msg_iter_var_next(i);
2319 	} while (i != last_sge);
2320 
2321 	sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2322 
2323 	/* To repair sg ring we need to shift entries. If we only
2324 	 * had a single entry though we can just replace it and
2325 	 * be done. Otherwise walk the ring and shift the entries.
2326 	 */
2327 	WARN_ON_ONCE(last_sge == first_sge);
2328 	shift = last_sge > first_sge ?
2329 		last_sge - first_sge - 1 :
2330 		NR_MSG_FRAG_IDS - first_sge + last_sge - 1;
2331 	if (!shift)
2332 		goto out;
2333 
2334 	i = first_sge;
2335 	sk_msg_iter_var_next(i);
2336 	do {
2337 		u32 move_from;
2338 
2339 		if (i + shift >= NR_MSG_FRAG_IDS)
2340 			move_from = i + shift - NR_MSG_FRAG_IDS;
2341 		else
2342 			move_from = i + shift;
2343 		if (move_from == msg->sg.end)
2344 			break;
2345 
2346 		msg->sg.data[i] = msg->sg.data[move_from];
2347 		msg->sg.data[move_from].length = 0;
2348 		msg->sg.data[move_from].page_link = 0;
2349 		msg->sg.data[move_from].offset = 0;
2350 		sk_msg_iter_var_next(i);
2351 	} while (1);
2352 
2353 	msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2354 		      msg->sg.end - shift + NR_MSG_FRAG_IDS :
2355 		      msg->sg.end - shift;
2356 out:
2357 	sk_msg_reset_curr(msg);
2358 	msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2359 	msg->data_end = msg->data + bytes;
2360 	return 0;
2361 }
2362 
2363 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2364 	.func		= bpf_msg_pull_data,
2365 	.gpl_only	= false,
2366 	.ret_type	= RET_INTEGER,
2367 	.arg1_type	= ARG_PTR_TO_CTX,
2368 	.arg2_type	= ARG_ANYTHING,
2369 	.arg3_type	= ARG_ANYTHING,
2370 	.arg4_type	= ARG_ANYTHING,
2371 };
2372 
BPF_CALL_4(bpf_msg_push_data,struct sk_msg *,msg,u32,start,u32,len,u64,flags)2373 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2374 	   u32, len, u64, flags)
2375 {
2376 	struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2377 	u32 new, i = 0, l = 0, space, copy = 0, offset = 0;
2378 	u8 *raw, *to, *from;
2379 	struct page *page;
2380 
2381 	if (unlikely(flags))
2382 		return -EINVAL;
2383 
2384 	/* First find the starting scatterlist element */
2385 	i = msg->sg.start;
2386 	do {
2387 		offset += l;
2388 		l = sk_msg_elem(msg, i)->length;
2389 
2390 		if (start < offset + l)
2391 			break;
2392 		sk_msg_iter_var_next(i);
2393 	} while (i != msg->sg.end);
2394 
2395 	if (start >= offset + l)
2396 		return -EINVAL;
2397 
2398 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2399 
2400 	/* If no space available will fallback to copy, we need at
2401 	 * least one scatterlist elem available to push data into
2402 	 * when start aligns to the beginning of an element or two
2403 	 * when it falls inside an element. We handle the start equals
2404 	 * offset case because its the common case for inserting a
2405 	 * header.
2406 	 */
2407 	if (!space || (space == 1 && start != offset))
2408 		copy = msg->sg.data[i].length;
2409 
2410 	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2411 			   get_order(copy + len));
2412 	if (unlikely(!page))
2413 		return -ENOMEM;
2414 
2415 	if (copy) {
2416 		int front, back;
2417 
2418 		raw = page_address(page);
2419 
2420 		psge = sk_msg_elem(msg, i);
2421 		front = start - offset;
2422 		back = psge->length - front;
2423 		from = sg_virt(psge);
2424 
2425 		if (front)
2426 			memcpy(raw, from, front);
2427 
2428 		if (back) {
2429 			from += front;
2430 			to = raw + front + len;
2431 
2432 			memcpy(to, from, back);
2433 		}
2434 
2435 		put_page(sg_page(psge));
2436 	} else if (start - offset) {
2437 		psge = sk_msg_elem(msg, i);
2438 		rsge = sk_msg_elem_cpy(msg, i);
2439 
2440 		psge->length = start - offset;
2441 		rsge.length -= psge->length;
2442 		rsge.offset += start;
2443 
2444 		sk_msg_iter_var_next(i);
2445 		sg_unmark_end(psge);
2446 		sg_unmark_end(&rsge);
2447 		sk_msg_iter_next(msg, end);
2448 	}
2449 
2450 	/* Slot(s) to place newly allocated data */
2451 	new = i;
2452 
2453 	/* Shift one or two slots as needed */
2454 	if (!copy) {
2455 		sge = sk_msg_elem_cpy(msg, i);
2456 
2457 		sk_msg_iter_var_next(i);
2458 		sg_unmark_end(&sge);
2459 		sk_msg_iter_next(msg, end);
2460 
2461 		nsge = sk_msg_elem_cpy(msg, i);
2462 		if (rsge.length) {
2463 			sk_msg_iter_var_next(i);
2464 			nnsge = sk_msg_elem_cpy(msg, i);
2465 		}
2466 
2467 		while (i != msg->sg.end) {
2468 			msg->sg.data[i] = sge;
2469 			sge = nsge;
2470 			sk_msg_iter_var_next(i);
2471 			if (rsge.length) {
2472 				nsge = nnsge;
2473 				nnsge = sk_msg_elem_cpy(msg, i);
2474 			} else {
2475 				nsge = sk_msg_elem_cpy(msg, i);
2476 			}
2477 		}
2478 	}
2479 
2480 	/* Place newly allocated data buffer */
2481 	sk_mem_charge(msg->sk, len);
2482 	msg->sg.size += len;
2483 	msg->sg.copy[new] = false;
2484 	sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2485 	if (rsge.length) {
2486 		get_page(sg_page(&rsge));
2487 		sk_msg_iter_var_next(new);
2488 		msg->sg.data[new] = rsge;
2489 	}
2490 
2491 	sk_msg_reset_curr(msg);
2492 	sk_msg_compute_data_pointers(msg);
2493 	return 0;
2494 }
2495 
2496 static const struct bpf_func_proto bpf_msg_push_data_proto = {
2497 	.func		= bpf_msg_push_data,
2498 	.gpl_only	= false,
2499 	.ret_type	= RET_INTEGER,
2500 	.arg1_type	= ARG_PTR_TO_CTX,
2501 	.arg2_type	= ARG_ANYTHING,
2502 	.arg3_type	= ARG_ANYTHING,
2503 	.arg4_type	= ARG_ANYTHING,
2504 };
2505 
sk_msg_shift_left(struct sk_msg * msg,int i)2506 static void sk_msg_shift_left(struct sk_msg *msg, int i)
2507 {
2508 	int prev;
2509 
2510 	do {
2511 		prev = i;
2512 		sk_msg_iter_var_next(i);
2513 		msg->sg.data[prev] = msg->sg.data[i];
2514 	} while (i != msg->sg.end);
2515 
2516 	sk_msg_iter_prev(msg, end);
2517 }
2518 
sk_msg_shift_right(struct sk_msg * msg,int i)2519 static void sk_msg_shift_right(struct sk_msg *msg, int i)
2520 {
2521 	struct scatterlist tmp, sge;
2522 
2523 	sk_msg_iter_next(msg, end);
2524 	sge = sk_msg_elem_cpy(msg, i);
2525 	sk_msg_iter_var_next(i);
2526 	tmp = sk_msg_elem_cpy(msg, i);
2527 
2528 	while (i != msg->sg.end) {
2529 		msg->sg.data[i] = sge;
2530 		sk_msg_iter_var_next(i);
2531 		sge = tmp;
2532 		tmp = sk_msg_elem_cpy(msg, i);
2533 	}
2534 }
2535 
BPF_CALL_4(bpf_msg_pop_data,struct sk_msg *,msg,u32,start,u32,len,u64,flags)2536 BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
2537 	   u32, len, u64, flags)
2538 {
2539 	u32 i = 0, l = 0, space, offset = 0;
2540 	u64 last = start + len;
2541 	int pop;
2542 
2543 	if (unlikely(flags))
2544 		return -EINVAL;
2545 
2546 	if (unlikely(len == 0))
2547 		return 0;
2548 
2549 	/* First find the starting scatterlist element */
2550 	i = msg->sg.start;
2551 	do {
2552 		offset += l;
2553 		l = sk_msg_elem(msg, i)->length;
2554 
2555 		if (start < offset + l)
2556 			break;
2557 		sk_msg_iter_var_next(i);
2558 	} while (i != msg->sg.end);
2559 
2560 	/* Bounds checks: start and pop must be inside message */
2561 	if (start >= offset + l || last >= msg->sg.size)
2562 		return -EINVAL;
2563 
2564 	space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2565 
2566 	pop = len;
2567 	/* --------------| offset
2568 	 * -| start      |-------- len -------|
2569 	 *
2570 	 *  |----- a ----|-------- pop -------|----- b ----|
2571 	 *  |______________________________________________| length
2572 	 *
2573 	 *
2574 	 * a:   region at front of scatter element to save
2575 	 * b:   region at back of scatter element to save when length > A + pop
2576 	 * pop: region to pop from element, same as input 'pop' here will be
2577 	 *      decremented below per iteration.
2578 	 *
2579 	 * Two top-level cases to handle when start != offset, first B is non
2580 	 * zero and second B is zero corresponding to when a pop includes more
2581 	 * than one element.
2582 	 *
2583 	 * Then if B is non-zero AND there is no space allocate space and
2584 	 * compact A, B regions into page. If there is space shift ring to
2585 	 * the rigth free'ing the next element in ring to place B, leaving
2586 	 * A untouched except to reduce length.
2587 	 */
2588 	if (start != offset) {
2589 		struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
2590 		int a = start;
2591 		int b = sge->length - pop - a;
2592 
2593 		sk_msg_iter_var_next(i);
2594 
2595 		if (pop < sge->length - a) {
2596 			if (space) {
2597 				sge->length = a;
2598 				sk_msg_shift_right(msg, i);
2599 				nsge = sk_msg_elem(msg, i);
2600 				get_page(sg_page(sge));
2601 				sg_set_page(nsge,
2602 					    sg_page(sge),
2603 					    b, sge->offset + pop + a);
2604 			} else {
2605 				struct page *page, *orig;
2606 				u8 *to, *from;
2607 
2608 				page = alloc_pages(__GFP_NOWARN |
2609 						   __GFP_COMP   | GFP_ATOMIC,
2610 						   get_order(a + b));
2611 				if (unlikely(!page))
2612 					return -ENOMEM;
2613 
2614 				sge->length = a;
2615 				orig = sg_page(sge);
2616 				from = sg_virt(sge);
2617 				to = page_address(page);
2618 				memcpy(to, from, a);
2619 				memcpy(to + a, from + a + pop, b);
2620 				sg_set_page(sge, page, a + b, 0);
2621 				put_page(orig);
2622 			}
2623 			pop = 0;
2624 		} else if (pop >= sge->length - a) {
2625 			pop -= (sge->length - a);
2626 			sge->length = a;
2627 		}
2628 	}
2629 
2630 	/* From above the current layout _must_ be as follows,
2631 	 *
2632 	 * -| offset
2633 	 * -| start
2634 	 *
2635 	 *  |---- pop ---|---------------- b ------------|
2636 	 *  |____________________________________________| length
2637 	 *
2638 	 * Offset and start of the current msg elem are equal because in the
2639 	 * previous case we handled offset != start and either consumed the
2640 	 * entire element and advanced to the next element OR pop == 0.
2641 	 *
2642 	 * Two cases to handle here are first pop is less than the length
2643 	 * leaving some remainder b above. Simply adjust the element's layout
2644 	 * in this case. Or pop >= length of the element so that b = 0. In this
2645 	 * case advance to next element decrementing pop.
2646 	 */
2647 	while (pop) {
2648 		struct scatterlist *sge = sk_msg_elem(msg, i);
2649 
2650 		if (pop < sge->length) {
2651 			sge->length -= pop;
2652 			sge->offset += pop;
2653 			pop = 0;
2654 		} else {
2655 			pop -= sge->length;
2656 			sk_msg_shift_left(msg, i);
2657 		}
2658 		sk_msg_iter_var_next(i);
2659 	}
2660 
2661 	sk_mem_uncharge(msg->sk, len - pop);
2662 	msg->sg.size -= (len - pop);
2663 	sk_msg_reset_curr(msg);
2664 	sk_msg_compute_data_pointers(msg);
2665 	return 0;
2666 }
2667 
2668 static const struct bpf_func_proto bpf_msg_pop_data_proto = {
2669 	.func		= bpf_msg_pop_data,
2670 	.gpl_only	= false,
2671 	.ret_type	= RET_INTEGER,
2672 	.arg1_type	= ARG_PTR_TO_CTX,
2673 	.arg2_type	= ARG_ANYTHING,
2674 	.arg3_type	= ARG_ANYTHING,
2675 	.arg4_type	= ARG_ANYTHING,
2676 };
2677 
BPF_CALL_1(bpf_get_cgroup_classid,const struct sk_buff *,skb)2678 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2679 {
2680 	return task_get_classid(skb);
2681 }
2682 
2683 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
2684 	.func           = bpf_get_cgroup_classid,
2685 	.gpl_only       = false,
2686 	.ret_type       = RET_INTEGER,
2687 	.arg1_type      = ARG_PTR_TO_CTX,
2688 };
2689 
BPF_CALL_1(bpf_get_route_realm,const struct sk_buff *,skb)2690 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2691 {
2692 	return dst_tclassid(skb);
2693 }
2694 
2695 static const struct bpf_func_proto bpf_get_route_realm_proto = {
2696 	.func           = bpf_get_route_realm,
2697 	.gpl_only       = false,
2698 	.ret_type       = RET_INTEGER,
2699 	.arg1_type      = ARG_PTR_TO_CTX,
2700 };
2701 
BPF_CALL_1(bpf_get_hash_recalc,struct sk_buff *,skb)2702 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2703 {
2704 	/* If skb_clear_hash() was called due to mangling, we can
2705 	 * trigger SW recalculation here. Later access to hash
2706 	 * can then use the inline skb->hash via context directly
2707 	 * instead of calling this helper again.
2708 	 */
2709 	return skb_get_hash(skb);
2710 }
2711 
2712 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
2713 	.func		= bpf_get_hash_recalc,
2714 	.gpl_only	= false,
2715 	.ret_type	= RET_INTEGER,
2716 	.arg1_type	= ARG_PTR_TO_CTX,
2717 };
2718 
BPF_CALL_1(bpf_set_hash_invalid,struct sk_buff *,skb)2719 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
2720 {
2721 	/* After all direct packet write, this can be used once for
2722 	 * triggering a lazy recalc on next skb_get_hash() invocation.
2723 	 */
2724 	skb_clear_hash(skb);
2725 	return 0;
2726 }
2727 
2728 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
2729 	.func		= bpf_set_hash_invalid,
2730 	.gpl_only	= false,
2731 	.ret_type	= RET_INTEGER,
2732 	.arg1_type	= ARG_PTR_TO_CTX,
2733 };
2734 
BPF_CALL_2(bpf_set_hash,struct sk_buff *,skb,u32,hash)2735 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
2736 {
2737 	/* Set user specified hash as L4(+), so that it gets returned
2738 	 * on skb_get_hash() call unless BPF prog later on triggers a
2739 	 * skb_clear_hash().
2740 	 */
2741 	__skb_set_sw_hash(skb, hash, true);
2742 	return 0;
2743 }
2744 
2745 static const struct bpf_func_proto bpf_set_hash_proto = {
2746 	.func		= bpf_set_hash,
2747 	.gpl_only	= false,
2748 	.ret_type	= RET_INTEGER,
2749 	.arg1_type	= ARG_PTR_TO_CTX,
2750 	.arg2_type	= ARG_ANYTHING,
2751 };
2752 
BPF_CALL_3(bpf_skb_vlan_push,struct sk_buff *,skb,__be16,vlan_proto,u16,vlan_tci)2753 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
2754 	   u16, vlan_tci)
2755 {
2756 	int ret;
2757 
2758 	if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
2759 		     vlan_proto != htons(ETH_P_8021AD)))
2760 		vlan_proto = htons(ETH_P_8021Q);
2761 
2762 	bpf_push_mac_rcsum(skb);
2763 	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2764 	bpf_pull_mac_rcsum(skb);
2765 
2766 	bpf_compute_data_pointers(skb);
2767 	return ret;
2768 }
2769 
2770 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2771 	.func           = bpf_skb_vlan_push,
2772 	.gpl_only       = false,
2773 	.ret_type       = RET_INTEGER,
2774 	.arg1_type      = ARG_PTR_TO_CTX,
2775 	.arg2_type      = ARG_ANYTHING,
2776 	.arg3_type      = ARG_ANYTHING,
2777 };
2778 
BPF_CALL_1(bpf_skb_vlan_pop,struct sk_buff *,skb)2779 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2780 {
2781 	int ret;
2782 
2783 	bpf_push_mac_rcsum(skb);
2784 	ret = skb_vlan_pop(skb);
2785 	bpf_pull_mac_rcsum(skb);
2786 
2787 	bpf_compute_data_pointers(skb);
2788 	return ret;
2789 }
2790 
2791 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2792 	.func           = bpf_skb_vlan_pop,
2793 	.gpl_only       = false,
2794 	.ret_type       = RET_INTEGER,
2795 	.arg1_type      = ARG_PTR_TO_CTX,
2796 };
2797 
bpf_skb_generic_push(struct sk_buff * skb,u32 off,u32 len)2798 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
2799 {
2800 	/* Caller already did skb_cow() with len as headroom,
2801 	 * so no need to do it here.
2802 	 */
2803 	skb_push(skb, len);
2804 	memmove(skb->data, skb->data + len, off);
2805 	memset(skb->data + off, 0, len);
2806 
2807 	/* No skb_postpush_rcsum(skb, skb->data + off, len)
2808 	 * needed here as it does not change the skb->csum
2809 	 * result for checksum complete when summing over
2810 	 * zeroed blocks.
2811 	 */
2812 	return 0;
2813 }
2814 
bpf_skb_generic_pop(struct sk_buff * skb,u32 off,u32 len)2815 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2816 {
2817 	void *old_data;
2818 
2819 	/* skb_ensure_writable() is not needed here, as we're
2820 	 * already working on an uncloned skb.
2821 	 */
2822 	if (unlikely(!pskb_may_pull(skb, off + len)))
2823 		return -ENOMEM;
2824 
2825 	old_data = skb->data;
2826 	__skb_pull(skb, len);
2827 	skb_postpull_rcsum(skb, old_data + off, len);
2828 	memmove(skb->data, old_data, off);
2829 
2830 	return 0;
2831 }
2832 
bpf_skb_net_hdr_push(struct sk_buff * skb,u32 off,u32 len)2833 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2834 {
2835 	bool trans_same = skb->transport_header == skb->network_header;
2836 	int ret;
2837 
2838 	/* There's no need for __skb_push()/__skb_pull() pair to
2839 	 * get to the start of the mac header as we're guaranteed
2840 	 * to always start from here under eBPF.
2841 	 */
2842 	ret = bpf_skb_generic_push(skb, off, len);
2843 	if (likely(!ret)) {
2844 		skb->mac_header -= len;
2845 		skb->network_header -= len;
2846 		if (trans_same)
2847 			skb->transport_header = skb->network_header;
2848 	}
2849 
2850 	return ret;
2851 }
2852 
bpf_skb_net_hdr_pop(struct sk_buff * skb,u32 off,u32 len)2853 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2854 {
2855 	bool trans_same = skb->transport_header == skb->network_header;
2856 	int ret;
2857 
2858 	/* Same here, __skb_push()/__skb_pull() pair not needed. */
2859 	ret = bpf_skb_generic_pop(skb, off, len);
2860 	if (likely(!ret)) {
2861 		skb->mac_header += len;
2862 		skb->network_header += len;
2863 		if (trans_same)
2864 			skb->transport_header = skb->network_header;
2865 	}
2866 
2867 	return ret;
2868 }
2869 
bpf_skb_proto_4_to_6(struct sk_buff * skb)2870 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2871 {
2872 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2873 	u32 off = skb_mac_header_len(skb);
2874 	int ret;
2875 
2876 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2877 		return -ENOTSUPP;
2878 
2879 	ret = skb_cow(skb, len_diff);
2880 	if (unlikely(ret < 0))
2881 		return ret;
2882 
2883 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2884 	if (unlikely(ret < 0))
2885 		return ret;
2886 
2887 	if (skb_is_gso(skb)) {
2888 		struct skb_shared_info *shinfo = skb_shinfo(skb);
2889 
2890 		/* SKB_GSO_TCPV4 needs to be changed into
2891 		 * SKB_GSO_TCPV6.
2892 		 */
2893 		if (shinfo->gso_type & SKB_GSO_TCPV4) {
2894 			shinfo->gso_type &= ~SKB_GSO_TCPV4;
2895 			shinfo->gso_type |=  SKB_GSO_TCPV6;
2896 		}
2897 
2898 		/* Header must be checked, and gso_segs recomputed. */
2899 		shinfo->gso_type |= SKB_GSO_DODGY;
2900 		shinfo->gso_segs = 0;
2901 	}
2902 
2903 	skb->protocol = htons(ETH_P_IPV6);
2904 	skb_clear_hash(skb);
2905 
2906 	return 0;
2907 }
2908 
bpf_skb_proto_6_to_4(struct sk_buff * skb)2909 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2910 {
2911 	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2912 	u32 off = skb_mac_header_len(skb);
2913 	int ret;
2914 
2915 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2916 		return -ENOTSUPP;
2917 
2918 	ret = skb_unclone(skb, GFP_ATOMIC);
2919 	if (unlikely(ret < 0))
2920 		return ret;
2921 
2922 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2923 	if (unlikely(ret < 0))
2924 		return ret;
2925 
2926 	if (skb_is_gso(skb)) {
2927 		struct skb_shared_info *shinfo = skb_shinfo(skb);
2928 
2929 		/* SKB_GSO_TCPV6 needs to be changed into
2930 		 * SKB_GSO_TCPV4.
2931 		 */
2932 		if (shinfo->gso_type & SKB_GSO_TCPV6) {
2933 			shinfo->gso_type &= ~SKB_GSO_TCPV6;
2934 			shinfo->gso_type |=  SKB_GSO_TCPV4;
2935 		}
2936 
2937 		/* Header must be checked, and gso_segs recomputed. */
2938 		shinfo->gso_type |= SKB_GSO_DODGY;
2939 		shinfo->gso_segs = 0;
2940 	}
2941 
2942 	skb->protocol = htons(ETH_P_IP);
2943 	skb_clear_hash(skb);
2944 
2945 	return 0;
2946 }
2947 
bpf_skb_proto_xlat(struct sk_buff * skb,__be16 to_proto)2948 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2949 {
2950 	__be16 from_proto = skb->protocol;
2951 
2952 	if (from_proto == htons(ETH_P_IP) &&
2953 	      to_proto == htons(ETH_P_IPV6))
2954 		return bpf_skb_proto_4_to_6(skb);
2955 
2956 	if (from_proto == htons(ETH_P_IPV6) &&
2957 	      to_proto == htons(ETH_P_IP))
2958 		return bpf_skb_proto_6_to_4(skb);
2959 
2960 	return -ENOTSUPP;
2961 }
2962 
BPF_CALL_3(bpf_skb_change_proto,struct sk_buff *,skb,__be16,proto,u64,flags)2963 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2964 	   u64, flags)
2965 {
2966 	int ret;
2967 
2968 	if (unlikely(flags))
2969 		return -EINVAL;
2970 
2971 	/* General idea is that this helper does the basic groundwork
2972 	 * needed for changing the protocol, and eBPF program fills the
2973 	 * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2974 	 * and other helpers, rather than passing a raw buffer here.
2975 	 *
2976 	 * The rationale is to keep this minimal and without a need to
2977 	 * deal with raw packet data. F.e. even if we would pass buffers
2978 	 * here, the program still needs to call the bpf_lX_csum_replace()
2979 	 * helpers anyway. Plus, this way we keep also separation of
2980 	 * concerns, since f.e. bpf_skb_store_bytes() should only take
2981 	 * care of stores.
2982 	 *
2983 	 * Currently, additional options and extension header space are
2984 	 * not supported, but flags register is reserved so we can adapt
2985 	 * that. For offloads, we mark packet as dodgy, so that headers
2986 	 * need to be verified first.
2987 	 */
2988 	ret = bpf_skb_proto_xlat(skb, proto);
2989 	bpf_compute_data_pointers(skb);
2990 	return ret;
2991 }
2992 
2993 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2994 	.func		= bpf_skb_change_proto,
2995 	.gpl_only	= false,
2996 	.ret_type	= RET_INTEGER,
2997 	.arg1_type	= ARG_PTR_TO_CTX,
2998 	.arg2_type	= ARG_ANYTHING,
2999 	.arg3_type	= ARG_ANYTHING,
3000 };
3001 
BPF_CALL_2(bpf_skb_change_type,struct sk_buff *,skb,u32,pkt_type)3002 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
3003 {
3004 	/* We only allow a restricted subset to be changed for now. */
3005 	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
3006 		     !skb_pkt_type_ok(pkt_type)))
3007 		return -EINVAL;
3008 
3009 	skb->pkt_type = pkt_type;
3010 	return 0;
3011 }
3012 
3013 static const struct bpf_func_proto bpf_skb_change_type_proto = {
3014 	.func		= bpf_skb_change_type,
3015 	.gpl_only	= false,
3016 	.ret_type	= RET_INTEGER,
3017 	.arg1_type	= ARG_PTR_TO_CTX,
3018 	.arg2_type	= ARG_ANYTHING,
3019 };
3020 
bpf_skb_net_base_len(const struct sk_buff * skb)3021 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
3022 {
3023 	switch (skb->protocol) {
3024 	case htons(ETH_P_IP):
3025 		return sizeof(struct iphdr);
3026 	case htons(ETH_P_IPV6):
3027 		return sizeof(struct ipv6hdr);
3028 	default:
3029 		return ~0U;
3030 	}
3031 }
3032 
3033 #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK	(BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3034 					 BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3035 
3036 #define BPF_F_ADJ_ROOM_MASK		(BPF_F_ADJ_ROOM_FIXED_GSO | \
3037 					 BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3038 					 BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3039 					 BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3040 					 BPF_F_ADJ_ROOM_ENCAP_L2( \
3041 					  BPF_ADJ_ROOM_ENCAP_L2_MASK))
3042 
bpf_skb_net_grow(struct sk_buff * skb,u32 off,u32 len_diff,u64 flags)3043 static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3044 			    u64 flags)
3045 {
3046 	u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3047 	bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3048 	u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3049 	unsigned int gso_type = SKB_GSO_DODGY;
3050 	int ret;
3051 
3052 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3053 		/* udp gso_size delineates datagrams, only allow if fixed */
3054 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3055 		    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3056 			return -ENOTSUPP;
3057 	}
3058 
3059 	ret = skb_cow_head(skb, len_diff);
3060 	if (unlikely(ret < 0))
3061 		return ret;
3062 
3063 	if (encap) {
3064 		if (skb->protocol != htons(ETH_P_IP) &&
3065 		    skb->protocol != htons(ETH_P_IPV6))
3066 			return -ENOTSUPP;
3067 
3068 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3069 		    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3070 			return -EINVAL;
3071 
3072 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3073 		    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3074 			return -EINVAL;
3075 
3076 		if (skb->encapsulation)
3077 			return -EALREADY;
3078 
3079 		mac_len = skb->network_header - skb->mac_header;
3080 		inner_net = skb->network_header;
3081 		if (inner_mac_len > len_diff)
3082 			return -EINVAL;
3083 		inner_trans = skb->transport_header;
3084 	}
3085 
3086 	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3087 	if (unlikely(ret < 0))
3088 		return ret;
3089 
3090 	if (encap) {
3091 		skb->inner_mac_header = inner_net - inner_mac_len;
3092 		skb->inner_network_header = inner_net;
3093 		skb->inner_transport_header = inner_trans;
3094 		skb_set_inner_protocol(skb, skb->protocol);
3095 
3096 		skb->encapsulation = 1;
3097 		skb_set_network_header(skb, mac_len);
3098 
3099 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3100 			gso_type |= SKB_GSO_UDP_TUNNEL;
3101 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3102 			gso_type |= SKB_GSO_GRE;
3103 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3104 			gso_type |= SKB_GSO_IPXIP6;
3105 		else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3106 			gso_type |= SKB_GSO_IPXIP4;
3107 
3108 		if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3109 		    flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3110 			int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3111 					sizeof(struct ipv6hdr) :
3112 					sizeof(struct iphdr);
3113 
3114 			skb_set_transport_header(skb, mac_len + nh_len);
3115 		}
3116 
3117 		/* Match skb->protocol to new outer l3 protocol */
3118 		if (skb->protocol == htons(ETH_P_IP) &&
3119 		    flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3120 			skb->protocol = htons(ETH_P_IPV6);
3121 		else if (skb->protocol == htons(ETH_P_IPV6) &&
3122 			 flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3123 			skb->protocol = htons(ETH_P_IP);
3124 	}
3125 
3126 	if (skb_is_gso(skb)) {
3127 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3128 
3129 		/* Due to header grow, MSS needs to be downgraded. */
3130 		if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3131 			skb_decrease_gso_size(shinfo, len_diff);
3132 
3133 		/* Header must be checked, and gso_segs recomputed. */
3134 		shinfo->gso_type |= gso_type;
3135 		shinfo->gso_segs = 0;
3136 	}
3137 
3138 	return 0;
3139 }
3140 
bpf_skb_net_shrink(struct sk_buff * skb,u32 off,u32 len_diff,u64 flags)3141 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3142 			      u64 flags)
3143 {
3144 	int ret;
3145 
3146 	if (flags & ~BPF_F_ADJ_ROOM_FIXED_GSO)
3147 		return -EINVAL;
3148 
3149 	if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3150 		/* udp gso_size delineates datagrams, only allow if fixed */
3151 		if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3152 		    !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3153 			return -ENOTSUPP;
3154 	}
3155 
3156 	ret = skb_unclone(skb, GFP_ATOMIC);
3157 	if (unlikely(ret < 0))
3158 		return ret;
3159 
3160 	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3161 	if (unlikely(ret < 0))
3162 		return ret;
3163 
3164 	if (skb_is_gso(skb)) {
3165 		struct skb_shared_info *shinfo = skb_shinfo(skb);
3166 
3167 		/* Due to header shrink, MSS can be upgraded. */
3168 		if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3169 			skb_increase_gso_size(shinfo, len_diff);
3170 
3171 		/* Header must be checked, and gso_segs recomputed. */
3172 		shinfo->gso_type |= SKB_GSO_DODGY;
3173 		shinfo->gso_segs = 0;
3174 	}
3175 
3176 	return 0;
3177 }
3178 
3179 #define BPF_SKB_MAX_LEN SKB_MAX_ALLOC
3180 
BPF_CALL_4(bpf_skb_adjust_room,struct sk_buff *,skb,s32,len_diff,u32,mode,u64,flags)3181 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3182 	   u32, mode, u64, flags)
3183 {
3184 	u32 len_cur, len_diff_abs = abs(len_diff);
3185 	u32 len_min = bpf_skb_net_base_len(skb);
3186 	u32 len_max = BPF_SKB_MAX_LEN;
3187 	__be16 proto = skb->protocol;
3188 	bool shrink = len_diff < 0;
3189 	u32 off;
3190 	int ret;
3191 
3192 	if (unlikely(flags & ~BPF_F_ADJ_ROOM_MASK))
3193 		return -EINVAL;
3194 	if (unlikely(len_diff_abs > 0xfffU))
3195 		return -EFAULT;
3196 	if (unlikely(proto != htons(ETH_P_IP) &&
3197 		     proto != htons(ETH_P_IPV6)))
3198 		return -ENOTSUPP;
3199 
3200 	off = skb_mac_header_len(skb);
3201 	switch (mode) {
3202 	case BPF_ADJ_ROOM_NET:
3203 		off += bpf_skb_net_base_len(skb);
3204 		break;
3205 	case BPF_ADJ_ROOM_MAC:
3206 		break;
3207 	default:
3208 		return -ENOTSUPP;
3209 	}
3210 
3211 	len_cur = skb->len - skb_network_offset(skb);
3212 	if ((shrink && (len_diff_abs >= len_cur ||
3213 			len_cur - len_diff_abs < len_min)) ||
3214 	    (!shrink && (skb->len + len_diff_abs > len_max &&
3215 			 !skb_is_gso(skb))))
3216 		return -ENOTSUPP;
3217 
3218 	ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3219 		       bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3220 
3221 	bpf_compute_data_pointers(skb);
3222 	return ret;
3223 }
3224 
3225 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3226 	.func		= bpf_skb_adjust_room,
3227 	.gpl_only	= false,
3228 	.ret_type	= RET_INTEGER,
3229 	.arg1_type	= ARG_PTR_TO_CTX,
3230 	.arg2_type	= ARG_ANYTHING,
3231 	.arg3_type	= ARG_ANYTHING,
3232 	.arg4_type	= ARG_ANYTHING,
3233 };
3234 
__bpf_skb_min_len(const struct sk_buff * skb)3235 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3236 {
3237 	u32 min_len = skb_network_offset(skb);
3238 
3239 	if (skb_transport_header_was_set(skb))
3240 		min_len = skb_transport_offset(skb);
3241 	if (skb->ip_summed == CHECKSUM_PARTIAL)
3242 		min_len = skb_checksum_start_offset(skb) +
3243 			  skb->csum_offset + sizeof(__sum16);
3244 	return min_len;
3245 }
3246 
bpf_skb_grow_rcsum(struct sk_buff * skb,unsigned int new_len)3247 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3248 {
3249 	unsigned int old_len = skb->len;
3250 	int ret;
3251 
3252 	ret = __skb_grow_rcsum(skb, new_len);
3253 	if (!ret)
3254 		memset(skb->data + old_len, 0, new_len - old_len);
3255 	return ret;
3256 }
3257 
bpf_skb_trim_rcsum(struct sk_buff * skb,unsigned int new_len)3258 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3259 {
3260 	return __skb_trim_rcsum(skb, new_len);
3261 }
3262 
__bpf_skb_change_tail(struct sk_buff * skb,u32 new_len,u64 flags)3263 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3264 					u64 flags)
3265 {
3266 	u32 max_len = BPF_SKB_MAX_LEN;
3267 	u32 min_len = __bpf_skb_min_len(skb);
3268 	int ret;
3269 
3270 	if (unlikely(flags || new_len > max_len || new_len < min_len))
3271 		return -EINVAL;
3272 	if (skb->encapsulation)
3273 		return -ENOTSUPP;
3274 
3275 	/* The basic idea of this helper is that it's performing the
3276 	 * needed work to either grow or trim an skb, and eBPF program
3277 	 * rewrites the rest via helpers like bpf_skb_store_bytes(),
3278 	 * bpf_lX_csum_replace() and others rather than passing a raw
3279 	 * buffer here. This one is a slow path helper and intended
3280 	 * for replies with control messages.
3281 	 *
3282 	 * Like in bpf_skb_change_proto(), we want to keep this rather
3283 	 * minimal and without protocol specifics so that we are able
3284 	 * to separate concerns as in bpf_skb_store_bytes() should only
3285 	 * be the one responsible for writing buffers.
3286 	 *
3287 	 * It's really expected to be a slow path operation here for
3288 	 * control message replies, so we're implicitly linearizing,
3289 	 * uncloning and drop offloads from the skb by this.
3290 	 */
3291 	ret = __bpf_try_make_writable(skb, skb->len);
3292 	if (!ret) {
3293 		if (new_len > skb->len)
3294 			ret = bpf_skb_grow_rcsum(skb, new_len);
3295 		else if (new_len < skb->len)
3296 			ret = bpf_skb_trim_rcsum(skb, new_len);
3297 		if (!ret && skb_is_gso(skb))
3298 			skb_gso_reset(skb);
3299 	}
3300 	return ret;
3301 }
3302 
BPF_CALL_3(bpf_skb_change_tail,struct sk_buff *,skb,u32,new_len,u64,flags)3303 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3304 	   u64, flags)
3305 {
3306 	int ret = __bpf_skb_change_tail(skb, new_len, flags);
3307 
3308 	bpf_compute_data_pointers(skb);
3309 	return ret;
3310 }
3311 
3312 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3313 	.func		= bpf_skb_change_tail,
3314 	.gpl_only	= false,
3315 	.ret_type	= RET_INTEGER,
3316 	.arg1_type	= ARG_PTR_TO_CTX,
3317 	.arg2_type	= ARG_ANYTHING,
3318 	.arg3_type	= ARG_ANYTHING,
3319 };
3320 
BPF_CALL_3(sk_skb_change_tail,struct sk_buff *,skb,u32,new_len,u64,flags)3321 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3322 	   u64, flags)
3323 {
3324 	int ret = __bpf_skb_change_tail(skb, new_len, flags);
3325 
3326 	bpf_compute_data_end_sk_skb(skb);
3327 	return ret;
3328 }
3329 
3330 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3331 	.func		= sk_skb_change_tail,
3332 	.gpl_only	= false,
3333 	.ret_type	= RET_INTEGER,
3334 	.arg1_type	= ARG_PTR_TO_CTX,
3335 	.arg2_type	= ARG_ANYTHING,
3336 	.arg3_type	= ARG_ANYTHING,
3337 };
3338 
__bpf_skb_change_head(struct sk_buff * skb,u32 head_room,u64 flags)3339 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3340 					u64 flags)
3341 {
3342 	u32 max_len = BPF_SKB_MAX_LEN;
3343 	u32 new_len = skb->len + head_room;
3344 	int ret;
3345 
3346 	if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3347 		     new_len < skb->len))
3348 		return -EINVAL;
3349 
3350 	ret = skb_cow(skb, head_room);
3351 	if (likely(!ret)) {
3352 		/* Idea for this helper is that we currently only
3353 		 * allow to expand on mac header. This means that
3354 		 * skb->protocol network header, etc, stay as is.
3355 		 * Compared to bpf_skb_change_tail(), we're more
3356 		 * flexible due to not needing to linearize or
3357 		 * reset GSO. Intention for this helper is to be
3358 		 * used by an L3 skb that needs to push mac header
3359 		 * for redirection into L2 device.
3360 		 */
3361 		__skb_push(skb, head_room);
3362 		memset(skb->data, 0, head_room);
3363 		skb_reset_mac_header(skb);
3364 		skb_reset_mac_len(skb);
3365 	}
3366 
3367 	return ret;
3368 }
3369 
BPF_CALL_3(bpf_skb_change_head,struct sk_buff *,skb,u32,head_room,u64,flags)3370 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3371 	   u64, flags)
3372 {
3373 	int ret = __bpf_skb_change_head(skb, head_room, flags);
3374 
3375 	bpf_compute_data_pointers(skb);
3376 	return ret;
3377 }
3378 
3379 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3380 	.func		= bpf_skb_change_head,
3381 	.gpl_only	= false,
3382 	.ret_type	= RET_INTEGER,
3383 	.arg1_type	= ARG_PTR_TO_CTX,
3384 	.arg2_type	= ARG_ANYTHING,
3385 	.arg3_type	= ARG_ANYTHING,
3386 };
3387 
BPF_CALL_3(sk_skb_change_head,struct sk_buff *,skb,u32,head_room,u64,flags)3388 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3389 	   u64, flags)
3390 {
3391 	int ret = __bpf_skb_change_head(skb, head_room, flags);
3392 
3393 	bpf_compute_data_end_sk_skb(skb);
3394 	return ret;
3395 }
3396 
3397 static const struct bpf_func_proto sk_skb_change_head_proto = {
3398 	.func		= sk_skb_change_head,
3399 	.gpl_only	= false,
3400 	.ret_type	= RET_INTEGER,
3401 	.arg1_type	= ARG_PTR_TO_CTX,
3402 	.arg2_type	= ARG_ANYTHING,
3403 	.arg3_type	= ARG_ANYTHING,
3404 };
xdp_get_metalen(const struct xdp_buff * xdp)3405 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3406 {
3407 	return xdp_data_meta_unsupported(xdp) ? 0 :
3408 	       xdp->data - xdp->data_meta;
3409 }
3410 
BPF_CALL_2(bpf_xdp_adjust_head,struct xdp_buff *,xdp,int,offset)3411 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3412 {
3413 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3414 	unsigned long metalen = xdp_get_metalen(xdp);
3415 	void *data_start = xdp_frame_end + metalen;
3416 	void *data = xdp->data + offset;
3417 
3418 	if (unlikely(data < data_start ||
3419 		     data > xdp->data_end - ETH_HLEN))
3420 		return -EINVAL;
3421 
3422 	if (metalen)
3423 		memmove(xdp->data_meta + offset,
3424 			xdp->data_meta, metalen);
3425 	xdp->data_meta += offset;
3426 	xdp->data = data;
3427 
3428 	return 0;
3429 }
3430 
3431 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3432 	.func		= bpf_xdp_adjust_head,
3433 	.gpl_only	= false,
3434 	.ret_type	= RET_INTEGER,
3435 	.arg1_type	= ARG_PTR_TO_CTX,
3436 	.arg2_type	= ARG_ANYTHING,
3437 };
3438 
BPF_CALL_2(bpf_xdp_adjust_tail,struct xdp_buff *,xdp,int,offset)3439 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3440 {
3441 	void *data_end = xdp->data_end + offset;
3442 
3443 	/* only shrinking is allowed for now. */
3444 	if (unlikely(offset >= 0))
3445 		return -EINVAL;
3446 
3447 	if (unlikely(data_end < xdp->data + ETH_HLEN))
3448 		return -EINVAL;
3449 
3450 	xdp->data_end = data_end;
3451 
3452 	return 0;
3453 }
3454 
3455 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3456 	.func		= bpf_xdp_adjust_tail,
3457 	.gpl_only	= false,
3458 	.ret_type	= RET_INTEGER,
3459 	.arg1_type	= ARG_PTR_TO_CTX,
3460 	.arg2_type	= ARG_ANYTHING,
3461 };
3462 
BPF_CALL_2(bpf_xdp_adjust_meta,struct xdp_buff *,xdp,int,offset)3463 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3464 {
3465 	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3466 	void *meta = xdp->data_meta + offset;
3467 	unsigned long metalen = xdp->data - meta;
3468 
3469 	if (xdp_data_meta_unsupported(xdp))
3470 		return -ENOTSUPP;
3471 	if (unlikely(meta < xdp_frame_end ||
3472 		     meta > xdp->data))
3473 		return -EINVAL;
3474 	if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3475 		     (metalen > 32)))
3476 		return -EACCES;
3477 
3478 	xdp->data_meta = meta;
3479 
3480 	return 0;
3481 }
3482 
3483 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3484 	.func		= bpf_xdp_adjust_meta,
3485 	.gpl_only	= false,
3486 	.ret_type	= RET_INTEGER,
3487 	.arg1_type	= ARG_PTR_TO_CTX,
3488 	.arg2_type	= ARG_ANYTHING,
3489 };
3490 
__bpf_tx_xdp(struct net_device * dev,struct bpf_map * map,struct xdp_buff * xdp,u32 index)3491 static int __bpf_tx_xdp(struct net_device *dev,
3492 			struct bpf_map *map,
3493 			struct xdp_buff *xdp,
3494 			u32 index)
3495 {
3496 	struct xdp_frame *xdpf;
3497 	int err, sent;
3498 
3499 	if (!dev->netdev_ops->ndo_xdp_xmit) {
3500 		return -EOPNOTSUPP;
3501 	}
3502 
3503 	err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
3504 	if (unlikely(err))
3505 		return err;
3506 
3507 	xdpf = convert_to_xdp_frame(xdp);
3508 	if (unlikely(!xdpf))
3509 		return -EOVERFLOW;
3510 
3511 	sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3512 	if (sent <= 0)
3513 		return sent;
3514 	return 0;
3515 }
3516 
3517 static noinline int
xdp_do_redirect_slow(struct net_device * dev,struct xdp_buff * xdp,struct bpf_prog * xdp_prog,struct bpf_redirect_info * ri)3518 xdp_do_redirect_slow(struct net_device *dev, struct xdp_buff *xdp,
3519 		     struct bpf_prog *xdp_prog, struct bpf_redirect_info *ri)
3520 {
3521 	struct net_device *fwd;
3522 	u32 index = ri->tgt_index;
3523 	int err;
3524 
3525 	fwd = dev_get_by_index_rcu(dev_net(dev), index);
3526 	ri->tgt_index = 0;
3527 	if (unlikely(!fwd)) {
3528 		err = -EINVAL;
3529 		goto err;
3530 	}
3531 
3532 	err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3533 	if (unlikely(err))
3534 		goto err;
3535 
3536 	_trace_xdp_redirect(dev, xdp_prog, index);
3537 	return 0;
3538 err:
3539 	_trace_xdp_redirect_err(dev, xdp_prog, index, err);
3540 	return err;
3541 }
3542 
__bpf_tx_xdp_map(struct net_device * dev_rx,void * fwd,struct bpf_map * map,struct xdp_buff * xdp,u32 index)3543 static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3544 			    struct bpf_map *map,
3545 			    struct xdp_buff *xdp,
3546 			    u32 index)
3547 {
3548 	int err;
3549 
3550 	switch (map->map_type) {
3551 	case BPF_MAP_TYPE_DEVMAP:
3552 	case BPF_MAP_TYPE_DEVMAP_HASH: {
3553 		struct bpf_dtab_netdev *dst = fwd;
3554 
3555 		err = dev_map_enqueue(dst, xdp, dev_rx);
3556 		if (unlikely(err))
3557 			return err;
3558 		break;
3559 	}
3560 	case BPF_MAP_TYPE_CPUMAP: {
3561 		struct bpf_cpu_map_entry *rcpu = fwd;
3562 
3563 		err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3564 		if (unlikely(err))
3565 			return err;
3566 		break;
3567 	}
3568 	case BPF_MAP_TYPE_XSKMAP: {
3569 		struct xdp_sock *xs = fwd;
3570 
3571 		err = __xsk_map_redirect(map, xdp, xs);
3572 		return err;
3573 	}
3574 	default:
3575 		return -EBADRQC;
3576 	}
3577 	return 0;
3578 }
3579 
xdp_do_flush_map(void)3580 void xdp_do_flush_map(void)
3581 {
3582 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3583 	struct bpf_map *map = ri->map_to_flush;
3584 
3585 	ri->map_to_flush = NULL;
3586 	if (map) {
3587 		switch (map->map_type) {
3588 		case BPF_MAP_TYPE_DEVMAP:
3589 		case BPF_MAP_TYPE_DEVMAP_HASH:
3590 			__dev_map_flush(map);
3591 			break;
3592 		case BPF_MAP_TYPE_CPUMAP:
3593 			__cpu_map_flush(map);
3594 			break;
3595 		case BPF_MAP_TYPE_XSKMAP:
3596 			__xsk_map_flush(map);
3597 			break;
3598 		default:
3599 			break;
3600 		}
3601 	}
3602 }
3603 EXPORT_SYMBOL_GPL(xdp_do_flush_map);
3604 
__xdp_map_lookup_elem(struct bpf_map * map,u32 index)3605 static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3606 {
3607 	switch (map->map_type) {
3608 	case BPF_MAP_TYPE_DEVMAP:
3609 		return __dev_map_lookup_elem(map, index);
3610 	case BPF_MAP_TYPE_DEVMAP_HASH:
3611 		return __dev_map_hash_lookup_elem(map, index);
3612 	case BPF_MAP_TYPE_CPUMAP:
3613 		return __cpu_map_lookup_elem(map, index);
3614 	case BPF_MAP_TYPE_XSKMAP:
3615 		return __xsk_map_lookup_elem(map, index);
3616 	default:
3617 		return NULL;
3618 	}
3619 }
3620 
bpf_clear_redirect_map(struct bpf_map * map)3621 void bpf_clear_redirect_map(struct bpf_map *map)
3622 {
3623 	struct bpf_redirect_info *ri;
3624 	int cpu;
3625 
3626 	for_each_possible_cpu(cpu) {
3627 		ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3628 		/* Avoid polluting remote cacheline due to writes if
3629 		 * not needed. Once we pass this test, we need the
3630 		 * cmpxchg() to make sure it hasn't been changed in
3631 		 * the meantime by remote CPU.
3632 		 */
3633 		if (unlikely(READ_ONCE(ri->map) == map))
3634 			cmpxchg(&ri->map, map, NULL);
3635 	}
3636 }
3637 
xdp_do_redirect_map(struct net_device * dev,struct xdp_buff * xdp,struct bpf_prog * xdp_prog,struct bpf_map * map,struct bpf_redirect_info * ri)3638 static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3639 			       struct bpf_prog *xdp_prog, struct bpf_map *map,
3640 			       struct bpf_redirect_info *ri)
3641 {
3642 	u32 index = ri->tgt_index;
3643 	void *fwd = ri->tgt_value;
3644 	int err;
3645 
3646 	ri->tgt_index = 0;
3647 	ri->tgt_value = NULL;
3648 	WRITE_ONCE(ri->map, NULL);
3649 
3650 	if (ri->map_to_flush && unlikely(ri->map_to_flush != map))
3651 		xdp_do_flush_map();
3652 
3653 	err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3654 	if (unlikely(err))
3655 		goto err;
3656 
3657 	ri->map_to_flush = map;
3658 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3659 	return 0;
3660 err:
3661 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3662 	return err;
3663 }
3664 
xdp_do_redirect(struct net_device * dev,struct xdp_buff * xdp,struct bpf_prog * xdp_prog)3665 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3666 		    struct bpf_prog *xdp_prog)
3667 {
3668 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3669 	struct bpf_map *map = READ_ONCE(ri->map);
3670 
3671 	if (likely(map))
3672 		return xdp_do_redirect_map(dev, xdp, xdp_prog, map, ri);
3673 
3674 	return xdp_do_redirect_slow(dev, xdp, xdp_prog, ri);
3675 }
3676 EXPORT_SYMBOL_GPL(xdp_do_redirect);
3677 
xdp_do_generic_redirect_map(struct net_device * dev,struct sk_buff * skb,struct xdp_buff * xdp,struct bpf_prog * xdp_prog,struct bpf_map * map)3678 static int xdp_do_generic_redirect_map(struct net_device *dev,
3679 				       struct sk_buff *skb,
3680 				       struct xdp_buff *xdp,
3681 				       struct bpf_prog *xdp_prog,
3682 				       struct bpf_map *map)
3683 {
3684 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3685 	u32 index = ri->tgt_index;
3686 	void *fwd = ri->tgt_value;
3687 	int err = 0;
3688 
3689 	ri->tgt_index = 0;
3690 	ri->tgt_value = NULL;
3691 	WRITE_ONCE(ri->map, NULL);
3692 
3693 	if (map->map_type == BPF_MAP_TYPE_DEVMAP ||
3694 	    map->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
3695 		struct bpf_dtab_netdev *dst = fwd;
3696 
3697 		err = dev_map_generic_redirect(dst, skb, xdp_prog);
3698 		if (unlikely(err))
3699 			goto err;
3700 	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3701 		struct xdp_sock *xs = fwd;
3702 
3703 		err = xsk_generic_rcv(xs, xdp);
3704 		if (err)
3705 			goto err;
3706 		consume_skb(skb);
3707 	} else {
3708 		/* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3709 		err = -EBADRQC;
3710 		goto err;
3711 	}
3712 
3713 	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3714 	return 0;
3715 err:
3716 	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3717 	return err;
3718 }
3719 
xdp_do_generic_redirect(struct net_device * dev,struct sk_buff * skb,struct xdp_buff * xdp,struct bpf_prog * xdp_prog)3720 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3721 			    struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3722 {
3723 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3724 	struct bpf_map *map = READ_ONCE(ri->map);
3725 	u32 index = ri->tgt_index;
3726 	struct net_device *fwd;
3727 	int err = 0;
3728 
3729 	if (map)
3730 		return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3731 						   map);
3732 	ri->tgt_index = 0;
3733 	fwd = dev_get_by_index_rcu(dev_net(dev), index);
3734 	if (unlikely(!fwd)) {
3735 		err = -EINVAL;
3736 		goto err;
3737 	}
3738 
3739 	err = xdp_ok_fwd_dev(fwd, skb->len);
3740 	if (unlikely(err))
3741 		goto err;
3742 
3743 	skb->dev = fwd;
3744 	_trace_xdp_redirect(dev, xdp_prog, index);
3745 	generic_xdp_tx(skb, xdp_prog);
3746 	return 0;
3747 err:
3748 	_trace_xdp_redirect_err(dev, xdp_prog, index, err);
3749 	return err;
3750 }
3751 EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
3752 
BPF_CALL_2(bpf_xdp_redirect,u32,ifindex,u64,flags)3753 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3754 {
3755 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3756 
3757 	if (unlikely(flags))
3758 		return XDP_ABORTED;
3759 
3760 	ri->flags = flags;
3761 	ri->tgt_index = ifindex;
3762 	ri->tgt_value = NULL;
3763 	WRITE_ONCE(ri->map, NULL);
3764 
3765 	return XDP_REDIRECT;
3766 }
3767 
3768 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3769 	.func           = bpf_xdp_redirect,
3770 	.gpl_only       = false,
3771 	.ret_type       = RET_INTEGER,
3772 	.arg1_type      = ARG_ANYTHING,
3773 	.arg2_type      = ARG_ANYTHING,
3774 };
3775 
BPF_CALL_3(bpf_xdp_redirect_map,struct bpf_map *,map,u32,ifindex,u64,flags)3776 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3777 	   u64, flags)
3778 {
3779 	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3780 
3781 	/* Lower bits of the flags are used as return code on lookup failure */
3782 	if (unlikely(flags > XDP_TX))
3783 		return XDP_ABORTED;
3784 
3785 	ri->tgt_value = __xdp_map_lookup_elem(map, ifindex);
3786 	if (unlikely(!ri->tgt_value)) {
3787 		/* If the lookup fails we want to clear out the state in the
3788 		 * redirect_info struct completely, so that if an eBPF program
3789 		 * performs multiple lookups, the last one always takes
3790 		 * precedence.
3791 		 */
3792 		WRITE_ONCE(ri->map, NULL);
3793 		return flags;
3794 	}
3795 
3796 	ri->flags = flags;
3797 	ri->tgt_index = ifindex;
3798 	WRITE_ONCE(ri->map, map);
3799 
3800 	return XDP_REDIRECT;
3801 }
3802 
3803 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3804 	.func           = bpf_xdp_redirect_map,
3805 	.gpl_only       = false,
3806 	.ret_type       = RET_INTEGER,
3807 	.arg1_type      = ARG_CONST_MAP_PTR,
3808 	.arg2_type      = ARG_ANYTHING,
3809 	.arg3_type      = ARG_ANYTHING,
3810 };
3811 
bpf_skb_copy(void * dst_buff,const void * skb,unsigned long off,unsigned long len)3812 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3813 				  unsigned long off, unsigned long len)
3814 {
3815 	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3816 
3817 	if (unlikely(!ptr))
3818 		return len;
3819 	if (ptr != dst_buff)
3820 		memcpy(dst_buff, ptr, len);
3821 
3822 	return 0;
3823 }
3824 
BPF_CALL_5(bpf_skb_event_output,struct sk_buff *,skb,struct bpf_map *,map,u64,flags,void *,meta,u64,meta_size)3825 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3826 	   u64, flags, void *, meta, u64, meta_size)
3827 {
3828 	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3829 
3830 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3831 		return -EINVAL;
3832 	if (unlikely(skb_size > skb->len))
3833 		return -EFAULT;
3834 
3835 	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3836 				bpf_skb_copy);
3837 }
3838 
3839 static const struct bpf_func_proto bpf_skb_event_output_proto = {
3840 	.func		= bpf_skb_event_output,
3841 	.gpl_only	= true,
3842 	.ret_type	= RET_INTEGER,
3843 	.arg1_type	= ARG_PTR_TO_CTX,
3844 	.arg2_type	= ARG_CONST_MAP_PTR,
3845 	.arg3_type	= ARG_ANYTHING,
3846 	.arg4_type	= ARG_PTR_TO_MEM,
3847 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
3848 };
3849 
bpf_tunnel_key_af(u64 flags)3850 static unsigned short bpf_tunnel_key_af(u64 flags)
3851 {
3852 	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3853 }
3854 
BPF_CALL_4(bpf_skb_get_tunnel_key,struct sk_buff *,skb,struct bpf_tunnel_key *,to,u32,size,u64,flags)3855 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3856 	   u32, size, u64, flags)
3857 {
3858 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3859 	u8 compat[sizeof(struct bpf_tunnel_key)];
3860 	void *to_orig = to;
3861 	int err;
3862 
3863 	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3864 		err = -EINVAL;
3865 		goto err_clear;
3866 	}
3867 	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3868 		err = -EPROTO;
3869 		goto err_clear;
3870 	}
3871 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3872 		err = -EINVAL;
3873 		switch (size) {
3874 		case offsetof(struct bpf_tunnel_key, tunnel_label):
3875 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
3876 			goto set_compat;
3877 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3878 			/* Fixup deprecated structure layouts here, so we have
3879 			 * a common path later on.
3880 			 */
3881 			if (ip_tunnel_info_af(info) != AF_INET)
3882 				goto err_clear;
3883 set_compat:
3884 			to = (struct bpf_tunnel_key *)compat;
3885 			break;
3886 		default:
3887 			goto err_clear;
3888 		}
3889 	}
3890 
3891 	to->tunnel_id = be64_to_cpu(info->key.tun_id);
3892 	to->tunnel_tos = info->key.tos;
3893 	to->tunnel_ttl = info->key.ttl;
3894 	to->tunnel_ext = 0;
3895 
3896 	if (flags & BPF_F_TUNINFO_IPV6) {
3897 		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3898 		       sizeof(to->remote_ipv6));
3899 		to->tunnel_label = be32_to_cpu(info->key.label);
3900 	} else {
3901 		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3902 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3903 		to->tunnel_label = 0;
3904 	}
3905 
3906 	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3907 		memcpy(to_orig, to, size);
3908 
3909 	return 0;
3910 err_clear:
3911 	memset(to_orig, 0, size);
3912 	return err;
3913 }
3914 
3915 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3916 	.func		= bpf_skb_get_tunnel_key,
3917 	.gpl_only	= false,
3918 	.ret_type	= RET_INTEGER,
3919 	.arg1_type	= ARG_PTR_TO_CTX,
3920 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
3921 	.arg3_type	= ARG_CONST_SIZE,
3922 	.arg4_type	= ARG_ANYTHING,
3923 };
3924 
BPF_CALL_3(bpf_skb_get_tunnel_opt,struct sk_buff *,skb,u8 *,to,u32,size)3925 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3926 {
3927 	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3928 	int err;
3929 
3930 	if (unlikely(!info ||
3931 		     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3932 		err = -ENOENT;
3933 		goto err_clear;
3934 	}
3935 	if (unlikely(size < info->options_len)) {
3936 		err = -ENOMEM;
3937 		goto err_clear;
3938 	}
3939 
3940 	ip_tunnel_info_opts_get(to, info);
3941 	if (size > info->options_len)
3942 		memset(to + info->options_len, 0, size - info->options_len);
3943 
3944 	return info->options_len;
3945 err_clear:
3946 	memset(to, 0, size);
3947 	return err;
3948 }
3949 
3950 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3951 	.func		= bpf_skb_get_tunnel_opt,
3952 	.gpl_only	= false,
3953 	.ret_type	= RET_INTEGER,
3954 	.arg1_type	= ARG_PTR_TO_CTX,
3955 	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
3956 	.arg3_type	= ARG_CONST_SIZE,
3957 };
3958 
3959 static struct metadata_dst __percpu *md_dst;
3960 
BPF_CALL_4(bpf_skb_set_tunnel_key,struct sk_buff *,skb,const struct bpf_tunnel_key *,from,u32,size,u64,flags)3961 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3962 	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3963 {
3964 	struct metadata_dst *md = this_cpu_ptr(md_dst);
3965 	u8 compat[sizeof(struct bpf_tunnel_key)];
3966 	struct ip_tunnel_info *info;
3967 
3968 	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3969 			       BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3970 		return -EINVAL;
3971 	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3972 		switch (size) {
3973 		case offsetof(struct bpf_tunnel_key, tunnel_label):
3974 		case offsetof(struct bpf_tunnel_key, tunnel_ext):
3975 		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3976 			/* Fixup deprecated structure layouts here, so we have
3977 			 * a common path later on.
3978 			 */
3979 			memcpy(compat, from, size);
3980 			memset(compat + size, 0, sizeof(compat) - size);
3981 			from = (const struct bpf_tunnel_key *) compat;
3982 			break;
3983 		default:
3984 			return -EINVAL;
3985 		}
3986 	}
3987 	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3988 		     from->tunnel_ext))
3989 		return -EINVAL;
3990 
3991 	skb_dst_drop(skb);
3992 	dst_hold((struct dst_entry *) md);
3993 	skb_dst_set(skb, (struct dst_entry *) md);
3994 
3995 	info = &md->u.tun_info;
3996 	memset(info, 0, sizeof(*info));
3997 	info->mode = IP_TUNNEL_INFO_TX;
3998 
3999 	info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
4000 	if (flags & BPF_F_DONT_FRAGMENT)
4001 		info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
4002 	if (flags & BPF_F_ZERO_CSUM_TX)
4003 		info->key.tun_flags &= ~TUNNEL_CSUM;
4004 	if (flags & BPF_F_SEQ_NUMBER)
4005 		info->key.tun_flags |= TUNNEL_SEQ;
4006 
4007 	info->key.tun_id = cpu_to_be64(from->tunnel_id);
4008 	info->key.tos = from->tunnel_tos;
4009 	info->key.ttl = from->tunnel_ttl;
4010 
4011 	if (flags & BPF_F_TUNINFO_IPV6) {
4012 		info->mode |= IP_TUNNEL_INFO_IPV6;
4013 		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
4014 		       sizeof(from->remote_ipv6));
4015 		info->key.label = cpu_to_be32(from->tunnel_label) &
4016 				  IPV6_FLOWLABEL_MASK;
4017 	} else {
4018 		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
4019 	}
4020 
4021 	return 0;
4022 }
4023 
4024 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
4025 	.func		= bpf_skb_set_tunnel_key,
4026 	.gpl_only	= false,
4027 	.ret_type	= RET_INTEGER,
4028 	.arg1_type	= ARG_PTR_TO_CTX,
4029 	.arg2_type	= ARG_PTR_TO_MEM,
4030 	.arg3_type	= ARG_CONST_SIZE,
4031 	.arg4_type	= ARG_ANYTHING,
4032 };
4033 
BPF_CALL_3(bpf_skb_set_tunnel_opt,struct sk_buff *,skb,const u8 *,from,u32,size)4034 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
4035 	   const u8 *, from, u32, size)
4036 {
4037 	struct ip_tunnel_info *info = skb_tunnel_info(skb);
4038 	const struct metadata_dst *md = this_cpu_ptr(md_dst);
4039 
4040 	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
4041 		return -EINVAL;
4042 	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
4043 		return -ENOMEM;
4044 
4045 	ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
4046 
4047 	return 0;
4048 }
4049 
4050 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
4051 	.func		= bpf_skb_set_tunnel_opt,
4052 	.gpl_only	= false,
4053 	.ret_type	= RET_INTEGER,
4054 	.arg1_type	= ARG_PTR_TO_CTX,
4055 	.arg2_type	= ARG_PTR_TO_MEM,
4056 	.arg3_type	= ARG_CONST_SIZE,
4057 };
4058 
4059 static const struct bpf_func_proto *
bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)4060 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4061 {
4062 	if (!md_dst) {
4063 		struct metadata_dst __percpu *tmp;
4064 
4065 		tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4066 						METADATA_IP_TUNNEL,
4067 						GFP_KERNEL);
4068 		if (!tmp)
4069 			return NULL;
4070 		if (cmpxchg(&md_dst, NULL, tmp))
4071 			metadata_dst_free_percpu(tmp);
4072 	}
4073 
4074 	switch (which) {
4075 	case BPF_FUNC_skb_set_tunnel_key:
4076 		return &bpf_skb_set_tunnel_key_proto;
4077 	case BPF_FUNC_skb_set_tunnel_opt:
4078 		return &bpf_skb_set_tunnel_opt_proto;
4079 	default:
4080 		return NULL;
4081 	}
4082 }
4083 
BPF_CALL_3(bpf_skb_under_cgroup,struct sk_buff *,skb,struct bpf_map *,map,u32,idx)4084 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4085 	   u32, idx)
4086 {
4087 	struct bpf_array *array = container_of(map, struct bpf_array, map);
4088 	struct cgroup *cgrp;
4089 	struct sock *sk;
4090 
4091 	sk = skb_to_full_sk(skb);
4092 	if (!sk || !sk_fullsock(sk))
4093 		return -ENOENT;
4094 	if (unlikely(idx >= array->map.max_entries))
4095 		return -E2BIG;
4096 
4097 	cgrp = READ_ONCE(array->ptrs[idx]);
4098 	if (unlikely(!cgrp))
4099 		return -EAGAIN;
4100 
4101 	return sk_under_cgroup_hierarchy(sk, cgrp);
4102 }
4103 
4104 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4105 	.func		= bpf_skb_under_cgroup,
4106 	.gpl_only	= false,
4107 	.ret_type	= RET_INTEGER,
4108 	.arg1_type	= ARG_PTR_TO_CTX,
4109 	.arg2_type	= ARG_CONST_MAP_PTR,
4110 	.arg3_type	= ARG_ANYTHING,
4111 };
4112 
4113 #ifdef CONFIG_SOCK_CGROUP_DATA
BPF_CALL_1(bpf_skb_cgroup_id,const struct sk_buff *,skb)4114 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4115 {
4116 	struct sock *sk = skb_to_full_sk(skb);
4117 	struct cgroup *cgrp;
4118 
4119 	if (!sk || !sk_fullsock(sk))
4120 		return 0;
4121 
4122 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4123 	return cgrp->kn->id.id;
4124 }
4125 
4126 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4127 	.func           = bpf_skb_cgroup_id,
4128 	.gpl_only       = false,
4129 	.ret_type       = RET_INTEGER,
4130 	.arg1_type      = ARG_PTR_TO_CTX,
4131 };
4132 
BPF_CALL_2(bpf_skb_ancestor_cgroup_id,const struct sk_buff *,skb,int,ancestor_level)4133 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4134 	   ancestor_level)
4135 {
4136 	struct sock *sk = skb_to_full_sk(skb);
4137 	struct cgroup *ancestor;
4138 	struct cgroup *cgrp;
4139 
4140 	if (!sk || !sk_fullsock(sk))
4141 		return 0;
4142 
4143 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4144 	ancestor = cgroup_ancestor(cgrp, ancestor_level);
4145 	if (!ancestor)
4146 		return 0;
4147 
4148 	return ancestor->kn->id.id;
4149 }
4150 
4151 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4152 	.func           = bpf_skb_ancestor_cgroup_id,
4153 	.gpl_only       = false,
4154 	.ret_type       = RET_INTEGER,
4155 	.arg1_type      = ARG_PTR_TO_CTX,
4156 	.arg2_type      = ARG_ANYTHING,
4157 };
4158 #endif
4159 
bpf_xdp_copy(void * dst_buff,const void * src_buff,unsigned long off,unsigned long len)4160 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
4161 				  unsigned long off, unsigned long len)
4162 {
4163 	memcpy(dst_buff, src_buff + off, len);
4164 	return 0;
4165 }
4166 
BPF_CALL_5(bpf_xdp_event_output,struct xdp_buff *,xdp,struct bpf_map *,map,u64,flags,void *,meta,u64,meta_size)4167 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
4168 	   u64, flags, void *, meta, u64, meta_size)
4169 {
4170 	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4171 
4172 	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4173 		return -EINVAL;
4174 	if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
4175 		return -EFAULT;
4176 
4177 	return bpf_event_output(map, flags, meta, meta_size, xdp->data,
4178 				xdp_size, bpf_xdp_copy);
4179 }
4180 
4181 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
4182 	.func		= bpf_xdp_event_output,
4183 	.gpl_only	= true,
4184 	.ret_type	= RET_INTEGER,
4185 	.arg1_type	= ARG_PTR_TO_CTX,
4186 	.arg2_type	= ARG_CONST_MAP_PTR,
4187 	.arg3_type	= ARG_ANYTHING,
4188 	.arg4_type	= ARG_PTR_TO_MEM,
4189 	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
4190 };
4191 
BPF_CALL_1(bpf_get_socket_cookie,struct sk_buff *,skb)4192 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
4193 {
4194 	return skb->sk ? sock_gen_cookie(skb->sk) : 0;
4195 }
4196 
4197 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
4198 	.func           = bpf_get_socket_cookie,
4199 	.gpl_only       = false,
4200 	.ret_type       = RET_INTEGER,
4201 	.arg1_type      = ARG_PTR_TO_CTX,
4202 };
4203 
BPF_CALL_1(bpf_get_socket_cookie_sock_addr,struct bpf_sock_addr_kern *,ctx)4204 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
4205 {
4206 	return sock_gen_cookie(ctx->sk);
4207 }
4208 
4209 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
4210 	.func		= bpf_get_socket_cookie_sock_addr,
4211 	.gpl_only	= false,
4212 	.ret_type	= RET_INTEGER,
4213 	.arg1_type	= ARG_PTR_TO_CTX,
4214 };
4215 
BPF_CALL_1(bpf_get_socket_cookie_sock_ops,struct bpf_sock_ops_kern *,ctx)4216 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
4217 {
4218 	return sock_gen_cookie(ctx->sk);
4219 }
4220 
4221 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
4222 	.func		= bpf_get_socket_cookie_sock_ops,
4223 	.gpl_only	= false,
4224 	.ret_type	= RET_INTEGER,
4225 	.arg1_type	= ARG_PTR_TO_CTX,
4226 };
4227 
BPF_CALL_1(bpf_get_socket_uid,struct sk_buff *,skb)4228 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
4229 {
4230 	struct sock *sk = sk_to_full_sk(skb->sk);
4231 	kuid_t kuid;
4232 
4233 	if (!sk || !sk_fullsock(sk))
4234 		return overflowuid;
4235 	kuid = sock_net_uid(sock_net(sk), sk);
4236 	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
4237 }
4238 
4239 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
4240 	.func           = bpf_get_socket_uid,
4241 	.gpl_only       = false,
4242 	.ret_type       = RET_INTEGER,
4243 	.arg1_type      = ARG_PTR_TO_CTX,
4244 };
4245 
BPF_CALL_5(bpf_sockopt_event_output,struct bpf_sock_ops_kern *,bpf_sock,struct bpf_map *,map,u64,flags,void *,data,u64,size)4246 BPF_CALL_5(bpf_sockopt_event_output, struct bpf_sock_ops_kern *, bpf_sock,
4247 	   struct bpf_map *, map, u64, flags, void *, data, u64, size)
4248 {
4249 	if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
4250 		return -EINVAL;
4251 
4252 	return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
4253 }
4254 
4255 static const struct bpf_func_proto bpf_sockopt_event_output_proto =  {
4256 	.func		= bpf_sockopt_event_output,
4257 	.gpl_only       = true,
4258 	.ret_type       = RET_INTEGER,
4259 	.arg1_type      = ARG_PTR_TO_CTX,
4260 	.arg2_type      = ARG_CONST_MAP_PTR,
4261 	.arg3_type      = ARG_ANYTHING,
4262 	.arg4_type      = ARG_PTR_TO_MEM,
4263 	.arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4264 };
4265 
BPF_CALL_5(bpf_setsockopt,struct bpf_sock_ops_kern *,bpf_sock,int,level,int,optname,char *,optval,int,optlen)4266 BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4267 	   int, level, int, optname, char *, optval, int, optlen)
4268 {
4269 	struct sock *sk = bpf_sock->sk;
4270 	int ret = 0;
4271 	int val;
4272 
4273 	if (!sk_fullsock(sk))
4274 		return -EINVAL;
4275 
4276 	if (level == SOL_SOCKET) {
4277 		if (optlen != sizeof(int))
4278 			return -EINVAL;
4279 		val = *((int *)optval);
4280 
4281 		/* Only some socketops are supported */
4282 		switch (optname) {
4283 		case SO_RCVBUF:
4284 			val = min_t(u32, val, sysctl_rmem_max);
4285 			val = min_t(int, val, INT_MAX / 2);
4286 			sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
4287 			WRITE_ONCE(sk->sk_rcvbuf,
4288 				   max_t(int, val * 2, SOCK_MIN_RCVBUF));
4289 			break;
4290 		case SO_SNDBUF:
4291 			val = min_t(u32, val, sysctl_wmem_max);
4292 			val = min_t(int, val, INT_MAX / 2);
4293 			sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
4294 			WRITE_ONCE(sk->sk_sndbuf,
4295 				   max_t(int, val * 2, SOCK_MIN_SNDBUF));
4296 			break;
4297 		case SO_MAX_PACING_RATE: /* 32bit version */
4298 			if (val != ~0U)
4299 				cmpxchg(&sk->sk_pacing_status,
4300 					SK_PACING_NONE,
4301 					SK_PACING_NEEDED);
4302 			sk->sk_max_pacing_rate = (val == ~0U) ?
4303 						 ~0UL : (unsigned int)val;
4304 			sk->sk_pacing_rate = min(sk->sk_pacing_rate,
4305 						 sk->sk_max_pacing_rate);
4306 			break;
4307 		case SO_PRIORITY:
4308 			sk->sk_priority = val;
4309 			break;
4310 		case SO_RCVLOWAT:
4311 			if (val < 0)
4312 				val = INT_MAX;
4313 			WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
4314 			break;
4315 		case SO_MARK:
4316 			if (sk->sk_mark != val) {
4317 				sk->sk_mark = val;
4318 				sk_dst_reset(sk);
4319 			}
4320 			break;
4321 		default:
4322 			ret = -EINVAL;
4323 		}
4324 #ifdef CONFIG_INET
4325 	} else if (level == SOL_IP) {
4326 		if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4327 			return -EINVAL;
4328 
4329 		val = *((int *)optval);
4330 		/* Only some options are supported */
4331 		switch (optname) {
4332 		case IP_TOS:
4333 			if (val < -1 || val > 0xff) {
4334 				ret = -EINVAL;
4335 			} else {
4336 				struct inet_sock *inet = inet_sk(sk);
4337 
4338 				if (val == -1)
4339 					val = 0;
4340 				inet->tos = val;
4341 			}
4342 			break;
4343 		default:
4344 			ret = -EINVAL;
4345 		}
4346 #if IS_ENABLED(CONFIG_IPV6)
4347 	} else if (level == SOL_IPV6) {
4348 		if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4349 			return -EINVAL;
4350 
4351 		val = *((int *)optval);
4352 		/* Only some options are supported */
4353 		switch (optname) {
4354 		case IPV6_TCLASS:
4355 			if (val < -1 || val > 0xff) {
4356 				ret = -EINVAL;
4357 			} else {
4358 				struct ipv6_pinfo *np = inet6_sk(sk);
4359 
4360 				if (val == -1)
4361 					val = 0;
4362 				np->tclass = val;
4363 			}
4364 			break;
4365 		default:
4366 			ret = -EINVAL;
4367 		}
4368 #endif
4369 	} else if (level == SOL_TCP &&
4370 		   sk->sk_prot->setsockopt == tcp_setsockopt) {
4371 		if (optname == TCP_CONGESTION) {
4372 			char name[TCP_CA_NAME_MAX];
4373 			bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
4374 
4375 			strncpy(name, optval, min_t(long, optlen,
4376 						    TCP_CA_NAME_MAX-1));
4377 			name[TCP_CA_NAME_MAX-1] = 0;
4378 			ret = tcp_set_congestion_control(sk, name, false,
4379 							 reinit, true);
4380 		} else {
4381 			struct tcp_sock *tp = tcp_sk(sk);
4382 
4383 			if (optlen != sizeof(int))
4384 				return -EINVAL;
4385 
4386 			val = *((int *)optval);
4387 			/* Only some options are supported */
4388 			switch (optname) {
4389 			case TCP_BPF_IW:
4390 				if (val <= 0 || tp->data_segs_out > tp->syn_data)
4391 					ret = -EINVAL;
4392 				else
4393 					tp->snd_cwnd = val;
4394 				break;
4395 			case TCP_BPF_SNDCWND_CLAMP:
4396 				if (val <= 0) {
4397 					ret = -EINVAL;
4398 				} else {
4399 					tp->snd_cwnd_clamp = val;
4400 					tp->snd_ssthresh = val;
4401 				}
4402 				break;
4403 			case TCP_SAVE_SYN:
4404 				if (val < 0 || val > 1)
4405 					ret = -EINVAL;
4406 				else
4407 					tp->save_syn = val;
4408 				break;
4409 			default:
4410 				ret = -EINVAL;
4411 			}
4412 		}
4413 #endif
4414 	} else {
4415 		ret = -EINVAL;
4416 	}
4417 	return ret;
4418 }
4419 
4420 static const struct bpf_func_proto bpf_setsockopt_proto = {
4421 	.func		= bpf_setsockopt,
4422 	.gpl_only	= false,
4423 	.ret_type	= RET_INTEGER,
4424 	.arg1_type	= ARG_PTR_TO_CTX,
4425 	.arg2_type	= ARG_ANYTHING,
4426 	.arg3_type	= ARG_ANYTHING,
4427 	.arg4_type	= ARG_PTR_TO_MEM,
4428 	.arg5_type	= ARG_CONST_SIZE,
4429 };
4430 
BPF_CALL_5(bpf_getsockopt,struct bpf_sock_ops_kern *,bpf_sock,int,level,int,optname,char *,optval,int,optlen)4431 BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4432 	   int, level, int, optname, char *, optval, int, optlen)
4433 {
4434 	struct sock *sk = bpf_sock->sk;
4435 
4436 	if (!sk_fullsock(sk))
4437 		goto err_clear;
4438 #ifdef CONFIG_INET
4439 	if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4440 		struct inet_connection_sock *icsk;
4441 		struct tcp_sock *tp;
4442 
4443 		switch (optname) {
4444 		case TCP_CONGESTION:
4445 			icsk = inet_csk(sk);
4446 
4447 			if (!icsk->icsk_ca_ops || optlen <= 1)
4448 				goto err_clear;
4449 			strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4450 			optval[optlen - 1] = 0;
4451 			break;
4452 		case TCP_SAVED_SYN:
4453 			tp = tcp_sk(sk);
4454 
4455 			if (optlen <= 0 || !tp->saved_syn ||
4456 			    optlen > tp->saved_syn[0])
4457 				goto err_clear;
4458 			memcpy(optval, tp->saved_syn + 1, optlen);
4459 			break;
4460 		default:
4461 			goto err_clear;
4462 		}
4463 	} else if (level == SOL_IP) {
4464 		struct inet_sock *inet = inet_sk(sk);
4465 
4466 		if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4467 			goto err_clear;
4468 
4469 		/* Only some options are supported */
4470 		switch (optname) {
4471 		case IP_TOS:
4472 			*((int *)optval) = (int)inet->tos;
4473 			break;
4474 		default:
4475 			goto err_clear;
4476 		}
4477 #if IS_ENABLED(CONFIG_IPV6)
4478 	} else if (level == SOL_IPV6) {
4479 		struct ipv6_pinfo *np = inet6_sk(sk);
4480 
4481 		if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4482 			goto err_clear;
4483 
4484 		/* Only some options are supported */
4485 		switch (optname) {
4486 		case IPV6_TCLASS:
4487 			*((int *)optval) = (int)np->tclass;
4488 			break;
4489 		default:
4490 			goto err_clear;
4491 		}
4492 #endif
4493 	} else {
4494 		goto err_clear;
4495 	}
4496 	return 0;
4497 #endif
4498 err_clear:
4499 	memset(optval, 0, optlen);
4500 	return -EINVAL;
4501 }
4502 
4503 static const struct bpf_func_proto bpf_getsockopt_proto = {
4504 	.func		= bpf_getsockopt,
4505 	.gpl_only	= false,
4506 	.ret_type	= RET_INTEGER,
4507 	.arg1_type	= ARG_PTR_TO_CTX,
4508 	.arg2_type	= ARG_ANYTHING,
4509 	.arg3_type	= ARG_ANYTHING,
4510 	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
4511 	.arg5_type	= ARG_CONST_SIZE,
4512 };
4513 
BPF_CALL_2(bpf_sock_ops_cb_flags_set,struct bpf_sock_ops_kern *,bpf_sock,int,argval)4514 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4515 	   int, argval)
4516 {
4517 	struct sock *sk = bpf_sock->sk;
4518 	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4519 
4520 	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4521 		return -EINVAL;
4522 
4523 	tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4524 
4525 	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4526 }
4527 
4528 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4529 	.func		= bpf_sock_ops_cb_flags_set,
4530 	.gpl_only	= false,
4531 	.ret_type	= RET_INTEGER,
4532 	.arg1_type	= ARG_PTR_TO_CTX,
4533 	.arg2_type	= ARG_ANYTHING,
4534 };
4535 
4536 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4537 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4538 
BPF_CALL_3(bpf_bind,struct bpf_sock_addr_kern *,ctx,struct sockaddr *,addr,int,addr_len)4539 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4540 	   int, addr_len)
4541 {
4542 #ifdef CONFIG_INET
4543 	struct sock *sk = ctx->sk;
4544 	int err;
4545 
4546 	/* Binding to port can be expensive so it's prohibited in the helper.
4547 	 * Only binding to IP is supported.
4548 	 */
4549 	err = -EINVAL;
4550 	if (addr_len < offsetofend(struct sockaddr, sa_family))
4551 		return err;
4552 	if (addr->sa_family == AF_INET) {
4553 		if (addr_len < sizeof(struct sockaddr_in))
4554 			return err;
4555 		if (((struct sockaddr_in *)addr)->sin_port != htons(0))
4556 			return err;
4557 		return __inet_bind(sk, addr, addr_len, true, false);
4558 #if IS_ENABLED(CONFIG_IPV6)
4559 	} else if (addr->sa_family == AF_INET6) {
4560 		if (addr_len < SIN6_LEN_RFC2133)
4561 			return err;
4562 		if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
4563 			return err;
4564 		/* ipv6_bpf_stub cannot be NULL, since it's called from
4565 		 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4566 		 */
4567 		return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
4568 #endif /* CONFIG_IPV6 */
4569 	}
4570 #endif /* CONFIG_INET */
4571 
4572 	return -EAFNOSUPPORT;
4573 }
4574 
4575 static const struct bpf_func_proto bpf_bind_proto = {
4576 	.func		= bpf_bind,
4577 	.gpl_only	= false,
4578 	.ret_type	= RET_INTEGER,
4579 	.arg1_type	= ARG_PTR_TO_CTX,
4580 	.arg2_type	= ARG_PTR_TO_MEM,
4581 	.arg3_type	= ARG_CONST_SIZE,
4582 };
4583 
4584 #ifdef CONFIG_XFRM
BPF_CALL_5(bpf_skb_get_xfrm_state,struct sk_buff *,skb,u32,index,struct bpf_xfrm_state *,to,u32,size,u64,flags)4585 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4586 	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
4587 {
4588 	const struct sec_path *sp = skb_sec_path(skb);
4589 	const struct xfrm_state *x;
4590 
4591 	if (!sp || unlikely(index >= sp->len || flags))
4592 		goto err_clear;
4593 
4594 	x = sp->xvec[index];
4595 
4596 	if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4597 		goto err_clear;
4598 
4599 	to->reqid = x->props.reqid;
4600 	to->spi = x->id.spi;
4601 	to->family = x->props.family;
4602 	to->ext = 0;
4603 
4604 	if (to->family == AF_INET6) {
4605 		memcpy(to->remote_ipv6, x->props.saddr.a6,
4606 		       sizeof(to->remote_ipv6));
4607 	} else {
4608 		to->remote_ipv4 = x->props.saddr.a4;
4609 		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4610 	}
4611 
4612 	return 0;
4613 err_clear:
4614 	memset(to, 0, size);
4615 	return -EINVAL;
4616 }
4617 
4618 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4619 	.func		= bpf_skb_get_xfrm_state,
4620 	.gpl_only	= false,
4621 	.ret_type	= RET_INTEGER,
4622 	.arg1_type	= ARG_PTR_TO_CTX,
4623 	.arg2_type	= ARG_ANYTHING,
4624 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
4625 	.arg4_type	= ARG_CONST_SIZE,
4626 	.arg5_type	= ARG_ANYTHING,
4627 };
4628 #endif
4629 
4630 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
bpf_fib_set_fwd_params(struct bpf_fib_lookup * params,const struct neighbour * neigh,const struct net_device * dev)4631 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4632 				  const struct neighbour *neigh,
4633 				  const struct net_device *dev)
4634 {
4635 	memcpy(params->dmac, neigh->ha, ETH_ALEN);
4636 	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4637 	params->h_vlan_TCI = 0;
4638 	params->h_vlan_proto = 0;
4639 
4640 	return 0;
4641 }
4642 #endif
4643 
4644 #if IS_ENABLED(CONFIG_INET)
bpf_ipv4_fib_lookup(struct net * net,struct bpf_fib_lookup * params,u32 flags,bool check_mtu)4645 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4646 			       u32 flags, bool check_mtu)
4647 {
4648 	struct fib_nh_common *nhc;
4649 	struct in_device *in_dev;
4650 	struct neighbour *neigh;
4651 	struct net_device *dev;
4652 	struct fib_result res;
4653 	struct flowi4 fl4;
4654 	int err;
4655 	u32 mtu;
4656 
4657 	dev = dev_get_by_index_rcu(net, params->ifindex);
4658 	if (unlikely(!dev))
4659 		return -ENODEV;
4660 
4661 	/* verify forwarding is enabled on this interface */
4662 	in_dev = __in_dev_get_rcu(dev);
4663 	if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4664 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
4665 
4666 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4667 		fl4.flowi4_iif = 1;
4668 		fl4.flowi4_oif = params->ifindex;
4669 	} else {
4670 		fl4.flowi4_iif = params->ifindex;
4671 		fl4.flowi4_oif = 0;
4672 	}
4673 	fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4674 	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4675 	fl4.flowi4_flags = 0;
4676 
4677 	fl4.flowi4_proto = params->l4_protocol;
4678 	fl4.daddr = params->ipv4_dst;
4679 	fl4.saddr = params->ipv4_src;
4680 	fl4.fl4_sport = params->sport;
4681 	fl4.fl4_dport = params->dport;
4682 	fl4.flowi4_multipath_hash = 0;
4683 
4684 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
4685 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4686 		struct fib_table *tb;
4687 
4688 		tb = fib_get_table(net, tbid);
4689 		if (unlikely(!tb))
4690 			return BPF_FIB_LKUP_RET_NOT_FWDED;
4691 
4692 		err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4693 	} else {
4694 		fl4.flowi4_mark = 0;
4695 		fl4.flowi4_secid = 0;
4696 		fl4.flowi4_tun_key.tun_id = 0;
4697 		fl4.flowi4_uid = sock_net_uid(net, NULL);
4698 
4699 		err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4700 	}
4701 
4702 	if (err) {
4703 		/* map fib lookup errors to RTN_ type */
4704 		if (err == -EINVAL)
4705 			return BPF_FIB_LKUP_RET_BLACKHOLE;
4706 		if (err == -EHOSTUNREACH)
4707 			return BPF_FIB_LKUP_RET_UNREACHABLE;
4708 		if (err == -EACCES)
4709 			return BPF_FIB_LKUP_RET_PROHIBIT;
4710 
4711 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4712 	}
4713 
4714 	if (res.type != RTN_UNICAST)
4715 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4716 
4717 	if (fib_info_num_path(res.fi) > 1)
4718 		fib_select_path(net, &res, &fl4, NULL);
4719 
4720 	if (check_mtu) {
4721 		mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4722 		if (params->tot_len > mtu)
4723 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4724 	}
4725 
4726 	nhc = res.nhc;
4727 
4728 	/* do not handle lwt encaps right now */
4729 	if (nhc->nhc_lwtstate)
4730 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4731 
4732 	dev = nhc->nhc_dev;
4733 
4734 	params->rt_metric = res.fi->fib_priority;
4735 	params->ifindex = dev->ifindex;
4736 
4737 	/* xdp and cls_bpf programs are run in RCU-bh so
4738 	 * rcu_read_lock_bh is not needed here
4739 	 */
4740 	if (likely(nhc->nhc_gw_family != AF_INET6)) {
4741 		if (nhc->nhc_gw_family)
4742 			params->ipv4_dst = nhc->nhc_gw.ipv4;
4743 
4744 		neigh = __ipv4_neigh_lookup_noref(dev,
4745 						 (__force u32)params->ipv4_dst);
4746 	} else {
4747 		struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
4748 
4749 		params->family = AF_INET6;
4750 		*dst = nhc->nhc_gw.ipv6;
4751 		neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4752 	}
4753 
4754 	if (!neigh || !(neigh->nud_state & NUD_VALID))
4755 		return BPF_FIB_LKUP_RET_NO_NEIGH;
4756 
4757 	return bpf_fib_set_fwd_params(params, neigh, dev);
4758 }
4759 #endif
4760 
4761 #if IS_ENABLED(CONFIG_IPV6)
bpf_ipv6_fib_lookup(struct net * net,struct bpf_fib_lookup * params,u32 flags,bool check_mtu)4762 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4763 			       u32 flags, bool check_mtu)
4764 {
4765 	struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4766 	struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4767 	struct fib6_result res = {};
4768 	struct neighbour *neigh;
4769 	struct net_device *dev;
4770 	struct inet6_dev *idev;
4771 	struct flowi6 fl6;
4772 	int strict = 0;
4773 	int oif, err;
4774 	u32 mtu;
4775 
4776 	/* link local addresses are never forwarded */
4777 	if (rt6_need_strict(dst) || rt6_need_strict(src))
4778 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4779 
4780 	dev = dev_get_by_index_rcu(net, params->ifindex);
4781 	if (unlikely(!dev))
4782 		return -ENODEV;
4783 
4784 	idev = __in6_dev_get_safely(dev);
4785 	if (unlikely(!idev || !idev->cnf.forwarding))
4786 		return BPF_FIB_LKUP_RET_FWD_DISABLED;
4787 
4788 	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4789 		fl6.flowi6_iif = 1;
4790 		oif = fl6.flowi6_oif = params->ifindex;
4791 	} else {
4792 		oif = fl6.flowi6_iif = params->ifindex;
4793 		fl6.flowi6_oif = 0;
4794 		strict = RT6_LOOKUP_F_HAS_SADDR;
4795 	}
4796 	fl6.flowlabel = params->flowinfo;
4797 	fl6.flowi6_scope = 0;
4798 	fl6.flowi6_flags = 0;
4799 	fl6.mp_hash = 0;
4800 
4801 	fl6.flowi6_proto = params->l4_protocol;
4802 	fl6.daddr = *dst;
4803 	fl6.saddr = *src;
4804 	fl6.fl6_sport = params->sport;
4805 	fl6.fl6_dport = params->dport;
4806 
4807 	if (flags & BPF_FIB_LOOKUP_DIRECT) {
4808 		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4809 		struct fib6_table *tb;
4810 
4811 		tb = ipv6_stub->fib6_get_table(net, tbid);
4812 		if (unlikely(!tb))
4813 			return BPF_FIB_LKUP_RET_NOT_FWDED;
4814 
4815 		err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
4816 						   strict);
4817 	} else {
4818 		fl6.flowi6_mark = 0;
4819 		fl6.flowi6_secid = 0;
4820 		fl6.flowi6_tun_key.tun_id = 0;
4821 		fl6.flowi6_uid = sock_net_uid(net, NULL);
4822 
4823 		err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
4824 	}
4825 
4826 	if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
4827 		     res.f6i == net->ipv6.fib6_null_entry))
4828 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4829 
4830 	switch (res.fib6_type) {
4831 	/* only unicast is forwarded */
4832 	case RTN_UNICAST:
4833 		break;
4834 	case RTN_BLACKHOLE:
4835 		return BPF_FIB_LKUP_RET_BLACKHOLE;
4836 	case RTN_UNREACHABLE:
4837 		return BPF_FIB_LKUP_RET_UNREACHABLE;
4838 	case RTN_PROHIBIT:
4839 		return BPF_FIB_LKUP_RET_PROHIBIT;
4840 	default:
4841 		return BPF_FIB_LKUP_RET_NOT_FWDED;
4842 	}
4843 
4844 	ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
4845 				    fl6.flowi6_oif != 0, NULL, strict);
4846 
4847 	if (check_mtu) {
4848 		mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
4849 		if (params->tot_len > mtu)
4850 			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4851 	}
4852 
4853 	if (res.nh->fib_nh_lws)
4854 		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4855 
4856 	if (res.nh->fib_nh_gw_family)
4857 		*dst = res.nh->fib_nh_gw6;
4858 
4859 	dev = res.nh->fib_nh_dev;
4860 	params->rt_metric = res.f6i->fib6_metric;
4861 	params->ifindex = dev->ifindex;
4862 
4863 	/* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4864 	 * not needed here.
4865 	 */
4866 	neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4867 	if (!neigh || !(neigh->nud_state & NUD_VALID))
4868 		return BPF_FIB_LKUP_RET_NO_NEIGH;
4869 
4870 	return bpf_fib_set_fwd_params(params, neigh, dev);
4871 }
4872 #endif
4873 
BPF_CALL_4(bpf_xdp_fib_lookup,struct xdp_buff *,ctx,struct bpf_fib_lookup *,params,int,plen,u32,flags)4874 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4875 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
4876 {
4877 	if (plen < sizeof(*params))
4878 		return -EINVAL;
4879 
4880 	if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4881 		return -EINVAL;
4882 
4883 	switch (params->family) {
4884 #if IS_ENABLED(CONFIG_INET)
4885 	case AF_INET:
4886 		return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4887 					   flags, true);
4888 #endif
4889 #if IS_ENABLED(CONFIG_IPV6)
4890 	case AF_INET6:
4891 		return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4892 					   flags, true);
4893 #endif
4894 	}
4895 	return -EAFNOSUPPORT;
4896 }
4897 
4898 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4899 	.func		= bpf_xdp_fib_lookup,
4900 	.gpl_only	= true,
4901 	.ret_type	= RET_INTEGER,
4902 	.arg1_type      = ARG_PTR_TO_CTX,
4903 	.arg2_type      = ARG_PTR_TO_MEM,
4904 	.arg3_type      = ARG_CONST_SIZE,
4905 	.arg4_type	= ARG_ANYTHING,
4906 };
4907 
BPF_CALL_4(bpf_skb_fib_lookup,struct sk_buff *,skb,struct bpf_fib_lookup *,params,int,plen,u32,flags)4908 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
4909 	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
4910 {
4911 	struct net *net = dev_net(skb->dev);
4912 	int rc = -EAFNOSUPPORT;
4913 	bool check_mtu = false;
4914 
4915 	if (plen < sizeof(*params))
4916 		return -EINVAL;
4917 
4918 	if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4919 		return -EINVAL;
4920 
4921 	if (params->tot_len)
4922 		check_mtu = true;
4923 
4924 	switch (params->family) {
4925 #if IS_ENABLED(CONFIG_INET)
4926 	case AF_INET:
4927 		rc = bpf_ipv4_fib_lookup(net, params, flags, check_mtu);
4928 		break;
4929 #endif
4930 #if IS_ENABLED(CONFIG_IPV6)
4931 	case AF_INET6:
4932 		rc = bpf_ipv6_fib_lookup(net, params, flags, check_mtu);
4933 		break;
4934 #endif
4935 	}
4936 
4937 	if (rc == BPF_FIB_LKUP_RET_SUCCESS && !check_mtu) {
4938 		struct net_device *dev;
4939 
4940 		/* When tot_len isn't provided by user, check skb
4941 		 * against MTU of FIB lookup resulting net_device
4942 		 */
4943 		dev = dev_get_by_index_rcu(net, params->ifindex);
4944 		if (!is_skb_forwardable(dev, skb))
4945 			rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4946 	}
4947 
4948 	return rc;
4949 }
4950 
4951 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
4952 	.func		= bpf_skb_fib_lookup,
4953 	.gpl_only	= true,
4954 	.ret_type	= RET_INTEGER,
4955 	.arg1_type      = ARG_PTR_TO_CTX,
4956 	.arg2_type      = ARG_PTR_TO_MEM,
4957 	.arg3_type      = ARG_CONST_SIZE,
4958 	.arg4_type	= ARG_ANYTHING,
4959 };
4960 
4961 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
bpf_push_seg6_encap(struct sk_buff * skb,u32 type,void * hdr,u32 len)4962 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
4963 {
4964 	int err;
4965 	struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
4966 
4967 	if (!seg6_validate_srh(srh, len))
4968 		return -EINVAL;
4969 
4970 	switch (type) {
4971 	case BPF_LWT_ENCAP_SEG6_INLINE:
4972 		if (skb->protocol != htons(ETH_P_IPV6))
4973 			return -EBADMSG;
4974 
4975 		err = seg6_do_srh_inline(skb, srh);
4976 		break;
4977 	case BPF_LWT_ENCAP_SEG6:
4978 		skb_reset_inner_headers(skb);
4979 		skb->encapsulation = 1;
4980 		err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
4981 		break;
4982 	default:
4983 		return -EINVAL;
4984 	}
4985 
4986 	bpf_compute_data_pointers(skb);
4987 	if (err)
4988 		return err;
4989 
4990 	skb_set_transport_header(skb, sizeof(struct ipv6hdr));
4991 
4992 	return seg6_lookup_nexthop(skb, NULL, 0);
4993 }
4994 #endif /* CONFIG_IPV6_SEG6_BPF */
4995 
4996 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
bpf_push_ip_encap(struct sk_buff * skb,void * hdr,u32 len,bool ingress)4997 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
4998 			     bool ingress)
4999 {
5000 	return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
5001 }
5002 #endif
5003 
BPF_CALL_4(bpf_lwt_in_push_encap,struct sk_buff *,skb,u32,type,void *,hdr,u32,len)5004 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
5005 	   u32, len)
5006 {
5007 	switch (type) {
5008 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5009 	case BPF_LWT_ENCAP_SEG6:
5010 	case BPF_LWT_ENCAP_SEG6_INLINE:
5011 		return bpf_push_seg6_encap(skb, type, hdr, len);
5012 #endif
5013 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
5014 	case BPF_LWT_ENCAP_IP:
5015 		return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
5016 #endif
5017 	default:
5018 		return -EINVAL;
5019 	}
5020 }
5021 
BPF_CALL_4(bpf_lwt_xmit_push_encap,struct sk_buff *,skb,u32,type,void *,hdr,u32,len)5022 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
5023 	   void *, hdr, u32, len)
5024 {
5025 	switch (type) {
5026 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
5027 	case BPF_LWT_ENCAP_IP:
5028 		return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
5029 #endif
5030 	default:
5031 		return -EINVAL;
5032 	}
5033 }
5034 
5035 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
5036 	.func		= bpf_lwt_in_push_encap,
5037 	.gpl_only	= false,
5038 	.ret_type	= RET_INTEGER,
5039 	.arg1_type	= ARG_PTR_TO_CTX,
5040 	.arg2_type	= ARG_ANYTHING,
5041 	.arg3_type	= ARG_PTR_TO_MEM,
5042 	.arg4_type	= ARG_CONST_SIZE
5043 };
5044 
5045 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
5046 	.func		= bpf_lwt_xmit_push_encap,
5047 	.gpl_only	= false,
5048 	.ret_type	= RET_INTEGER,
5049 	.arg1_type	= ARG_PTR_TO_CTX,
5050 	.arg2_type	= ARG_ANYTHING,
5051 	.arg3_type	= ARG_PTR_TO_MEM,
5052 	.arg4_type	= ARG_CONST_SIZE
5053 };
5054 
5055 #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)5056 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
5057 	   const void *, from, u32, len)
5058 {
5059 	struct seg6_bpf_srh_state *srh_state =
5060 		this_cpu_ptr(&seg6_bpf_srh_states);
5061 	struct ipv6_sr_hdr *srh = srh_state->srh;
5062 	void *srh_tlvs, *srh_end, *ptr;
5063 	int srhoff = 0;
5064 
5065 	if (srh == NULL)
5066 		return -EINVAL;
5067 
5068 	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
5069 	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
5070 
5071 	ptr = skb->data + offset;
5072 	if (ptr >= srh_tlvs && ptr + len <= srh_end)
5073 		srh_state->valid = false;
5074 	else if (ptr < (void *)&srh->flags ||
5075 		 ptr + len > (void *)&srh->segments)
5076 		return -EFAULT;
5077 
5078 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
5079 		return -EFAULT;
5080 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5081 		return -EINVAL;
5082 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5083 
5084 	memcpy(skb->data + offset, from, len);
5085 	return 0;
5086 }
5087 
5088 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
5089 	.func		= bpf_lwt_seg6_store_bytes,
5090 	.gpl_only	= false,
5091 	.ret_type	= RET_INTEGER,
5092 	.arg1_type	= ARG_PTR_TO_CTX,
5093 	.arg2_type	= ARG_ANYTHING,
5094 	.arg3_type	= ARG_PTR_TO_MEM,
5095 	.arg4_type	= ARG_CONST_SIZE
5096 };
5097 
bpf_update_srh_state(struct sk_buff * skb)5098 static void bpf_update_srh_state(struct sk_buff *skb)
5099 {
5100 	struct seg6_bpf_srh_state *srh_state =
5101 		this_cpu_ptr(&seg6_bpf_srh_states);
5102 	int srhoff = 0;
5103 
5104 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
5105 		srh_state->srh = NULL;
5106 	} else {
5107 		srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5108 		srh_state->hdrlen = srh_state->srh->hdrlen << 3;
5109 		srh_state->valid = true;
5110 	}
5111 }
5112 
BPF_CALL_4(bpf_lwt_seg6_action,struct sk_buff *,skb,u32,action,void *,param,u32,param_len)5113 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
5114 	   u32, action, void *, param, u32, param_len)
5115 {
5116 	struct seg6_bpf_srh_state *srh_state =
5117 		this_cpu_ptr(&seg6_bpf_srh_states);
5118 	int hdroff = 0;
5119 	int err;
5120 
5121 	switch (action) {
5122 	case SEG6_LOCAL_ACTION_END_X:
5123 		if (!seg6_bpf_has_valid_srh(skb))
5124 			return -EBADMSG;
5125 		if (param_len != sizeof(struct in6_addr))
5126 			return -EINVAL;
5127 		return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
5128 	case SEG6_LOCAL_ACTION_END_T:
5129 		if (!seg6_bpf_has_valid_srh(skb))
5130 			return -EBADMSG;
5131 		if (param_len != sizeof(int))
5132 			return -EINVAL;
5133 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5134 	case SEG6_LOCAL_ACTION_END_DT6:
5135 		if (!seg6_bpf_has_valid_srh(skb))
5136 			return -EBADMSG;
5137 		if (param_len != sizeof(int))
5138 			return -EINVAL;
5139 
5140 		if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
5141 			return -EBADMSG;
5142 		if (!pskb_pull(skb, hdroff))
5143 			return -EBADMSG;
5144 
5145 		skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
5146 		skb_reset_network_header(skb);
5147 		skb_reset_transport_header(skb);
5148 		skb->encapsulation = 0;
5149 
5150 		bpf_compute_data_pointers(skb);
5151 		bpf_update_srh_state(skb);
5152 		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5153 	case SEG6_LOCAL_ACTION_END_B6:
5154 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5155 			return -EBADMSG;
5156 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
5157 					  param, param_len);
5158 		if (!err)
5159 			bpf_update_srh_state(skb);
5160 
5161 		return err;
5162 	case SEG6_LOCAL_ACTION_END_B6_ENCAP:
5163 		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5164 			return -EBADMSG;
5165 		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
5166 					  param, param_len);
5167 		if (!err)
5168 			bpf_update_srh_state(skb);
5169 
5170 		return err;
5171 	default:
5172 		return -EINVAL;
5173 	}
5174 }
5175 
5176 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
5177 	.func		= bpf_lwt_seg6_action,
5178 	.gpl_only	= false,
5179 	.ret_type	= RET_INTEGER,
5180 	.arg1_type	= ARG_PTR_TO_CTX,
5181 	.arg2_type	= ARG_ANYTHING,
5182 	.arg3_type	= ARG_PTR_TO_MEM,
5183 	.arg4_type	= ARG_CONST_SIZE
5184 };
5185 
BPF_CALL_3(bpf_lwt_seg6_adjust_srh,struct sk_buff *,skb,u32,offset,s32,len)5186 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
5187 	   s32, len)
5188 {
5189 	struct seg6_bpf_srh_state *srh_state =
5190 		this_cpu_ptr(&seg6_bpf_srh_states);
5191 	struct ipv6_sr_hdr *srh = srh_state->srh;
5192 	void *srh_end, *srh_tlvs, *ptr;
5193 	struct ipv6hdr *hdr;
5194 	int srhoff = 0;
5195 	int ret;
5196 
5197 	if (unlikely(srh == NULL))
5198 		return -EINVAL;
5199 
5200 	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
5201 			((srh->first_segment + 1) << 4));
5202 	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
5203 			srh_state->hdrlen);
5204 	ptr = skb->data + offset;
5205 
5206 	if (unlikely(ptr < srh_tlvs || ptr > srh_end))
5207 		return -EFAULT;
5208 	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
5209 		return -EFAULT;
5210 
5211 	if (len > 0) {
5212 		ret = skb_cow_head(skb, len);
5213 		if (unlikely(ret < 0))
5214 			return ret;
5215 
5216 		ret = bpf_skb_net_hdr_push(skb, offset, len);
5217 	} else {
5218 		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
5219 	}
5220 
5221 	bpf_compute_data_pointers(skb);
5222 	if (unlikely(ret < 0))
5223 		return ret;
5224 
5225 	hdr = (struct ipv6hdr *)skb->data;
5226 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
5227 
5228 	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5229 		return -EINVAL;
5230 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5231 	srh_state->hdrlen += len;
5232 	srh_state->valid = false;
5233 	return 0;
5234 }
5235 
5236 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
5237 	.func		= bpf_lwt_seg6_adjust_srh,
5238 	.gpl_only	= false,
5239 	.ret_type	= RET_INTEGER,
5240 	.arg1_type	= ARG_PTR_TO_CTX,
5241 	.arg2_type	= ARG_ANYTHING,
5242 	.arg3_type	= ARG_ANYTHING,
5243 };
5244 #endif /* CONFIG_IPV6_SEG6_BPF */
5245 
5246 #ifdef CONFIG_INET
sk_lookup(struct net * net,struct bpf_sock_tuple * tuple,int dif,int sdif,u8 family,u8 proto)5247 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
5248 			      int dif, int sdif, u8 family, u8 proto)
5249 {
5250 	bool refcounted = false;
5251 	struct sock *sk = NULL;
5252 
5253 	if (family == AF_INET) {
5254 		__be32 src4 = tuple->ipv4.saddr;
5255 		__be32 dst4 = tuple->ipv4.daddr;
5256 
5257 		if (proto == IPPROTO_TCP)
5258 			sk = __inet_lookup(net, &tcp_hashinfo, NULL, 0,
5259 					   src4, tuple->ipv4.sport,
5260 					   dst4, tuple->ipv4.dport,
5261 					   dif, sdif, &refcounted);
5262 		else
5263 			sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
5264 					       dst4, tuple->ipv4.dport,
5265 					       dif, sdif, &udp_table, NULL);
5266 #if IS_ENABLED(CONFIG_IPV6)
5267 	} else {
5268 		struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
5269 		struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
5270 
5271 		if (proto == IPPROTO_TCP)
5272 			sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0,
5273 					    src6, tuple->ipv6.sport,
5274 					    dst6, ntohs(tuple->ipv6.dport),
5275 					    dif, sdif, &refcounted);
5276 		else if (likely(ipv6_bpf_stub))
5277 			sk = ipv6_bpf_stub->udp6_lib_lookup(net,
5278 							    src6, tuple->ipv6.sport,
5279 							    dst6, tuple->ipv6.dport,
5280 							    dif, sdif,
5281 							    &udp_table, NULL);
5282 #endif
5283 	}
5284 
5285 	if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
5286 		WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5287 		sk = NULL;
5288 	}
5289 	return sk;
5290 }
5291 
5292 /* bpf_skc_lookup performs the core lookup for different types of sockets,
5293  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
5294  * Returns the socket as an 'unsigned long' to simplify the casting in the
5295  * callers to satisfy BPF_CALL declarations.
5296  */
5297 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)5298 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5299 		 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5300 		 u64 flags)
5301 {
5302 	struct sock *sk = NULL;
5303 	u8 family = AF_UNSPEC;
5304 	struct net *net;
5305 	int sdif;
5306 
5307 	if (len == sizeof(tuple->ipv4))
5308 		family = AF_INET;
5309 	else if (len == sizeof(tuple->ipv6))
5310 		family = AF_INET6;
5311 	else
5312 		return NULL;
5313 
5314 	if (unlikely(family == AF_UNSPEC || flags ||
5315 		     !((s32)netns_id < 0 || netns_id <= S32_MAX)))
5316 		goto out;
5317 
5318 	if (family == AF_INET)
5319 		sdif = inet_sdif(skb);
5320 	else
5321 		sdif = inet6_sdif(skb);
5322 
5323 	if ((s32)netns_id < 0) {
5324 		net = caller_net;
5325 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5326 	} else {
5327 		net = get_net_ns_by_id(caller_net, netns_id);
5328 		if (unlikely(!net))
5329 			goto out;
5330 		sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5331 		put_net(net);
5332 	}
5333 
5334 out:
5335 	return sk;
5336 }
5337 
5338 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)5339 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5340 		struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5341 		u64 flags)
5342 {
5343 	struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
5344 					   ifindex, proto, netns_id, flags);
5345 
5346 	if (sk) {
5347 		struct sock *sk2 = sk_to_full_sk(sk);
5348 
5349 		/* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
5350 		 * sock refcnt is decremented to prevent a request_sock leak.
5351 		 */
5352 		if (!sk_fullsock(sk2))
5353 			sk2 = NULL;
5354 		if (sk2 != sk) {
5355 			sock_gen_put(sk);
5356 			/* Ensure there is no need to bump sk2 refcnt */
5357 			if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
5358 				WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5359 				return NULL;
5360 			}
5361 			sk = sk2;
5362 		}
5363 	}
5364 
5365 	return sk;
5366 }
5367 
5368 static struct sock *
bpf_skc_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,u8 proto,u64 netns_id,u64 flags)5369 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5370 	       u8 proto, u64 netns_id, u64 flags)
5371 {
5372 	struct net *caller_net;
5373 	int ifindex;
5374 
5375 	if (skb->dev) {
5376 		caller_net = dev_net(skb->dev);
5377 		ifindex = skb->dev->ifindex;
5378 	} else {
5379 		caller_net = sock_net(skb->sk);
5380 		ifindex = 0;
5381 	}
5382 
5383 	return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
5384 				netns_id, flags);
5385 }
5386 
5387 static struct sock *
bpf_sk_lookup(struct sk_buff * skb,struct bpf_sock_tuple * tuple,u32 len,u8 proto,u64 netns_id,u64 flags)5388 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5389 	      u8 proto, u64 netns_id, u64 flags)
5390 {
5391 	struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
5392 					 flags);
5393 
5394 	if (sk) {
5395 		struct sock *sk2 = sk_to_full_sk(sk);
5396 
5397 		/* sk_to_full_sk() may return (sk)->rsk_listener, so make sure the original sk
5398 		 * sock refcnt is decremented to prevent a request_sock leak.
5399 		 */
5400 		if (!sk_fullsock(sk2))
5401 			sk2 = NULL;
5402 		if (sk2 != sk) {
5403 			sock_gen_put(sk);
5404 			/* Ensure there is no need to bump sk2 refcnt */
5405 			if (unlikely(sk2 && !sock_flag(sk2, SOCK_RCU_FREE))) {
5406 				WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5407 				return NULL;
5408 			}
5409 			sk = sk2;
5410 		}
5411 	}
5412 
5413 	return sk;
5414 }
5415 
BPF_CALL_5(bpf_skc_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)5416 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
5417 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5418 {
5419 	return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
5420 					     netns_id, flags);
5421 }
5422 
5423 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
5424 	.func		= bpf_skc_lookup_tcp,
5425 	.gpl_only	= false,
5426 	.pkt_access	= true,
5427 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
5428 	.arg1_type	= ARG_PTR_TO_CTX,
5429 	.arg2_type	= ARG_PTR_TO_MEM,
5430 	.arg3_type	= ARG_CONST_SIZE,
5431 	.arg4_type	= ARG_ANYTHING,
5432 	.arg5_type	= ARG_ANYTHING,
5433 };
5434 
BPF_CALL_5(bpf_sk_lookup_tcp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)5435 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
5436 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5437 {
5438 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
5439 					    netns_id, flags);
5440 }
5441 
5442 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
5443 	.func		= bpf_sk_lookup_tcp,
5444 	.gpl_only	= false,
5445 	.pkt_access	= true,
5446 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
5447 	.arg1_type	= ARG_PTR_TO_CTX,
5448 	.arg2_type	= ARG_PTR_TO_MEM,
5449 	.arg3_type	= ARG_CONST_SIZE,
5450 	.arg4_type	= ARG_ANYTHING,
5451 	.arg5_type	= ARG_ANYTHING,
5452 };
5453 
BPF_CALL_5(bpf_sk_lookup_udp,struct sk_buff *,skb,struct bpf_sock_tuple *,tuple,u32,len,u64,netns_id,u64,flags)5454 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
5455 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5456 {
5457 	return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
5458 					    netns_id, flags);
5459 }
5460 
5461 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
5462 	.func		= bpf_sk_lookup_udp,
5463 	.gpl_only	= false,
5464 	.pkt_access	= true,
5465 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
5466 	.arg1_type	= ARG_PTR_TO_CTX,
5467 	.arg2_type	= ARG_PTR_TO_MEM,
5468 	.arg3_type	= ARG_CONST_SIZE,
5469 	.arg4_type	= ARG_ANYTHING,
5470 	.arg5_type	= ARG_ANYTHING,
5471 };
5472 
BPF_CALL_1(bpf_sk_release,struct sock *,sk)5473 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
5474 {
5475 	/* Only full sockets have sk->sk_flags. */
5476 	if (!sk_fullsock(sk) || !sock_flag(sk, SOCK_RCU_FREE))
5477 		sock_gen_put(sk);
5478 	return 0;
5479 }
5480 
5481 static const struct bpf_func_proto bpf_sk_release_proto = {
5482 	.func		= bpf_sk_release,
5483 	.gpl_only	= false,
5484 	.ret_type	= RET_INTEGER,
5485 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
5486 };
5487 
BPF_CALL_5(bpf_xdp_sk_lookup_udp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)5488 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
5489 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5490 {
5491 	struct net *caller_net = dev_net(ctx->rxq->dev);
5492 	int ifindex = ctx->rxq->dev->ifindex;
5493 
5494 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5495 					      ifindex, IPPROTO_UDP, netns_id,
5496 					      flags);
5497 }
5498 
5499 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
5500 	.func           = bpf_xdp_sk_lookup_udp,
5501 	.gpl_only       = false,
5502 	.pkt_access     = true,
5503 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5504 	.arg1_type      = ARG_PTR_TO_CTX,
5505 	.arg2_type      = ARG_PTR_TO_MEM,
5506 	.arg3_type      = ARG_CONST_SIZE,
5507 	.arg4_type      = ARG_ANYTHING,
5508 	.arg5_type      = ARG_ANYTHING,
5509 };
5510 
BPF_CALL_5(bpf_xdp_skc_lookup_tcp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)5511 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
5512 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5513 {
5514 	struct net *caller_net = dev_net(ctx->rxq->dev);
5515 	int ifindex = ctx->rxq->dev->ifindex;
5516 
5517 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
5518 					       ifindex, IPPROTO_TCP, netns_id,
5519 					       flags);
5520 }
5521 
5522 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
5523 	.func           = bpf_xdp_skc_lookup_tcp,
5524 	.gpl_only       = false,
5525 	.pkt_access     = true,
5526 	.ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5527 	.arg1_type      = ARG_PTR_TO_CTX,
5528 	.arg2_type      = ARG_PTR_TO_MEM,
5529 	.arg3_type      = ARG_CONST_SIZE,
5530 	.arg4_type      = ARG_ANYTHING,
5531 	.arg5_type      = ARG_ANYTHING,
5532 };
5533 
BPF_CALL_5(bpf_xdp_sk_lookup_tcp,struct xdp_buff *,ctx,struct bpf_sock_tuple *,tuple,u32,len,u32,netns_id,u64,flags)5534 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
5535 	   struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5536 {
5537 	struct net *caller_net = dev_net(ctx->rxq->dev);
5538 	int ifindex = ctx->rxq->dev->ifindex;
5539 
5540 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5541 					      ifindex, IPPROTO_TCP, netns_id,
5542 					      flags);
5543 }
5544 
5545 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
5546 	.func           = bpf_xdp_sk_lookup_tcp,
5547 	.gpl_only       = false,
5548 	.pkt_access     = true,
5549 	.ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5550 	.arg1_type      = ARG_PTR_TO_CTX,
5551 	.arg2_type      = ARG_PTR_TO_MEM,
5552 	.arg3_type      = ARG_CONST_SIZE,
5553 	.arg4_type      = ARG_ANYTHING,
5554 	.arg5_type      = ARG_ANYTHING,
5555 };
5556 
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)5557 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5558 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5559 {
5560 	return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
5561 					       sock_net(ctx->sk), 0,
5562 					       IPPROTO_TCP, netns_id, flags);
5563 }
5564 
5565 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
5566 	.func		= bpf_sock_addr_skc_lookup_tcp,
5567 	.gpl_only	= false,
5568 	.ret_type	= RET_PTR_TO_SOCK_COMMON_OR_NULL,
5569 	.arg1_type	= ARG_PTR_TO_CTX,
5570 	.arg2_type	= ARG_PTR_TO_MEM,
5571 	.arg3_type	= ARG_CONST_SIZE,
5572 	.arg4_type	= ARG_ANYTHING,
5573 	.arg5_type	= ARG_ANYTHING,
5574 };
5575 
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)5576 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5577 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5578 {
5579 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5580 					      sock_net(ctx->sk), 0, IPPROTO_TCP,
5581 					      netns_id, flags);
5582 }
5583 
5584 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
5585 	.func		= bpf_sock_addr_sk_lookup_tcp,
5586 	.gpl_only	= false,
5587 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
5588 	.arg1_type	= ARG_PTR_TO_CTX,
5589 	.arg2_type	= ARG_PTR_TO_MEM,
5590 	.arg3_type	= ARG_CONST_SIZE,
5591 	.arg4_type	= ARG_ANYTHING,
5592 	.arg5_type	= ARG_ANYTHING,
5593 };
5594 
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)5595 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
5596 	   struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5597 {
5598 	return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5599 					      sock_net(ctx->sk), 0, IPPROTO_UDP,
5600 					      netns_id, flags);
5601 }
5602 
5603 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
5604 	.func		= bpf_sock_addr_sk_lookup_udp,
5605 	.gpl_only	= false,
5606 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
5607 	.arg1_type	= ARG_PTR_TO_CTX,
5608 	.arg2_type	= ARG_PTR_TO_MEM,
5609 	.arg3_type	= ARG_CONST_SIZE,
5610 	.arg4_type	= ARG_ANYTHING,
5611 	.arg5_type	= ARG_ANYTHING,
5612 };
5613 
bpf_tcp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)5614 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5615 				  struct bpf_insn_access_aux *info)
5616 {
5617 	if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
5618 					  icsk_retransmits))
5619 		return false;
5620 
5621 	if (off % size != 0)
5622 		return false;
5623 
5624 	switch (off) {
5625 	case offsetof(struct bpf_tcp_sock, bytes_received):
5626 	case offsetof(struct bpf_tcp_sock, bytes_acked):
5627 		return size == sizeof(__u64);
5628 	default:
5629 		return size == sizeof(__u32);
5630 	}
5631 }
5632 
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)5633 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
5634 				    const struct bpf_insn *si,
5635 				    struct bpf_insn *insn_buf,
5636 				    struct bpf_prog *prog, u32 *target_size)
5637 {
5638 	struct bpf_insn *insn = insn_buf;
5639 
5640 #define BPF_TCP_SOCK_GET_COMMON(FIELD)					\
5641 	do {								\
5642 		BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, FIELD) >	\
5643 			     FIELD_SIZEOF(struct bpf_tcp_sock, FIELD));	\
5644 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
5645 				      si->dst_reg, si->src_reg,		\
5646 				      offsetof(struct tcp_sock, FIELD)); \
5647 	} while (0)
5648 
5649 #define BPF_INET_SOCK_GET_COMMON(FIELD)					\
5650 	do {								\
5651 		BUILD_BUG_ON(FIELD_SIZEOF(struct inet_connection_sock,	\
5652 					  FIELD) >			\
5653 			     FIELD_SIZEOF(struct bpf_tcp_sock, FIELD));	\
5654 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			\
5655 					struct inet_connection_sock,	\
5656 					FIELD),				\
5657 				      si->dst_reg, si->src_reg,		\
5658 				      offsetof(				\
5659 					struct inet_connection_sock,	\
5660 					FIELD));			\
5661 	} while (0)
5662 
5663 	if (insn > insn_buf)
5664 		return insn - insn_buf;
5665 
5666 	switch (si->off) {
5667 	case offsetof(struct bpf_tcp_sock, rtt_min):
5668 		BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
5669 			     sizeof(struct minmax));
5670 		BUILD_BUG_ON(sizeof(struct minmax) <
5671 			     sizeof(struct minmax_sample));
5672 
5673 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5674 				      offsetof(struct tcp_sock, rtt_min) +
5675 				      offsetof(struct minmax_sample, v));
5676 		break;
5677 	case offsetof(struct bpf_tcp_sock, snd_cwnd):
5678 		BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
5679 		break;
5680 	case offsetof(struct bpf_tcp_sock, srtt_us):
5681 		BPF_TCP_SOCK_GET_COMMON(srtt_us);
5682 		break;
5683 	case offsetof(struct bpf_tcp_sock, snd_ssthresh):
5684 		BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
5685 		break;
5686 	case offsetof(struct bpf_tcp_sock, rcv_nxt):
5687 		BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
5688 		break;
5689 	case offsetof(struct bpf_tcp_sock, snd_nxt):
5690 		BPF_TCP_SOCK_GET_COMMON(snd_nxt);
5691 		break;
5692 	case offsetof(struct bpf_tcp_sock, snd_una):
5693 		BPF_TCP_SOCK_GET_COMMON(snd_una);
5694 		break;
5695 	case offsetof(struct bpf_tcp_sock, mss_cache):
5696 		BPF_TCP_SOCK_GET_COMMON(mss_cache);
5697 		break;
5698 	case offsetof(struct bpf_tcp_sock, ecn_flags):
5699 		BPF_TCP_SOCK_GET_COMMON(ecn_flags);
5700 		break;
5701 	case offsetof(struct bpf_tcp_sock, rate_delivered):
5702 		BPF_TCP_SOCK_GET_COMMON(rate_delivered);
5703 		break;
5704 	case offsetof(struct bpf_tcp_sock, rate_interval_us):
5705 		BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
5706 		break;
5707 	case offsetof(struct bpf_tcp_sock, packets_out):
5708 		BPF_TCP_SOCK_GET_COMMON(packets_out);
5709 		break;
5710 	case offsetof(struct bpf_tcp_sock, retrans_out):
5711 		BPF_TCP_SOCK_GET_COMMON(retrans_out);
5712 		break;
5713 	case offsetof(struct bpf_tcp_sock, total_retrans):
5714 		BPF_TCP_SOCK_GET_COMMON(total_retrans);
5715 		break;
5716 	case offsetof(struct bpf_tcp_sock, segs_in):
5717 		BPF_TCP_SOCK_GET_COMMON(segs_in);
5718 		break;
5719 	case offsetof(struct bpf_tcp_sock, data_segs_in):
5720 		BPF_TCP_SOCK_GET_COMMON(data_segs_in);
5721 		break;
5722 	case offsetof(struct bpf_tcp_sock, segs_out):
5723 		BPF_TCP_SOCK_GET_COMMON(segs_out);
5724 		break;
5725 	case offsetof(struct bpf_tcp_sock, data_segs_out):
5726 		BPF_TCP_SOCK_GET_COMMON(data_segs_out);
5727 		break;
5728 	case offsetof(struct bpf_tcp_sock, lost_out):
5729 		BPF_TCP_SOCK_GET_COMMON(lost_out);
5730 		break;
5731 	case offsetof(struct bpf_tcp_sock, sacked_out):
5732 		BPF_TCP_SOCK_GET_COMMON(sacked_out);
5733 		break;
5734 	case offsetof(struct bpf_tcp_sock, bytes_received):
5735 		BPF_TCP_SOCK_GET_COMMON(bytes_received);
5736 		break;
5737 	case offsetof(struct bpf_tcp_sock, bytes_acked):
5738 		BPF_TCP_SOCK_GET_COMMON(bytes_acked);
5739 		break;
5740 	case offsetof(struct bpf_tcp_sock, dsack_dups):
5741 		BPF_TCP_SOCK_GET_COMMON(dsack_dups);
5742 		break;
5743 	case offsetof(struct bpf_tcp_sock, delivered):
5744 		BPF_TCP_SOCK_GET_COMMON(delivered);
5745 		break;
5746 	case offsetof(struct bpf_tcp_sock, delivered_ce):
5747 		BPF_TCP_SOCK_GET_COMMON(delivered_ce);
5748 		break;
5749 	case offsetof(struct bpf_tcp_sock, icsk_retransmits):
5750 		BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
5751 		break;
5752 	}
5753 
5754 	return insn - insn_buf;
5755 }
5756 
BPF_CALL_1(bpf_tcp_sock,struct sock *,sk)5757 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
5758 {
5759 	if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
5760 		return (unsigned long)sk;
5761 
5762 	return (unsigned long)NULL;
5763 }
5764 
5765 const struct bpf_func_proto bpf_tcp_sock_proto = {
5766 	.func		= bpf_tcp_sock,
5767 	.gpl_only	= false,
5768 	.ret_type	= RET_PTR_TO_TCP_SOCK_OR_NULL,
5769 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
5770 };
5771 
BPF_CALL_1(bpf_get_listener_sock,struct sock *,sk)5772 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
5773 {
5774 	sk = sk_to_full_sk(sk);
5775 
5776 	if (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
5777 		return (unsigned long)sk;
5778 
5779 	return (unsigned long)NULL;
5780 }
5781 
5782 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
5783 	.func		= bpf_get_listener_sock,
5784 	.gpl_only	= false,
5785 	.ret_type	= RET_PTR_TO_SOCKET_OR_NULL,
5786 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
5787 };
5788 
BPF_CALL_1(bpf_skb_ecn_set_ce,struct sk_buff *,skb)5789 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
5790 {
5791 	unsigned int iphdr_len;
5792 
5793 	switch (skb_protocol(skb, true)) {
5794 	case cpu_to_be16(ETH_P_IP):
5795 		iphdr_len = sizeof(struct iphdr);
5796 		break;
5797 	case cpu_to_be16(ETH_P_IPV6):
5798 		iphdr_len = sizeof(struct ipv6hdr);
5799 		break;
5800 	default:
5801 		return 0;
5802 	}
5803 
5804 	if (skb_headlen(skb) < iphdr_len)
5805 		return 0;
5806 
5807 	if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
5808 		return 0;
5809 
5810 	return INET_ECN_set_ce(skb);
5811 }
5812 
bpf_xdp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)5813 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5814 				  struct bpf_insn_access_aux *info)
5815 {
5816 	if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
5817 		return false;
5818 
5819 	if (off % size != 0)
5820 		return false;
5821 
5822 	switch (off) {
5823 	default:
5824 		return size == sizeof(__u32);
5825 	}
5826 }
5827 
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)5828 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
5829 				    const struct bpf_insn *si,
5830 				    struct bpf_insn *insn_buf,
5831 				    struct bpf_prog *prog, u32 *target_size)
5832 {
5833 	struct bpf_insn *insn = insn_buf;
5834 
5835 #define BPF_XDP_SOCK_GET(FIELD)						\
5836 	do {								\
5837 		BUILD_BUG_ON(FIELD_SIZEOF(struct xdp_sock, FIELD) >	\
5838 			     FIELD_SIZEOF(struct bpf_xdp_sock, FIELD));	\
5839 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
5840 				      si->dst_reg, si->src_reg,		\
5841 				      offsetof(struct xdp_sock, FIELD)); \
5842 	} while (0)
5843 
5844 	switch (si->off) {
5845 	case offsetof(struct bpf_xdp_sock, queue_id):
5846 		BPF_XDP_SOCK_GET(queue_id);
5847 		break;
5848 	}
5849 
5850 	return insn - insn_buf;
5851 }
5852 
5853 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
5854 	.func           = bpf_skb_ecn_set_ce,
5855 	.gpl_only       = false,
5856 	.ret_type       = RET_INTEGER,
5857 	.arg1_type      = ARG_PTR_TO_CTX,
5858 };
5859 
BPF_CALL_5(bpf_tcp_check_syncookie,struct sock *,sk,void *,iph,u32,iph_len,struct tcphdr *,th,u32,th_len)5860 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5861 	   struct tcphdr *, th, u32, th_len)
5862 {
5863 #ifdef CONFIG_SYN_COOKIES
5864 	u32 cookie;
5865 	int ret;
5866 
5867 	if (unlikely(th_len < sizeof(*th)))
5868 		return -EINVAL;
5869 
5870 	/* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
5871 	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5872 		return -EINVAL;
5873 
5874 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
5875 		return -EINVAL;
5876 
5877 	if (!th->ack || th->rst || th->syn)
5878 		return -ENOENT;
5879 
5880 	if (unlikely(iph_len < sizeof(struct iphdr)))
5881 		return -EINVAL;
5882 
5883 	if (tcp_synq_no_recent_overflow(sk))
5884 		return -ENOENT;
5885 
5886 	cookie = ntohl(th->ack_seq) - 1;
5887 
5888 	/* Both struct iphdr and struct ipv6hdr have the version field at the
5889 	 * same offset so we can cast to the shorter header (struct iphdr).
5890 	 */
5891 	switch (((struct iphdr *)iph)->version) {
5892 	case 4:
5893 		if (sk->sk_family == AF_INET6 && ipv6_only_sock(sk))
5894 			return -EINVAL;
5895 
5896 		ret = __cookie_v4_check((struct iphdr *)iph, th, cookie);
5897 		break;
5898 
5899 #if IS_BUILTIN(CONFIG_IPV6)
5900 	case 6:
5901 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
5902 			return -EINVAL;
5903 
5904 		if (sk->sk_family != AF_INET6)
5905 			return -EINVAL;
5906 
5907 		ret = __cookie_v6_check((struct ipv6hdr *)iph, th, cookie);
5908 		break;
5909 #endif /* CONFIG_IPV6 */
5910 
5911 	default:
5912 		return -EPROTONOSUPPORT;
5913 	}
5914 
5915 	if (ret > 0)
5916 		return 0;
5917 
5918 	return -ENOENT;
5919 #else
5920 	return -ENOTSUPP;
5921 #endif
5922 }
5923 
5924 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
5925 	.func		= bpf_tcp_check_syncookie,
5926 	.gpl_only	= true,
5927 	.pkt_access	= true,
5928 	.ret_type	= RET_INTEGER,
5929 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
5930 	.arg2_type	= ARG_PTR_TO_MEM,
5931 	.arg3_type	= ARG_CONST_SIZE,
5932 	.arg4_type	= ARG_PTR_TO_MEM,
5933 	.arg5_type	= ARG_CONST_SIZE,
5934 };
5935 
BPF_CALL_5(bpf_tcp_gen_syncookie,struct sock *,sk,void *,iph,u32,iph_len,struct tcphdr *,th,u32,th_len)5936 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5937 	   struct tcphdr *, th, u32, th_len)
5938 {
5939 #ifdef CONFIG_SYN_COOKIES
5940 	u32 cookie;
5941 	u16 mss;
5942 
5943 	if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
5944 		return -EINVAL;
5945 
5946 	if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5947 		return -EINVAL;
5948 
5949 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies))
5950 		return -ENOENT;
5951 
5952 	if (!th->syn || th->ack || th->fin || th->rst)
5953 		return -EINVAL;
5954 
5955 	if (unlikely(iph_len < sizeof(struct iphdr)))
5956 		return -EINVAL;
5957 
5958 	/* Both struct iphdr and struct ipv6hdr have the version field at the
5959 	 * same offset so we can cast to the shorter header (struct iphdr).
5960 	 */
5961 	switch (((struct iphdr *)iph)->version) {
5962 	case 4:
5963 		if (sk->sk_family == AF_INET6 && sk->sk_ipv6only)
5964 			return -EINVAL;
5965 
5966 		mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
5967 		break;
5968 
5969 #if IS_BUILTIN(CONFIG_IPV6)
5970 	case 6:
5971 		if (unlikely(iph_len < sizeof(struct ipv6hdr)))
5972 			return -EINVAL;
5973 
5974 		if (sk->sk_family != AF_INET6)
5975 			return -EINVAL;
5976 
5977 		mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
5978 		break;
5979 #endif /* CONFIG_IPV6 */
5980 
5981 	default:
5982 		return -EPROTONOSUPPORT;
5983 	}
5984 	if (mss == 0)
5985 		return -ENOENT;
5986 
5987 	return cookie | ((u64)mss << 32);
5988 #else
5989 	return -EOPNOTSUPP;
5990 #endif /* CONFIG_SYN_COOKIES */
5991 }
5992 
5993 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
5994 	.func		= bpf_tcp_gen_syncookie,
5995 	.gpl_only	= true, /* __cookie_v*_init_sequence() is GPL */
5996 	.pkt_access	= true,
5997 	.ret_type	= RET_INTEGER,
5998 	.arg1_type	= ARG_PTR_TO_SOCK_COMMON,
5999 	.arg2_type	= ARG_PTR_TO_MEM,
6000 	.arg3_type	= ARG_CONST_SIZE,
6001 	.arg4_type	= ARG_PTR_TO_MEM,
6002 	.arg5_type	= ARG_CONST_SIZE,
6003 };
6004 
6005 #endif /* CONFIG_INET */
6006 
bpf_helper_changes_pkt_data(void * func)6007 bool bpf_helper_changes_pkt_data(void *func)
6008 {
6009 	if (func == bpf_skb_vlan_push ||
6010 	    func == bpf_skb_vlan_pop ||
6011 	    func == bpf_skb_store_bytes ||
6012 	    func == bpf_skb_change_proto ||
6013 	    func == bpf_skb_change_head ||
6014 	    func == sk_skb_change_head ||
6015 	    func == bpf_skb_change_tail ||
6016 	    func == sk_skb_change_tail ||
6017 	    func == bpf_skb_adjust_room ||
6018 	    func == bpf_skb_pull_data ||
6019 	    func == sk_skb_pull_data ||
6020 	    func == bpf_clone_redirect ||
6021 	    func == bpf_l3_csum_replace ||
6022 	    func == bpf_l4_csum_replace ||
6023 	    func == bpf_xdp_adjust_head ||
6024 	    func == bpf_xdp_adjust_meta ||
6025 	    func == bpf_msg_pull_data ||
6026 	    func == bpf_msg_push_data ||
6027 	    func == bpf_msg_pop_data ||
6028 	    func == bpf_xdp_adjust_tail ||
6029 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6030 	    func == bpf_lwt_seg6_store_bytes ||
6031 	    func == bpf_lwt_seg6_adjust_srh ||
6032 	    func == bpf_lwt_seg6_action ||
6033 #endif
6034 	    func == bpf_lwt_in_push_encap ||
6035 	    func == bpf_lwt_xmit_push_encap)
6036 		return true;
6037 
6038 	return false;
6039 }
6040 
6041 static const struct bpf_func_proto *
bpf_base_func_proto(enum bpf_func_id func_id)6042 bpf_base_func_proto(enum bpf_func_id func_id)
6043 {
6044 	switch (func_id) {
6045 	case BPF_FUNC_map_lookup_elem:
6046 		return &bpf_map_lookup_elem_proto;
6047 	case BPF_FUNC_map_update_elem:
6048 		return &bpf_map_update_elem_proto;
6049 	case BPF_FUNC_map_delete_elem:
6050 		return &bpf_map_delete_elem_proto;
6051 	case BPF_FUNC_map_push_elem:
6052 		return &bpf_map_push_elem_proto;
6053 	case BPF_FUNC_map_pop_elem:
6054 		return &bpf_map_pop_elem_proto;
6055 	case BPF_FUNC_map_peek_elem:
6056 		return &bpf_map_peek_elem_proto;
6057 	case BPF_FUNC_get_prandom_u32:
6058 		return &bpf_get_prandom_u32_proto;
6059 	case BPF_FUNC_get_smp_processor_id:
6060 		return &bpf_get_raw_smp_processor_id_proto;
6061 	case BPF_FUNC_get_numa_node_id:
6062 		return &bpf_get_numa_node_id_proto;
6063 	case BPF_FUNC_tail_call:
6064 		return &bpf_tail_call_proto;
6065 	case BPF_FUNC_ktime_get_ns:
6066 		return &bpf_ktime_get_ns_proto;
6067 	case BPF_FUNC_ktime_get_boot_ns:
6068 		return &bpf_ktime_get_boot_ns_proto;
6069 	default:
6070 		break;
6071 	}
6072 
6073 	if (!capable(CAP_SYS_ADMIN))
6074 		return NULL;
6075 
6076 	switch (func_id) {
6077 	case BPF_FUNC_spin_lock:
6078 		return &bpf_spin_lock_proto;
6079 	case BPF_FUNC_spin_unlock:
6080 		return &bpf_spin_unlock_proto;
6081 	case BPF_FUNC_trace_printk:
6082 		return bpf_get_trace_printk_proto();
6083 	default:
6084 		return NULL;
6085 	}
6086 }
6087 
6088 static const struct bpf_func_proto *
sock_filter_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6089 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6090 {
6091 	switch (func_id) {
6092 	/* inet and inet6 sockets are created in a process
6093 	 * context so there is always a valid uid/gid
6094 	 */
6095 	case BPF_FUNC_get_current_uid_gid:
6096 		return &bpf_get_current_uid_gid_proto;
6097 	case BPF_FUNC_get_local_storage:
6098 		return &bpf_get_local_storage_proto;
6099 	default:
6100 		return bpf_base_func_proto(func_id);
6101 	}
6102 }
6103 
6104 static const struct bpf_func_proto *
sock_addr_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6105 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6106 {
6107 	switch (func_id) {
6108 	/* inet and inet6 sockets are created in a process
6109 	 * context so there is always a valid uid/gid
6110 	 */
6111 	case BPF_FUNC_get_current_uid_gid:
6112 		return &bpf_get_current_uid_gid_proto;
6113 	case BPF_FUNC_bind:
6114 		switch (prog->expected_attach_type) {
6115 		case BPF_CGROUP_INET4_CONNECT:
6116 		case BPF_CGROUP_INET6_CONNECT:
6117 			return &bpf_bind_proto;
6118 		default:
6119 			return NULL;
6120 		}
6121 	case BPF_FUNC_get_socket_cookie:
6122 		return &bpf_get_socket_cookie_sock_addr_proto;
6123 	case BPF_FUNC_get_local_storage:
6124 		return &bpf_get_local_storage_proto;
6125 #ifdef CONFIG_INET
6126 	case BPF_FUNC_sk_lookup_tcp:
6127 		return &bpf_sock_addr_sk_lookup_tcp_proto;
6128 	case BPF_FUNC_sk_lookup_udp:
6129 		return &bpf_sock_addr_sk_lookup_udp_proto;
6130 	case BPF_FUNC_sk_release:
6131 		return &bpf_sk_release_proto;
6132 	case BPF_FUNC_skc_lookup_tcp:
6133 		return &bpf_sock_addr_skc_lookup_tcp_proto;
6134 #endif /* CONFIG_INET */
6135 	case BPF_FUNC_sk_storage_get:
6136 		return &bpf_sk_storage_get_proto;
6137 	case BPF_FUNC_sk_storage_delete:
6138 		return &bpf_sk_storage_delete_proto;
6139 	default:
6140 		return bpf_base_func_proto(func_id);
6141 	}
6142 }
6143 
6144 static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6145 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6146 {
6147 	switch (func_id) {
6148 	case BPF_FUNC_skb_load_bytes:
6149 		return &bpf_skb_load_bytes_proto;
6150 	case BPF_FUNC_skb_load_bytes_relative:
6151 		return &bpf_skb_load_bytes_relative_proto;
6152 	case BPF_FUNC_get_socket_cookie:
6153 		return &bpf_get_socket_cookie_proto;
6154 	case BPF_FUNC_get_socket_uid:
6155 		return &bpf_get_socket_uid_proto;
6156 	case BPF_FUNC_perf_event_output:
6157 		return &bpf_skb_event_output_proto;
6158 	default:
6159 		return bpf_base_func_proto(func_id);
6160 	}
6161 }
6162 
6163 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
6164 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
6165 
6166 static const struct bpf_func_proto *
cg_skb_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6167 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6168 {
6169 	switch (func_id) {
6170 	case BPF_FUNC_get_local_storage:
6171 		return &bpf_get_local_storage_proto;
6172 	case BPF_FUNC_sk_fullsock:
6173 		return &bpf_sk_fullsock_proto;
6174 	case BPF_FUNC_sk_storage_get:
6175 		return &bpf_sk_storage_get_proto;
6176 	case BPF_FUNC_sk_storage_delete:
6177 		return &bpf_sk_storage_delete_proto;
6178 	case BPF_FUNC_perf_event_output:
6179 		return &bpf_skb_event_output_proto;
6180 #ifdef CONFIG_SOCK_CGROUP_DATA
6181 	case BPF_FUNC_skb_cgroup_id:
6182 		return &bpf_skb_cgroup_id_proto;
6183 #endif
6184 #ifdef CONFIG_INET
6185 	case BPF_FUNC_tcp_sock:
6186 		return &bpf_tcp_sock_proto;
6187 	case BPF_FUNC_get_listener_sock:
6188 		return &bpf_get_listener_sock_proto;
6189 	case BPF_FUNC_skb_ecn_set_ce:
6190 		return &bpf_skb_ecn_set_ce_proto;
6191 #endif
6192 	default:
6193 		return sk_filter_func_proto(func_id, prog);
6194 	}
6195 }
6196 
6197 static const struct bpf_func_proto *
tc_cls_act_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6198 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6199 {
6200 	switch (func_id) {
6201 	case BPF_FUNC_skb_store_bytes:
6202 		return &bpf_skb_store_bytes_proto;
6203 	case BPF_FUNC_skb_load_bytes:
6204 		return &bpf_skb_load_bytes_proto;
6205 	case BPF_FUNC_skb_load_bytes_relative:
6206 		return &bpf_skb_load_bytes_relative_proto;
6207 	case BPF_FUNC_skb_pull_data:
6208 		return &bpf_skb_pull_data_proto;
6209 	case BPF_FUNC_csum_diff:
6210 		return &bpf_csum_diff_proto;
6211 	case BPF_FUNC_csum_update:
6212 		return &bpf_csum_update_proto;
6213 	case BPF_FUNC_l3_csum_replace:
6214 		return &bpf_l3_csum_replace_proto;
6215 	case BPF_FUNC_l4_csum_replace:
6216 		return &bpf_l4_csum_replace_proto;
6217 	case BPF_FUNC_clone_redirect:
6218 		return &bpf_clone_redirect_proto;
6219 	case BPF_FUNC_get_cgroup_classid:
6220 		return &bpf_get_cgroup_classid_proto;
6221 	case BPF_FUNC_skb_vlan_push:
6222 		return &bpf_skb_vlan_push_proto;
6223 	case BPF_FUNC_skb_vlan_pop:
6224 		return &bpf_skb_vlan_pop_proto;
6225 	case BPF_FUNC_skb_change_proto:
6226 		return &bpf_skb_change_proto_proto;
6227 	case BPF_FUNC_skb_change_type:
6228 		return &bpf_skb_change_type_proto;
6229 	case BPF_FUNC_skb_adjust_room:
6230 		return &bpf_skb_adjust_room_proto;
6231 	case BPF_FUNC_skb_change_tail:
6232 		return &bpf_skb_change_tail_proto;
6233 	case BPF_FUNC_skb_change_head:
6234 		return &bpf_skb_change_head_proto;
6235 	case BPF_FUNC_skb_get_tunnel_key:
6236 		return &bpf_skb_get_tunnel_key_proto;
6237 	case BPF_FUNC_skb_set_tunnel_key:
6238 		return bpf_get_skb_set_tunnel_proto(func_id);
6239 	case BPF_FUNC_skb_get_tunnel_opt:
6240 		return &bpf_skb_get_tunnel_opt_proto;
6241 	case BPF_FUNC_skb_set_tunnel_opt:
6242 		return bpf_get_skb_set_tunnel_proto(func_id);
6243 	case BPF_FUNC_redirect:
6244 		return &bpf_redirect_proto;
6245 	case BPF_FUNC_get_route_realm:
6246 		return &bpf_get_route_realm_proto;
6247 	case BPF_FUNC_get_hash_recalc:
6248 		return &bpf_get_hash_recalc_proto;
6249 	case BPF_FUNC_set_hash_invalid:
6250 		return &bpf_set_hash_invalid_proto;
6251 	case BPF_FUNC_set_hash:
6252 		return &bpf_set_hash_proto;
6253 	case BPF_FUNC_perf_event_output:
6254 		return &bpf_skb_event_output_proto;
6255 	case BPF_FUNC_get_smp_processor_id:
6256 		return &bpf_get_smp_processor_id_proto;
6257 	case BPF_FUNC_skb_under_cgroup:
6258 		return &bpf_skb_under_cgroup_proto;
6259 	case BPF_FUNC_get_socket_cookie:
6260 		return &bpf_get_socket_cookie_proto;
6261 	case BPF_FUNC_get_socket_uid:
6262 		return &bpf_get_socket_uid_proto;
6263 	case BPF_FUNC_fib_lookup:
6264 		return &bpf_skb_fib_lookup_proto;
6265 	case BPF_FUNC_sk_fullsock:
6266 		return &bpf_sk_fullsock_proto;
6267 	case BPF_FUNC_sk_storage_get:
6268 		return &bpf_sk_storage_get_proto;
6269 	case BPF_FUNC_sk_storage_delete:
6270 		return &bpf_sk_storage_delete_proto;
6271 #ifdef CONFIG_XFRM
6272 	case BPF_FUNC_skb_get_xfrm_state:
6273 		return &bpf_skb_get_xfrm_state_proto;
6274 #endif
6275 #ifdef CONFIG_SOCK_CGROUP_DATA
6276 	case BPF_FUNC_skb_cgroup_id:
6277 		return &bpf_skb_cgroup_id_proto;
6278 	case BPF_FUNC_skb_ancestor_cgroup_id:
6279 		return &bpf_skb_ancestor_cgroup_id_proto;
6280 #endif
6281 #ifdef CONFIG_INET
6282 	case BPF_FUNC_sk_lookup_tcp:
6283 		return &bpf_sk_lookup_tcp_proto;
6284 	case BPF_FUNC_sk_lookup_udp:
6285 		return &bpf_sk_lookup_udp_proto;
6286 	case BPF_FUNC_sk_release:
6287 		return &bpf_sk_release_proto;
6288 	case BPF_FUNC_tcp_sock:
6289 		return &bpf_tcp_sock_proto;
6290 	case BPF_FUNC_get_listener_sock:
6291 		return &bpf_get_listener_sock_proto;
6292 	case BPF_FUNC_skc_lookup_tcp:
6293 		return &bpf_skc_lookup_tcp_proto;
6294 	case BPF_FUNC_tcp_check_syncookie:
6295 		return &bpf_tcp_check_syncookie_proto;
6296 	case BPF_FUNC_skb_ecn_set_ce:
6297 		return &bpf_skb_ecn_set_ce_proto;
6298 	case BPF_FUNC_tcp_gen_syncookie:
6299 		return &bpf_tcp_gen_syncookie_proto;
6300 #endif
6301 	default:
6302 		return bpf_base_func_proto(func_id);
6303 	}
6304 }
6305 
6306 static const struct bpf_func_proto *
xdp_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6307 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6308 {
6309 	switch (func_id) {
6310 	case BPF_FUNC_perf_event_output:
6311 		return &bpf_xdp_event_output_proto;
6312 	case BPF_FUNC_get_smp_processor_id:
6313 		return &bpf_get_smp_processor_id_proto;
6314 	case BPF_FUNC_csum_diff:
6315 		return &bpf_csum_diff_proto;
6316 	case BPF_FUNC_xdp_adjust_head:
6317 		return &bpf_xdp_adjust_head_proto;
6318 	case BPF_FUNC_xdp_adjust_meta:
6319 		return &bpf_xdp_adjust_meta_proto;
6320 	case BPF_FUNC_redirect:
6321 		return &bpf_xdp_redirect_proto;
6322 	case BPF_FUNC_redirect_map:
6323 		return &bpf_xdp_redirect_map_proto;
6324 	case BPF_FUNC_xdp_adjust_tail:
6325 		return &bpf_xdp_adjust_tail_proto;
6326 	case BPF_FUNC_fib_lookup:
6327 		return &bpf_xdp_fib_lookup_proto;
6328 #ifdef CONFIG_INET
6329 	case BPF_FUNC_sk_lookup_udp:
6330 		return &bpf_xdp_sk_lookup_udp_proto;
6331 	case BPF_FUNC_sk_lookup_tcp:
6332 		return &bpf_xdp_sk_lookup_tcp_proto;
6333 	case BPF_FUNC_sk_release:
6334 		return &bpf_sk_release_proto;
6335 	case BPF_FUNC_skc_lookup_tcp:
6336 		return &bpf_xdp_skc_lookup_tcp_proto;
6337 	case BPF_FUNC_tcp_check_syncookie:
6338 		return &bpf_tcp_check_syncookie_proto;
6339 	case BPF_FUNC_tcp_gen_syncookie:
6340 		return &bpf_tcp_gen_syncookie_proto;
6341 #endif
6342 	default:
6343 		return bpf_base_func_proto(func_id);
6344 	}
6345 }
6346 
6347 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
6348 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
6349 
6350 static const struct bpf_func_proto *
sock_ops_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6351 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6352 {
6353 	switch (func_id) {
6354 	case BPF_FUNC_setsockopt:
6355 		return &bpf_setsockopt_proto;
6356 	case BPF_FUNC_getsockopt:
6357 		return &bpf_getsockopt_proto;
6358 	case BPF_FUNC_sock_ops_cb_flags_set:
6359 		return &bpf_sock_ops_cb_flags_set_proto;
6360 	case BPF_FUNC_sock_map_update:
6361 		return &bpf_sock_map_update_proto;
6362 	case BPF_FUNC_sock_hash_update:
6363 		return &bpf_sock_hash_update_proto;
6364 	case BPF_FUNC_get_socket_cookie:
6365 		return &bpf_get_socket_cookie_sock_ops_proto;
6366 	case BPF_FUNC_get_local_storage:
6367 		return &bpf_get_local_storage_proto;
6368 	case BPF_FUNC_perf_event_output:
6369 		return &bpf_sockopt_event_output_proto;
6370 	case BPF_FUNC_sk_storage_get:
6371 		return &bpf_sk_storage_get_proto;
6372 	case BPF_FUNC_sk_storage_delete:
6373 		return &bpf_sk_storage_delete_proto;
6374 #ifdef CONFIG_INET
6375 	case BPF_FUNC_tcp_sock:
6376 		return &bpf_tcp_sock_proto;
6377 #endif /* CONFIG_INET */
6378 	default:
6379 		return bpf_base_func_proto(func_id);
6380 	}
6381 }
6382 
6383 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
6384 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
6385 
6386 static const struct bpf_func_proto *
sk_msg_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6387 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6388 {
6389 	switch (func_id) {
6390 	case BPF_FUNC_msg_redirect_map:
6391 		return &bpf_msg_redirect_map_proto;
6392 	case BPF_FUNC_msg_redirect_hash:
6393 		return &bpf_msg_redirect_hash_proto;
6394 	case BPF_FUNC_msg_apply_bytes:
6395 		return &bpf_msg_apply_bytes_proto;
6396 	case BPF_FUNC_msg_cork_bytes:
6397 		return &bpf_msg_cork_bytes_proto;
6398 	case BPF_FUNC_msg_pull_data:
6399 		return &bpf_msg_pull_data_proto;
6400 	case BPF_FUNC_msg_push_data:
6401 		return &bpf_msg_push_data_proto;
6402 	case BPF_FUNC_msg_pop_data:
6403 		return &bpf_msg_pop_data_proto;
6404 	default:
6405 		return bpf_base_func_proto(func_id);
6406 	}
6407 }
6408 
6409 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
6410 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
6411 
6412 static const struct bpf_func_proto *
sk_skb_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6413 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6414 {
6415 	switch (func_id) {
6416 	case BPF_FUNC_skb_store_bytes:
6417 		return &bpf_skb_store_bytes_proto;
6418 	case BPF_FUNC_skb_load_bytes:
6419 		return &bpf_skb_load_bytes_proto;
6420 	case BPF_FUNC_skb_pull_data:
6421 		return &sk_skb_pull_data_proto;
6422 	case BPF_FUNC_skb_change_tail:
6423 		return &sk_skb_change_tail_proto;
6424 	case BPF_FUNC_skb_change_head:
6425 		return &sk_skb_change_head_proto;
6426 	case BPF_FUNC_get_socket_cookie:
6427 		return &bpf_get_socket_cookie_proto;
6428 	case BPF_FUNC_get_socket_uid:
6429 		return &bpf_get_socket_uid_proto;
6430 	case BPF_FUNC_sk_redirect_map:
6431 		return &bpf_sk_redirect_map_proto;
6432 	case BPF_FUNC_sk_redirect_hash:
6433 		return &bpf_sk_redirect_hash_proto;
6434 	case BPF_FUNC_perf_event_output:
6435 		return &bpf_skb_event_output_proto;
6436 #ifdef CONFIG_INET
6437 	case BPF_FUNC_sk_lookup_tcp:
6438 		return &bpf_sk_lookup_tcp_proto;
6439 	case BPF_FUNC_sk_lookup_udp:
6440 		return &bpf_sk_lookup_udp_proto;
6441 	case BPF_FUNC_sk_release:
6442 		return &bpf_sk_release_proto;
6443 	case BPF_FUNC_skc_lookup_tcp:
6444 		return &bpf_skc_lookup_tcp_proto;
6445 #endif
6446 	default:
6447 		return bpf_base_func_proto(func_id);
6448 	}
6449 }
6450 
6451 static const struct bpf_func_proto *
flow_dissector_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6452 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6453 {
6454 	switch (func_id) {
6455 	case BPF_FUNC_skb_load_bytes:
6456 		return &bpf_flow_dissector_load_bytes_proto;
6457 	default:
6458 		return bpf_base_func_proto(func_id);
6459 	}
6460 }
6461 
6462 static const struct bpf_func_proto *
lwt_out_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6463 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6464 {
6465 	switch (func_id) {
6466 	case BPF_FUNC_skb_load_bytes:
6467 		return &bpf_skb_load_bytes_proto;
6468 	case BPF_FUNC_skb_pull_data:
6469 		return &bpf_skb_pull_data_proto;
6470 	case BPF_FUNC_csum_diff:
6471 		return &bpf_csum_diff_proto;
6472 	case BPF_FUNC_get_cgroup_classid:
6473 		return &bpf_get_cgroup_classid_proto;
6474 	case BPF_FUNC_get_route_realm:
6475 		return &bpf_get_route_realm_proto;
6476 	case BPF_FUNC_get_hash_recalc:
6477 		return &bpf_get_hash_recalc_proto;
6478 	case BPF_FUNC_perf_event_output:
6479 		return &bpf_skb_event_output_proto;
6480 	case BPF_FUNC_get_smp_processor_id:
6481 		return &bpf_get_smp_processor_id_proto;
6482 	case BPF_FUNC_skb_under_cgroup:
6483 		return &bpf_skb_under_cgroup_proto;
6484 	default:
6485 		return bpf_base_func_proto(func_id);
6486 	}
6487 }
6488 
6489 static const struct bpf_func_proto *
lwt_in_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6490 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6491 {
6492 	switch (func_id) {
6493 	case BPF_FUNC_lwt_push_encap:
6494 		return &bpf_lwt_in_push_encap_proto;
6495 	default:
6496 		return lwt_out_func_proto(func_id, prog);
6497 	}
6498 }
6499 
6500 static const struct bpf_func_proto *
lwt_xmit_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6501 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6502 {
6503 	switch (func_id) {
6504 	case BPF_FUNC_skb_get_tunnel_key:
6505 		return &bpf_skb_get_tunnel_key_proto;
6506 	case BPF_FUNC_skb_set_tunnel_key:
6507 		return bpf_get_skb_set_tunnel_proto(func_id);
6508 	case BPF_FUNC_skb_get_tunnel_opt:
6509 		return &bpf_skb_get_tunnel_opt_proto;
6510 	case BPF_FUNC_skb_set_tunnel_opt:
6511 		return bpf_get_skb_set_tunnel_proto(func_id);
6512 	case BPF_FUNC_redirect:
6513 		return &bpf_redirect_proto;
6514 	case BPF_FUNC_clone_redirect:
6515 		return &bpf_clone_redirect_proto;
6516 	case BPF_FUNC_skb_change_tail:
6517 		return &bpf_skb_change_tail_proto;
6518 	case BPF_FUNC_skb_change_head:
6519 		return &bpf_skb_change_head_proto;
6520 	case BPF_FUNC_skb_store_bytes:
6521 		return &bpf_skb_store_bytes_proto;
6522 	case BPF_FUNC_csum_update:
6523 		return &bpf_csum_update_proto;
6524 	case BPF_FUNC_l3_csum_replace:
6525 		return &bpf_l3_csum_replace_proto;
6526 	case BPF_FUNC_l4_csum_replace:
6527 		return &bpf_l4_csum_replace_proto;
6528 	case BPF_FUNC_set_hash_invalid:
6529 		return &bpf_set_hash_invalid_proto;
6530 	case BPF_FUNC_lwt_push_encap:
6531 		return &bpf_lwt_xmit_push_encap_proto;
6532 	default:
6533 		return lwt_out_func_proto(func_id, prog);
6534 	}
6535 }
6536 
6537 static const struct bpf_func_proto *
lwt_seg6local_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)6538 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6539 {
6540 	switch (func_id) {
6541 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6542 	case BPF_FUNC_lwt_seg6_store_bytes:
6543 		return &bpf_lwt_seg6_store_bytes_proto;
6544 	case BPF_FUNC_lwt_seg6_action:
6545 		return &bpf_lwt_seg6_action_proto;
6546 	case BPF_FUNC_lwt_seg6_adjust_srh:
6547 		return &bpf_lwt_seg6_adjust_srh_proto;
6548 #endif
6549 	default:
6550 		return lwt_out_func_proto(func_id, prog);
6551 	}
6552 }
6553 
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)6554 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
6555 				    const struct bpf_prog *prog,
6556 				    struct bpf_insn_access_aux *info)
6557 {
6558 	const int size_default = sizeof(__u32);
6559 
6560 	if (off < 0 || off >= sizeof(struct __sk_buff))
6561 		return false;
6562 
6563 	/* The verifier guarantees that size > 0. */
6564 	if (off % size != 0)
6565 		return false;
6566 
6567 	switch (off) {
6568 	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6569 		if (off + size > offsetofend(struct __sk_buff, cb[4]))
6570 			return false;
6571 		break;
6572 	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
6573 	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
6574 	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
6575 	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
6576 	case bpf_ctx_range(struct __sk_buff, data):
6577 	case bpf_ctx_range(struct __sk_buff, data_meta):
6578 	case bpf_ctx_range(struct __sk_buff, data_end):
6579 		if (size != size_default)
6580 			return false;
6581 		break;
6582 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6583 		return false;
6584 	case bpf_ctx_range(struct __sk_buff, tstamp):
6585 		if (size != sizeof(__u64))
6586 			return false;
6587 		break;
6588 	case offsetof(struct __sk_buff, sk):
6589 		if (type == BPF_WRITE || size != sizeof(__u64))
6590 			return false;
6591 		info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
6592 		break;
6593 	default:
6594 		/* Only narrow read access allowed for now. */
6595 		if (type == BPF_WRITE) {
6596 			if (size != size_default)
6597 				return false;
6598 		} else {
6599 			bpf_ctx_record_field_size(info, size_default);
6600 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6601 				return false;
6602 		}
6603 	}
6604 
6605 	return true;
6606 }
6607 
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)6608 static bool sk_filter_is_valid_access(int off, int size,
6609 				      enum bpf_access_type type,
6610 				      const struct bpf_prog *prog,
6611 				      struct bpf_insn_access_aux *info)
6612 {
6613 	switch (off) {
6614 	case bpf_ctx_range(struct __sk_buff, tc_classid):
6615 	case bpf_ctx_range(struct __sk_buff, data):
6616 	case bpf_ctx_range(struct __sk_buff, data_meta):
6617 	case bpf_ctx_range(struct __sk_buff, data_end):
6618 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6619 	case bpf_ctx_range(struct __sk_buff, tstamp):
6620 	case bpf_ctx_range(struct __sk_buff, wire_len):
6621 		return false;
6622 	}
6623 
6624 	if (type == BPF_WRITE) {
6625 		switch (off) {
6626 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6627 			break;
6628 		default:
6629 			return false;
6630 		}
6631 	}
6632 
6633 	return bpf_skb_is_valid_access(off, size, type, prog, info);
6634 }
6635 
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)6636 static bool cg_skb_is_valid_access(int off, int size,
6637 				   enum bpf_access_type type,
6638 				   const struct bpf_prog *prog,
6639 				   struct bpf_insn_access_aux *info)
6640 {
6641 	switch (off) {
6642 	case bpf_ctx_range(struct __sk_buff, tc_classid):
6643 	case bpf_ctx_range(struct __sk_buff, data_meta):
6644 	case bpf_ctx_range(struct __sk_buff, wire_len):
6645 		return false;
6646 	case bpf_ctx_range(struct __sk_buff, data):
6647 	case bpf_ctx_range(struct __sk_buff, data_end):
6648 		if (!capable(CAP_SYS_ADMIN))
6649 			return false;
6650 		break;
6651 	}
6652 
6653 	if (type == BPF_WRITE) {
6654 		switch (off) {
6655 		case bpf_ctx_range(struct __sk_buff, mark):
6656 		case bpf_ctx_range(struct __sk_buff, priority):
6657 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6658 			break;
6659 		case bpf_ctx_range(struct __sk_buff, tstamp):
6660 			if (!capable(CAP_SYS_ADMIN))
6661 				return false;
6662 			break;
6663 		default:
6664 			return false;
6665 		}
6666 	}
6667 
6668 	switch (off) {
6669 	case bpf_ctx_range(struct __sk_buff, data):
6670 		info->reg_type = PTR_TO_PACKET;
6671 		break;
6672 	case bpf_ctx_range(struct __sk_buff, data_end):
6673 		info->reg_type = PTR_TO_PACKET_END;
6674 		break;
6675 	}
6676 
6677 	return bpf_skb_is_valid_access(off, size, type, prog, info);
6678 }
6679 
lwt_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)6680 static bool lwt_is_valid_access(int off, int size,
6681 				enum bpf_access_type type,
6682 				const struct bpf_prog *prog,
6683 				struct bpf_insn_access_aux *info)
6684 {
6685 	switch (off) {
6686 	case bpf_ctx_range(struct __sk_buff, tc_classid):
6687 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6688 	case bpf_ctx_range(struct __sk_buff, data_meta):
6689 	case bpf_ctx_range(struct __sk_buff, tstamp):
6690 	case bpf_ctx_range(struct __sk_buff, wire_len):
6691 		return false;
6692 	}
6693 
6694 	if (type == BPF_WRITE) {
6695 		switch (off) {
6696 		case bpf_ctx_range(struct __sk_buff, mark):
6697 		case bpf_ctx_range(struct __sk_buff, priority):
6698 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6699 			break;
6700 		default:
6701 			return false;
6702 		}
6703 	}
6704 
6705 	switch (off) {
6706 	case bpf_ctx_range(struct __sk_buff, data):
6707 		info->reg_type = PTR_TO_PACKET;
6708 		break;
6709 	case bpf_ctx_range(struct __sk_buff, data_end):
6710 		info->reg_type = PTR_TO_PACKET_END;
6711 		break;
6712 	}
6713 
6714 	return bpf_skb_is_valid_access(off, size, type, prog, info);
6715 }
6716 
6717 /* Attach type specific accesses */
__sock_filter_check_attach_type(int off,enum bpf_access_type access_type,enum bpf_attach_type attach_type)6718 static bool __sock_filter_check_attach_type(int off,
6719 					    enum bpf_access_type access_type,
6720 					    enum bpf_attach_type attach_type)
6721 {
6722 	switch (off) {
6723 	case offsetof(struct bpf_sock, bound_dev_if):
6724 	case offsetof(struct bpf_sock, mark):
6725 	case offsetof(struct bpf_sock, priority):
6726 		switch (attach_type) {
6727 		case BPF_CGROUP_INET_SOCK_CREATE:
6728 			goto full_access;
6729 		default:
6730 			return false;
6731 		}
6732 	case bpf_ctx_range(struct bpf_sock, src_ip4):
6733 		switch (attach_type) {
6734 		case BPF_CGROUP_INET4_POST_BIND:
6735 			goto read_only;
6736 		default:
6737 			return false;
6738 		}
6739 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6740 		switch (attach_type) {
6741 		case BPF_CGROUP_INET6_POST_BIND:
6742 			goto read_only;
6743 		default:
6744 			return false;
6745 		}
6746 	case bpf_ctx_range(struct bpf_sock, src_port):
6747 		switch (attach_type) {
6748 		case BPF_CGROUP_INET4_POST_BIND:
6749 		case BPF_CGROUP_INET6_POST_BIND:
6750 			goto read_only;
6751 		default:
6752 			return false;
6753 		}
6754 	}
6755 read_only:
6756 	return access_type == BPF_READ;
6757 full_access:
6758 	return true;
6759 }
6760 
bpf_sock_common_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)6761 bool bpf_sock_common_is_valid_access(int off, int size,
6762 				     enum bpf_access_type type,
6763 				     struct bpf_insn_access_aux *info)
6764 {
6765 	switch (off) {
6766 	case bpf_ctx_range_till(struct bpf_sock, type, priority):
6767 		return false;
6768 	default:
6769 		return bpf_sock_is_valid_access(off, size, type, info);
6770 	}
6771 }
6772 
bpf_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)6773 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
6774 			      struct bpf_insn_access_aux *info)
6775 {
6776 	const int size_default = sizeof(__u32);
6777 	int field_size;
6778 
6779 	if (off < 0 || off >= sizeof(struct bpf_sock))
6780 		return false;
6781 	if (off % size != 0)
6782 		return false;
6783 
6784 	switch (off) {
6785 	case offsetof(struct bpf_sock, state):
6786 	case offsetof(struct bpf_sock, family):
6787 	case offsetof(struct bpf_sock, type):
6788 	case offsetof(struct bpf_sock, protocol):
6789 	case offsetof(struct bpf_sock, src_port):
6790 	case bpf_ctx_range(struct bpf_sock, src_ip4):
6791 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6792 	case bpf_ctx_range(struct bpf_sock, dst_ip4):
6793 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
6794 		bpf_ctx_record_field_size(info, size_default);
6795 		return bpf_ctx_narrow_access_ok(off, size, size_default);
6796 	case bpf_ctx_range(struct bpf_sock, dst_port):
6797 		field_size = size == size_default ?
6798 			size_default : sizeof_field(struct bpf_sock, dst_port);
6799 		bpf_ctx_record_field_size(info, field_size);
6800 		return bpf_ctx_narrow_access_ok(off, size, field_size);
6801 	case offsetofend(struct bpf_sock, dst_port) ...
6802 	     offsetof(struct bpf_sock, dst_ip4) - 1:
6803 		return false;
6804 	}
6805 
6806 	return size == size_default;
6807 }
6808 
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)6809 static bool sock_filter_is_valid_access(int off, int size,
6810 					enum bpf_access_type type,
6811 					const struct bpf_prog *prog,
6812 					struct bpf_insn_access_aux *info)
6813 {
6814 	if (!bpf_sock_is_valid_access(off, size, type, info))
6815 		return false;
6816 	return __sock_filter_check_attach_type(off, type,
6817 					       prog->expected_attach_type);
6818 }
6819 
bpf_noop_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)6820 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
6821 			     const struct bpf_prog *prog)
6822 {
6823 	/* Neither direct read nor direct write requires any preliminary
6824 	 * action.
6825 	 */
6826 	return 0;
6827 }
6828 
bpf_unclone_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog,int drop_verdict)6829 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
6830 				const struct bpf_prog *prog, int drop_verdict)
6831 {
6832 	struct bpf_insn *insn = insn_buf;
6833 
6834 	if (!direct_write)
6835 		return 0;
6836 
6837 	/* if (!skb->cloned)
6838 	 *       goto start;
6839 	 *
6840 	 * (Fast-path, otherwise approximation that we might be
6841 	 *  a clone, do the rest in helper.)
6842 	 */
6843 	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
6844 	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
6845 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
6846 
6847 	/* ret = bpf_skb_pull_data(skb, 0); */
6848 	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
6849 	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
6850 	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
6851 			       BPF_FUNC_skb_pull_data);
6852 	/* if (!ret)
6853 	 *      goto restore;
6854 	 * return TC_ACT_SHOT;
6855 	 */
6856 	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
6857 	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
6858 	*insn++ = BPF_EXIT_INSN();
6859 
6860 	/* restore: */
6861 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
6862 	/* start: */
6863 	*insn++ = prog->insnsi[0];
6864 
6865 	return insn - insn_buf;
6866 }
6867 
bpf_gen_ld_abs(const struct bpf_insn * orig,struct bpf_insn * insn_buf)6868 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
6869 			  struct bpf_insn *insn_buf)
6870 {
6871 	bool indirect = BPF_MODE(orig->code) == BPF_IND;
6872 	struct bpf_insn *insn = insn_buf;
6873 
6874 	if (!indirect) {
6875 		*insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
6876 	} else {
6877 		*insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
6878 		if (orig->imm)
6879 			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
6880 	}
6881 	/* We're guaranteed here that CTX is in R6. */
6882 	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
6883 
6884 	switch (BPF_SIZE(orig->code)) {
6885 	case BPF_B:
6886 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
6887 		break;
6888 	case BPF_H:
6889 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
6890 		break;
6891 	case BPF_W:
6892 		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
6893 		break;
6894 	}
6895 
6896 	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
6897 	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
6898 	*insn++ = BPF_EXIT_INSN();
6899 
6900 	return insn - insn_buf;
6901 }
6902 
tc_cls_act_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)6903 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
6904 			       const struct bpf_prog *prog)
6905 {
6906 	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
6907 }
6908 
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)6909 static bool tc_cls_act_is_valid_access(int off, int size,
6910 				       enum bpf_access_type type,
6911 				       const struct bpf_prog *prog,
6912 				       struct bpf_insn_access_aux *info)
6913 {
6914 	if (type == BPF_WRITE) {
6915 		switch (off) {
6916 		case bpf_ctx_range(struct __sk_buff, mark):
6917 		case bpf_ctx_range(struct __sk_buff, tc_index):
6918 		case bpf_ctx_range(struct __sk_buff, priority):
6919 		case bpf_ctx_range(struct __sk_buff, tc_classid):
6920 		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6921 		case bpf_ctx_range(struct __sk_buff, tstamp):
6922 		case bpf_ctx_range(struct __sk_buff, queue_mapping):
6923 			break;
6924 		default:
6925 			return false;
6926 		}
6927 	}
6928 
6929 	switch (off) {
6930 	case bpf_ctx_range(struct __sk_buff, data):
6931 		info->reg_type = PTR_TO_PACKET;
6932 		break;
6933 	case bpf_ctx_range(struct __sk_buff, data_meta):
6934 		info->reg_type = PTR_TO_PACKET_META;
6935 		break;
6936 	case bpf_ctx_range(struct __sk_buff, data_end):
6937 		info->reg_type = PTR_TO_PACKET_END;
6938 		break;
6939 	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6940 		return false;
6941 	}
6942 
6943 	return bpf_skb_is_valid_access(off, size, type, prog, info);
6944 }
6945 
__is_valid_xdp_access(int off,int size)6946 static bool __is_valid_xdp_access(int off, int size)
6947 {
6948 	if (off < 0 || off >= sizeof(struct xdp_md))
6949 		return false;
6950 	if (off % size != 0)
6951 		return false;
6952 	if (size != sizeof(__u32))
6953 		return false;
6954 
6955 	return true;
6956 }
6957 
xdp_is_valid_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)6958 static bool xdp_is_valid_access(int off, int size,
6959 				enum bpf_access_type type,
6960 				const struct bpf_prog *prog,
6961 				struct bpf_insn_access_aux *info)
6962 {
6963 	if (type == BPF_WRITE) {
6964 		if (bpf_prog_is_dev_bound(prog->aux)) {
6965 			switch (off) {
6966 			case offsetof(struct xdp_md, rx_queue_index):
6967 				return __is_valid_xdp_access(off, size);
6968 			}
6969 		}
6970 		return false;
6971 	}
6972 
6973 	switch (off) {
6974 	case offsetof(struct xdp_md, data):
6975 		info->reg_type = PTR_TO_PACKET;
6976 		break;
6977 	case offsetof(struct xdp_md, data_meta):
6978 		info->reg_type = PTR_TO_PACKET_META;
6979 		break;
6980 	case offsetof(struct xdp_md, data_end):
6981 		info->reg_type = PTR_TO_PACKET_END;
6982 		break;
6983 	}
6984 
6985 	return __is_valid_xdp_access(off, size);
6986 }
6987 
bpf_warn_invalid_xdp_action(u32 act)6988 void bpf_warn_invalid_xdp_action(u32 act)
6989 {
6990 	const u32 act_max = XDP_REDIRECT;
6991 
6992 	pr_warn_once("%s XDP return value %u, expect packet loss!\n",
6993 		     act > act_max ? "Illegal" : "Driver unsupported",
6994 		     act);
6995 }
6996 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
6997 
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)6998 static bool sock_addr_is_valid_access(int off, int size,
6999 				      enum bpf_access_type type,
7000 				      const struct bpf_prog *prog,
7001 				      struct bpf_insn_access_aux *info)
7002 {
7003 	const int size_default = sizeof(__u32);
7004 
7005 	if (off < 0 || off >= sizeof(struct bpf_sock_addr))
7006 		return false;
7007 	if (off % size != 0)
7008 		return false;
7009 
7010 	/* Disallow access to IPv6 fields from IPv4 contex and vise
7011 	 * versa.
7012 	 */
7013 	switch (off) {
7014 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
7015 		switch (prog->expected_attach_type) {
7016 		case BPF_CGROUP_INET4_BIND:
7017 		case BPF_CGROUP_INET4_CONNECT:
7018 		case BPF_CGROUP_UDP4_SENDMSG:
7019 		case BPF_CGROUP_UDP4_RECVMSG:
7020 			break;
7021 		default:
7022 			return false;
7023 		}
7024 		break;
7025 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7026 		switch (prog->expected_attach_type) {
7027 		case BPF_CGROUP_INET6_BIND:
7028 		case BPF_CGROUP_INET6_CONNECT:
7029 		case BPF_CGROUP_UDP6_SENDMSG:
7030 		case BPF_CGROUP_UDP6_RECVMSG:
7031 			break;
7032 		default:
7033 			return false;
7034 		}
7035 		break;
7036 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
7037 		switch (prog->expected_attach_type) {
7038 		case BPF_CGROUP_UDP4_SENDMSG:
7039 			break;
7040 		default:
7041 			return false;
7042 		}
7043 		break;
7044 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7045 				msg_src_ip6[3]):
7046 		switch (prog->expected_attach_type) {
7047 		case BPF_CGROUP_UDP6_SENDMSG:
7048 			break;
7049 		default:
7050 			return false;
7051 		}
7052 		break;
7053 	}
7054 
7055 	switch (off) {
7056 	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
7057 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7058 	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
7059 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7060 				msg_src_ip6[3]):
7061 		if (type == BPF_READ) {
7062 			bpf_ctx_record_field_size(info, size_default);
7063 
7064 			if (bpf_ctx_wide_access_ok(off, size,
7065 						   struct bpf_sock_addr,
7066 						   user_ip6))
7067 				return true;
7068 
7069 			if (bpf_ctx_wide_access_ok(off, size,
7070 						   struct bpf_sock_addr,
7071 						   msg_src_ip6))
7072 				return true;
7073 
7074 			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
7075 				return false;
7076 		} else {
7077 			if (bpf_ctx_wide_access_ok(off, size,
7078 						   struct bpf_sock_addr,
7079 						   user_ip6))
7080 				return true;
7081 
7082 			if (bpf_ctx_wide_access_ok(off, size,
7083 						   struct bpf_sock_addr,
7084 						   msg_src_ip6))
7085 				return true;
7086 
7087 			if (size != size_default)
7088 				return false;
7089 		}
7090 		break;
7091 	case bpf_ctx_range(struct bpf_sock_addr, user_port):
7092 		if (size != size_default)
7093 			return false;
7094 		break;
7095 	case offsetof(struct bpf_sock_addr, sk):
7096 		if (type != BPF_READ)
7097 			return false;
7098 		if (size != sizeof(__u64))
7099 			return false;
7100 		info->reg_type = PTR_TO_SOCKET;
7101 		break;
7102 	default:
7103 		if (type == BPF_READ) {
7104 			if (size != size_default)
7105 				return false;
7106 		} else {
7107 			return false;
7108 		}
7109 	}
7110 
7111 	return true;
7112 }
7113 
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)7114 static bool sock_ops_is_valid_access(int off, int size,
7115 				     enum bpf_access_type type,
7116 				     const struct bpf_prog *prog,
7117 				     struct bpf_insn_access_aux *info)
7118 {
7119 	const int size_default = sizeof(__u32);
7120 
7121 	if (off < 0 || off >= sizeof(struct bpf_sock_ops))
7122 		return false;
7123 
7124 	/* The verifier guarantees that size > 0. */
7125 	if (off % size != 0)
7126 		return false;
7127 
7128 	if (type == BPF_WRITE) {
7129 		switch (off) {
7130 		case offsetof(struct bpf_sock_ops, reply):
7131 		case offsetof(struct bpf_sock_ops, sk_txhash):
7132 			if (size != size_default)
7133 				return false;
7134 			break;
7135 		default:
7136 			return false;
7137 		}
7138 	} else {
7139 		switch (off) {
7140 		case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
7141 					bytes_acked):
7142 			if (size != sizeof(__u64))
7143 				return false;
7144 			break;
7145 		case offsetof(struct bpf_sock_ops, sk):
7146 			if (size != sizeof(__u64))
7147 				return false;
7148 			info->reg_type = PTR_TO_SOCKET_OR_NULL;
7149 			break;
7150 		default:
7151 			if (size != size_default)
7152 				return false;
7153 			break;
7154 		}
7155 	}
7156 
7157 	return true;
7158 }
7159 
sk_skb_prologue(struct bpf_insn * insn_buf,bool direct_write,const struct bpf_prog * prog)7160 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
7161 			   const struct bpf_prog *prog)
7162 {
7163 	return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
7164 }
7165 
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)7166 static bool sk_skb_is_valid_access(int off, int size,
7167 				   enum bpf_access_type type,
7168 				   const struct bpf_prog *prog,
7169 				   struct bpf_insn_access_aux *info)
7170 {
7171 	switch (off) {
7172 	case bpf_ctx_range(struct __sk_buff, tc_classid):
7173 	case bpf_ctx_range(struct __sk_buff, data_meta):
7174 	case bpf_ctx_range(struct __sk_buff, tstamp):
7175 	case bpf_ctx_range(struct __sk_buff, wire_len):
7176 		return false;
7177 	}
7178 
7179 	if (type == BPF_WRITE) {
7180 		switch (off) {
7181 		case bpf_ctx_range(struct __sk_buff, tc_index):
7182 		case bpf_ctx_range(struct __sk_buff, priority):
7183 			break;
7184 		default:
7185 			return false;
7186 		}
7187 	}
7188 
7189 	switch (off) {
7190 	case bpf_ctx_range(struct __sk_buff, mark):
7191 		return false;
7192 	case bpf_ctx_range(struct __sk_buff, data):
7193 		info->reg_type = PTR_TO_PACKET;
7194 		break;
7195 	case bpf_ctx_range(struct __sk_buff, data_end):
7196 		info->reg_type = PTR_TO_PACKET_END;
7197 		break;
7198 	}
7199 
7200 	return bpf_skb_is_valid_access(off, size, type, prog, info);
7201 }
7202 
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)7203 static bool sk_msg_is_valid_access(int off, int size,
7204 				   enum bpf_access_type type,
7205 				   const struct bpf_prog *prog,
7206 				   struct bpf_insn_access_aux *info)
7207 {
7208 	if (type == BPF_WRITE)
7209 		return false;
7210 
7211 	if (off % size != 0)
7212 		return false;
7213 
7214 	switch (off) {
7215 	case offsetof(struct sk_msg_md, data):
7216 		info->reg_type = PTR_TO_PACKET;
7217 		if (size != sizeof(__u64))
7218 			return false;
7219 		break;
7220 	case offsetof(struct sk_msg_md, data_end):
7221 		info->reg_type = PTR_TO_PACKET_END;
7222 		if (size != sizeof(__u64))
7223 			return false;
7224 		break;
7225 	case bpf_ctx_range(struct sk_msg_md, family):
7226 	case bpf_ctx_range(struct sk_msg_md, remote_ip4):
7227 	case bpf_ctx_range(struct sk_msg_md, local_ip4):
7228 	case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
7229 	case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
7230 	case bpf_ctx_range(struct sk_msg_md, remote_port):
7231 	case bpf_ctx_range(struct sk_msg_md, local_port):
7232 	case bpf_ctx_range(struct sk_msg_md, size):
7233 		if (size != sizeof(__u32))
7234 			return false;
7235 		break;
7236 	default:
7237 		return false;
7238 	}
7239 	return true;
7240 }
7241 
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)7242 static bool flow_dissector_is_valid_access(int off, int size,
7243 					   enum bpf_access_type type,
7244 					   const struct bpf_prog *prog,
7245 					   struct bpf_insn_access_aux *info)
7246 {
7247 	const int size_default = sizeof(__u32);
7248 
7249 	if (off < 0 || off >= sizeof(struct __sk_buff))
7250 		return false;
7251 
7252 	if (type == BPF_WRITE)
7253 		return false;
7254 
7255 	switch (off) {
7256 	case bpf_ctx_range(struct __sk_buff, data):
7257 		if (size != size_default)
7258 			return false;
7259 		info->reg_type = PTR_TO_PACKET;
7260 		return true;
7261 	case bpf_ctx_range(struct __sk_buff, data_end):
7262 		if (size != size_default)
7263 			return false;
7264 		info->reg_type = PTR_TO_PACKET_END;
7265 		return true;
7266 	case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
7267 		if (size != sizeof(__u64))
7268 			return false;
7269 		info->reg_type = PTR_TO_FLOW_KEYS;
7270 		return true;
7271 	default:
7272 		return false;
7273 	}
7274 }
7275 
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)7276 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
7277 					     const struct bpf_insn *si,
7278 					     struct bpf_insn *insn_buf,
7279 					     struct bpf_prog *prog,
7280 					     u32 *target_size)
7281 
7282 {
7283 	struct bpf_insn *insn = insn_buf;
7284 
7285 	switch (si->off) {
7286 	case offsetof(struct __sk_buff, data):
7287 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
7288 				      si->dst_reg, si->src_reg,
7289 				      offsetof(struct bpf_flow_dissector, data));
7290 		break;
7291 
7292 	case offsetof(struct __sk_buff, data_end):
7293 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
7294 				      si->dst_reg, si->src_reg,
7295 				      offsetof(struct bpf_flow_dissector, data_end));
7296 		break;
7297 
7298 	case offsetof(struct __sk_buff, flow_keys):
7299 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
7300 				      si->dst_reg, si->src_reg,
7301 				      offsetof(struct bpf_flow_dissector, flow_keys));
7302 		break;
7303 	}
7304 
7305 	return insn - insn_buf;
7306 }
7307 
bpf_convert_shinfo_access(const struct bpf_insn * si,struct bpf_insn * insn)7308 static struct bpf_insn *bpf_convert_shinfo_access(const struct bpf_insn *si,
7309 						  struct bpf_insn *insn)
7310 {
7311 	/* si->dst_reg = skb_shinfo(SKB); */
7312 #ifdef NET_SKBUFF_DATA_USES_OFFSET
7313 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7314 			      BPF_REG_AX, si->src_reg,
7315 			      offsetof(struct sk_buff, end));
7316 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
7317 			      si->dst_reg, si->src_reg,
7318 			      offsetof(struct sk_buff, head));
7319 	*insn++ = BPF_ALU64_REG(BPF_ADD, si->dst_reg, BPF_REG_AX);
7320 #else
7321 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7322 			      si->dst_reg, si->src_reg,
7323 			      offsetof(struct sk_buff, end));
7324 #endif
7325 
7326 	return insn;
7327 }
7328 
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)7329 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
7330 				  const struct bpf_insn *si,
7331 				  struct bpf_insn *insn_buf,
7332 				  struct bpf_prog *prog, u32 *target_size)
7333 {
7334 	struct bpf_insn *insn = insn_buf;
7335 	int off;
7336 
7337 	switch (si->off) {
7338 	case offsetof(struct __sk_buff, len):
7339 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7340 				      bpf_target_off(struct sk_buff, len, 4,
7341 						     target_size));
7342 		break;
7343 
7344 	case offsetof(struct __sk_buff, protocol):
7345 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7346 				      bpf_target_off(struct sk_buff, protocol, 2,
7347 						     target_size));
7348 		break;
7349 
7350 	case offsetof(struct __sk_buff, vlan_proto):
7351 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7352 				      bpf_target_off(struct sk_buff, vlan_proto, 2,
7353 						     target_size));
7354 		break;
7355 
7356 	case offsetof(struct __sk_buff, priority):
7357 		if (type == BPF_WRITE)
7358 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7359 					      bpf_target_off(struct sk_buff, priority, 4,
7360 							     target_size));
7361 		else
7362 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7363 					      bpf_target_off(struct sk_buff, priority, 4,
7364 							     target_size));
7365 		break;
7366 
7367 	case offsetof(struct __sk_buff, ingress_ifindex):
7368 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7369 				      bpf_target_off(struct sk_buff, skb_iif, 4,
7370 						     target_size));
7371 		break;
7372 
7373 	case offsetof(struct __sk_buff, ifindex):
7374 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7375 				      si->dst_reg, si->src_reg,
7376 				      offsetof(struct sk_buff, dev));
7377 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
7378 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7379 				      bpf_target_off(struct net_device, ifindex, 4,
7380 						     target_size));
7381 		break;
7382 
7383 	case offsetof(struct __sk_buff, hash):
7384 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7385 				      bpf_target_off(struct sk_buff, hash, 4,
7386 						     target_size));
7387 		break;
7388 
7389 	case offsetof(struct __sk_buff, mark):
7390 		if (type == BPF_WRITE)
7391 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7392 					      bpf_target_off(struct sk_buff, mark, 4,
7393 							     target_size));
7394 		else
7395 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7396 					      bpf_target_off(struct sk_buff, mark, 4,
7397 							     target_size));
7398 		break;
7399 
7400 	case offsetof(struct __sk_buff, pkt_type):
7401 		*target_size = 1;
7402 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7403 				      PKT_TYPE_OFFSET());
7404 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
7405 #ifdef __BIG_ENDIAN_BITFIELD
7406 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
7407 #endif
7408 		break;
7409 
7410 	case offsetof(struct __sk_buff, queue_mapping):
7411 		if (type == BPF_WRITE) {
7412 			*insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
7413 			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7414 					      bpf_target_off(struct sk_buff,
7415 							     queue_mapping,
7416 							     2, target_size));
7417 		} else {
7418 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7419 					      bpf_target_off(struct sk_buff,
7420 							     queue_mapping,
7421 							     2, target_size));
7422 		}
7423 		break;
7424 
7425 	case offsetof(struct __sk_buff, vlan_present):
7426 		*target_size = 1;
7427 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7428 				      PKT_VLAN_PRESENT_OFFSET());
7429 		if (PKT_VLAN_PRESENT_BIT)
7430 			*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT);
7431 		if (PKT_VLAN_PRESENT_BIT < 7)
7432 			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
7433 		break;
7434 
7435 	case offsetof(struct __sk_buff, vlan_tci):
7436 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7437 				      bpf_target_off(struct sk_buff, vlan_tci, 2,
7438 						     target_size));
7439 		break;
7440 
7441 	case offsetof(struct __sk_buff, cb[0]) ...
7442 	     offsetofend(struct __sk_buff, cb[4]) - 1:
7443 		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
7444 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
7445 			      offsetof(struct qdisc_skb_cb, data)) %
7446 			     sizeof(__u64));
7447 
7448 		prog->cb_access = 1;
7449 		off  = si->off;
7450 		off -= offsetof(struct __sk_buff, cb[0]);
7451 		off += offsetof(struct sk_buff, cb);
7452 		off += offsetof(struct qdisc_skb_cb, data);
7453 		if (type == BPF_WRITE)
7454 			*insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
7455 					      si->src_reg, off);
7456 		else
7457 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
7458 					      si->src_reg, off);
7459 		break;
7460 
7461 	case offsetof(struct __sk_buff, tc_classid):
7462 		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
7463 
7464 		off  = si->off;
7465 		off -= offsetof(struct __sk_buff, tc_classid);
7466 		off += offsetof(struct sk_buff, cb);
7467 		off += offsetof(struct qdisc_skb_cb, tc_classid);
7468 		*target_size = 2;
7469 		if (type == BPF_WRITE)
7470 			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
7471 					      si->src_reg, off);
7472 		else
7473 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
7474 					      si->src_reg, off);
7475 		break;
7476 
7477 	case offsetof(struct __sk_buff, data):
7478 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
7479 				      si->dst_reg, si->src_reg,
7480 				      offsetof(struct sk_buff, data));
7481 		break;
7482 
7483 	case offsetof(struct __sk_buff, data_meta):
7484 		off  = si->off;
7485 		off -= offsetof(struct __sk_buff, data_meta);
7486 		off += offsetof(struct sk_buff, cb);
7487 		off += offsetof(struct bpf_skb_data_end, data_meta);
7488 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7489 				      si->src_reg, off);
7490 		break;
7491 
7492 	case offsetof(struct __sk_buff, data_end):
7493 		off  = si->off;
7494 		off -= offsetof(struct __sk_buff, data_end);
7495 		off += offsetof(struct sk_buff, cb);
7496 		off += offsetof(struct bpf_skb_data_end, data_end);
7497 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7498 				      si->src_reg, off);
7499 		break;
7500 
7501 	case offsetof(struct __sk_buff, tc_index):
7502 #ifdef CONFIG_NET_SCHED
7503 		if (type == BPF_WRITE)
7504 			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7505 					      bpf_target_off(struct sk_buff, tc_index, 2,
7506 							     target_size));
7507 		else
7508 			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7509 					      bpf_target_off(struct sk_buff, tc_index, 2,
7510 							     target_size));
7511 #else
7512 		*target_size = 2;
7513 		if (type == BPF_WRITE)
7514 			*insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
7515 		else
7516 			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7517 #endif
7518 		break;
7519 
7520 	case offsetof(struct __sk_buff, napi_id):
7521 #if defined(CONFIG_NET_RX_BUSY_POLL)
7522 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7523 				      bpf_target_off(struct sk_buff, napi_id, 4,
7524 						     target_size));
7525 		*insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
7526 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7527 #else
7528 		*target_size = 4;
7529 		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7530 #endif
7531 		break;
7532 	case offsetof(struct __sk_buff, family):
7533 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7534 
7535 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7536 				      si->dst_reg, si->src_reg,
7537 				      offsetof(struct sk_buff, sk));
7538 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7539 				      bpf_target_off(struct sock_common,
7540 						     skc_family,
7541 						     2, target_size));
7542 		break;
7543 	case offsetof(struct __sk_buff, remote_ip4):
7544 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7545 
7546 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7547 				      si->dst_reg, si->src_reg,
7548 				      offsetof(struct sk_buff, sk));
7549 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7550 				      bpf_target_off(struct sock_common,
7551 						     skc_daddr,
7552 						     4, target_size));
7553 		break;
7554 	case offsetof(struct __sk_buff, local_ip4):
7555 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7556 					  skc_rcv_saddr) != 4);
7557 
7558 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7559 				      si->dst_reg, si->src_reg,
7560 				      offsetof(struct sk_buff, sk));
7561 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7562 				      bpf_target_off(struct sock_common,
7563 						     skc_rcv_saddr,
7564 						     4, target_size));
7565 		break;
7566 	case offsetof(struct __sk_buff, remote_ip6[0]) ...
7567 	     offsetof(struct __sk_buff, remote_ip6[3]):
7568 #if IS_ENABLED(CONFIG_IPV6)
7569 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7570 					  skc_v6_daddr.s6_addr32[0]) != 4);
7571 
7572 		off = si->off;
7573 		off -= offsetof(struct __sk_buff, remote_ip6[0]);
7574 
7575 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7576 				      si->dst_reg, si->src_reg,
7577 				      offsetof(struct sk_buff, sk));
7578 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7579 				      offsetof(struct sock_common,
7580 					       skc_v6_daddr.s6_addr32[0]) +
7581 				      off);
7582 #else
7583 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7584 #endif
7585 		break;
7586 	case offsetof(struct __sk_buff, local_ip6[0]) ...
7587 	     offsetof(struct __sk_buff, local_ip6[3]):
7588 #if IS_ENABLED(CONFIG_IPV6)
7589 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7590 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7591 
7592 		off = si->off;
7593 		off -= offsetof(struct __sk_buff, local_ip6[0]);
7594 
7595 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7596 				      si->dst_reg, si->src_reg,
7597 				      offsetof(struct sk_buff, sk));
7598 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7599 				      offsetof(struct sock_common,
7600 					       skc_v6_rcv_saddr.s6_addr32[0]) +
7601 				      off);
7602 #else
7603 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7604 #endif
7605 		break;
7606 
7607 	case offsetof(struct __sk_buff, remote_port):
7608 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7609 
7610 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7611 				      si->dst_reg, si->src_reg,
7612 				      offsetof(struct sk_buff, sk));
7613 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7614 				      bpf_target_off(struct sock_common,
7615 						     skc_dport,
7616 						     2, target_size));
7617 #ifndef __BIG_ENDIAN_BITFIELD
7618 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7619 #endif
7620 		break;
7621 
7622 	case offsetof(struct __sk_buff, local_port):
7623 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7624 
7625 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7626 				      si->dst_reg, si->src_reg,
7627 				      offsetof(struct sk_buff, sk));
7628 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7629 				      bpf_target_off(struct sock_common,
7630 						     skc_num, 2, target_size));
7631 		break;
7632 
7633 	case offsetof(struct __sk_buff, tstamp):
7634 		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tstamp) != 8);
7635 
7636 		if (type == BPF_WRITE)
7637 			*insn++ = BPF_STX_MEM(BPF_DW,
7638 					      si->dst_reg, si->src_reg,
7639 					      bpf_target_off(struct sk_buff,
7640 							     tstamp, 8,
7641 							     target_size));
7642 		else
7643 			*insn++ = BPF_LDX_MEM(BPF_DW,
7644 					      si->dst_reg, si->src_reg,
7645 					      bpf_target_off(struct sk_buff,
7646 							     tstamp, 8,
7647 							     target_size));
7648 		break;
7649 
7650 	case offsetof(struct __sk_buff, gso_segs):
7651 		insn = bpf_convert_shinfo_access(si, insn);
7652 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
7653 				      si->dst_reg, si->dst_reg,
7654 				      bpf_target_off(struct skb_shared_info,
7655 						     gso_segs, 2,
7656 						     target_size));
7657 		break;
7658 	case offsetof(struct __sk_buff, gso_size):
7659 		insn = bpf_convert_shinfo_access(si, insn);
7660 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_size),
7661 				      si->dst_reg, si->dst_reg,
7662 				      bpf_target_off(struct skb_shared_info,
7663 						     gso_size, 2,
7664 						     target_size));
7665 		break;
7666 	case offsetof(struct __sk_buff, wire_len):
7667 		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, pkt_len) != 4);
7668 
7669 		off = si->off;
7670 		off -= offsetof(struct __sk_buff, wire_len);
7671 		off += offsetof(struct sk_buff, cb);
7672 		off += offsetof(struct qdisc_skb_cb, pkt_len);
7673 		*target_size = 4;
7674 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
7675 		break;
7676 
7677 	case offsetof(struct __sk_buff, sk):
7678 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7679 				      si->dst_reg, si->src_reg,
7680 				      offsetof(struct sk_buff, sk));
7681 		break;
7682 	}
7683 
7684 	return insn - insn_buf;
7685 }
7686 
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)7687 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
7688 				const struct bpf_insn *si,
7689 				struct bpf_insn *insn_buf,
7690 				struct bpf_prog *prog, u32 *target_size)
7691 {
7692 	struct bpf_insn *insn = insn_buf;
7693 	int off;
7694 
7695 	switch (si->off) {
7696 	case offsetof(struct bpf_sock, bound_dev_if):
7697 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
7698 
7699 		if (type == BPF_WRITE)
7700 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7701 					offsetof(struct sock, sk_bound_dev_if));
7702 		else
7703 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7704 				      offsetof(struct sock, sk_bound_dev_if));
7705 		break;
7706 
7707 	case offsetof(struct bpf_sock, mark):
7708 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);
7709 
7710 		if (type == BPF_WRITE)
7711 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7712 					offsetof(struct sock, sk_mark));
7713 		else
7714 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7715 				      offsetof(struct sock, sk_mark));
7716 		break;
7717 
7718 	case offsetof(struct bpf_sock, priority):
7719 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);
7720 
7721 		if (type == BPF_WRITE)
7722 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7723 					offsetof(struct sock, sk_priority));
7724 		else
7725 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7726 				      offsetof(struct sock, sk_priority));
7727 		break;
7728 
7729 	case offsetof(struct bpf_sock, family):
7730 		*insn++ = BPF_LDX_MEM(
7731 			BPF_FIELD_SIZEOF(struct sock_common, skc_family),
7732 			si->dst_reg, si->src_reg,
7733 			bpf_target_off(struct sock_common,
7734 				       skc_family,
7735 				       FIELD_SIZEOF(struct sock_common,
7736 						    skc_family),
7737 				       target_size));
7738 		break;
7739 
7740 	case offsetof(struct bpf_sock, type):
7741 		BUILD_BUG_ON(HWEIGHT32(SK_FL_TYPE_MASK) != BITS_PER_BYTE * 2);
7742 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7743 				      offsetof(struct sock, __sk_flags_offset));
7744 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7745 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7746 		*target_size = 2;
7747 		break;
7748 
7749 	case offsetof(struct bpf_sock, protocol):
7750 		BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7751 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7752 				      offsetof(struct sock, __sk_flags_offset));
7753 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7754 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
7755 		*target_size = 1;
7756 		break;
7757 
7758 	case offsetof(struct bpf_sock, src_ip4):
7759 		*insn++ = BPF_LDX_MEM(
7760 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7761 			bpf_target_off(struct sock_common, skc_rcv_saddr,
7762 				       FIELD_SIZEOF(struct sock_common,
7763 						    skc_rcv_saddr),
7764 				       target_size));
7765 		break;
7766 
7767 	case offsetof(struct bpf_sock, dst_ip4):
7768 		*insn++ = BPF_LDX_MEM(
7769 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7770 			bpf_target_off(struct sock_common, skc_daddr,
7771 				       FIELD_SIZEOF(struct sock_common,
7772 						    skc_daddr),
7773 				       target_size));
7774 		break;
7775 
7776 	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
7777 #if IS_ENABLED(CONFIG_IPV6)
7778 		off = si->off;
7779 		off -= offsetof(struct bpf_sock, src_ip6[0]);
7780 		*insn++ = BPF_LDX_MEM(
7781 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7782 			bpf_target_off(
7783 				struct sock_common,
7784 				skc_v6_rcv_saddr.s6_addr32[0],
7785 				FIELD_SIZEOF(struct sock_common,
7786 					     skc_v6_rcv_saddr.s6_addr32[0]),
7787 				target_size) + off);
7788 #else
7789 		(void)off;
7790 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7791 #endif
7792 		break;
7793 
7794 	case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
7795 #if IS_ENABLED(CONFIG_IPV6)
7796 		off = si->off;
7797 		off -= offsetof(struct bpf_sock, dst_ip6[0]);
7798 		*insn++ = BPF_LDX_MEM(
7799 			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7800 			bpf_target_off(struct sock_common,
7801 				       skc_v6_daddr.s6_addr32[0],
7802 				       FIELD_SIZEOF(struct sock_common,
7803 						    skc_v6_daddr.s6_addr32[0]),
7804 				       target_size) + off);
7805 #else
7806 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7807 		*target_size = 4;
7808 #endif
7809 		break;
7810 
7811 	case offsetof(struct bpf_sock, src_port):
7812 		*insn++ = BPF_LDX_MEM(
7813 			BPF_FIELD_SIZEOF(struct sock_common, skc_num),
7814 			si->dst_reg, si->src_reg,
7815 			bpf_target_off(struct sock_common, skc_num,
7816 				       FIELD_SIZEOF(struct sock_common,
7817 						    skc_num),
7818 				       target_size));
7819 		break;
7820 
7821 	case offsetof(struct bpf_sock, dst_port):
7822 		*insn++ = BPF_LDX_MEM(
7823 			BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
7824 			si->dst_reg, si->src_reg,
7825 			bpf_target_off(struct sock_common, skc_dport,
7826 				       FIELD_SIZEOF(struct sock_common,
7827 						    skc_dport),
7828 				       target_size));
7829 		break;
7830 
7831 	case offsetof(struct bpf_sock, state):
7832 		*insn++ = BPF_LDX_MEM(
7833 			BPF_FIELD_SIZEOF(struct sock_common, skc_state),
7834 			si->dst_reg, si->src_reg,
7835 			bpf_target_off(struct sock_common, skc_state,
7836 				       FIELD_SIZEOF(struct sock_common,
7837 						    skc_state),
7838 				       target_size));
7839 		break;
7840 	}
7841 
7842 	return insn - insn_buf;
7843 }
7844 
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)7845 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
7846 					 const struct bpf_insn *si,
7847 					 struct bpf_insn *insn_buf,
7848 					 struct bpf_prog *prog, u32 *target_size)
7849 {
7850 	struct bpf_insn *insn = insn_buf;
7851 
7852 	switch (si->off) {
7853 	case offsetof(struct __sk_buff, ifindex):
7854 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7855 				      si->dst_reg, si->src_reg,
7856 				      offsetof(struct sk_buff, dev));
7857 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7858 				      bpf_target_off(struct net_device, ifindex, 4,
7859 						     target_size));
7860 		break;
7861 	default:
7862 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
7863 					      target_size);
7864 	}
7865 
7866 	return insn - insn_buf;
7867 }
7868 
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)7869 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
7870 				  const struct bpf_insn *si,
7871 				  struct bpf_insn *insn_buf,
7872 				  struct bpf_prog *prog, u32 *target_size)
7873 {
7874 	struct bpf_insn *insn = insn_buf;
7875 
7876 	switch (si->off) {
7877 	case offsetof(struct xdp_md, data):
7878 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
7879 				      si->dst_reg, si->src_reg,
7880 				      offsetof(struct xdp_buff, data));
7881 		break;
7882 	case offsetof(struct xdp_md, data_meta):
7883 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
7884 				      si->dst_reg, si->src_reg,
7885 				      offsetof(struct xdp_buff, data_meta));
7886 		break;
7887 	case offsetof(struct xdp_md, data_end):
7888 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
7889 				      si->dst_reg, si->src_reg,
7890 				      offsetof(struct xdp_buff, data_end));
7891 		break;
7892 	case offsetof(struct xdp_md, ingress_ifindex):
7893 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7894 				      si->dst_reg, si->src_reg,
7895 				      offsetof(struct xdp_buff, rxq));
7896 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
7897 				      si->dst_reg, si->dst_reg,
7898 				      offsetof(struct xdp_rxq_info, dev));
7899 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7900 				      offsetof(struct net_device, ifindex));
7901 		break;
7902 	case offsetof(struct xdp_md, rx_queue_index):
7903 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7904 				      si->dst_reg, si->src_reg,
7905 				      offsetof(struct xdp_buff, rxq));
7906 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7907 				      offsetof(struct xdp_rxq_info,
7908 					       queue_index));
7909 		break;
7910 	}
7911 
7912 	return insn - insn_buf;
7913 }
7914 
7915 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
7916  * context Structure, F is Field in context structure that contains a pointer
7917  * to Nested Structure of type NS that has the field NF.
7918  *
7919  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
7920  * sure that SIZE is not greater than actual size of S.F.NF.
7921  *
7922  * If offset OFF is provided, the load happens from that offset relative to
7923  * offset of NF.
7924  */
7925 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)	       \
7926 	do {								       \
7927 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
7928 				      si->src_reg, offsetof(S, F));	       \
7929 		*insn++ = BPF_LDX_MEM(					       \
7930 			SIZE, si->dst_reg, si->dst_reg,			       \
7931 			bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),	       \
7932 				       target_size)			       \
7933 				+ OFF);					       \
7934 	} while (0)
7935 
7936 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)			       \
7937 	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,		       \
7938 					     BPF_FIELD_SIZEOF(NS, NF), 0)
7939 
7940 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
7941  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
7942  *
7943  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
7944  * "register" since two registers available in convert_ctx_access are not
7945  * enough: we can't override neither SRC, since it contains value to store, nor
7946  * DST since it contains pointer to context that may be used by later
7947  * instructions. But we need a temporary place to save pointer to nested
7948  * structure whose field we want to store to.
7949  */
7950 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE, OFF, TF)	       \
7951 	do {								       \
7952 		int tmp_reg = BPF_REG_9;				       \
7953 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
7954 			--tmp_reg;					       \
7955 		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
7956 			--tmp_reg;					       \
7957 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,	       \
7958 				      offsetof(S, TF));			       \
7959 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,	       \
7960 				      si->dst_reg, offsetof(S, F));	       \
7961 		*insn++ = BPF_STX_MEM(SIZE, tmp_reg, si->src_reg,	       \
7962 			bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),	       \
7963 				       target_size)			       \
7964 				+ OFF);					       \
7965 		*insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,	       \
7966 				      offsetof(S, TF));			       \
7967 	} while (0)
7968 
7969 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
7970 						      TF)		       \
7971 	do {								       \
7972 		if (type == BPF_WRITE) {				       \
7973 			SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE,   \
7974 							 OFF, TF);	       \
7975 		} else {						       \
7976 			SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(		       \
7977 				S, NS, F, NF, SIZE, OFF);  \
7978 		}							       \
7979 	} while (0)
7980 
7981 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)		       \
7982 	SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(			       \
7983 		S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
7984 
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)7985 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
7986 					const struct bpf_insn *si,
7987 					struct bpf_insn *insn_buf,
7988 					struct bpf_prog *prog, u32 *target_size)
7989 {
7990 	struct bpf_insn *insn = insn_buf;
7991 	int off;
7992 
7993 	switch (si->off) {
7994 	case offsetof(struct bpf_sock_addr, user_family):
7995 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7996 					    struct sockaddr, uaddr, sa_family);
7997 		break;
7998 
7999 	case offsetof(struct bpf_sock_addr, user_ip4):
8000 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8001 			struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
8002 			sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
8003 		break;
8004 
8005 	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
8006 		off = si->off;
8007 		off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
8008 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8009 			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
8010 			sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
8011 			tmp_reg);
8012 		break;
8013 
8014 	case offsetof(struct bpf_sock_addr, user_port):
8015 		/* To get port we need to know sa_family first and then treat
8016 		 * sockaddr as either sockaddr_in or sockaddr_in6.
8017 		 * Though we can simplify since port field has same offset and
8018 		 * size in both structures.
8019 		 * Here we check this invariant and use just one of the
8020 		 * structures if it's true.
8021 		 */
8022 		BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
8023 			     offsetof(struct sockaddr_in6, sin6_port));
8024 		BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
8025 			     FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
8026 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
8027 						     struct sockaddr_in6, uaddr,
8028 						     sin6_port, tmp_reg);
8029 		break;
8030 
8031 	case offsetof(struct bpf_sock_addr, family):
8032 		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
8033 					    struct sock, sk, sk_family);
8034 		break;
8035 
8036 	case offsetof(struct bpf_sock_addr, type):
8037 		SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
8038 			struct bpf_sock_addr_kern, struct sock, sk,
8039 			__sk_flags_offset, BPF_W, 0);
8040 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
8041 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
8042 		break;
8043 
8044 	case offsetof(struct bpf_sock_addr, protocol):
8045 		SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
8046 			struct bpf_sock_addr_kern, struct sock, sk,
8047 			__sk_flags_offset, BPF_W, 0);
8048 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
8049 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
8050 					SK_FL_PROTO_SHIFT);
8051 		break;
8052 
8053 	case offsetof(struct bpf_sock_addr, msg_src_ip4):
8054 		/* Treat t_ctx as struct in_addr for msg_src_ip4. */
8055 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8056 			struct bpf_sock_addr_kern, struct in_addr, t_ctx,
8057 			s_addr, BPF_SIZE(si->code), 0, tmp_reg);
8058 		break;
8059 
8060 	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
8061 				msg_src_ip6[3]):
8062 		off = si->off;
8063 		off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
8064 		/* Treat t_ctx as struct in6_addr for msg_src_ip6. */
8065 		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
8066 			struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
8067 			s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
8068 		break;
8069 	case offsetof(struct bpf_sock_addr, sk):
8070 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_addr_kern, sk),
8071 				      si->dst_reg, si->src_reg,
8072 				      offsetof(struct bpf_sock_addr_kern, sk));
8073 		break;
8074 	}
8075 
8076 	return insn - insn_buf;
8077 }
8078 
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)8079 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
8080 				       const struct bpf_insn *si,
8081 				       struct bpf_insn *insn_buf,
8082 				       struct bpf_prog *prog,
8083 				       u32 *target_size)
8084 {
8085 	struct bpf_insn *insn = insn_buf;
8086 	int off;
8087 
8088 /* Helper macro for adding read access to tcp_sock or sock fields. */
8089 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
8090 	do {								      \
8091 		BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >		      \
8092 			     FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
8093 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
8094 						struct bpf_sock_ops_kern,     \
8095 						is_fullsock),		      \
8096 				      si->dst_reg, si->src_reg,		      \
8097 				      offsetof(struct bpf_sock_ops_kern,      \
8098 					       is_fullsock));		      \
8099 		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);	      \
8100 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
8101 						struct bpf_sock_ops_kern, sk),\
8102 				      si->dst_reg, si->src_reg,		      \
8103 				      offsetof(struct bpf_sock_ops_kern, sk));\
8104 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,		      \
8105 						       OBJ_FIELD),	      \
8106 				      si->dst_reg, si->dst_reg,		      \
8107 				      offsetof(OBJ, OBJ_FIELD));	      \
8108 	} while (0)
8109 
8110 #define SOCK_OPS_GET_SK()							      \
8111 	do {								      \
8112 		int fullsock_reg = si->dst_reg, reg = BPF_REG_9, jmp = 1;     \
8113 		if (si->dst_reg == reg || si->src_reg == reg)		      \
8114 			reg--;						      \
8115 		if (si->dst_reg == reg || si->src_reg == reg)		      \
8116 			reg--;						      \
8117 		if (si->dst_reg == si->src_reg) {			      \
8118 			*insn++ = BPF_STX_MEM(BPF_DW, si->src_reg, reg,	      \
8119 					  offsetof(struct bpf_sock_ops_kern,  \
8120 					  temp));			      \
8121 			fullsock_reg = reg;				      \
8122 			jmp += 2;					      \
8123 		}							      \
8124 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
8125 						struct bpf_sock_ops_kern,     \
8126 						is_fullsock),		      \
8127 				      fullsock_reg, si->src_reg,	      \
8128 				      offsetof(struct bpf_sock_ops_kern,      \
8129 					       is_fullsock));		      \
8130 		*insn++ = BPF_JMP_IMM(BPF_JEQ, fullsock_reg, 0, jmp);	      \
8131 		if (si->dst_reg == si->src_reg)				      \
8132 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
8133 				      offsetof(struct bpf_sock_ops_kern,      \
8134 				      temp));				      \
8135 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
8136 						struct bpf_sock_ops_kern, sk),\
8137 				      si->dst_reg, si->src_reg,		      \
8138 				      offsetof(struct bpf_sock_ops_kern, sk));\
8139 		if (si->dst_reg == si->src_reg)	{			      \
8140 			*insn++ = BPF_JMP_A(1);				      \
8141 			*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->src_reg,	      \
8142 				      offsetof(struct bpf_sock_ops_kern,      \
8143 				      temp));				      \
8144 		}							      \
8145 	} while (0)
8146 
8147 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
8148 		SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
8149 
8150 /* Helper macro for adding write access to tcp_sock or sock fields.
8151  * The macro is called with two registers, dst_reg which contains a pointer
8152  * to ctx (context) and src_reg which contains the value that should be
8153  * stored. However, we need an additional register since we cannot overwrite
8154  * dst_reg because it may be used later in the program.
8155  * Instead we "borrow" one of the other register. We first save its value
8156  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
8157  * it at the end of the macro.
8158  */
8159 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
8160 	do {								      \
8161 		int reg = BPF_REG_9;					      \
8162 		BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >		      \
8163 			     FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
8164 		if (si->dst_reg == reg || si->src_reg == reg)		      \
8165 			reg--;						      \
8166 		if (si->dst_reg == reg || si->src_reg == reg)		      \
8167 			reg--;						      \
8168 		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,		      \
8169 				      offsetof(struct bpf_sock_ops_kern,      \
8170 					       temp));			      \
8171 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
8172 						struct bpf_sock_ops_kern,     \
8173 						is_fullsock),		      \
8174 				      reg, si->dst_reg,			      \
8175 				      offsetof(struct bpf_sock_ops_kern,      \
8176 					       is_fullsock));		      \
8177 		*insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);		      \
8178 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
8179 						struct bpf_sock_ops_kern, sk),\
8180 				      reg, si->dst_reg,			      \
8181 				      offsetof(struct bpf_sock_ops_kern, sk));\
8182 		*insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),	      \
8183 				      reg, si->src_reg,			      \
8184 				      offsetof(OBJ, OBJ_FIELD));	      \
8185 		*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,		      \
8186 				      offsetof(struct bpf_sock_ops_kern,      \
8187 					       temp));			      \
8188 	} while (0)
8189 
8190 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)	      \
8191 	do {								      \
8192 		if (TYPE == BPF_WRITE)					      \
8193 			SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
8194 		else							      \
8195 			SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
8196 	} while (0)
8197 
8198 	if (insn > insn_buf)
8199 		return insn - insn_buf;
8200 
8201 	switch (si->off) {
8202 	case offsetof(struct bpf_sock_ops, op) ...
8203 	     offsetof(struct bpf_sock_ops, replylong[3]):
8204 		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
8205 			     FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
8206 		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
8207 			     FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
8208 		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
8209 			     FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
8210 		off = si->off;
8211 		off -= offsetof(struct bpf_sock_ops, op);
8212 		off += offsetof(struct bpf_sock_ops_kern, op);
8213 		if (type == BPF_WRITE)
8214 			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
8215 					      off);
8216 		else
8217 			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
8218 					      off);
8219 		break;
8220 
8221 	case offsetof(struct bpf_sock_ops, family):
8222 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
8223 
8224 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8225 					      struct bpf_sock_ops_kern, sk),
8226 				      si->dst_reg, si->src_reg,
8227 				      offsetof(struct bpf_sock_ops_kern, sk));
8228 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8229 				      offsetof(struct sock_common, skc_family));
8230 		break;
8231 
8232 	case offsetof(struct bpf_sock_ops, remote_ip4):
8233 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
8234 
8235 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8236 						struct bpf_sock_ops_kern, sk),
8237 				      si->dst_reg, si->src_reg,
8238 				      offsetof(struct bpf_sock_ops_kern, sk));
8239 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8240 				      offsetof(struct sock_common, skc_daddr));
8241 		break;
8242 
8243 	case offsetof(struct bpf_sock_ops, local_ip4):
8244 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8245 					  skc_rcv_saddr) != 4);
8246 
8247 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8248 					      struct bpf_sock_ops_kern, sk),
8249 				      si->dst_reg, si->src_reg,
8250 				      offsetof(struct bpf_sock_ops_kern, sk));
8251 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8252 				      offsetof(struct sock_common,
8253 					       skc_rcv_saddr));
8254 		break;
8255 
8256 	case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
8257 	     offsetof(struct bpf_sock_ops, remote_ip6[3]):
8258 #if IS_ENABLED(CONFIG_IPV6)
8259 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8260 					  skc_v6_daddr.s6_addr32[0]) != 4);
8261 
8262 		off = si->off;
8263 		off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
8264 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8265 						struct bpf_sock_ops_kern, sk),
8266 				      si->dst_reg, si->src_reg,
8267 				      offsetof(struct bpf_sock_ops_kern, sk));
8268 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8269 				      offsetof(struct sock_common,
8270 					       skc_v6_daddr.s6_addr32[0]) +
8271 				      off);
8272 #else
8273 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8274 #endif
8275 		break;
8276 
8277 	case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
8278 	     offsetof(struct bpf_sock_ops, local_ip6[3]):
8279 #if IS_ENABLED(CONFIG_IPV6)
8280 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8281 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8282 
8283 		off = si->off;
8284 		off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
8285 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8286 						struct bpf_sock_ops_kern, sk),
8287 				      si->dst_reg, si->src_reg,
8288 				      offsetof(struct bpf_sock_ops_kern, sk));
8289 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8290 				      offsetof(struct sock_common,
8291 					       skc_v6_rcv_saddr.s6_addr32[0]) +
8292 				      off);
8293 #else
8294 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8295 #endif
8296 		break;
8297 
8298 	case offsetof(struct bpf_sock_ops, remote_port):
8299 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
8300 
8301 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8302 						struct bpf_sock_ops_kern, sk),
8303 				      si->dst_reg, si->src_reg,
8304 				      offsetof(struct bpf_sock_ops_kern, sk));
8305 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8306 				      offsetof(struct sock_common, skc_dport));
8307 #ifndef __BIG_ENDIAN_BITFIELD
8308 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8309 #endif
8310 		break;
8311 
8312 	case offsetof(struct bpf_sock_ops, local_port):
8313 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
8314 
8315 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8316 						struct bpf_sock_ops_kern, sk),
8317 				      si->dst_reg, si->src_reg,
8318 				      offsetof(struct bpf_sock_ops_kern, sk));
8319 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8320 				      offsetof(struct sock_common, skc_num));
8321 		break;
8322 
8323 	case offsetof(struct bpf_sock_ops, is_fullsock):
8324 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8325 						struct bpf_sock_ops_kern,
8326 						is_fullsock),
8327 				      si->dst_reg, si->src_reg,
8328 				      offsetof(struct bpf_sock_ops_kern,
8329 					       is_fullsock));
8330 		break;
8331 
8332 	case offsetof(struct bpf_sock_ops, state):
8333 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);
8334 
8335 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8336 						struct bpf_sock_ops_kern, sk),
8337 				      si->dst_reg, si->src_reg,
8338 				      offsetof(struct bpf_sock_ops_kern, sk));
8339 		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
8340 				      offsetof(struct sock_common, skc_state));
8341 		break;
8342 
8343 	case offsetof(struct bpf_sock_ops, rtt_min):
8344 		BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
8345 			     sizeof(struct minmax));
8346 		BUILD_BUG_ON(sizeof(struct minmax) <
8347 			     sizeof(struct minmax_sample));
8348 
8349 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8350 						struct bpf_sock_ops_kern, sk),
8351 				      si->dst_reg, si->src_reg,
8352 				      offsetof(struct bpf_sock_ops_kern, sk));
8353 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8354 				      offsetof(struct tcp_sock, rtt_min) +
8355 				      FIELD_SIZEOF(struct minmax_sample, t));
8356 		break;
8357 
8358 	case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
8359 		SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
8360 				   struct tcp_sock);
8361 		break;
8362 
8363 	case offsetof(struct bpf_sock_ops, sk_txhash):
8364 		SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
8365 					  struct sock, type);
8366 		break;
8367 	case offsetof(struct bpf_sock_ops, snd_cwnd):
8368 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_cwnd);
8369 		break;
8370 	case offsetof(struct bpf_sock_ops, srtt_us):
8371 		SOCK_OPS_GET_TCP_SOCK_FIELD(srtt_us);
8372 		break;
8373 	case offsetof(struct bpf_sock_ops, snd_ssthresh):
8374 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_ssthresh);
8375 		break;
8376 	case offsetof(struct bpf_sock_ops, rcv_nxt):
8377 		SOCK_OPS_GET_TCP_SOCK_FIELD(rcv_nxt);
8378 		break;
8379 	case offsetof(struct bpf_sock_ops, snd_nxt):
8380 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_nxt);
8381 		break;
8382 	case offsetof(struct bpf_sock_ops, snd_una):
8383 		SOCK_OPS_GET_TCP_SOCK_FIELD(snd_una);
8384 		break;
8385 	case offsetof(struct bpf_sock_ops, mss_cache):
8386 		SOCK_OPS_GET_TCP_SOCK_FIELD(mss_cache);
8387 		break;
8388 	case offsetof(struct bpf_sock_ops, ecn_flags):
8389 		SOCK_OPS_GET_TCP_SOCK_FIELD(ecn_flags);
8390 		break;
8391 	case offsetof(struct bpf_sock_ops, rate_delivered):
8392 		SOCK_OPS_GET_TCP_SOCK_FIELD(rate_delivered);
8393 		break;
8394 	case offsetof(struct bpf_sock_ops, rate_interval_us):
8395 		SOCK_OPS_GET_TCP_SOCK_FIELD(rate_interval_us);
8396 		break;
8397 	case offsetof(struct bpf_sock_ops, packets_out):
8398 		SOCK_OPS_GET_TCP_SOCK_FIELD(packets_out);
8399 		break;
8400 	case offsetof(struct bpf_sock_ops, retrans_out):
8401 		SOCK_OPS_GET_TCP_SOCK_FIELD(retrans_out);
8402 		break;
8403 	case offsetof(struct bpf_sock_ops, total_retrans):
8404 		SOCK_OPS_GET_TCP_SOCK_FIELD(total_retrans);
8405 		break;
8406 	case offsetof(struct bpf_sock_ops, segs_in):
8407 		SOCK_OPS_GET_TCP_SOCK_FIELD(segs_in);
8408 		break;
8409 	case offsetof(struct bpf_sock_ops, data_segs_in):
8410 		SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_in);
8411 		break;
8412 	case offsetof(struct bpf_sock_ops, segs_out):
8413 		SOCK_OPS_GET_TCP_SOCK_FIELD(segs_out);
8414 		break;
8415 	case offsetof(struct bpf_sock_ops, data_segs_out):
8416 		SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_out);
8417 		break;
8418 	case offsetof(struct bpf_sock_ops, lost_out):
8419 		SOCK_OPS_GET_TCP_SOCK_FIELD(lost_out);
8420 		break;
8421 	case offsetof(struct bpf_sock_ops, sacked_out):
8422 		SOCK_OPS_GET_TCP_SOCK_FIELD(sacked_out);
8423 		break;
8424 	case offsetof(struct bpf_sock_ops, bytes_received):
8425 		SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_received);
8426 		break;
8427 	case offsetof(struct bpf_sock_ops, bytes_acked):
8428 		SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_acked);
8429 		break;
8430 	case offsetof(struct bpf_sock_ops, sk):
8431 		SOCK_OPS_GET_SK();
8432 		break;
8433 	}
8434 	return insn - insn_buf;
8435 }
8436 
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)8437 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
8438 				     const struct bpf_insn *si,
8439 				     struct bpf_insn *insn_buf,
8440 				     struct bpf_prog *prog, u32 *target_size)
8441 {
8442 	struct bpf_insn *insn = insn_buf;
8443 	int off;
8444 
8445 	switch (si->off) {
8446 	case offsetof(struct __sk_buff, data_end):
8447 		off  = si->off;
8448 		off -= offsetof(struct __sk_buff, data_end);
8449 		off += offsetof(struct sk_buff, cb);
8450 		off += offsetof(struct tcp_skb_cb, bpf.data_end);
8451 		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
8452 				      si->src_reg, off);
8453 		break;
8454 	case offsetof(struct __sk_buff, cb[0]) ...
8455 	     offsetofend(struct __sk_buff, cb[4]) - 1:
8456 		BUILD_BUG_ON(sizeof_field(struct sk_skb_cb, data) < 20);
8457 		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
8458 			      offsetof(struct sk_skb_cb, data)) %
8459 			     sizeof(__u64));
8460 
8461 		prog->cb_access = 1;
8462 		off  = si->off;
8463 		off -= offsetof(struct __sk_buff, cb[0]);
8464 		off += offsetof(struct sk_buff, cb);
8465 		off += offsetof(struct sk_skb_cb, data);
8466 		if (type == BPF_WRITE)
8467 			*insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
8468 					      si->src_reg, off);
8469 		else
8470 			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
8471 					      si->src_reg, off);
8472 		break;
8473 
8474 
8475 	default:
8476 		return bpf_convert_ctx_access(type, si, insn_buf, prog,
8477 					      target_size);
8478 	}
8479 
8480 	return insn - insn_buf;
8481 }
8482 
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)8483 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
8484 				     const struct bpf_insn *si,
8485 				     struct bpf_insn *insn_buf,
8486 				     struct bpf_prog *prog, u32 *target_size)
8487 {
8488 	struct bpf_insn *insn = insn_buf;
8489 #if IS_ENABLED(CONFIG_IPV6)
8490 	int off;
8491 #endif
8492 
8493 	/* convert ctx uses the fact sg element is first in struct */
8494 	BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
8495 
8496 	switch (si->off) {
8497 	case offsetof(struct sk_msg_md, data):
8498 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
8499 				      si->dst_reg, si->src_reg,
8500 				      offsetof(struct sk_msg, data));
8501 		break;
8502 	case offsetof(struct sk_msg_md, data_end):
8503 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
8504 				      si->dst_reg, si->src_reg,
8505 				      offsetof(struct sk_msg, data_end));
8506 		break;
8507 	case offsetof(struct sk_msg_md, family):
8508 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
8509 
8510 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8511 					      struct sk_msg, sk),
8512 				      si->dst_reg, si->src_reg,
8513 				      offsetof(struct sk_msg, sk));
8514 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8515 				      offsetof(struct sock_common, skc_family));
8516 		break;
8517 
8518 	case offsetof(struct sk_msg_md, remote_ip4):
8519 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
8520 
8521 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8522 						struct sk_msg, sk),
8523 				      si->dst_reg, si->src_reg,
8524 				      offsetof(struct sk_msg, sk));
8525 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8526 				      offsetof(struct sock_common, skc_daddr));
8527 		break;
8528 
8529 	case offsetof(struct sk_msg_md, local_ip4):
8530 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8531 					  skc_rcv_saddr) != 4);
8532 
8533 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8534 					      struct sk_msg, sk),
8535 				      si->dst_reg, si->src_reg,
8536 				      offsetof(struct sk_msg, sk));
8537 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8538 				      offsetof(struct sock_common,
8539 					       skc_rcv_saddr));
8540 		break;
8541 
8542 	case offsetof(struct sk_msg_md, remote_ip6[0]) ...
8543 	     offsetof(struct sk_msg_md, remote_ip6[3]):
8544 #if IS_ENABLED(CONFIG_IPV6)
8545 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8546 					  skc_v6_daddr.s6_addr32[0]) != 4);
8547 
8548 		off = si->off;
8549 		off -= offsetof(struct sk_msg_md, remote_ip6[0]);
8550 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8551 						struct sk_msg, sk),
8552 				      si->dst_reg, si->src_reg,
8553 				      offsetof(struct sk_msg, sk));
8554 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8555 				      offsetof(struct sock_common,
8556 					       skc_v6_daddr.s6_addr32[0]) +
8557 				      off);
8558 #else
8559 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8560 #endif
8561 		break;
8562 
8563 	case offsetof(struct sk_msg_md, local_ip6[0]) ...
8564 	     offsetof(struct sk_msg_md, local_ip6[3]):
8565 #if IS_ENABLED(CONFIG_IPV6)
8566 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8567 					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8568 
8569 		off = si->off;
8570 		off -= offsetof(struct sk_msg_md, local_ip6[0]);
8571 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8572 						struct sk_msg, sk),
8573 				      si->dst_reg, si->src_reg,
8574 				      offsetof(struct sk_msg, sk));
8575 		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8576 				      offsetof(struct sock_common,
8577 					       skc_v6_rcv_saddr.s6_addr32[0]) +
8578 				      off);
8579 #else
8580 		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8581 #endif
8582 		break;
8583 
8584 	case offsetof(struct sk_msg_md, remote_port):
8585 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
8586 
8587 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8588 						struct sk_msg, sk),
8589 				      si->dst_reg, si->src_reg,
8590 				      offsetof(struct sk_msg, sk));
8591 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8592 				      offsetof(struct sock_common, skc_dport));
8593 #ifndef __BIG_ENDIAN_BITFIELD
8594 		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8595 #endif
8596 		break;
8597 
8598 	case offsetof(struct sk_msg_md, local_port):
8599 		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
8600 
8601 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8602 						struct sk_msg, sk),
8603 				      si->dst_reg, si->src_reg,
8604 				      offsetof(struct sk_msg, sk));
8605 		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8606 				      offsetof(struct sock_common, skc_num));
8607 		break;
8608 
8609 	case offsetof(struct sk_msg_md, size):
8610 		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
8611 				      si->dst_reg, si->src_reg,
8612 				      offsetof(struct sk_msg_sg, size));
8613 		break;
8614 	}
8615 
8616 	return insn - insn_buf;
8617 }
8618 
8619 const struct bpf_verifier_ops sk_filter_verifier_ops = {
8620 	.get_func_proto		= sk_filter_func_proto,
8621 	.is_valid_access	= sk_filter_is_valid_access,
8622 	.convert_ctx_access	= bpf_convert_ctx_access,
8623 	.gen_ld_abs		= bpf_gen_ld_abs,
8624 };
8625 
8626 const struct bpf_prog_ops sk_filter_prog_ops = {
8627 	.test_run		= bpf_prog_test_run_skb,
8628 };
8629 
8630 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
8631 	.get_func_proto		= tc_cls_act_func_proto,
8632 	.is_valid_access	= tc_cls_act_is_valid_access,
8633 	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
8634 	.gen_prologue		= tc_cls_act_prologue,
8635 	.gen_ld_abs		= bpf_gen_ld_abs,
8636 };
8637 
8638 const struct bpf_prog_ops tc_cls_act_prog_ops = {
8639 	.test_run		= bpf_prog_test_run_skb,
8640 };
8641 
8642 const struct bpf_verifier_ops xdp_verifier_ops = {
8643 	.get_func_proto		= xdp_func_proto,
8644 	.is_valid_access	= xdp_is_valid_access,
8645 	.convert_ctx_access	= xdp_convert_ctx_access,
8646 	.gen_prologue		= bpf_noop_prologue,
8647 };
8648 
8649 const struct bpf_prog_ops xdp_prog_ops = {
8650 	.test_run		= bpf_prog_test_run_xdp,
8651 };
8652 
8653 const struct bpf_verifier_ops cg_skb_verifier_ops = {
8654 	.get_func_proto		= cg_skb_func_proto,
8655 	.is_valid_access	= cg_skb_is_valid_access,
8656 	.convert_ctx_access	= bpf_convert_ctx_access,
8657 };
8658 
8659 const struct bpf_prog_ops cg_skb_prog_ops = {
8660 	.test_run		= bpf_prog_test_run_skb,
8661 };
8662 
8663 const struct bpf_verifier_ops lwt_in_verifier_ops = {
8664 	.get_func_proto		= lwt_in_func_proto,
8665 	.is_valid_access	= lwt_is_valid_access,
8666 	.convert_ctx_access	= bpf_convert_ctx_access,
8667 };
8668 
8669 const struct bpf_prog_ops lwt_in_prog_ops = {
8670 	.test_run		= bpf_prog_test_run_skb,
8671 };
8672 
8673 const struct bpf_verifier_ops lwt_out_verifier_ops = {
8674 	.get_func_proto		= lwt_out_func_proto,
8675 	.is_valid_access	= lwt_is_valid_access,
8676 	.convert_ctx_access	= bpf_convert_ctx_access,
8677 };
8678 
8679 const struct bpf_prog_ops lwt_out_prog_ops = {
8680 	.test_run		= bpf_prog_test_run_skb,
8681 };
8682 
8683 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
8684 	.get_func_proto		= lwt_xmit_func_proto,
8685 	.is_valid_access	= lwt_is_valid_access,
8686 	.convert_ctx_access	= bpf_convert_ctx_access,
8687 	.gen_prologue		= tc_cls_act_prologue,
8688 };
8689 
8690 const struct bpf_prog_ops lwt_xmit_prog_ops = {
8691 	.test_run		= bpf_prog_test_run_skb,
8692 };
8693 
8694 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
8695 	.get_func_proto		= lwt_seg6local_func_proto,
8696 	.is_valid_access	= lwt_is_valid_access,
8697 	.convert_ctx_access	= bpf_convert_ctx_access,
8698 };
8699 
8700 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
8701 	.test_run		= bpf_prog_test_run_skb,
8702 };
8703 
8704 const struct bpf_verifier_ops cg_sock_verifier_ops = {
8705 	.get_func_proto		= sock_filter_func_proto,
8706 	.is_valid_access	= sock_filter_is_valid_access,
8707 	.convert_ctx_access	= bpf_sock_convert_ctx_access,
8708 };
8709 
8710 const struct bpf_prog_ops cg_sock_prog_ops = {
8711 };
8712 
8713 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
8714 	.get_func_proto		= sock_addr_func_proto,
8715 	.is_valid_access	= sock_addr_is_valid_access,
8716 	.convert_ctx_access	= sock_addr_convert_ctx_access,
8717 };
8718 
8719 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
8720 };
8721 
8722 const struct bpf_verifier_ops sock_ops_verifier_ops = {
8723 	.get_func_proto		= sock_ops_func_proto,
8724 	.is_valid_access	= sock_ops_is_valid_access,
8725 	.convert_ctx_access	= sock_ops_convert_ctx_access,
8726 };
8727 
8728 const struct bpf_prog_ops sock_ops_prog_ops = {
8729 };
8730 
8731 const struct bpf_verifier_ops sk_skb_verifier_ops = {
8732 	.get_func_proto		= sk_skb_func_proto,
8733 	.is_valid_access	= sk_skb_is_valid_access,
8734 	.convert_ctx_access	= sk_skb_convert_ctx_access,
8735 	.gen_prologue		= sk_skb_prologue,
8736 };
8737 
8738 const struct bpf_prog_ops sk_skb_prog_ops = {
8739 };
8740 
8741 const struct bpf_verifier_ops sk_msg_verifier_ops = {
8742 	.get_func_proto		= sk_msg_func_proto,
8743 	.is_valid_access	= sk_msg_is_valid_access,
8744 	.convert_ctx_access	= sk_msg_convert_ctx_access,
8745 	.gen_prologue		= bpf_noop_prologue,
8746 };
8747 
8748 const struct bpf_prog_ops sk_msg_prog_ops = {
8749 };
8750 
8751 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
8752 	.get_func_proto		= flow_dissector_func_proto,
8753 	.is_valid_access	= flow_dissector_is_valid_access,
8754 	.convert_ctx_access	= flow_dissector_convert_ctx_access,
8755 };
8756 
8757 const struct bpf_prog_ops flow_dissector_prog_ops = {
8758 	.test_run		= bpf_prog_test_run_flow_dissector,
8759 };
8760 
sk_detach_filter(struct sock * sk)8761 int sk_detach_filter(struct sock *sk)
8762 {
8763 	int ret = -ENOENT;
8764 	struct sk_filter *filter;
8765 
8766 	if (sock_flag(sk, SOCK_FILTER_LOCKED))
8767 		return -EPERM;
8768 
8769 	filter = rcu_dereference_protected(sk->sk_filter,
8770 					   lockdep_sock_is_held(sk));
8771 	if (filter) {
8772 		RCU_INIT_POINTER(sk->sk_filter, NULL);
8773 		sk_filter_uncharge(sk, filter);
8774 		ret = 0;
8775 	}
8776 
8777 	return ret;
8778 }
8779 EXPORT_SYMBOL_GPL(sk_detach_filter);
8780 
sk_get_filter(struct sock * sk,struct sock_filter __user * ubuf,unsigned int len)8781 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
8782 		  unsigned int len)
8783 {
8784 	struct sock_fprog_kern *fprog;
8785 	struct sk_filter *filter;
8786 	int ret = 0;
8787 
8788 	lock_sock(sk);
8789 	filter = rcu_dereference_protected(sk->sk_filter,
8790 					   lockdep_sock_is_held(sk));
8791 	if (!filter)
8792 		goto out;
8793 
8794 	/* We're copying the filter that has been originally attached,
8795 	 * so no conversion/decode needed anymore. eBPF programs that
8796 	 * have no original program cannot be dumped through this.
8797 	 */
8798 	ret = -EACCES;
8799 	fprog = filter->prog->orig_prog;
8800 	if (!fprog)
8801 		goto out;
8802 
8803 	ret = fprog->len;
8804 	if (!len)
8805 		/* User space only enquires number of filter blocks. */
8806 		goto out;
8807 
8808 	ret = -EINVAL;
8809 	if (len < fprog->len)
8810 		goto out;
8811 
8812 	ret = -EFAULT;
8813 	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
8814 		goto out;
8815 
8816 	/* Instead of bytes, the API requests to return the number
8817 	 * of filter blocks.
8818 	 */
8819 	ret = fprog->len;
8820 out:
8821 	release_sock(sk);
8822 	return ret;
8823 }
8824 
8825 #ifdef CONFIG_INET
8826 struct sk_reuseport_kern {
8827 	struct sk_buff *skb;
8828 	struct sock *sk;
8829 	struct sock *selected_sk;
8830 	void *data_end;
8831 	u32 hash;
8832 	u32 reuseport_id;
8833 	bool bind_inany;
8834 };
8835 
bpf_init_reuseport_kern(struct sk_reuseport_kern * reuse_kern,struct sock_reuseport * reuse,struct sock * sk,struct sk_buff * skb,u32 hash)8836 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
8837 				    struct sock_reuseport *reuse,
8838 				    struct sock *sk, struct sk_buff *skb,
8839 				    u32 hash)
8840 {
8841 	reuse_kern->skb = skb;
8842 	reuse_kern->sk = sk;
8843 	reuse_kern->selected_sk = NULL;
8844 	reuse_kern->data_end = skb->data + skb_headlen(skb);
8845 	reuse_kern->hash = hash;
8846 	reuse_kern->reuseport_id = reuse->reuseport_id;
8847 	reuse_kern->bind_inany = reuse->bind_inany;
8848 }
8849 
bpf_run_sk_reuseport(struct sock_reuseport * reuse,struct sock * sk,struct bpf_prog * prog,struct sk_buff * skb,u32 hash)8850 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
8851 				  struct bpf_prog *prog, struct sk_buff *skb,
8852 				  u32 hash)
8853 {
8854 	struct sk_reuseport_kern reuse_kern;
8855 	enum sk_action action;
8856 
8857 	bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
8858 	action = BPF_PROG_RUN(prog, &reuse_kern);
8859 
8860 	if (action == SK_PASS)
8861 		return reuse_kern.selected_sk;
8862 	else
8863 		return ERR_PTR(-ECONNREFUSED);
8864 }
8865 
BPF_CALL_4(sk_select_reuseport,struct sk_reuseport_kern *,reuse_kern,struct bpf_map *,map,void *,key,u32,flags)8866 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
8867 	   struct bpf_map *, map, void *, key, u32, flags)
8868 {
8869 	struct sock_reuseport *reuse;
8870 	struct sock *selected_sk;
8871 
8872 	selected_sk = map->ops->map_lookup_elem(map, key);
8873 	if (!selected_sk)
8874 		return -ENOENT;
8875 
8876 	reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
8877 	if (!reuse)
8878 		/* selected_sk is unhashed (e.g. by close()) after the
8879 		 * above map_lookup_elem().  Treat selected_sk has already
8880 		 * been removed from the map.
8881 		 */
8882 		return -ENOENT;
8883 
8884 	if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
8885 		struct sock *sk;
8886 
8887 		if (unlikely(!reuse_kern->reuseport_id))
8888 			/* There is a small race between adding the
8889 			 * sk to the map and setting the
8890 			 * reuse_kern->reuseport_id.
8891 			 * Treat it as the sk has not been added to
8892 			 * the bpf map yet.
8893 			 */
8894 			return -ENOENT;
8895 
8896 		sk = reuse_kern->sk;
8897 		if (sk->sk_protocol != selected_sk->sk_protocol)
8898 			return -EPROTOTYPE;
8899 		else if (sk->sk_family != selected_sk->sk_family)
8900 			return -EAFNOSUPPORT;
8901 
8902 		/* Catch all. Likely bound to a different sockaddr. */
8903 		return -EBADFD;
8904 	}
8905 
8906 	reuse_kern->selected_sk = selected_sk;
8907 
8908 	return 0;
8909 }
8910 
8911 static const struct bpf_func_proto sk_select_reuseport_proto = {
8912 	.func           = sk_select_reuseport,
8913 	.gpl_only       = false,
8914 	.ret_type       = RET_INTEGER,
8915 	.arg1_type	= ARG_PTR_TO_CTX,
8916 	.arg2_type      = ARG_CONST_MAP_PTR,
8917 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
8918 	.arg4_type	= ARG_ANYTHING,
8919 };
8920 
BPF_CALL_4(sk_reuseport_load_bytes,const struct sk_reuseport_kern *,reuse_kern,u32,offset,void *,to,u32,len)8921 BPF_CALL_4(sk_reuseport_load_bytes,
8922 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8923 	   void *, to, u32, len)
8924 {
8925 	return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
8926 }
8927 
8928 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
8929 	.func		= sk_reuseport_load_bytes,
8930 	.gpl_only	= false,
8931 	.ret_type	= RET_INTEGER,
8932 	.arg1_type	= ARG_PTR_TO_CTX,
8933 	.arg2_type	= ARG_ANYTHING,
8934 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
8935 	.arg4_type	= ARG_CONST_SIZE,
8936 };
8937 
BPF_CALL_5(sk_reuseport_load_bytes_relative,const struct sk_reuseport_kern *,reuse_kern,u32,offset,void *,to,u32,len,u32,start_header)8938 BPF_CALL_5(sk_reuseport_load_bytes_relative,
8939 	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8940 	   void *, to, u32, len, u32, start_header)
8941 {
8942 	return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
8943 					       len, start_header);
8944 }
8945 
8946 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
8947 	.func		= sk_reuseport_load_bytes_relative,
8948 	.gpl_only	= false,
8949 	.ret_type	= RET_INTEGER,
8950 	.arg1_type	= ARG_PTR_TO_CTX,
8951 	.arg2_type	= ARG_ANYTHING,
8952 	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
8953 	.arg4_type	= ARG_CONST_SIZE,
8954 	.arg5_type	= ARG_ANYTHING,
8955 };
8956 
8957 static const struct bpf_func_proto *
sk_reuseport_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)8958 sk_reuseport_func_proto(enum bpf_func_id func_id,
8959 			const struct bpf_prog *prog)
8960 {
8961 	switch (func_id) {
8962 	case BPF_FUNC_sk_select_reuseport:
8963 		return &sk_select_reuseport_proto;
8964 	case BPF_FUNC_skb_load_bytes:
8965 		return &sk_reuseport_load_bytes_proto;
8966 	case BPF_FUNC_skb_load_bytes_relative:
8967 		return &sk_reuseport_load_bytes_relative_proto;
8968 	default:
8969 		return bpf_base_func_proto(func_id);
8970 	}
8971 }
8972 
8973 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)8974 sk_reuseport_is_valid_access(int off, int size,
8975 			     enum bpf_access_type type,
8976 			     const struct bpf_prog *prog,
8977 			     struct bpf_insn_access_aux *info)
8978 {
8979 	const u32 size_default = sizeof(__u32);
8980 
8981 	if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
8982 	    off % size || type != BPF_READ)
8983 		return false;
8984 
8985 	switch (off) {
8986 	case offsetof(struct sk_reuseport_md, data):
8987 		info->reg_type = PTR_TO_PACKET;
8988 		return size == sizeof(__u64);
8989 
8990 	case offsetof(struct sk_reuseport_md, data_end):
8991 		info->reg_type = PTR_TO_PACKET_END;
8992 		return size == sizeof(__u64);
8993 
8994 	case offsetof(struct sk_reuseport_md, hash):
8995 		return size == size_default;
8996 
8997 	/* Fields that allow narrowing */
8998 	case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
8999 		if (size < FIELD_SIZEOF(struct sk_buff, protocol))
9000 			return false;
9001 		/* fall through */
9002 	case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
9003 	case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
9004 	case bpf_ctx_range(struct sk_reuseport_md, len):
9005 		bpf_ctx_record_field_size(info, size_default);
9006 		return bpf_ctx_narrow_access_ok(off, size, size_default);
9007 
9008 	default:
9009 		return false;
9010 	}
9011 }
9012 
9013 #define SK_REUSEPORT_LOAD_FIELD(F) ({					\
9014 	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
9015 			      si->dst_reg, si->src_reg,			\
9016 			      bpf_target_off(struct sk_reuseport_kern, F, \
9017 					     FIELD_SIZEOF(struct sk_reuseport_kern, F), \
9018 					     target_size));		\
9019 	})
9020 
9021 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)				\
9022 	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
9023 				    struct sk_buff,			\
9024 				    skb,				\
9025 				    SKB_FIELD)
9026 
9027 #define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
9028 	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,	\
9029 					     struct sock,		\
9030 					     sk,			\
9031 					     SK_FIELD, BPF_SIZE, EXTRA_OFF)
9032 
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)9033 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
9034 					   const struct bpf_insn *si,
9035 					   struct bpf_insn *insn_buf,
9036 					   struct bpf_prog *prog,
9037 					   u32 *target_size)
9038 {
9039 	struct bpf_insn *insn = insn_buf;
9040 
9041 	switch (si->off) {
9042 	case offsetof(struct sk_reuseport_md, data):
9043 		SK_REUSEPORT_LOAD_SKB_FIELD(data);
9044 		break;
9045 
9046 	case offsetof(struct sk_reuseport_md, len):
9047 		SK_REUSEPORT_LOAD_SKB_FIELD(len);
9048 		break;
9049 
9050 	case offsetof(struct sk_reuseport_md, eth_protocol):
9051 		SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
9052 		break;
9053 
9054 	case offsetof(struct sk_reuseport_md, ip_protocol):
9055 		BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
9056 		SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
9057 						    BPF_W, 0);
9058 		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
9059 		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
9060 					SK_FL_PROTO_SHIFT);
9061 		/* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
9062 		 * aware.  No further narrowing or masking is needed.
9063 		 */
9064 		*target_size = 1;
9065 		break;
9066 
9067 	case offsetof(struct sk_reuseport_md, data_end):
9068 		SK_REUSEPORT_LOAD_FIELD(data_end);
9069 		break;
9070 
9071 	case offsetof(struct sk_reuseport_md, hash):
9072 		SK_REUSEPORT_LOAD_FIELD(hash);
9073 		break;
9074 
9075 	case offsetof(struct sk_reuseport_md, bind_inany):
9076 		SK_REUSEPORT_LOAD_FIELD(bind_inany);
9077 		break;
9078 	}
9079 
9080 	return insn - insn_buf;
9081 }
9082 
9083 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
9084 	.get_func_proto		= sk_reuseport_func_proto,
9085 	.is_valid_access	= sk_reuseport_is_valid_access,
9086 	.convert_ctx_access	= sk_reuseport_convert_ctx_access,
9087 };
9088 
9089 const struct bpf_prog_ops sk_reuseport_prog_ops = {
9090 };
9091 #endif /* CONFIG_INET */
9092