filter.c 110.8 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3
/*
 * Linux Socket Filter - Kernel level socket filtering
 *
4 5
 * Based on the design of the Berkeley Packet Filter. The new
 * internal format has been designed by PLUMgrid:
L
Linus Torvalds 已提交
6
 *
7 8 9 10 11 12 13
 *	Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
 *
 * Authors:
 *
 *	Jay Schulist <jschlst@samba.org>
 *	Alexei Starovoitov <ast@plumgrid.com>
 *	Daniel Borkmann <dborkman@redhat.com>
L
Linus Torvalds 已提交
14 15 16 17 18 19 20
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *
 * Andi Kleen - Fix a few bad bugs and races.
21
 * Kris Katterjohn - Added many additional checks in bpf_check_classic()
L
Linus Torvalds 已提交
22 23 24 25 26 27 28
 */

#include <linux/module.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
29
#include <linux/sock_diag.h>
L
Linus Torvalds 已提交
30 31 32 33
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_packet.h>
34
#include <linux/if_arp.h>
35
#include <linux/gfp.h>
L
Linus Torvalds 已提交
36 37
#include <net/ip.h>
#include <net/protocol.h>
38
#include <net/netlink.h>
L
Linus Torvalds 已提交
39 40
#include <linux/skbuff.h>
#include <net/sock.h>
41
#include <net/flow_dissector.h>
L
Linus Torvalds 已提交
42 43
#include <linux/errno.h>
#include <linux/timer.h>
44
#include <linux/uaccess.h>
45
#include <asm/unaligned.h>
L
Linus Torvalds 已提交
46
#include <linux/filter.h>
47
#include <linux/ratelimit.h>
48
#include <linux/seccomp.h>
E
Eric Dumazet 已提交
49
#include <linux/if_vlan.h>
50
#include <linux/bpf.h>
51
#include <net/sch_generic.h>
52
#include <net/cls_cgroup.h>
53
#include <net/dst_metadata.h>
54
#include <net/dst.h>
55
#include <net/sock_reuseport.h>
56
#include <net/busy_poll.h>
57
#include <net/tcp.h>
58
#include <linux/bpf_trace.h>
L
Linus Torvalds 已提交
59

S
Stephen Hemminger 已提交
60
/**
61
 *	sk_filter_trim_cap - run a packet through a socket filter
S
Stephen Hemminger 已提交
62 63
 *	@sk: sock associated with &sk_buff
 *	@skb: buffer to filter
64
 *	@cap: limit on how short the eBPF program may trim the packet
S
Stephen Hemminger 已提交
65
 *
66 67
 * Run the eBPF program and then cut skb->data to correct size returned by
 * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
S
Stephen Hemminger 已提交
68
 * than pkt_len we keep whole skb->data. This is the socket level
69
 * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
S
Stephen Hemminger 已提交
70 71 72
 * be accepted or -EPERM if the packet should be tossed.
 *
 */
73
int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
S
Stephen Hemminger 已提交
74 75 76 77
{
	int err;
	struct sk_filter *filter;

78 79 80 81 82
	/*
	 * If the skb was allocated from pfmemalloc reserves, only
	 * allow SOCK_MEMALLOC sockets to use it as this socket is
	 * helping free memory
	 */
83 84
	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
		NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
85
		return -ENOMEM;
86
	}
87 88 89 90
	err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
	if (err)
		return err;

S
Stephen Hemminger 已提交
91 92 93 94
	err = security_sock_rcv_skb(sk, skb);
	if (err)
		return err;

95 96
	rcu_read_lock();
	filter = rcu_dereference(sk->sk_filter);
S
Stephen Hemminger 已提交
97
	if (filter) {
98 99 100 101 102 103
		struct sock *save_sk = skb->sk;
		unsigned int pkt_len;

		skb->sk = sk;
		pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
		skb->sk = save_sk;
104
		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
S
Stephen Hemminger 已提交
105
	}
106
	rcu_read_unlock();
S
Stephen Hemminger 已提交
107 108 109

	return err;
}
110
EXPORT_SYMBOL(sk_filter_trim_cap);
S
Stephen Hemminger 已提交
111

112
BPF_CALL_1(__skb_get_pay_offset, struct sk_buff *, skb)
113
{
114
	return skb_get_poff(skb);
115 116
}

117
BPF_CALL_3(__skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
118 119 120 121 122 123
{
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

124 125 126
	if (skb->len < sizeof(struct nlattr))
		return 0;

127
	if (a > skb->len - sizeof(struct nlattr))
128 129
		return 0;

130
	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
131 132 133 134 135 136
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

137
BPF_CALL_3(__skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
138 139 140 141 142 143
{
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

144 145 146
	if (skb->len < sizeof(struct nlattr))
		return 0;

147
	if (a > skb->len - sizeof(struct nlattr))
148 149
		return 0;

150 151
	nla = (struct nlattr *) &skb->data[a];
	if (nla->nla_len > skb->len - a)
152 153
		return 0;

154
	nla = nla_find_nested(nla, x);
155 156 157 158 159 160
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

161
BPF_CALL_0(__get_raw_cpu_id)
162 163 164 165
{
	return raw_smp_processor_id();
}

166 167 168 169 170 171
static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
	.func		= __get_raw_cpu_id,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
};

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
			      struct bpf_insn *insn_buf)
{
	struct bpf_insn *insn = insn_buf;

	switch (skb_field) {
	case SKF_AD_MARK:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);

		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
				      offsetof(struct sk_buff, mark));
		break;

	case SKF_AD_PKTTYPE:
		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
		*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
#ifdef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
#endif
		break;

	case SKF_AD_QUEUE:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);

		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
				      offsetof(struct sk_buff, queue_mapping));
		break;
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

	case SKF_AD_VLAN_TAG:
	case SKF_AD_VLAN_TAG_PRESENT:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
		BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);

		/* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
				      offsetof(struct sk_buff, vlan_tci));
		if (skb_field == SKF_AD_VLAN_TAG) {
			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
						~VLAN_TAG_PRESENT);
		} else {
			/* dst_reg >>= 12 */
			*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
			/* dst_reg &= 1 */
			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
		}
		break;
218 219 220 221 222
	}

	return insn - insn_buf;
}

223
static bool convert_bpf_extensions(struct sock_filter *fp,
224
				   struct bpf_insn **insnp)
225
{
226
	struct bpf_insn *insn = *insnp;
227
	u32 cnt;
228 229 230

	switch (fp->k) {
	case SKF_AD_OFF + SKF_AD_PROTOCOL:
231 232 233 234 235 236 237
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);

		/* A = *(u16 *) (CTX + offsetof(protocol)) */
		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
				      offsetof(struct sk_buff, protocol));
		/* A = ntohs(A) [emitting a nop or swap16] */
		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
238 239 240
		break;

	case SKF_AD_OFF + SKF_AD_PKTTYPE:
241 242
		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
243 244 245 246 247 248
		break;

	case SKF_AD_OFF + SKF_AD_IFINDEX:
	case SKF_AD_OFF + SKF_AD_HATYPE:
		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
249

250
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
251 252 253 254 255 256 257 258 259 260 261
				      BPF_REG_TMP, BPF_REG_CTX,
				      offsetof(struct sk_buff, dev));
		/* if (tmp != 0) goto pc + 1 */
		*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
		*insn++ = BPF_EXIT_INSN();
		if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
					    offsetof(struct net_device, ifindex));
		else
			*insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
					    offsetof(struct net_device, type));
262 263 264
		break;

	case SKF_AD_OFF + SKF_AD_MARK:
265 266
		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
267 268 269 270 271
		break;

	case SKF_AD_OFF + SKF_AD_RXHASH:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);

272 273
		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
				    offsetof(struct sk_buff, hash));
274 275 276
		break;

	case SKF_AD_OFF + SKF_AD_QUEUE:
277 278
		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
279 280 281
		break;

	case SKF_AD_OFF + SKF_AD_VLAN_TAG:
282 283 284 285
		cnt = convert_skb_access(SKF_AD_VLAN_TAG,
					 BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
		break;
286

287 288 289 290
	case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
		cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
					 BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
291 292
		break;

293 294 295 296 297 298 299 300 301 302
	case SKF_AD_OFF + SKF_AD_VLAN_TPID:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);

		/* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
				      offsetof(struct sk_buff, vlan_proto));
		/* A = ntohs(A) [emitting a nop or swap16] */
		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
		break;

303 304 305 306
	case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
	case SKF_AD_OFF + SKF_AD_NLATTR:
	case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
	case SKF_AD_OFF + SKF_AD_CPU:
C
Chema Gonzalez 已提交
307
	case SKF_AD_OFF + SKF_AD_RANDOM:
308
		/* arg1 = CTX */
309
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
310
		/* arg2 = A */
311
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
312
		/* arg3 = X */
313
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
314
		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
315 316
		switch (fp->k) {
		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
317
			*insn = BPF_EMIT_CALL(__skb_get_pay_offset);
318 319
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR:
320
			*insn = BPF_EMIT_CALL(__skb_get_nlattr);
321 322
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
323
			*insn = BPF_EMIT_CALL(__skb_get_nlattr_nest);
324 325
			break;
		case SKF_AD_OFF + SKF_AD_CPU:
326
			*insn = BPF_EMIT_CALL(__get_raw_cpu_id);
327
			break;
C
Chema Gonzalez 已提交
328
		case SKF_AD_OFF + SKF_AD_RANDOM:
329 330
			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
			bpf_user_rnd_init_once();
C
Chema Gonzalez 已提交
331
			break;
332 333 334 335
		}
		break;

	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
336 337
		/* A ^= X */
		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
		break;

	default:
		/* This is just a dummy call to avoid letting the compiler
		 * evict __bpf_call_base() as an optimization. Placed here
		 * where no-one bothers.
		 */
		BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
		return false;
	}

	*insnp = insn;
	return true;
}

/**
354
 *	bpf_convert_filter - convert filter program
355 356
 *	@prog: the user passed filter program
 *	@len: the length of the user passed filter program
357
 *	@new_prog: allocated 'struct bpf_prog' or NULL
358 359
 *	@new_len: pointer to store length of converted program
 *
360 361
 * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
 * style extended BPF (eBPF).
362 363 364
 * Conversion workflow:
 *
 * 1) First pass for calculating the new program length:
365
 *   bpf_convert_filter(old_prog, old_len, NULL, &new_len)
366 367 368
 *
 * 2) 2nd pass to remap in two passes: 1st pass finds new
 *    jump offsets, 2nd pass remapping:
369
 *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len);
370
 */
371
static int bpf_convert_filter(struct sock_filter *prog, int len,
372
			      struct bpf_prog *new_prog, int *new_len)
373
{
374 375
	int new_flen = 0, pass = 0, target, i, stack_off;
	struct bpf_insn *new_insn, *first_insn = NULL;
376 377 378 379 380
	struct sock_filter *fp;
	int *addrs = NULL;
	u8 bpf_src;

	BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
381
	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
382

383
	if (len <= 0 || len > BPF_MAXINSNS)
384 385 386
		return -EINVAL;

	if (new_prog) {
387
		first_insn = new_prog->insnsi;
388 389
		addrs = kcalloc(len, sizeof(*addrs),
				GFP_KERNEL | __GFP_NOWARN);
390 391 392 393 394
		if (!addrs)
			return -ENOMEM;
	}

do_pass:
395
	new_insn = first_insn;
396 397
	fp = prog;

398
	/* Classic BPF related prologue emission. */
399
	if (new_prog) {
400 401 402 403 404 405 406 407 408 409 410 411 412 413
		/* Classic BPF expects A and X to be reset first. These need
		 * to be guaranteed to be the first two instructions.
		 */
		*new_insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
		*new_insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);

		/* All programs must keep CTX in callee saved BPF_REG_CTX.
		 * In eBPF case it's done by the compiler, here we need to
		 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
		 */
		*new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
	} else {
		new_insn += 3;
	}
414 415

	for (i = 0; i < len; fp++, i++) {
416 417
		struct bpf_insn tmp_insns[6] = { };
		struct bpf_insn *insn = tmp_insns;
418 419

		if (addrs)
420
			addrs[i] = new_insn - first_insn;
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459

		switch (fp->code) {
		/* All arithmetic insns and skb loads map as-is. */
		case BPF_ALU | BPF_ADD | BPF_X:
		case BPF_ALU | BPF_ADD | BPF_K:
		case BPF_ALU | BPF_SUB | BPF_X:
		case BPF_ALU | BPF_SUB | BPF_K:
		case BPF_ALU | BPF_AND | BPF_X:
		case BPF_ALU | BPF_AND | BPF_K:
		case BPF_ALU | BPF_OR | BPF_X:
		case BPF_ALU | BPF_OR | BPF_K:
		case BPF_ALU | BPF_LSH | BPF_X:
		case BPF_ALU | BPF_LSH | BPF_K:
		case BPF_ALU | BPF_RSH | BPF_X:
		case BPF_ALU | BPF_RSH | BPF_K:
		case BPF_ALU | BPF_XOR | BPF_X:
		case BPF_ALU | BPF_XOR | BPF_K:
		case BPF_ALU | BPF_MUL | BPF_X:
		case BPF_ALU | BPF_MUL | BPF_K:
		case BPF_ALU | BPF_DIV | BPF_X:
		case BPF_ALU | BPF_DIV | BPF_K:
		case BPF_ALU | BPF_MOD | BPF_X:
		case BPF_ALU | BPF_MOD | BPF_K:
		case BPF_ALU | BPF_NEG:
		case BPF_LD | BPF_ABS | BPF_W:
		case BPF_LD | BPF_ABS | BPF_H:
		case BPF_LD | BPF_ABS | BPF_B:
		case BPF_LD | BPF_IND | BPF_W:
		case BPF_LD | BPF_IND | BPF_H:
		case BPF_LD | BPF_IND | BPF_B:
			/* Check for overloaded BPF extension and
			 * directly convert it if found, otherwise
			 * just move on with mapping.
			 */
			if (BPF_CLASS(fp->code) == BPF_LD &&
			    BPF_MODE(fp->code) == BPF_ABS &&
			    convert_bpf_extensions(fp, &insn))
				break;

460
			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
461 462
			break;

463 464 465 466 467 468 469
		/* Jump transformation cannot use BPF block macros
		 * everywhere as offset calculation and target updates
		 * require a bit more work than the rest, i.e. jump
		 * opcodes map as-is, but offsets need adjustment.
		 */

#define BPF_EMIT_JMP							\
470 471 472 473 474 475 476 477
	do {								\
		if (target >= len || target < 0)			\
			goto err;					\
		insn->off = addrs ? addrs[target] - addrs[i] - 1 : 0;	\
		/* Adjust pc relative offset for 2nd or 3rd insn. */	\
		insn->off -= insn - tmp_insns;				\
	} while (0)

478 479 480 481
		case BPF_JMP | BPF_JA:
			target = i + fp->k + 1;
			insn->code = fp->code;
			BPF_EMIT_JMP;
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
			break;

		case BPF_JMP | BPF_JEQ | BPF_K:
		case BPF_JMP | BPF_JEQ | BPF_X:
		case BPF_JMP | BPF_JSET | BPF_K:
		case BPF_JMP | BPF_JSET | BPF_X:
		case BPF_JMP | BPF_JGT | BPF_K:
		case BPF_JMP | BPF_JGT | BPF_X:
		case BPF_JMP | BPF_JGE | BPF_K:
		case BPF_JMP | BPF_JGE | BPF_X:
			if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
				/* BPF immediates are signed, zero extend
				 * immediate into tmp register and use it
				 * in compare insn.
				 */
497
				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
498

499 500
				insn->dst_reg = BPF_REG_A;
				insn->src_reg = BPF_REG_TMP;
501 502
				bpf_src = BPF_X;
			} else {
503
				insn->dst_reg = BPF_REG_A;
504 505
				insn->imm = fp->k;
				bpf_src = BPF_SRC(fp->code);
506
				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
L
Linus Torvalds 已提交
507
			}
508 509 510 511 512

			/* Common case where 'jump_false' is next insn. */
			if (fp->jf == 0) {
				insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
				target = i + fp->jt + 1;
513
				BPF_EMIT_JMP;
514
				break;
L
Linus Torvalds 已提交
515
			}
516

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
			/* Convert some jumps when 'jump_true' is next insn. */
			if (fp->jt == 0) {
				switch (BPF_OP(fp->code)) {
				case BPF_JEQ:
					insn->code = BPF_JMP | BPF_JNE | bpf_src;
					break;
				case BPF_JGT:
					insn->code = BPF_JMP | BPF_JLE | bpf_src;
					break;
				case BPF_JGE:
					insn->code = BPF_JMP | BPF_JLT | bpf_src;
					break;
				default:
					goto jmp_rest;
				}

533
				target = i + fp->jf + 1;
534
				BPF_EMIT_JMP;
535
				break;
536
			}
537
jmp_rest:
538 539 540
			/* Other jumps are mapped into two insns: Jxx and JA. */
			target = i + fp->jt + 1;
			insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
541
			BPF_EMIT_JMP;
542 543 544 545
			insn++;

			insn->code = BPF_JMP | BPF_JA;
			target = i + fp->jf + 1;
546
			BPF_EMIT_JMP;
547 548 549 550
			break;

		/* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
		case BPF_LDX | BPF_MSH | BPF_B:
551
			/* tmp = A */
552
			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_A);
553
			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
554
			*insn++ = BPF_LD_ABS(BPF_B, fp->k);
555
			/* A &= 0xf */
556
			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
557
			/* A <<= 2 */
558
			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
559
			/* X = A */
560
			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
561
			/* A = tmp */
562
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
563 564
			break;

565 566 567
		/* RET_K is remaped into 2 insns. RET_A case doesn't need an
		 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
		 */
568 569
		case BPF_RET | BPF_A:
		case BPF_RET | BPF_K:
570 571 572
			if (BPF_RVAL(fp->code) == BPF_K)
				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
							0, fp->k);
573
			*insn = BPF_EXIT_INSN();
574 575 576 577 578
			break;

		/* Store to stack. */
		case BPF_ST:
		case BPF_STX:
579
			stack_off = fp->k * 4  + 4;
580 581
			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
					    BPF_ST ? BPF_REG_A : BPF_REG_X,
582 583 584 585 586 587 588
					    -stack_off);
			/* check_load_and_stores() verifies that classic BPF can
			 * load from stack only after write, so tracking
			 * stack_depth for ST|STX insns is enough
			 */
			if (new_prog && new_prog->aux->stack_depth < stack_off)
				new_prog->aux->stack_depth = stack_off;
589 590 591 592 593
			break;

		/* Load from stack. */
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
594
			stack_off = fp->k * 4  + 4;
595 596
			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
597
					    -stack_off);
598 599 600 601 602
			break;

		/* A = K or X = K */
		case BPF_LD | BPF_IMM:
		case BPF_LDX | BPF_IMM:
603 604
			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
					      BPF_REG_A : BPF_REG_X, fp->k);
605 606 607 608
			break;

		/* X = A */
		case BPF_MISC | BPF_TAX:
609
			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
610 611 612 613
			break;

		/* A = X */
		case BPF_MISC | BPF_TXA:
614
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
615 616 617 618 619
			break;

		/* A = skb->len or X = skb->len */
		case BPF_LD | BPF_W | BPF_LEN:
		case BPF_LDX | BPF_W | BPF_LEN:
620 621 622
			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
					    BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
					    offsetof(struct sk_buff, len));
623 624
			break;

625
		/* Access seccomp_data fields. */
626
		case BPF_LDX | BPF_ABS | BPF_W:
627 628
			/* A = *(u32 *) (ctx + K) */
			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
629 630
			break;

S
Stephen Hemminger 已提交
631
		/* Unknown instruction. */
L
Linus Torvalds 已提交
632
		default:
633
			goto err;
L
Linus Torvalds 已提交
634
		}
635 636 637 638 639 640

		insn++;
		if (new_prog)
			memcpy(new_insn, tmp_insns,
			       sizeof(*insn) * (insn - tmp_insns));
		new_insn += insn - tmp_insns;
L
Linus Torvalds 已提交
641 642
	}

643 644
	if (!new_prog) {
		/* Only calculating new length. */
645
		*new_len = new_insn - first_insn;
646 647 648 649
		return 0;
	}

	pass++;
650 651
	if (new_flen != new_insn - first_insn) {
		new_flen = new_insn - first_insn;
652 653 654 655 656 657 658
		if (pass > 2)
			goto err;
		goto do_pass;
	}

	kfree(addrs);
	BUG_ON(*new_len != new_flen);
L
Linus Torvalds 已提交
659
	return 0;
660 661 662
err:
	kfree(addrs);
	return -EINVAL;
L
Linus Torvalds 已提交
663 664
}

665 666
/* Security:
 *
667
 * As we dont want to clear mem[] array for each packet going through
L
Li RongQing 已提交
668
 * __bpf_prog_run(), we check that filter loaded by user never try to read
669
 * a cell if not previously written, and we check all branches to be sure
L
Lucas De Marchi 已提交
670
 * a malicious user doesn't try to abuse us.
671
 */
672
static int check_load_and_stores(const struct sock_filter *filter, int flen)
673
{
674
	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
675 676 677
	int pc, ret = 0;

	BUILD_BUG_ON(BPF_MEMWORDS > 16);
678

679
	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
680 681
	if (!masks)
		return -ENOMEM;
682

683 684 685 686 687 688
	memset(masks, 0xff, flen * sizeof(*masks));

	for (pc = 0; pc < flen; pc++) {
		memvalid &= masks[pc];

		switch (filter[pc].code) {
689 690
		case BPF_ST:
		case BPF_STX:
691 692
			memvalid |= (1 << filter[pc].k);
			break;
693 694
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
695 696 697 698 699
			if (!(memvalid & (1 << filter[pc].k))) {
				ret = -EINVAL;
				goto error;
			}
			break;
700 701
		case BPF_JMP | BPF_JA:
			/* A jump must set masks on target */
702 703 704
			masks[pc + 1 + filter[pc].k] &= memvalid;
			memvalid = ~0;
			break;
705 706 707 708 709 710 711 712 713
		case BPF_JMP | BPF_JEQ | BPF_K:
		case BPF_JMP | BPF_JEQ | BPF_X:
		case BPF_JMP | BPF_JGE | BPF_K:
		case BPF_JMP | BPF_JGE | BPF_X:
		case BPF_JMP | BPF_JGT | BPF_K:
		case BPF_JMP | BPF_JGT | BPF_X:
		case BPF_JMP | BPF_JSET | BPF_K:
		case BPF_JMP | BPF_JSET | BPF_X:
			/* A jump must set masks on targets */
714 715 716 717 718 719 720 721 722 723 724
			masks[pc + 1 + filter[pc].jt] &= memvalid;
			masks[pc + 1 + filter[pc].jf] &= memvalid;
			memvalid = ~0;
			break;
		}
	}
error:
	kfree(masks);
	return ret;
}

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
static bool chk_code_allowed(u16 code_to_probe)
{
	static const bool codes[] = {
		/* 32 bit ALU operations */
		[BPF_ALU | BPF_ADD | BPF_K] = true,
		[BPF_ALU | BPF_ADD | BPF_X] = true,
		[BPF_ALU | BPF_SUB | BPF_K] = true,
		[BPF_ALU | BPF_SUB | BPF_X] = true,
		[BPF_ALU | BPF_MUL | BPF_K] = true,
		[BPF_ALU | BPF_MUL | BPF_X] = true,
		[BPF_ALU | BPF_DIV | BPF_K] = true,
		[BPF_ALU | BPF_DIV | BPF_X] = true,
		[BPF_ALU | BPF_MOD | BPF_K] = true,
		[BPF_ALU | BPF_MOD | BPF_X] = true,
		[BPF_ALU | BPF_AND | BPF_K] = true,
		[BPF_ALU | BPF_AND | BPF_X] = true,
		[BPF_ALU | BPF_OR | BPF_K] = true,
		[BPF_ALU | BPF_OR | BPF_X] = true,
		[BPF_ALU | BPF_XOR | BPF_K] = true,
		[BPF_ALU | BPF_XOR | BPF_X] = true,
		[BPF_ALU | BPF_LSH | BPF_K] = true,
		[BPF_ALU | BPF_LSH | BPF_X] = true,
		[BPF_ALU | BPF_RSH | BPF_K] = true,
		[BPF_ALU | BPF_RSH | BPF_X] = true,
		[BPF_ALU | BPF_NEG] = true,
		/* Load instructions */
		[BPF_LD | BPF_W | BPF_ABS] = true,
		[BPF_LD | BPF_H | BPF_ABS] = true,
		[BPF_LD | BPF_B | BPF_ABS] = true,
		[BPF_LD | BPF_W | BPF_LEN] = true,
		[BPF_LD | BPF_W | BPF_IND] = true,
		[BPF_LD | BPF_H | BPF_IND] = true,
		[BPF_LD | BPF_B | BPF_IND] = true,
		[BPF_LD | BPF_IMM] = true,
		[BPF_LD | BPF_MEM] = true,
		[BPF_LDX | BPF_W | BPF_LEN] = true,
		[BPF_LDX | BPF_B | BPF_MSH] = true,
		[BPF_LDX | BPF_IMM] = true,
		[BPF_LDX | BPF_MEM] = true,
		/* Store instructions */
		[BPF_ST] = true,
		[BPF_STX] = true,
		/* Misc instructions */
		[BPF_MISC | BPF_TAX] = true,
		[BPF_MISC | BPF_TXA] = true,
		/* Return instructions */
		[BPF_RET | BPF_K] = true,
		[BPF_RET | BPF_A] = true,
		/* Jump instructions */
		[BPF_JMP | BPF_JA] = true,
		[BPF_JMP | BPF_JEQ | BPF_K] = true,
		[BPF_JMP | BPF_JEQ | BPF_X] = true,
		[BPF_JMP | BPF_JGE | BPF_K] = true,
		[BPF_JMP | BPF_JGE | BPF_X] = true,
		[BPF_JMP | BPF_JGT | BPF_K] = true,
		[BPF_JMP | BPF_JGT | BPF_X] = true,
		[BPF_JMP | BPF_JSET | BPF_K] = true,
		[BPF_JMP | BPF_JSET | BPF_X] = true,
	};

	if (code_to_probe >= ARRAY_SIZE(codes))
		return false;

	return codes[code_to_probe];
}

791 792 793 794 795 796 797 798 799 800 801
static bool bpf_check_basics_ok(const struct sock_filter *filter,
				unsigned int flen)
{
	if (filter == NULL)
		return false;
	if (flen == 0 || flen > BPF_MAXINSNS)
		return false;

	return true;
}

L
Linus Torvalds 已提交
802
/**
803
 *	bpf_check_classic - verify socket filter code
L
Linus Torvalds 已提交
804 805 806 807 808
 *	@filter: filter to verify
 *	@flen: length of filter
 *
 * Check the user's filter code. If we let some ugly
 * filter code slip through kaboom! The filter must contain
809 810
 * no references or jumps that are out of range, no illegal
 * instructions, and must end with a RET instruction.
L
Linus Torvalds 已提交
811
 *
812 813 814
 * All jumps are forward as they are not signed.
 *
 * Returns 0 if the rule set is legal or -EINVAL if not.
L
Linus Torvalds 已提交
815
 */
816 817
static int bpf_check_classic(const struct sock_filter *filter,
			     unsigned int flen)
L
Linus Torvalds 已提交
818
{
819
	bool anc_found;
820
	int pc;
L
Linus Torvalds 已提交
821

822
	/* Check the filter code now */
L
Linus Torvalds 已提交
823
	for (pc = 0; pc < flen; pc++) {
824
		const struct sock_filter *ftest = &filter[pc];
825

826 827
		/* May we actually operate on this code? */
		if (!chk_code_allowed(ftest->code))
828
			return -EINVAL;
829

830
		/* Some instructions need special checks */
831 832 833 834
		switch (ftest->code) {
		case BPF_ALU | BPF_DIV | BPF_K:
		case BPF_ALU | BPF_MOD | BPF_K:
			/* Check for division by zero */
E
Eric Dumazet 已提交
835 836 837
			if (ftest->k == 0)
				return -EINVAL;
			break;
R
Rabin Vincent 已提交
838 839 840 841 842
		case BPF_ALU | BPF_LSH | BPF_K:
		case BPF_ALU | BPF_RSH | BPF_K:
			if (ftest->k >= 32)
				return -EINVAL;
			break;
843 844 845 846 847
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
		case BPF_ST:
		case BPF_STX:
			/* Check for invalid memory addresses */
848 849 850
			if (ftest->k >= BPF_MEMWORDS)
				return -EINVAL;
			break;
851 852
		case BPF_JMP | BPF_JA:
			/* Note, the large ftest->k might cause loops.
853 854 855
			 * Compare this with conditional jumps below,
			 * where offsets are limited. --ANK (981016)
			 */
856
			if (ftest->k >= (unsigned int)(flen - pc - 1))
857
				return -EINVAL;
858
			break;
859 860 861 862 863 864 865 866 867
		case BPF_JMP | BPF_JEQ | BPF_K:
		case BPF_JMP | BPF_JEQ | BPF_X:
		case BPF_JMP | BPF_JGE | BPF_K:
		case BPF_JMP | BPF_JGE | BPF_X:
		case BPF_JMP | BPF_JGT | BPF_K:
		case BPF_JMP | BPF_JGT | BPF_X:
		case BPF_JMP | BPF_JSET | BPF_K:
		case BPF_JMP | BPF_JSET | BPF_X:
			/* Both conditionals must be safe */
868
			if (pc + ftest->jt + 1 >= flen ||
869 870
			    pc + ftest->jf + 1 >= flen)
				return -EINVAL;
871
			break;
872 873 874
		case BPF_LD | BPF_W | BPF_ABS:
		case BPF_LD | BPF_H | BPF_ABS:
		case BPF_LD | BPF_B | BPF_ABS:
875
			anc_found = false;
876 877 878
			if (bpf_anc_helper(ftest) & BPF_ANC)
				anc_found = true;
			/* Ancillary operation unknown or unsupported */
879 880
			if (anc_found == false && ftest->k >= SKF_AD_OFF)
				return -EINVAL;
881 882
		}
	}
883

884
	/* Last instruction must be a RET code */
885
	switch (filter[flen - 1].code) {
886 887
	case BPF_RET | BPF_K:
	case BPF_RET | BPF_A:
888
		return check_load_and_stores(filter, flen);
889
	}
890

891
	return -EINVAL;
L
Linus Torvalds 已提交
892 893
}

894 895
static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
				      const struct sock_fprog *fprog)
896
{
897
	unsigned int fsize = bpf_classic_proglen(fprog);
898 899 900 901 902 903 904 905
	struct sock_fprog_kern *fkprog;

	fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
	if (!fp->orig_prog)
		return -ENOMEM;

	fkprog = fp->orig_prog;
	fkprog->len = fprog->len;
906 907 908

	fkprog->filter = kmemdup(fp->insns, fsize,
				 GFP_KERNEL | __GFP_NOWARN);
909 910 911 912 913 914 915 916
	if (!fkprog->filter) {
		kfree(fp->orig_prog);
		return -ENOMEM;
	}

	return 0;
}

917
static void bpf_release_orig_filter(struct bpf_prog *fp)
918 919 920 921 922 923 924 925 926
{
	struct sock_fprog_kern *fprog = fp->orig_prog;

	if (fprog) {
		kfree(fprog->filter);
		kfree(fprog);
	}
}

927 928
static void __bpf_prog_release(struct bpf_prog *prog)
{
929
	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
930 931 932 933 934
		bpf_prog_put(prog);
	} else {
		bpf_release_orig_filter(prog);
		bpf_prog_free(prog);
	}
935 936
}

937 938
static void __sk_filter_release(struct sk_filter *fp)
{
939 940
	__bpf_prog_release(fp->prog);
	kfree(fp);
941 942
}

943
/**
E
Eric Dumazet 已提交
944
 * 	sk_filter_release_rcu - Release a socket filter by rcu_head
945 946
 *	@rcu: rcu_head that contains the sk_filter to free
 */
947
static void sk_filter_release_rcu(struct rcu_head *rcu)
948 949 950
{
	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);

951
	__sk_filter_release(fp);
952
}
953 954 955 956 957 958 959 960 961

/**
 *	sk_filter_release - release a socket filter
 *	@fp: filter to remove
 *
 *	Remove a filter from a socket and release its resources.
 */
static void sk_filter_release(struct sk_filter *fp)
{
962
	if (refcount_dec_and_test(&fp->refcnt))
963 964 965 966 967
		call_rcu(&fp->rcu, sk_filter_release_rcu);
}

void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
{
968
	u32 filter_size = bpf_prog_size(fp->prog->len);
969

970 971
	atomic_sub(filter_size, &sk->sk_omem_alloc);
	sk_filter_release(fp);
972
}
973

974 975 976
/* try to charge the socket memory if there is space available
 * return true on success
 */
977
static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
978
{
979
	u32 filter_size = bpf_prog_size(fp->prog->len);
980 981 982 983 984 985

	/* same check as in sock_kmalloc() */
	if (filter_size <= sysctl_optmem_max &&
	    atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
		atomic_add(filter_size, &sk->sk_omem_alloc);
		return true;
986
	}
987
	return false;
988 989
}

990 991 992 993 994 995 996 997
bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
{
	bool ret = __sk_filter_charge(sk, fp);
	if (ret)
		refcount_inc(&fp->refcnt);
	return ret;
}

998
static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
999 1000
{
	struct sock_filter *old_prog;
1001
	struct bpf_prog *old_fp;
1002
	int err, new_len, old_len = fp->len;
1003 1004 1005 1006 1007 1008 1009

	/* We are free to overwrite insns et al right here as it
	 * won't be used at this point in time anymore internally
	 * after the migration to the internal BPF instruction
	 * representation.
	 */
	BUILD_BUG_ON(sizeof(struct sock_filter) !=
1010
		     sizeof(struct bpf_insn));
1011 1012 1013 1014 1015 1016

	/* Conversion cannot happen on overlapping memory areas,
	 * so we need to keep the user BPF around until the 2nd
	 * pass. At this time, the user BPF is stored in fp->insns.
	 */
	old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1017
			   GFP_KERNEL | __GFP_NOWARN);
1018 1019 1020 1021 1022 1023
	if (!old_prog) {
		err = -ENOMEM;
		goto out_err;
	}

	/* 1st pass: calculate the new program length. */
1024
	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
1025 1026 1027 1028 1029
	if (err)
		goto out_err_free;

	/* Expand fp for appending the new filter representation. */
	old_fp = fp;
1030
	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	if (!fp) {
		/* The old_fp is still around in case we couldn't
		 * allocate new memory, so uncharge on that one.
		 */
		fp = old_fp;
		err = -ENOMEM;
		goto out_err_free;
	}

	fp->len = new_len;

1042
	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1043
	err = bpf_convert_filter(old_prog, old_len, fp, &new_len);
1044
	if (err)
1045
		/* 2nd bpf_convert_filter() can fail only if it fails
1046 1047
		 * to allocate memory, remapping must succeed. Note,
		 * that at this time old_fp has already been released
1048
		 * by krealloc().
1049 1050 1051
		 */
		goto out_err_free;

1052 1053 1054 1055 1056
	/* We are guaranteed to never error here with cBPF to eBPF
	 * transitions, since there's no issue with type compatibility
	 * checks on program arrays.
	 */
	fp = bpf_prog_select_runtime(fp, &err);
1057

1058 1059 1060 1061 1062 1063
	kfree(old_prog);
	return fp;

out_err_free:
	kfree(old_prog);
out_err:
1064
	__bpf_prog_release(fp);
1065 1066 1067
	return ERR_PTR(err);
}

1068 1069
static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
					   bpf_aux_classic_check_t trans)
1070 1071 1072
{
	int err;

1073
	fp->bpf_func = NULL;
1074
	fp->jited = 0;
1075

1076
	err = bpf_check_classic(fp->insns, fp->len);
1077
	if (err) {
1078
		__bpf_prog_release(fp);
1079
		return ERR_PTR(err);
1080
	}
1081

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	/* There might be additional checks and transformations
	 * needed on classic filters, f.e. in case of seccomp.
	 */
	if (trans) {
		err = trans(fp->insns, fp->len);
		if (err) {
			__bpf_prog_release(fp);
			return ERR_PTR(err);
		}
	}

1093 1094 1095
	/* Probe if we can JIT compile the filter and if so, do
	 * the compilation of the filter.
	 */
1096
	bpf_jit_compile(fp);
1097 1098 1099 1100

	/* JIT compiler couldn't process this filter, so do the
	 * internal BPF translation for the optimized interpreter.
	 */
1101
	if (!fp->jited)
1102
		fp = bpf_migrate_filter(fp);
1103 1104

	return fp;
1105 1106 1107
}

/**
1108
 *	bpf_prog_create - create an unattached filter
R
Randy Dunlap 已提交
1109
 *	@pfp: the unattached filter that is created
1110
 *	@fprog: the filter program
1111
 *
R
Randy Dunlap 已提交
1112
 * Create a filter independent of any socket. We first run some
1113 1114 1115 1116
 * sanity checks on it to make sure it does not explode on us later.
 * If an error occurs or there is insufficient memory for the filter
 * a negative errno code is returned. On success the return is zero.
 */
1117
int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1118
{
1119
	unsigned int fsize = bpf_classic_proglen(fprog);
1120
	struct bpf_prog *fp;
1121 1122

	/* Make sure new filter is there and in the right amounts. */
1123
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1124 1125
		return -EINVAL;

1126
	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1127 1128
	if (!fp)
		return -ENOMEM;
1129

1130 1131 1132
	memcpy(fp->insns, fprog->filter, fsize);

	fp->len = fprog->len;
1133 1134 1135 1136 1137
	/* Since unattached filters are not copied back to user
	 * space through sk_get_filter(), we do not need to hold
	 * a copy here, and can spare us the work.
	 */
	fp->orig_prog = NULL;
1138

1139
	/* bpf_prepare_filter() already takes care of freeing
1140 1141
	 * memory in case something goes wrong.
	 */
1142
	fp = bpf_prepare_filter(fp, NULL);
1143 1144
	if (IS_ERR(fp))
		return PTR_ERR(fp);
1145 1146 1147 1148

	*pfp = fp;
	return 0;
}
1149
EXPORT_SYMBOL_GPL(bpf_prog_create);
1150

1151 1152 1153 1154 1155
/**
 *	bpf_prog_create_from_user - create an unattached filter from user buffer
 *	@pfp: the unattached filter that is created
 *	@fprog: the filter program
 *	@trans: post-classic verifier transformation handler
1156
 *	@save_orig: save classic BPF program
1157 1158 1159 1160 1161 1162
 *
 * This function effectively does the same as bpf_prog_create(), only
 * that it builds up its insns buffer from user space provided buffer.
 * It also allows for passing a bpf_aux_classic_check_t handler.
 */
int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1163
			      bpf_aux_classic_check_t trans, bool save_orig)
1164 1165 1166
{
	unsigned int fsize = bpf_classic_proglen(fprog);
	struct bpf_prog *fp;
1167
	int err;
1168 1169

	/* Make sure new filter is there and in the right amounts. */
1170
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
		return -EINVAL;

	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
	if (!fp)
		return -ENOMEM;

	if (copy_from_user(fp->insns, fprog->filter, fsize)) {
		__bpf_prog_free(fp);
		return -EFAULT;
	}

	fp->len = fprog->len;
	fp->orig_prog = NULL;

1185 1186 1187 1188 1189 1190 1191 1192
	if (save_orig) {
		err = bpf_prog_store_orig_filter(fp, fprog);
		if (err) {
			__bpf_prog_free(fp);
			return -ENOMEM;
		}
	}

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
	/* bpf_prepare_filter() already takes care of freeing
	 * memory in case something goes wrong.
	 */
	fp = bpf_prepare_filter(fp, trans);
	if (IS_ERR(fp))
		return PTR_ERR(fp);

	*pfp = fp;
	return 0;
}
1203
EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1204

1205
void bpf_prog_destroy(struct bpf_prog *fp)
1206
{
1207
	__bpf_prog_release(fp);
1208
}
1209
EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1210

1211
static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1212 1213 1214 1215 1216 1217 1218 1219 1220
{
	struct sk_filter *fp, *old_fp;

	fp = kmalloc(sizeof(*fp), GFP_KERNEL);
	if (!fp)
		return -ENOMEM;

	fp->prog = prog;

1221
	if (!__sk_filter_charge(sk, fp)) {
1222 1223 1224
		kfree(fp);
		return -ENOMEM;
	}
1225
	refcount_set(&fp->refcnt, 1);
1226

1227 1228
	old_fp = rcu_dereference_protected(sk->sk_filter,
					   lockdep_sock_is_held(sk));
1229
	rcu_assign_pointer(sk->sk_filter, fp);
1230

1231 1232 1233 1234 1235 1236
	if (old_fp)
		sk_filter_uncharge(sk, old_fp);

	return 0;
}

1237 1238 1239 1240 1241 1242 1243 1244
static int __reuseport_attach_prog(struct bpf_prog *prog, struct sock *sk)
{
	struct bpf_prog *old_prog;
	int err;

	if (bpf_prog_size(prog->len) > sysctl_optmem_max)
		return -ENOMEM;

1245
	if (sk_unhashed(sk) && sk->sk_reuseport) {
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
		err = reuseport_alloc(sk);
		if (err)
			return err;
	} else if (!rcu_access_pointer(sk->sk_reuseport_cb)) {
		/* The socket wasn't bound with SO_REUSEPORT */
		return -EINVAL;
	}

	old_prog = reuseport_attach_prog(sk, prog);
	if (old_prog)
		bpf_prog_destroy(old_prog);

	return 0;
}

static
struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
L
Linus Torvalds 已提交
1263
{
1264
	unsigned int fsize = bpf_classic_proglen(fprog);
1265
	struct bpf_prog *prog;
L
Linus Torvalds 已提交
1266 1267
	int err;

1268
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1269
		return ERR_PTR(-EPERM);
1270

L
Linus Torvalds 已提交
1271
	/* Make sure new filter is there and in the right amounts. */
1272
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1273
		return ERR_PTR(-EINVAL);
L
Linus Torvalds 已提交
1274

1275
	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1276
	if (!prog)
1277
		return ERR_PTR(-ENOMEM);
1278

1279
	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1280
		__bpf_prog_free(prog);
1281
		return ERR_PTR(-EFAULT);
L
Linus Torvalds 已提交
1282 1283
	}

1284
	prog->len = fprog->len;
L
Linus Torvalds 已提交
1285

1286
	err = bpf_prog_store_orig_filter(prog, fprog);
1287
	if (err) {
1288
		__bpf_prog_free(prog);
1289
		return ERR_PTR(-ENOMEM);
1290 1291
	}

1292
	/* bpf_prepare_filter() already takes care of freeing
1293 1294
	 * memory in case something goes wrong.
	 */
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
	return bpf_prepare_filter(prog, NULL);
}

/**
 *	sk_attach_filter - attach a socket filter
 *	@fprog: the filter program
 *	@sk: the socket to use
 *
 * Attach the user's filter code. We first run some sanity checks on
 * it to make sure it does not explode on us later. If an error
 * occurs or there is insufficient memory for the filter a negative
 * errno code is returned. On success the return is zero.
 */
1308
int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1309 1310 1311 1312
{
	struct bpf_prog *prog = __get_filter(fprog, sk);
	int err;

1313 1314 1315
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1316
	err = __sk_attach_prog(prog, sk);
1317
	if (err < 0) {
1318
		__bpf_prog_release(prog);
1319
		return err;
1320 1321
	}

1322
	return 0;
L
Linus Torvalds 已提交
1323
}
1324
EXPORT_SYMBOL_GPL(sk_attach_filter);
L
Linus Torvalds 已提交
1325

1326
int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1327
{
1328
	struct bpf_prog *prog = __get_filter(fprog, sk);
1329
	int err;
1330

1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
	if (IS_ERR(prog))
		return PTR_ERR(prog);

	err = __reuseport_attach_prog(prog, sk);
	if (err < 0) {
		__bpf_prog_release(prog);
		return err;
	}

	return 0;
}

static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
{
1345
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1346
		return ERR_PTR(-EPERM);
1347

1348
	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
}

int sk_attach_bpf(u32 ufd, struct sock *sk)
{
	struct bpf_prog *prog = __get_bpf(ufd, sk);
	int err;

	if (IS_ERR(prog))
		return PTR_ERR(prog);

1359
	err = __sk_attach_prog(prog, sk);
1360
	if (err < 0) {
1361
		bpf_prog_put(prog);
1362
		return err;
1363 1364 1365 1366 1367
	}

	return 0;
}

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
{
	struct bpf_prog *prog = __get_bpf(ufd, sk);
	int err;

	if (IS_ERR(prog))
		return PTR_ERR(prog);

	err = __reuseport_attach_prog(prog, sk);
	if (err < 0) {
		bpf_prog_put(prog);
		return err;
	}

	return 0;
}

1385 1386 1387 1388 1389 1390 1391 1392
struct bpf_scratchpad {
	union {
		__be32 diff[MAX_BPF_STACK / sizeof(__be32)];
		u8     buff[MAX_BPF_STACK];
	};
};

static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1393

1394 1395 1396 1397 1398 1399
static inline int __bpf_try_make_writable(struct sk_buff *skb,
					  unsigned int write_len)
{
	return skb_ensure_writable(skb, write_len);
}

1400 1401 1402
static inline int bpf_try_make_writable(struct sk_buff *skb,
					unsigned int write_len)
{
1403
	int err = __bpf_try_make_writable(skb, write_len);
1404

1405
	bpf_compute_data_end(skb);
1406 1407 1408
	return err;
}

1409 1410 1411 1412 1413
static int bpf_try_make_head_writable(struct sk_buff *skb)
{
	return bpf_try_make_writable(skb, skb_headlen(skb));
}

1414 1415 1416 1417 1418 1419
static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
{
	if (skb_at_tc_ingress(skb))
		skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
}

1420 1421 1422 1423 1424 1425
static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
{
	if (skb_at_tc_ingress(skb))
		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
}

1426 1427
BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
	   const void *, from, u32, len, u64, flags)
1428 1429 1430
{
	void *ptr;

1431
	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1432
		return -EINVAL;
1433
	if (unlikely(offset > 0xffff))
1434
		return -EFAULT;
1435
	if (unlikely(bpf_try_make_writable(skb, offset + len)))
1436 1437
		return -EFAULT;

1438
	ptr = skb->data + offset;
1439
	if (flags & BPF_F_RECOMPUTE_CSUM)
1440
		__skb_postpull_rcsum(skb, ptr, len, offset);
1441 1442 1443

	memcpy(ptr, from, len);

1444
	if (flags & BPF_F_RECOMPUTE_CSUM)
1445
		__skb_postpush_rcsum(skb, ptr, len, offset);
1446 1447
	if (flags & BPF_F_INVALIDATE_HASH)
		skb_clear_hash(skb);
1448

1449 1450 1451
	return 0;
}

1452
static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1453 1454 1455 1456 1457
	.func		= bpf_skb_store_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
1458 1459
	.arg3_type	= ARG_PTR_TO_MEM,
	.arg4_type	= ARG_CONST_SIZE,
1460 1461 1462
	.arg5_type	= ARG_ANYTHING,
};

1463 1464
BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
	   void *, to, u32, len)
1465 1466 1467
{
	void *ptr;

1468
	if (unlikely(offset > 0xffff))
1469
		goto err_clear;
1470 1471 1472

	ptr = skb_header_pointer(skb, offset, len, to);
	if (unlikely(!ptr))
1473
		goto err_clear;
1474 1475 1476 1477
	if (ptr != to)
		memcpy(to, ptr, len);

	return 0;
1478 1479 1480
err_clear:
	memset(to, 0, len);
	return -EFAULT;
1481 1482
}

1483
static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1484 1485 1486 1487 1488
	.func		= bpf_skb_load_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
1489 1490
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
1491 1492
};

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
{
	/* Idea is the following: should the needed direct read/write
	 * test fail during runtime, we can pull in more data and redo
	 * again, since implicitly, we invalidate previous checks here.
	 *
	 * Or, since we know how much we need to make read/writeable,
	 * this can be done once at the program beginning for direct
	 * access case. By this we overcome limitations of only current
	 * headroom being accessible.
	 */
	return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
}

static const struct bpf_func_proto bpf_skb_pull_data_proto = {
	.func		= bpf_skb_pull_data,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

1515 1516
BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
	   u64, from, u64, to, u64, flags)
1517
{
1518
	__sum16 *ptr;
1519

1520 1521
	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
		return -EINVAL;
1522
	if (unlikely(offset > 0xffff || offset & 1))
1523
		return -EFAULT;
1524
	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1525 1526
		return -EFAULT;

1527
	ptr = (__sum16 *)(skb->data + offset);
1528
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1529 1530 1531 1532 1533 1534
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		csum_replace_by_diff(ptr, to);
		break;
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	case 2:
		csum_replace2(ptr, from, to);
		break;
	case 4:
		csum_replace4(ptr, from, to);
		break;
	default:
		return -EINVAL;
	}

	return 0;
}

1548
static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
	.func		= bpf_l3_csum_replace,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
	.arg5_type	= ARG_ANYTHING,
};

1559 1560
BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
	   u64, from, u64, to, u64, flags)
1561
{
1562
	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1563
	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1564
	bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1565
	__sum16 *ptr;
1566

1567 1568
	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
			       BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1569
		return -EINVAL;
1570
	if (unlikely(offset > 0xffff || offset & 1))
1571
		return -EFAULT;
1572
	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1573 1574
		return -EFAULT;

1575
	ptr = (__sum16 *)(skb->data + offset);
1576
	if (is_mmzero && !do_mforce && !*ptr)
1577
		return 0;
1578

1579
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1580 1581 1582 1583 1584 1585
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
		break;
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
	case 2:
		inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
		break;
	case 4:
		inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
		break;
	default:
		return -EINVAL;
	}

1596 1597
	if (is_mmzero && !*ptr)
		*ptr = CSUM_MANGLED_0;
1598 1599 1600
	return 0;
}

1601
static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1602 1603 1604 1605 1606 1607 1608 1609
	.func		= bpf_l4_csum_replace,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
	.arg5_type	= ARG_ANYTHING,
1610 1611
};

1612 1613
BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
	   __be32 *, to, u32, to_size, __wsum, seed)
1614
{
1615
	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1616
	u32 diff_size = from_size + to_size;
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
	int i, j = 0;

	/* This is quite flexible, some examples:
	 *
	 * from_size == 0, to_size > 0,  seed := csum --> pushing data
	 * from_size > 0,  to_size == 0, seed := csum --> pulling data
	 * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
	 *
	 * Even for diffing, from_size and to_size don't need to be equal.
	 */
	if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
		     diff_size > sizeof(sp->diff)))
		return -EINVAL;

	for (i = 0; i < from_size / sizeof(__be32); i++, j++)
		sp->diff[j] = ~from[i];
	for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
		sp->diff[j] = to[i];

	return csum_partial(sp->diff, diff_size, seed);
}

1639
static const struct bpf_func_proto bpf_csum_diff_proto = {
1640 1641
	.func		= bpf_csum_diff,
	.gpl_only	= false,
1642
	.pkt_access	= true,
1643
	.ret_type	= RET_INTEGER,
1644 1645 1646 1647
	.arg1_type	= ARG_PTR_TO_MEM,
	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
	.arg3_type	= ARG_PTR_TO_MEM,
	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
1648 1649 1650
	.arg5_type	= ARG_ANYTHING,
};

1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
{
	/* The interface is to be used in combination with bpf_csum_diff()
	 * for direct packet writes. csum rotation for alignment as well
	 * as emulating csum_sub() can be done from the eBPF program.
	 */
	if (skb->ip_summed == CHECKSUM_COMPLETE)
		return (skb->csum = csum_add(skb->csum, csum));

	return -ENOTSUPP;
}

static const struct bpf_func_proto bpf_csum_update_proto = {
	.func		= bpf_csum_update,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

1671 1672 1673 1674 1675
static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
{
	return dev_forward_skb(dev, skb);
}

1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
				      struct sk_buff *skb)
{
	int ret = ____dev_forward_skb(dev, skb);

	if (likely(!ret)) {
		skb->dev = dev;
		ret = netif_rx(skb);
	}

	return ret;
}

1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
{
	int ret;

	if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) {
		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
		kfree_skb(skb);
		return -ENETDOWN;
	}

	skb->dev = dev;

	__this_cpu_inc(xmit_recursion);
	ret = dev_queue_xmit(skb);
	__this_cpu_dec(xmit_recursion);

	return ret;
}

1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
				 u32 flags)
{
	/* skb->mac_len is not set on normal egress */
	unsigned int mlen = skb->network_header - skb->mac_header;

	__skb_pull(skb, mlen);

	/* At ingress, the mac header has already been pulled once.
	 * At egress, skb_pospull_rcsum has to be done in case that
	 * the skb is originated from ingress (i.e. a forwarded skb)
	 * to ensure that rcsum starts at net header.
	 */
	if (!skb_at_tc_ingress(skb))
		skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
	skb_pop_mac_header(skb);
	skb_reset_mac_len(skb);
	return flags & BPF_F_INGRESS ?
	       __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
}

static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
				 u32 flags)
{
1732 1733 1734 1735 1736 1737
	/* Verify that a link layer header is carried */
	if (unlikely(skb->mac_header >= skb->network_header)) {
		kfree_skb(skb);
		return -ERANGE;
	}

1738 1739 1740 1741 1742 1743 1744 1745
	bpf_push_mac_rcsum(skb);
	return flags & BPF_F_INGRESS ?
	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
}

static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
			  u32 flags)
{
1746
	if (dev_is_mac_header_xmit(dev))
1747
		return __bpf_redirect_common(skb, dev, flags);
1748 1749
	else
		return __bpf_redirect_no_mac(skb, dev, flags);
1750 1751
}

1752
BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
1753 1754
{
	struct net_device *dev;
1755 1756
	struct sk_buff *clone;
	int ret;
1757

1758 1759 1760
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return -EINVAL;

1761 1762 1763 1764
	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
	if (unlikely(!dev))
		return -EINVAL;

1765 1766
	clone = skb_clone(skb, GFP_ATOMIC);
	if (unlikely(!clone))
1767 1768
		return -ENOMEM;

1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
	/* For direct write, we need to keep the invariant that the skbs
	 * we're dealing with need to be uncloned. Should uncloning fail
	 * here, we need to free the just generated clone to unclone once
	 * again.
	 */
	ret = bpf_try_make_head_writable(skb);
	if (unlikely(ret)) {
		kfree_skb(clone);
		return -ENOMEM;
	}

1780
	return __bpf_redirect(clone, dev, flags);
1781 1782
}

1783
static const struct bpf_func_proto bpf_clone_redirect_proto = {
1784 1785 1786 1787 1788 1789 1790 1791
	.func           = bpf_clone_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};

1792 1793 1794
struct redirect_info {
	u32 ifindex;
	u32 flags;
1795
	struct bpf_map *map;
1796
	struct bpf_map *map_to_flush;
1797 1798 1799
};

static DEFINE_PER_CPU(struct redirect_info, redirect_info);
1800

1801
BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
1802 1803 1804
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);

1805 1806 1807
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return TC_ACT_SHOT;

1808 1809
	ri->ifindex = ifindex;
	ri->flags = flags;
1810
	ri->map = NULL;
1811

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
	return TC_ACT_REDIRECT;
}

int skb_do_redirect(struct sk_buff *skb)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);
	struct net_device *dev;

	dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex);
	ri->ifindex = 0;
	if (unlikely(!dev)) {
		kfree_skb(skb);
		return -EINVAL;
	}

1827
	return __bpf_redirect(skb, dev, ri->flags);
1828 1829
}

1830
static const struct bpf_func_proto bpf_redirect_proto = {
1831 1832 1833 1834 1835 1836 1837
	.func           = bpf_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_ANYTHING,
	.arg2_type      = ARG_ANYTHING,
};

1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
BPF_CALL_3(bpf_sk_redirect_map, struct bpf_map *, map, u32, key, u64, flags)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);

	if (unlikely(flags))
		return SK_ABORTED;

	ri->ifindex = key;
	ri->flags = flags;
	ri->map = map;

	return SK_REDIRECT;
}

struct sock *do_sk_redirect_map(void)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);
	struct sock *sk = NULL;

	if (ri->map) {
		sk = __sock_map_lookup_elem(ri->map, ri->ifindex);

		ri->ifindex = 0;
		ri->map = NULL;
		/* we do not clear flags for future lookup */
	}

	return sk;
}

static const struct bpf_func_proto bpf_sk_redirect_map_proto = {
	.func           = bpf_sk_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_CONST_MAP_PTR,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};

1877
BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
1878
{
1879
	return task_get_classid(skb);
1880 1881 1882 1883 1884 1885 1886 1887 1888
}

static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
	.func           = bpf_get_cgroup_classid,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

1889
BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
1890
{
1891
	return dst_tclassid(skb);
1892 1893 1894 1895 1896 1897 1898 1899 1900
}

static const struct bpf_func_proto bpf_get_route_realm_proto = {
	.func           = bpf_get_route_realm,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

1901
BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
1902 1903 1904 1905 1906 1907
{
	/* If skb_clear_hash() was called due to mangling, we can
	 * trigger SW recalculation here. Later access to hash
	 * can then use the inline skb->hash via context directly
	 * instead of calling this helper again.
	 */
1908
	return skb_get_hash(skb);
1909 1910 1911 1912 1913 1914 1915 1916 1917
}

static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
	.func		= bpf_get_hash_recalc,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
};

1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
{
	/* After all direct packet write, this can be used once for
	 * triggering a lazy recalc on next skb_get_hash() invocation.
	 */
	skb_clear_hash(skb);
	return 0;
}

static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
	.func		= bpf_set_hash_invalid,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
};

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
{
	/* Set user specified hash as L4(+), so that it gets returned
	 * on skb_get_hash() call unless BPF prog later on triggers a
	 * skb_clear_hash().
	 */
	__skb_set_sw_hash(skb, hash, true);
	return 0;
}

static const struct bpf_func_proto bpf_set_hash_proto = {
	.func		= bpf_set_hash,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

1952 1953
BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
	   u16, vlan_tci)
1954
{
1955
	int ret;
1956 1957 1958 1959 1960

	if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
		     vlan_proto != htons(ETH_P_8021AD)))
		vlan_proto = htons(ETH_P_8021Q);

1961
	bpf_push_mac_rcsum(skb);
1962
	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
1963 1964
	bpf_pull_mac_rcsum(skb);

1965 1966
	bpf_compute_data_end(skb);
	return ret;
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
}

const struct bpf_func_proto bpf_skb_vlan_push_proto = {
	.func           = bpf_skb_vlan_push,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};
1977
EXPORT_SYMBOL_GPL(bpf_skb_vlan_push_proto);
1978

1979
BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
1980
{
1981
	int ret;
1982

1983
	bpf_push_mac_rcsum(skb);
1984
	ret = skb_vlan_pop(skb);
1985 1986
	bpf_pull_mac_rcsum(skb);

1987 1988
	bpf_compute_data_end(skb);
	return ret;
1989 1990 1991 1992 1993 1994 1995 1996
}

const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
	.func           = bpf_skb_vlan_pop,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};
1997
EXPORT_SYMBOL_GPL(bpf_skb_vlan_pop_proto);
1998

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
{
	/* Caller already did skb_cow() with len as headroom,
	 * so no need to do it here.
	 */
	skb_push(skb, len);
	memmove(skb->data, skb->data + len, off);
	memset(skb->data + off, 0, len);

	/* No skb_postpush_rcsum(skb, skb->data + off, len)
	 * needed here as it does not change the skb->csum
	 * result for checksum complete when summing over
	 * zeroed blocks.
	 */
	return 0;
}

static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
{
	/* skb_ensure_writable() is not needed here, as we're
	 * already working on an uncloned skb.
	 */
	if (unlikely(!pskb_may_pull(skb, off + len)))
		return -ENOMEM;

	skb_postpull_rcsum(skb, skb->data + off, len);
	memmove(skb->data + len, skb->data, off);
	__skb_pull(skb, len);

	return 0;
}

static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
{
	bool trans_same = skb->transport_header == skb->network_header;
	int ret;

	/* There's no need for __skb_push()/__skb_pull() pair to
	 * get to the start of the mac header as we're guaranteed
	 * to always start from here under eBPF.
	 */
	ret = bpf_skb_generic_push(skb, off, len);
	if (likely(!ret)) {
		skb->mac_header -= len;
		skb->network_header -= len;
		if (trans_same)
			skb->transport_header = skb->network_header;
	}

	return ret;
}

static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
{
	bool trans_same = skb->transport_header == skb->network_header;
	int ret;

	/* Same here, __skb_push()/__skb_pull() pair not needed. */
	ret = bpf_skb_generic_pop(skb, off, len);
	if (likely(!ret)) {
		skb->mac_header += len;
		skb->network_header += len;
		if (trans_same)
			skb->transport_header = skb->network_header;
	}

	return ret;
}

static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
{
	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2071
	u32 off = skb_mac_header_len(skb);
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
	int ret;

	ret = skb_cow(skb, len_diff);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
2083 2084
		/* SKB_GSO_TCPV4 needs to be changed into
		 * SKB_GSO_TCPV6.
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
		 */
		if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
			skb_shinfo(skb)->gso_type &= ~SKB_GSO_TCPV4;
			skb_shinfo(skb)->gso_type |=  SKB_GSO_TCPV6;
		}

		/* Due to IPv6 header, MSS needs to be downgraded. */
		skb_shinfo(skb)->gso_size -= len_diff;
		/* Header must be checked, and gso_segs recomputed. */
		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
		skb_shinfo(skb)->gso_segs = 0;
	}

	skb->protocol = htons(ETH_P_IPV6);
	skb_clear_hash(skb);

	return 0;
}

static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
{
	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2107
	u32 off = skb_mac_header_len(skb);
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
	int ret;

	ret = skb_unclone(skb, GFP_ATOMIC);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
2119 2120
		/* SKB_GSO_TCPV6 needs to be changed into
		 * SKB_GSO_TCPV4.
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
		 */
		if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) {
			skb_shinfo(skb)->gso_type &= ~SKB_GSO_TCPV6;
			skb_shinfo(skb)->gso_type |=  SKB_GSO_TCPV4;
		}

		/* Due to IPv4 header, MSS can be upgraded. */
		skb_shinfo(skb)->gso_size += len_diff;
		/* Header must be checked, and gso_segs recomputed. */
		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
		skb_shinfo(skb)->gso_segs = 0;
	}

	skb->protocol = htons(ETH_P_IP);
	skb_clear_hash(skb);

	return 0;
}

static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
{
	__be16 from_proto = skb->protocol;

	if (from_proto == htons(ETH_P_IP) &&
	      to_proto == htons(ETH_P_IPV6))
		return bpf_skb_proto_4_to_6(skb);

	if (from_proto == htons(ETH_P_IPV6) &&
	      to_proto == htons(ETH_P_IP))
		return bpf_skb_proto_6_to_4(skb);

	return -ENOTSUPP;
}

2155 2156
BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
	   u64, flags)
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
{
	int ret;

	if (unlikely(flags))
		return -EINVAL;

	/* General idea is that this helper does the basic groundwork
	 * needed for changing the protocol, and eBPF program fills the
	 * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
	 * and other helpers, rather than passing a raw buffer here.
	 *
	 * The rationale is to keep this minimal and without a need to
	 * deal with raw packet data. F.e. even if we would pass buffers
	 * here, the program still needs to call the bpf_lX_csum_replace()
	 * helpers anyway. Plus, this way we keep also separation of
	 * concerns, since f.e. bpf_skb_store_bytes() should only take
	 * care of stores.
	 *
	 * Currently, additional options and extension header space are
	 * not supported, but flags register is reserved so we can adapt
	 * that. For offloads, we mark packet as dodgy, so that headers
	 * need to be verified first.
	 */
	ret = bpf_skb_proto_xlat(skb, proto);
	bpf_compute_data_end(skb);
	return ret;
}

static const struct bpf_func_proto bpf_skb_change_proto_proto = {
	.func		= bpf_skb_change_proto,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

2194
BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2195 2196
{
	/* We only allow a restricted subset to be changed for now. */
2197 2198
	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
		     !skb_pkt_type_ok(pkt_type)))
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
		return -EINVAL;

	skb->pkt_type = pkt_type;
	return 0;
}

static const struct bpf_func_proto bpf_skb_change_type_proto = {
	.func		= bpf_skb_change_type,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
{
	switch (skb->protocol) {
	case htons(ETH_P_IP):
		return sizeof(struct iphdr);
	case htons(ETH_P_IPV6):
		return sizeof(struct ipv6hdr);
	default:
		return ~0U;
	}
}

static int bpf_skb_net_grow(struct sk_buff *skb, u32 len_diff)
{
	u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
	int ret;

	ret = skb_cow(skb, len_diff);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
		/* Due to header grow, MSS needs to be downgraded. */
		skb_shinfo(skb)->gso_size -= len_diff;
		/* Header must be checked, and gso_segs recomputed. */
		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
		skb_shinfo(skb)->gso_segs = 0;
	}

	return 0;
}

static int bpf_skb_net_shrink(struct sk_buff *skb, u32 len_diff)
{
	u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
	int ret;

	ret = skb_unclone(skb, GFP_ATOMIC);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
		/* Due to header shrink, MSS can be upgraded. */
		skb_shinfo(skb)->gso_size += len_diff;
		/* Header must be checked, and gso_segs recomputed. */
		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
		skb_shinfo(skb)->gso_segs = 0;
	}

	return 0;
}

static u32 __bpf_skb_max_len(const struct sk_buff *skb)
{
	return skb->dev->mtu + skb->dev->hard_header_len;
}

static int bpf_skb_adjust_net(struct sk_buff *skb, s32 len_diff)
{
	bool trans_same = skb->transport_header == skb->network_header;
	u32 len_cur, len_diff_abs = abs(len_diff);
	u32 len_min = bpf_skb_net_base_len(skb);
	u32 len_max = __bpf_skb_max_len(skb);
	__be16 proto = skb->protocol;
	bool shrink = len_diff < 0;
	int ret;

	if (unlikely(len_diff_abs > 0xfffU))
		return -EFAULT;
	if (unlikely(proto != htons(ETH_P_IP) &&
		     proto != htons(ETH_P_IPV6)))
		return -ENOTSUPP;

	len_cur = skb->len - skb_network_offset(skb);
	if (skb_transport_header_was_set(skb) && !trans_same)
		len_cur = skb_network_header_len(skb);
	if ((shrink && (len_diff_abs >= len_cur ||
			len_cur - len_diff_abs < len_min)) ||
	    (!shrink && (skb->len + len_diff_abs > len_max &&
			 !skb_is_gso(skb))))
		return -ENOTSUPP;

	ret = shrink ? bpf_skb_net_shrink(skb, len_diff_abs) :
		       bpf_skb_net_grow(skb, len_diff_abs);

	bpf_compute_data_end(skb);
2307
	return ret;
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
}

BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
	   u32, mode, u64, flags)
{
	if (unlikely(flags))
		return -EINVAL;
	if (likely(mode == BPF_ADJ_ROOM_NET))
		return bpf_skb_adjust_net(skb, len_diff);

	return -ENOTSUPP;
}

static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
	.func		= bpf_skb_adjust_room,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
};

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
static u32 __bpf_skb_min_len(const struct sk_buff *skb)
{
	u32 min_len = skb_network_offset(skb);

	if (skb_transport_header_was_set(skb))
		min_len = skb_transport_offset(skb);
	if (skb->ip_summed == CHECKSUM_PARTIAL)
		min_len = skb_checksum_start_offset(skb) +
			  skb->csum_offset + sizeof(__sum16);
	return min_len;
}

static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
{
	unsigned int old_len = skb->len;
	int ret;

	ret = __skb_grow_rcsum(skb, new_len);
	if (!ret)
		memset(skb->data + old_len, 0, new_len - old_len);
	return ret;
}

static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
{
	return __skb_trim_rcsum(skb, new_len);
}

2359 2360
BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
	   u64, flags)
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
{
	u32 max_len = __bpf_skb_max_len(skb);
	u32 min_len = __bpf_skb_min_len(skb);
	int ret;

	if (unlikely(flags || new_len > max_len || new_len < min_len))
		return -EINVAL;
	if (skb->encapsulation)
		return -ENOTSUPP;

	/* The basic idea of this helper is that it's performing the
	 * needed work to either grow or trim an skb, and eBPF program
	 * rewrites the rest via helpers like bpf_skb_store_bytes(),
	 * bpf_lX_csum_replace() and others rather than passing a raw
	 * buffer here. This one is a slow path helper and intended
	 * for replies with control messages.
	 *
	 * Like in bpf_skb_change_proto(), we want to keep this rather
	 * minimal and without protocol specifics so that we are able
	 * to separate concerns as in bpf_skb_store_bytes() should only
	 * be the one responsible for writing buffers.
	 *
	 * It's really expected to be a slow path operation here for
	 * control message replies, so we're implicitly linearizing,
	 * uncloning and drop offloads from the skb by this.
	 */
	ret = __bpf_try_make_writable(skb, skb->len);
	if (!ret) {
		if (new_len > skb->len)
			ret = bpf_skb_grow_rcsum(skb, new_len);
		else if (new_len < skb->len)
			ret = bpf_skb_trim_rcsum(skb, new_len);
		if (!ret && skb_is_gso(skb))
			skb_gso_reset(skb);
	}

	bpf_compute_data_end(skb);
	return ret;
}

static const struct bpf_func_proto bpf_skb_change_tail_proto = {
	.func		= bpf_skb_change_tail,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
	   u64, flags)
{
	u32 max_len = __bpf_skb_max_len(skb);
	u32 new_len = skb->len + head_room;
	int ret;

	if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
		     new_len < skb->len))
		return -EINVAL;

	ret = skb_cow(skb, head_room);
	if (likely(!ret)) {
		/* Idea for this helper is that we currently only
		 * allow to expand on mac header. This means that
		 * skb->protocol network header, etc, stay as is.
		 * Compared to bpf_skb_change_tail(), we're more
		 * flexible due to not needing to linearize or
		 * reset GSO. Intention for this helper is to be
		 * used by an L3 skb that needs to push mac header
		 * for redirection into L2 device.
		 */
		__skb_push(skb, head_room);
		memset(skb->data, 0, head_room);
		skb_reset_mac_header(skb);
	}

	bpf_compute_data_end(skb);
	return 0;
}

static const struct bpf_func_proto bpf_skb_change_head_proto = {
	.func		= bpf_skb_change_head,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
{
	void *data = xdp->data + offset;

	if (unlikely(data < xdp->data_hard_start ||
		     data > xdp->data_end - ETH_HLEN))
		return -EINVAL;

	xdp->data = data;

	return 0;
}

static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
	.func		= bpf_xdp_adjust_head,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

2471 2472 2473 2474
static int __bpf_tx_xdp(struct net_device *dev,
			struct bpf_map *map,
			struct xdp_buff *xdp,
			u32 index)
2475
{
2476 2477 2478 2479
	int err;

	if (!dev->netdev_ops->ndo_xdp_xmit) {
		return -EOPNOTSUPP;
2480
	}
2481 2482 2483 2484 2485 2486 2487 2488

	err = dev->netdev_ops->ndo_xdp_xmit(dev, xdp);
	if (err)
		return err;
	if (map)
		__dev_map_insert_ctx(map, index);
	else
		dev->netdev_ops->ndo_xdp_flush(dev);
2489
	return 0;
2490 2491
}

2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
void xdp_do_flush_map(void)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);
	struct bpf_map *map = ri->map_to_flush;

	ri->map_to_flush = NULL;
	if (map)
		__dev_map_flush(map);
}
EXPORT_SYMBOL_GPL(xdp_do_flush_map);

2503 2504
static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
			       struct bpf_prog *xdp_prog)
2505 2506 2507
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);
	struct bpf_map *map = ri->map;
2508
	u32 index = ri->ifindex;
2509
	struct net_device *fwd;
2510
	int err;
2511 2512 2513 2514

	ri->ifindex = 0;
	ri->map = NULL;

2515
	fwd = __dev_map_lookup_elem(map, index);
2516 2517
	if (!fwd) {
		err = -EINVAL;
2518
		goto out;
2519
	}
2520
	if (ri->map_to_flush && ri->map_to_flush != map)
2521 2522 2523 2524 2525
		xdp_do_flush_map();

	err = __bpf_tx_xdp(fwd, map, xdp, index);
	if (likely(!err))
		ri->map_to_flush = map;
2526
out:
2527
	trace_xdp_redirect(dev, fwd, xdp_prog, XDP_REDIRECT, err);
2528 2529 2530
	return err;
}

2531 2532
int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
		    struct bpf_prog *xdp_prog)
2533 2534
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);
2535
	struct net_device *fwd;
W
William Tu 已提交
2536
	u32 index = ri->ifindex;
2537
	int err;
2538

2539 2540 2541
	if (ri->map)
		return xdp_do_redirect_map(dev, xdp, xdp_prog);

W
William Tu 已提交
2542
	fwd = dev_get_by_index_rcu(dev_net(dev), index);
2543
	ri->ifindex = 0;
2544
	if (unlikely(!fwd)) {
2545 2546
		err = -EINVAL;
		goto out;
2547 2548
	}

2549 2550 2551 2552
	err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
out:
	trace_xdp_redirect(dev, fwd, xdp_prog, XDP_REDIRECT, err);
	return err;
2553 2554 2555
}
EXPORT_SYMBOL_GPL(xdp_do_redirect);

2556 2557 2558 2559
int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);
	unsigned int len;
W
William Tu 已提交
2560
	u32 index = ri->ifindex;
2561

W
William Tu 已提交
2562
	dev = dev_get_by_index_rcu(dev_net(dev), index);
2563 2564
	ri->ifindex = 0;
	if (unlikely(!dev)) {
2565
		return -EINVAL;
2566 2567 2568
	}

	if (unlikely(!(dev->flags & IFF_UP)))
2569
		return -ENETDOWN;
2570 2571
	len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
	if (skb->len > len)
2572
		return -E2BIG;
2573 2574 2575 2576 2577 2578

	skb->dev = dev;
	return 0;
}
EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);

2579 2580 2581 2582 2583 2584 2585 2586 2587
BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);

	if (unlikely(flags))
		return XDP_ABORTED;

	ri->ifindex = ifindex;
	ri->flags = flags;
2588

2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
	return XDP_REDIRECT;
}

static const struct bpf_func_proto bpf_xdp_redirect_proto = {
	.func           = bpf_xdp_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_ANYTHING,
	.arg2_type      = ARG_ANYTHING,
};

2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex, u64, flags)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);

	if (unlikely(flags))
		return XDP_ABORTED;

	ri->ifindex = ifindex;
	ri->flags = flags;
	ri->map = map;

	return XDP_REDIRECT;
}

static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
	.func           = bpf_xdp_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_CONST_MAP_PTR,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};

2623
bool bpf_helper_changes_pkt_data(void *func)
2624
{
2625 2626 2627 2628
	if (func == bpf_skb_vlan_push ||
	    func == bpf_skb_vlan_pop ||
	    func == bpf_skb_store_bytes ||
	    func == bpf_skb_change_proto ||
2629
	    func == bpf_skb_change_head ||
2630
	    func == bpf_skb_change_tail ||
2631
	    func == bpf_skb_adjust_room ||
2632
	    func == bpf_skb_pull_data ||
2633
	    func == bpf_clone_redirect ||
2634
	    func == bpf_l3_csum_replace ||
2635 2636
	    func == bpf_l4_csum_replace ||
	    func == bpf_xdp_adjust_head)
2637 2638
		return true;

2639 2640 2641
	return false;
}

2642
static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
2643
				  unsigned long off, unsigned long len)
2644
{
2645
	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
2646 2647 2648 2649 2650 2651 2652 2653 2654

	if (unlikely(!ptr))
		return len;
	if (ptr != dst_buff)
		memcpy(dst_buff, ptr, len);

	return 0;
}

2655 2656
BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
	   u64, flags, void *, meta, u64, meta_size)
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
{
	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;

	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
		return -EINVAL;
	if (unlikely(skb_size > skb->len))
		return -EFAULT;

	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
				bpf_skb_copy);
}

static const struct bpf_func_proto bpf_skb_event_output_proto = {
	.func		= bpf_skb_event_output,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
2676 2677
	.arg4_type	= ARG_PTR_TO_MEM,
	.arg5_type	= ARG_CONST_SIZE,
2678 2679
};

2680 2681 2682 2683 2684
static unsigned short bpf_tunnel_key_af(u64 flags)
{
	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
}

2685 2686
BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
	   u32, size, u64, flags)
2687
{
2688 2689
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
	u8 compat[sizeof(struct bpf_tunnel_key)];
2690 2691
	void *to_orig = to;
	int err;
2692

2693 2694 2695 2696 2697 2698 2699 2700
	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
		err = -EINVAL;
		goto err_clear;
	}
	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
		err = -EPROTO;
		goto err_clear;
	}
2701
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
2702
		err = -EINVAL;
2703
		switch (size) {
2704
		case offsetof(struct bpf_tunnel_key, tunnel_label):
2705
		case offsetof(struct bpf_tunnel_key, tunnel_ext):
2706
			goto set_compat;
2707 2708 2709 2710 2711
		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
			/* Fixup deprecated structure layouts here, so we have
			 * a common path later on.
			 */
			if (ip_tunnel_info_af(info) != AF_INET)
2712
				goto err_clear;
2713
set_compat:
2714 2715 2716
			to = (struct bpf_tunnel_key *)compat;
			break;
		default:
2717
			goto err_clear;
2718 2719
		}
	}
2720 2721

	to->tunnel_id = be64_to_cpu(info->key.tun_id);
2722 2723 2724
	to->tunnel_tos = info->key.tos;
	to->tunnel_ttl = info->key.ttl;

2725
	if (flags & BPF_F_TUNINFO_IPV6) {
2726 2727
		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
		       sizeof(to->remote_ipv6));
2728 2729
		to->tunnel_label = be32_to_cpu(info->key.label);
	} else {
2730
		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
2731
	}
2732 2733

	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
2734
		memcpy(to_orig, to, size);
2735 2736

	return 0;
2737 2738 2739
err_clear:
	memset(to_orig, 0, size);
	return err;
2740 2741
}

2742
static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
2743 2744 2745 2746
	.func		= bpf_skb_get_tunnel_key,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
2747 2748
	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg3_type	= ARG_CONST_SIZE,
2749 2750 2751
	.arg4_type	= ARG_ANYTHING,
};

2752
BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
2753 2754
{
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
2755
	int err;
2756 2757

	if (unlikely(!info ||
2758 2759 2760 2761 2762 2763 2764 2765
		     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
		err = -ENOENT;
		goto err_clear;
	}
	if (unlikely(size < info->options_len)) {
		err = -ENOMEM;
		goto err_clear;
	}
2766 2767

	ip_tunnel_info_opts_get(to, info);
2768 2769
	if (size > info->options_len)
		memset(to + info->options_len, 0, size - info->options_len);
2770 2771

	return info->options_len;
2772 2773 2774
err_clear:
	memset(to, 0, size);
	return err;
2775 2776 2777 2778 2779 2780 2781
}

static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
	.func		= bpf_skb_get_tunnel_opt,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
2782 2783
	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg3_type	= ARG_CONST_SIZE,
2784 2785
};

2786 2787
static struct metadata_dst __percpu *md_dst;

2788 2789
BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
2790 2791
{
	struct metadata_dst *md = this_cpu_ptr(md_dst);
2792
	u8 compat[sizeof(struct bpf_tunnel_key)];
2793 2794
	struct ip_tunnel_info *info;

2795 2796
	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
			       BPF_F_DONT_FRAGMENT)))
2797
		return -EINVAL;
2798 2799
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
		switch (size) {
2800
		case offsetof(struct bpf_tunnel_key, tunnel_label):
2801
		case offsetof(struct bpf_tunnel_key, tunnel_ext):
2802 2803 2804 2805 2806 2807
		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
			/* Fixup deprecated structure layouts here, so we have
			 * a common path later on.
			 */
			memcpy(compat, from, size);
			memset(compat + size, 0, sizeof(compat) - size);
2808
			from = (const struct bpf_tunnel_key *) compat;
2809 2810 2811 2812 2813
			break;
		default:
			return -EINVAL;
		}
	}
2814 2815
	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
		     from->tunnel_ext))
2816
		return -EINVAL;
2817 2818 2819 2820 2821 2822 2823

	skb_dst_drop(skb);
	dst_hold((struct dst_entry *) md);
	skb_dst_set(skb, (struct dst_entry *) md);

	info = &md->u.tun_info;
	info->mode = IP_TUNNEL_INFO_TX;
2824

2825
	info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
2826 2827 2828
	if (flags & BPF_F_DONT_FRAGMENT)
		info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;

2829
	info->key.tun_id = cpu_to_be64(from->tunnel_id);
2830 2831 2832 2833 2834 2835 2836
	info->key.tos = from->tunnel_tos;
	info->key.ttl = from->tunnel_ttl;

	if (flags & BPF_F_TUNINFO_IPV6) {
		info->mode |= IP_TUNNEL_INFO_IPV6;
		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
		       sizeof(from->remote_ipv6));
2837 2838
		info->key.label = cpu_to_be32(from->tunnel_label) &
				  IPV6_FLOWLABEL_MASK;
2839 2840
	} else {
		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
2841 2842
		if (flags & BPF_F_ZERO_CSUM_TX)
			info->key.tun_flags &= ~TUNNEL_CSUM;
2843
	}
2844 2845 2846 2847

	return 0;
}

2848
static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
2849 2850 2851 2852
	.func		= bpf_skb_set_tunnel_key,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
2853 2854
	.arg2_type	= ARG_PTR_TO_MEM,
	.arg3_type	= ARG_CONST_SIZE,
2855 2856 2857
	.arg4_type	= ARG_ANYTHING,
};

2858 2859
BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
	   const u8 *, from, u32, size)
2860 2861 2862 2863 2864 2865
{
	struct ip_tunnel_info *info = skb_tunnel_info(skb);
	const struct metadata_dst *md = this_cpu_ptr(md_dst);

	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
		return -EINVAL;
2866
	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
		return -ENOMEM;

	ip_tunnel_info_opts_set(info, from, size);

	return 0;
}

static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
	.func		= bpf_skb_set_tunnel_opt,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
2879 2880
	.arg2_type	= ARG_PTR_TO_MEM,
	.arg3_type	= ARG_CONST_SIZE,
2881 2882 2883 2884
};

static const struct bpf_func_proto *
bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
2885 2886
{
	if (!md_dst) {
2887 2888
		/* Race is not possible, since it's called from verifier
		 * that is holding verifier mutex.
2889
		 */
2890
		md_dst = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
2891
						   METADATA_IP_TUNNEL,
2892
						   GFP_KERNEL);
2893 2894 2895
		if (!md_dst)
			return NULL;
	}
2896 2897 2898 2899 2900 2901 2902 2903 2904

	switch (which) {
	case BPF_FUNC_skb_set_tunnel_key:
		return &bpf_skb_set_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_opt:
		return &bpf_skb_set_tunnel_opt_proto;
	default:
		return NULL;
	}
2905 2906
}

2907 2908
BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
	   u32, idx)
2909 2910 2911 2912 2913
{
	struct bpf_array *array = container_of(map, struct bpf_array, map);
	struct cgroup *cgrp;
	struct sock *sk;

2914
	sk = skb_to_full_sk(skb);
2915 2916
	if (!sk || !sk_fullsock(sk))
		return -ENOENT;
2917
	if (unlikely(idx >= array->map.max_entries))
2918 2919
		return -E2BIG;

2920
	cgrp = READ_ONCE(array->ptrs[idx]);
2921 2922 2923
	if (unlikely(!cgrp))
		return -EAGAIN;

2924
	return sk_under_cgroup_hierarchy(sk, cgrp);
2925 2926
}

2927 2928
static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
	.func		= bpf_skb_under_cgroup,
2929 2930 2931 2932 2933 2934 2935
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
};

2936 2937 2938 2939 2940 2941 2942
static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
				  unsigned long off, unsigned long len)
{
	memcpy(dst_buff, src_buff + off, len);
	return 0;
}

2943 2944
BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
	   u64, flags, void *, meta, u64, meta_size)
2945 2946 2947 2948 2949 2950 2951 2952
{
	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;

	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
		return -EINVAL;
	if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
		return -EFAULT;

M
Martin KaFai Lau 已提交
2953 2954
	return bpf_event_output(map, flags, meta, meta_size, xdp->data,
				xdp_size, bpf_xdp_copy);
2955 2956 2957 2958 2959 2960 2961 2962 2963
}

static const struct bpf_func_proto bpf_xdp_event_output_proto = {
	.func		= bpf_xdp_event_output,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
2964 2965
	.arg4_type	= ARG_PTR_TO_MEM,
	.arg5_type	= ARG_CONST_SIZE,
2966 2967
};

2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
{
	return skb->sk ? sock_gen_cookie(skb->sk) : 0;
}

static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
	.func           = bpf_get_socket_cookie,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997
BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
{
	struct sock *sk = sk_to_full_sk(skb->sk);
	kuid_t kuid;

	if (!sk || !sk_fullsock(sk))
		return overflowuid;
	kuid = sock_net_uid(sock_net(sk), sk);
	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
}

static const struct bpf_func_proto bpf_get_socket_uid_proto = {
	.func           = bpf_get_socket_uid,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
	   int, level, int, optname, char *, optval, int, optlen)
{
	struct sock *sk = bpf_sock->sk;
	int ret = 0;
	int val;

	if (!sk_fullsock(sk))
		return -EINVAL;

	if (level == SOL_SOCKET) {
		if (optlen != sizeof(int))
			return -EINVAL;
		val = *((int *)optval);

		/* Only some socketops are supported */
		switch (optname) {
		case SO_RCVBUF:
			sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
			sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
			break;
		case SO_SNDBUF:
			sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
			sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
			break;
		case SO_MAX_PACING_RATE:
			sk->sk_max_pacing_rate = val;
			sk->sk_pacing_rate = min(sk->sk_pacing_rate,
						 sk->sk_max_pacing_rate);
			break;
		case SO_PRIORITY:
			sk->sk_priority = val;
			break;
		case SO_RCVLOWAT:
			if (val < 0)
				val = INT_MAX;
			sk->sk_rcvlowat = val ? : 1;
			break;
		case SO_MARK:
			sk->sk_mark = val;
			break;
		default:
			ret = -EINVAL;
		}
L
Lawrence Brakmo 已提交
3042
#ifdef CONFIG_INET
3043 3044
	} else if (level == SOL_TCP &&
		   sk->sk_prot->setsockopt == tcp_setsockopt) {
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
		if (optname == TCP_CONGESTION) {
			char name[TCP_CA_NAME_MAX];

			strncpy(name, optval, min_t(long, optlen,
						    TCP_CA_NAME_MAX-1));
			name[TCP_CA_NAME_MAX-1] = 0;
			ret = tcp_set_congestion_control(sk, name, false);
			if (!ret && bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN)
				/* replacing an existing ca */
				tcp_reinit_congestion_control(sk,
					inet_csk(sk)->icsk_ca_ops);
		} else {
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
			struct tcp_sock *tp = tcp_sk(sk);

			if (optlen != sizeof(int))
				return -EINVAL;

			val = *((int *)optval);
			/* Only some options are supported */
			switch (optname) {
			case TCP_BPF_IW:
				if (val <= 0 || tp->data_segs_out > 0)
					ret = -EINVAL;
				else
					tp->snd_cwnd = val;
				break;
3071 3072 3073 3074 3075 3076 3077
			case TCP_BPF_SNDCWND_CLAMP:
				if (val <= 0) {
					ret = -EINVAL;
				} else {
					tp->snd_cwnd_clamp = val;
					tp->snd_ssthresh = val;
				}
3078
				break;
3079 3080 3081
			default:
				ret = -EINVAL;
			}
3082
		}
3083
		ret = -EINVAL;
3084
#endif
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101
	} else {
		ret = -EINVAL;
	}
	return ret;
}

static const struct bpf_func_proto bpf_setsockopt_proto = {
	.func		= bpf_setsockopt,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_PTR_TO_MEM,
	.arg5_type	= ARG_CONST_SIZE,
};

3102
static const struct bpf_func_proto *
3103
bpf_base_func_proto(enum bpf_func_id func_id)
3104 3105 3106 3107 3108 3109 3110 3111
{
	switch (func_id) {
	case BPF_FUNC_map_lookup_elem:
		return &bpf_map_lookup_elem_proto;
	case BPF_FUNC_map_update_elem:
		return &bpf_map_update_elem_proto;
	case BPF_FUNC_map_delete_elem:
		return &bpf_map_delete_elem_proto;
3112 3113
	case BPF_FUNC_get_prandom_u32:
		return &bpf_get_prandom_u32_proto;
3114
	case BPF_FUNC_get_smp_processor_id:
3115
		return &bpf_get_raw_smp_processor_id_proto;
3116 3117
	case BPF_FUNC_get_numa_node_id:
		return &bpf_get_numa_node_id_proto;
3118 3119
	case BPF_FUNC_tail_call:
		return &bpf_tail_call_proto;
3120 3121
	case BPF_FUNC_ktime_get_ns:
		return &bpf_ktime_get_ns_proto;
3122
	case BPF_FUNC_trace_printk:
3123 3124
		if (capable(CAP_SYS_ADMIN))
			return bpf_get_trace_printk_proto();
3125 3126 3127 3128 3129
	default:
		return NULL;
	}
}

3130 3131 3132 3133 3134 3135
static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
3136 3137
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_proto;
3138 3139
	case BPF_FUNC_get_socket_uid:
		return &bpf_get_socket_uid_proto;
3140 3141 3142 3143 3144
	default:
		return bpf_base_func_proto(func_id);
	}
}

3145 3146 3147 3148 3149 3150
static const struct bpf_func_proto *
tc_cls_act_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
	case BPF_FUNC_skb_store_bytes:
		return &bpf_skb_store_bytes_proto;
3151 3152
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
3153 3154
	case BPF_FUNC_skb_pull_data:
		return &bpf_skb_pull_data_proto;
3155 3156
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
3157 3158
	case BPF_FUNC_csum_update:
		return &bpf_csum_update_proto;
3159 3160 3161 3162
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
3163 3164
	case BPF_FUNC_clone_redirect:
		return &bpf_clone_redirect_proto;
3165 3166
	case BPF_FUNC_get_cgroup_classid:
		return &bpf_get_cgroup_classid_proto;
3167 3168 3169 3170
	case BPF_FUNC_skb_vlan_push:
		return &bpf_skb_vlan_push_proto;
	case BPF_FUNC_skb_vlan_pop:
		return &bpf_skb_vlan_pop_proto;
3171 3172
	case BPF_FUNC_skb_change_proto:
		return &bpf_skb_change_proto_proto;
3173 3174
	case BPF_FUNC_skb_change_type:
		return &bpf_skb_change_type_proto;
3175 3176
	case BPF_FUNC_skb_adjust_room:
		return &bpf_skb_adjust_room_proto;
3177 3178
	case BPF_FUNC_skb_change_tail:
		return &bpf_skb_change_tail_proto;
3179 3180 3181
	case BPF_FUNC_skb_get_tunnel_key:
		return &bpf_skb_get_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_key:
3182 3183 3184 3185 3186
		return bpf_get_skb_set_tunnel_proto(func_id);
	case BPF_FUNC_skb_get_tunnel_opt:
		return &bpf_skb_get_tunnel_opt_proto;
	case BPF_FUNC_skb_set_tunnel_opt:
		return bpf_get_skb_set_tunnel_proto(func_id);
3187 3188
	case BPF_FUNC_redirect:
		return &bpf_redirect_proto;
3189 3190
	case BPF_FUNC_get_route_realm:
		return &bpf_get_route_realm_proto;
3191 3192
	case BPF_FUNC_get_hash_recalc:
		return &bpf_get_hash_recalc_proto;
3193 3194
	case BPF_FUNC_set_hash_invalid:
		return &bpf_set_hash_invalid_proto;
3195 3196
	case BPF_FUNC_set_hash:
		return &bpf_set_hash_proto;
3197
	case BPF_FUNC_perf_event_output:
3198
		return &bpf_skb_event_output_proto;
3199 3200
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
3201 3202
	case BPF_FUNC_skb_under_cgroup:
		return &bpf_skb_under_cgroup_proto;
3203 3204
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_proto;
3205 3206
	case BPF_FUNC_get_socket_uid:
		return &bpf_get_socket_uid_proto;
3207
	default:
3208
		return bpf_base_func_proto(func_id);
3209 3210 3211
	}
}

3212 3213 3214
static const struct bpf_func_proto *
xdp_func_proto(enum bpf_func_id func_id)
{
3215 3216 3217
	switch (func_id) {
	case BPF_FUNC_perf_event_output:
		return &bpf_xdp_event_output_proto;
3218 3219
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
3220 3221
	case BPF_FUNC_xdp_adjust_head:
		return &bpf_xdp_adjust_head_proto;
3222 3223
	case BPF_FUNC_redirect:
		return &bpf_xdp_redirect_proto;
3224
	case BPF_FUNC_redirect_map:
3225
		return &bpf_xdp_redirect_map_proto;
3226
	default:
3227
		return bpf_base_func_proto(func_id);
3228
	}
3229 3230
}

3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
static const struct bpf_func_proto *
lwt_inout_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
	case BPF_FUNC_skb_pull_data:
		return &bpf_skb_pull_data_proto;
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
	case BPF_FUNC_get_cgroup_classid:
		return &bpf_get_cgroup_classid_proto;
	case BPF_FUNC_get_route_realm:
		return &bpf_get_route_realm_proto;
	case BPF_FUNC_get_hash_recalc:
		return &bpf_get_hash_recalc_proto;
	case BPF_FUNC_perf_event_output:
		return &bpf_skb_event_output_proto;
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
	case BPF_FUNC_skb_under_cgroup:
		return &bpf_skb_under_cgroup_proto;
	default:
3254
		return bpf_base_func_proto(func_id);
3255 3256 3257
	}
}

3258 3259 3260 3261 3262 3263
static const struct bpf_func_proto *
	sock_ops_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
	case BPF_FUNC_setsockopt:
		return &bpf_setsockopt_proto;
3264 3265
	case BPF_FUNC_sock_map_update:
		return &bpf_sock_map_update_proto;
3266 3267 3268 3269 3270
	default:
		return bpf_base_func_proto(func_id);
	}
}

3271 3272 3273
static const struct bpf_func_proto *sk_skb_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
3274 3275
	case BPF_FUNC_skb_store_bytes:
		return &bpf_skb_store_bytes_proto;
3276 3277
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
3278 3279 3280 3281 3282 3283
	case BPF_FUNC_skb_pull_data:
		return &bpf_skb_pull_data_proto;
	case BPF_FUNC_skb_change_tail:
		return &bpf_skb_change_tail_proto;
	case BPF_FUNC_skb_change_head:
		return &bpf_skb_change_head_proto;
3284 3285 3286 3287
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_proto;
	case BPF_FUNC_get_socket_uid:
		return &bpf_get_socket_uid_proto;
3288 3289
	case BPF_FUNC_sk_redirect_map:
		return &bpf_sk_redirect_map_proto;
3290 3291 3292 3293 3294
	default:
		return bpf_base_func_proto(func_id);
	}
}

3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329
static const struct bpf_func_proto *
lwt_xmit_func_proto(enum bpf_func_id func_id)
{
	switch (func_id) {
	case BPF_FUNC_skb_get_tunnel_key:
		return &bpf_skb_get_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_key:
		return bpf_get_skb_set_tunnel_proto(func_id);
	case BPF_FUNC_skb_get_tunnel_opt:
		return &bpf_skb_get_tunnel_opt_proto;
	case BPF_FUNC_skb_set_tunnel_opt:
		return bpf_get_skb_set_tunnel_proto(func_id);
	case BPF_FUNC_redirect:
		return &bpf_redirect_proto;
	case BPF_FUNC_clone_redirect:
		return &bpf_clone_redirect_proto;
	case BPF_FUNC_skb_change_tail:
		return &bpf_skb_change_tail_proto;
	case BPF_FUNC_skb_change_head:
		return &bpf_skb_change_head_proto;
	case BPF_FUNC_skb_store_bytes:
		return &bpf_skb_store_bytes_proto;
	case BPF_FUNC_csum_update:
		return &bpf_csum_update_proto;
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
	case BPF_FUNC_set_hash_invalid:
		return &bpf_set_hash_invalid_proto;
	default:
		return lwt_inout_func_proto(func_id);
	}
}

3330 3331
static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
				    struct bpf_insn_access_aux *info)
3332
{
3333
	const int size_default = sizeof(__u32);
3334

3335 3336
	if (off < 0 || off >= sizeof(struct __sk_buff))
		return false;
3337

3338
	/* The verifier guarantees that size > 0. */
3339 3340
	if (off % size != 0)
		return false;
3341 3342

	switch (off) {
3343 3344
	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
		if (off + size > offsetofend(struct __sk_buff, cb[4]))
3345 3346
			return false;
		break;
3347 3348 3349 3350
	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
3351 3352 3353
	case bpf_ctx_range(struct __sk_buff, data):
	case bpf_ctx_range(struct __sk_buff, data_end):
		if (size != size_default)
3354
			return false;
3355 3356
		break;
	default:
3357
		/* Only narrow read access allowed for now. */
3358
		if (type == BPF_WRITE) {
3359
			if (size != size_default)
3360 3361
				return false;
		} else {
3362 3363
			bpf_ctx_record_field_size(info, size_default);
			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
3364
				return false;
3365
		}
3366
	}
3367 3368 3369 3370

	return true;
}

3371
static bool sk_filter_is_valid_access(int off, int size,
3372
				      enum bpf_access_type type,
3373
				      struct bpf_insn_access_aux *info)
3374
{
3375
	switch (off) {
3376 3377 3378
	case bpf_ctx_range(struct __sk_buff, tc_classid):
	case bpf_ctx_range(struct __sk_buff, data):
	case bpf_ctx_range(struct __sk_buff, data_end):
3379
	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
3380
		return false;
3381
	}
3382

3383 3384
	if (type == BPF_WRITE) {
		switch (off) {
3385
		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3386 3387 3388 3389 3390 3391
			break;
		default:
			return false;
		}
	}

3392
	return bpf_skb_is_valid_access(off, size, type, info);
3393 3394
}

3395 3396
static bool lwt_is_valid_access(int off, int size,
				enum bpf_access_type type,
3397
				struct bpf_insn_access_aux *info)
3398 3399
{
	switch (off) {
3400
	case bpf_ctx_range(struct __sk_buff, tc_classid):
3401
	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
3402 3403 3404 3405 3406
		return false;
	}

	if (type == BPF_WRITE) {
		switch (off) {
3407 3408 3409
		case bpf_ctx_range(struct __sk_buff, mark):
		case bpf_ctx_range(struct __sk_buff, priority):
		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3410 3411 3412 3413 3414 3415
			break;
		default:
			return false;
		}
	}

3416 3417 3418 3419 3420 3421 3422 3423 3424 3425
	switch (off) {
	case bpf_ctx_range(struct __sk_buff, data):
		info->reg_type = PTR_TO_PACKET;
		break;
	case bpf_ctx_range(struct __sk_buff, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		break;
	}

	return bpf_skb_is_valid_access(off, size, type, info);
3426 3427
}

3428 3429
static bool sock_filter_is_valid_access(int off, int size,
					enum bpf_access_type type,
3430
					struct bpf_insn_access_aux *info)
3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
{
	if (type == BPF_WRITE) {
		switch (off) {
		case offsetof(struct bpf_sock, bound_dev_if):
			break;
		default:
			return false;
		}
	}

	if (off < 0 || off + size > sizeof(struct bpf_sock))
		return false;
	/* The verifier guarantees that size > 0. */
	if (off % size != 0)
		return false;
	if (size != sizeof(__u32))
		return false;

	return true;
}

3452 3453
static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
				const struct bpf_prog *prog, int drop_verdict)
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
{
	struct bpf_insn *insn = insn_buf;

	if (!direct_write)
		return 0;

	/* if (!skb->cloned)
	 *       goto start;
	 *
	 * (Fast-path, otherwise approximation that we might be
	 *  a clone, do the rest in helper.)
	 */
	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);

	/* ret = bpf_skb_pull_data(skb, 0); */
	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
			       BPF_FUNC_skb_pull_data);
	/* if (!ret)
	 *      goto restore;
	 * return TC_ACT_SHOT;
	 */
	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
3480
	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
	*insn++ = BPF_EXIT_INSN();

	/* restore: */
	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
	/* start: */
	*insn++ = prog->insnsi[0];

	return insn - insn_buf;
}

3491 3492 3493 3494 3495 3496
static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
			       const struct bpf_prog *prog)
{
	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
}

3497
static bool tc_cls_act_is_valid_access(int off, int size,
3498
				       enum bpf_access_type type,
3499
				       struct bpf_insn_access_aux *info)
3500 3501 3502
{
	if (type == BPF_WRITE) {
		switch (off) {
3503 3504 3505 3506 3507
		case bpf_ctx_range(struct __sk_buff, mark):
		case bpf_ctx_range(struct __sk_buff, tc_index):
		case bpf_ctx_range(struct __sk_buff, priority):
		case bpf_ctx_range(struct __sk_buff, tc_classid):
		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
3508 3509 3510 3511 3512
			break;
		default:
			return false;
		}
	}
3513

3514 3515 3516 3517 3518 3519 3520
	switch (off) {
	case bpf_ctx_range(struct __sk_buff, data):
		info->reg_type = PTR_TO_PACKET;
		break;
	case bpf_ctx_range(struct __sk_buff, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		break;
3521 3522
	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
		return false;
3523 3524 3525
	}

	return bpf_skb_is_valid_access(off, size, type, info);
3526 3527
}

3528
static bool __is_valid_xdp_access(int off, int size)
3529 3530 3531 3532 3533
{
	if (off < 0 || off >= sizeof(struct xdp_md))
		return false;
	if (off % size != 0)
		return false;
D
Daniel Borkmann 已提交
3534
	if (size != sizeof(__u32))
3535 3536 3537 3538 3539 3540 3541
		return false;

	return true;
}

static bool xdp_is_valid_access(int off, int size,
				enum bpf_access_type type,
3542
				struct bpf_insn_access_aux *info)
3543 3544 3545 3546 3547 3548
{
	if (type == BPF_WRITE)
		return false;

	switch (off) {
	case offsetof(struct xdp_md, data):
3549
		info->reg_type = PTR_TO_PACKET;
3550 3551
		break;
	case offsetof(struct xdp_md, data_end):
3552
		info->reg_type = PTR_TO_PACKET_END;
3553 3554 3555
		break;
	}

3556
	return __is_valid_xdp_access(off, size);
3557 3558 3559 3560 3561 3562 3563 3564
}

void bpf_warn_invalid_xdp_action(u32 act)
{
	WARN_ONCE(1, "Illegal XDP return value %u, expect packet loss\n", act);
}
EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);

L
Lawrence Brakmo 已提交
3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594
static bool __is_valid_sock_ops_access(int off, int size)
{
	if (off < 0 || off >= sizeof(struct bpf_sock_ops))
		return false;
	/* The verifier guarantees that size > 0. */
	if (off % size != 0)
		return false;
	if (size != sizeof(__u32))
		return false;

	return true;
}

static bool sock_ops_is_valid_access(int off, int size,
				     enum bpf_access_type type,
				     struct bpf_insn_access_aux *info)
{
	if (type == BPF_WRITE) {
		switch (off) {
		case offsetof(struct bpf_sock_ops, op) ...
		     offsetof(struct bpf_sock_ops, replylong[3]):
			break;
		default:
			return false;
		}
	}

	return __is_valid_sock_ops_access(off, size);
}

3595 3596 3597
static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
			   const struct bpf_prog *prog)
{
3598
	return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
3599 3600
}

3601 3602 3603 3604
static bool sk_skb_is_valid_access(int off, int size,
				   enum bpf_access_type type,
				   struct bpf_insn_access_aux *info)
{
3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615
	if (type == BPF_WRITE) {
		switch (off) {
		case bpf_ctx_range(struct __sk_buff, mark):
		case bpf_ctx_range(struct __sk_buff, tc_index):
		case bpf_ctx_range(struct __sk_buff, priority):
			break;
		default:
			return false;
		}
	}

3616
	switch (off) {
3617 3618
	case bpf_ctx_range(struct __sk_buff, tc_classid):
		return false;
3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629
	case bpf_ctx_range(struct __sk_buff, data):
		info->reg_type = PTR_TO_PACKET;
		break;
	case bpf_ctx_range(struct __sk_buff, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		break;
	}

	return bpf_skb_is_valid_access(off, size, type, info);
}

3630 3631 3632
static u32 bpf_convert_ctx_access(enum bpf_access_type type,
				  const struct bpf_insn *si,
				  struct bpf_insn *insn_buf,
3633
				  struct bpf_prog *prog, u32 *target_size)
3634 3635
{
	struct bpf_insn *insn = insn_buf;
3636
	int off;
3637

3638
	switch (si->off) {
3639
	case offsetof(struct __sk_buff, len):
3640
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3641 3642
				      bpf_target_off(struct sk_buff, len, 4,
						     target_size));
3643 3644
		break;

3645
	case offsetof(struct __sk_buff, protocol):
3646
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3647 3648
				      bpf_target_off(struct sk_buff, protocol, 2,
						     target_size));
3649 3650
		break;

3651
	case offsetof(struct __sk_buff, vlan_proto):
3652
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3653 3654
				      bpf_target_off(struct sk_buff, vlan_proto, 2,
						     target_size));
3655 3656
		break;

3657
	case offsetof(struct __sk_buff, priority):
3658
		if (type == BPF_WRITE)
3659
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3660 3661
					      bpf_target_off(struct sk_buff, priority, 4,
							     target_size));
3662
		else
3663
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3664 3665
					      bpf_target_off(struct sk_buff, priority, 4,
							     target_size));
3666 3667
		break;

3668
	case offsetof(struct __sk_buff, ingress_ifindex):
3669
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3670 3671
				      bpf_target_off(struct sk_buff, skb_iif, 4,
						     target_size));
3672 3673 3674
		break;

	case offsetof(struct __sk_buff, ifindex):
3675
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
3676
				      si->dst_reg, si->src_reg,
3677
				      offsetof(struct sk_buff, dev));
3678 3679
		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3680 3681
				      bpf_target_off(struct net_device, ifindex, 4,
						     target_size));
3682 3683
		break;

3684
	case offsetof(struct __sk_buff, hash):
3685
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3686 3687
				      bpf_target_off(struct sk_buff, hash, 4,
						     target_size));
3688 3689
		break;

3690
	case offsetof(struct __sk_buff, mark):
3691
		if (type == BPF_WRITE)
3692
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3693 3694
					      bpf_target_off(struct sk_buff, mark, 4,
							     target_size));
3695
		else
3696
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3697 3698
					      bpf_target_off(struct sk_buff, mark, 4,
							     target_size));
3699
		break;
3700 3701

	case offsetof(struct __sk_buff, pkt_type):
3702 3703 3704 3705 3706 3707 3708 3709
		*target_size = 1;
		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
				      PKT_TYPE_OFFSET());
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
#ifdef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
#endif
		break;
3710 3711

	case offsetof(struct __sk_buff, queue_mapping):
3712 3713 3714 3715
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
				      bpf_target_off(struct sk_buff, queue_mapping, 2,
						     target_size));
		break;
3716 3717 3718

	case offsetof(struct __sk_buff, vlan_present):
	case offsetof(struct __sk_buff, vlan_tci):
3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
		BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);

		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
				      bpf_target_off(struct sk_buff, vlan_tci, 2,
						     target_size));
		if (si->off == offsetof(struct __sk_buff, vlan_tci)) {
			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg,
						~VLAN_TAG_PRESENT);
		} else {
			*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 12);
			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
		}
		break;
3732 3733

	case offsetof(struct __sk_buff, cb[0]) ...
3734
	     offsetofend(struct __sk_buff, cb[4]) - 1:
3735
		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
3736 3737 3738
		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
			      offsetof(struct qdisc_skb_cb, data)) %
			     sizeof(__u64));
3739

3740
		prog->cb_access = 1;
3741 3742 3743 3744
		off  = si->off;
		off -= offsetof(struct __sk_buff, cb[0]);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct qdisc_skb_cb, data);
3745
		if (type == BPF_WRITE)
3746
			*insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
3747
					      si->src_reg, off);
3748
		else
3749
			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
3750
					      si->src_reg, off);
3751 3752
		break;

3753
	case offsetof(struct __sk_buff, tc_classid):
3754 3755 3756 3757 3758 3759
		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);

		off  = si->off;
		off -= offsetof(struct __sk_buff, tc_classid);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct qdisc_skb_cb, tc_classid);
3760
		*target_size = 2;
3761
		if (type == BPF_WRITE)
3762 3763
			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
					      si->src_reg, off);
3764
		else
3765 3766
			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
					      si->src_reg, off);
3767 3768
		break;

3769
	case offsetof(struct __sk_buff, data):
3770
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
3771
				      si->dst_reg, si->src_reg,
3772 3773 3774 3775
				      offsetof(struct sk_buff, data));
		break;

	case offsetof(struct __sk_buff, data_end):
3776 3777 3778 3779 3780 3781
		off  = si->off;
		off -= offsetof(struct __sk_buff, data_end);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct bpf_skb_data_end, data_end);
		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
				      si->src_reg, off);
3782 3783
		break;

3784 3785 3786
	case offsetof(struct __sk_buff, tc_index):
#ifdef CONFIG_NET_SCHED
		if (type == BPF_WRITE)
3787
			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
3788 3789
					      bpf_target_off(struct sk_buff, tc_index, 2,
							     target_size));
3790
		else
3791
			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3792 3793
					      bpf_target_off(struct sk_buff, tc_index, 2,
							     target_size));
3794
#else
3795
		*target_size = 2;
3796
		if (type == BPF_WRITE)
3797
			*insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
3798
		else
3799
			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
3800 3801 3802 3803 3804 3805
#endif
		break;

	case offsetof(struct __sk_buff, napi_id):
#if defined(CONFIG_NET_RX_BUSY_POLL)
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3806 3807
				      bpf_target_off(struct sk_buff, napi_id, 4,
						     target_size));
3808 3809 3810
		*insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
#else
3811
		*target_size = 4;
3812
		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
3813
#endif
3814
		break;
3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914
	case offsetof(struct __sk_buff, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_family,
						     2, target_size));
		break;
	case offsetof(struct __sk_buff, remote_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_daddr,
						     4, target_size));
		break;
	case offsetof(struct __sk_buff, local_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_rcv_saddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_rcv_saddr,
						     4, target_size));
		break;
	case offsetof(struct __sk_buff, remote_ip6[0]) ...
	     offsetof(struct __sk_buff, remote_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_daddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct __sk_buff, remote_ip6[0]);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_daddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;
	case offsetof(struct __sk_buff, local_ip6[0]) ...
	     offsetof(struct __sk_buff, local_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct __sk_buff, local_ip6[0]);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_rcv_saddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct __sk_buff, remote_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_dport,
						     2, target_size));
#ifndef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
#endif
		break;

	case offsetof(struct __sk_buff, local_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_num, 2, target_size));
		break;
3915 3916 3917
	}

	return insn - insn_buf;
3918 3919
}

3920
static u32 sock_filter_convert_ctx_access(enum bpf_access_type type,
3921
					  const struct bpf_insn *si,
3922
					  struct bpf_insn *insn_buf,
3923
					  struct bpf_prog *prog, u32 *target_size)
3924 3925 3926
{
	struct bpf_insn *insn = insn_buf;

3927
	switch (si->off) {
3928 3929 3930 3931
	case offsetof(struct bpf_sock, bound_dev_if):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);

		if (type == BPF_WRITE)
3932
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
3933 3934
					offsetof(struct sock, sk_bound_dev_if));
		else
3935
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3936 3937
				      offsetof(struct sock, sk_bound_dev_if));
		break;
3938 3939 3940 3941

	case offsetof(struct bpf_sock, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_family) != 2);

3942
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
3943 3944 3945 3946
				      offsetof(struct sock, sk_family));
		break;

	case offsetof(struct bpf_sock, type):
3947
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3948
				      offsetof(struct sock, __sk_flags_offset));
3949 3950
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
3951 3952 3953
		break;

	case offsetof(struct bpf_sock, protocol):
3954
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
3955
				      offsetof(struct sock, __sk_flags_offset));
3956 3957
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
3958
		break;
3959 3960 3961 3962 3963
	}

	return insn - insn_buf;
}

3964 3965
static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
					 const struct bpf_insn *si,
3966
					 struct bpf_insn *insn_buf,
3967
					 struct bpf_prog *prog, u32 *target_size)
3968 3969 3970
{
	struct bpf_insn *insn = insn_buf;

3971
	switch (si->off) {
3972 3973
	case offsetof(struct __sk_buff, ifindex):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
3974
				      si->dst_reg, si->src_reg,
3975
				      offsetof(struct sk_buff, dev));
3976
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
3977 3978
				      bpf_target_off(struct net_device, ifindex, 4,
						     target_size));
3979 3980
		break;
	default:
3981 3982
		return bpf_convert_ctx_access(type, si, insn_buf, prog,
					      target_size);
3983 3984 3985 3986 3987
	}

	return insn - insn_buf;
}

3988 3989
static u32 xdp_convert_ctx_access(enum bpf_access_type type,
				  const struct bpf_insn *si,
3990
				  struct bpf_insn *insn_buf,
3991
				  struct bpf_prog *prog, u32 *target_size)
3992 3993 3994
{
	struct bpf_insn *insn = insn_buf;

3995
	switch (si->off) {
3996
	case offsetof(struct xdp_md, data):
3997
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
3998
				      si->dst_reg, si->src_reg,
3999 4000 4001
				      offsetof(struct xdp_buff, data));
		break;
	case offsetof(struct xdp_md, data_end):
4002
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
4003
				      si->dst_reg, si->src_reg,
4004 4005 4006 4007 4008 4009 4010
				      offsetof(struct xdp_buff, data_end));
		break;
	}

	return insn - insn_buf;
}

L
Lawrence Brakmo 已提交
4011 4012 4013
static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
				       const struct bpf_insn *si,
				       struct bpf_insn *insn_buf,
4014 4015
				       struct bpf_prog *prog,
				       u32 *target_size)
L
Lawrence Brakmo 已提交
4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143
{
	struct bpf_insn *insn = insn_buf;
	int off;

	switch (si->off) {
	case offsetof(struct bpf_sock_ops, op) ...
	     offsetof(struct bpf_sock_ops, replylong[3]):
		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
			     FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
			     FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
			     FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
		off = si->off;
		off -= offsetof(struct bpf_sock_ops, op);
		off += offsetof(struct bpf_sock_ops_kern, op);
		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
					      off);
		else
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
					      off);
		break;

	case offsetof(struct bpf_sock_ops, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
					      struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_family));
		break;

	case offsetof(struct bpf_sock_ops, remote_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_daddr));
		break;

	case offsetof(struct bpf_sock_ops, local_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_rcv_saddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
					      struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_rcv_saddr));
		break;

	case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
	     offsetof(struct bpf_sock_ops, remote_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_daddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_daddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
	     offsetof(struct bpf_sock_ops, local_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_rcv_saddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct bpf_sock_ops, remote_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_dport));
#ifndef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
#endif
		break;

	case offsetof(struct bpf_sock_ops, local_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_num));
		break;
	}
	return insn - insn_buf;
}

4144
const struct bpf_verifier_ops sk_filter_prog_ops = {
4145 4146
	.get_func_proto		= sk_filter_func_proto,
	.is_valid_access	= sk_filter_is_valid_access,
4147
	.convert_ctx_access	= bpf_convert_ctx_access,
4148 4149
};

4150
const struct bpf_verifier_ops tc_cls_act_prog_ops = {
4151 4152
	.get_func_proto		= tc_cls_act_func_proto,
	.is_valid_access	= tc_cls_act_is_valid_access,
4153
	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
4154
	.gen_prologue		= tc_cls_act_prologue,
4155
	.test_run		= bpf_prog_test_run_skb,
4156 4157
};

4158
const struct bpf_verifier_ops xdp_prog_ops = {
4159 4160 4161
	.get_func_proto		= xdp_func_proto,
	.is_valid_access	= xdp_is_valid_access,
	.convert_ctx_access	= xdp_convert_ctx_access,
4162
	.test_run		= bpf_prog_test_run_xdp,
4163 4164
};

4165
const struct bpf_verifier_ops cg_skb_prog_ops = {
4166
	.get_func_proto		= sk_filter_func_proto,
4167
	.is_valid_access	= sk_filter_is_valid_access,
4168
	.convert_ctx_access	= bpf_convert_ctx_access,
4169
	.test_run		= bpf_prog_test_run_skb,
4170 4171
};

4172
const struct bpf_verifier_ops lwt_inout_prog_ops = {
4173 4174
	.get_func_proto		= lwt_inout_func_proto,
	.is_valid_access	= lwt_is_valid_access,
4175
	.convert_ctx_access	= bpf_convert_ctx_access,
4176
	.test_run		= bpf_prog_test_run_skb,
4177 4178
};

4179
const struct bpf_verifier_ops lwt_xmit_prog_ops = {
4180 4181
	.get_func_proto		= lwt_xmit_func_proto,
	.is_valid_access	= lwt_is_valid_access,
4182
	.convert_ctx_access	= bpf_convert_ctx_access,
4183
	.gen_prologue		= tc_cls_act_prologue,
4184
	.test_run		= bpf_prog_test_run_skb,
4185 4186
};

4187
const struct bpf_verifier_ops cg_sock_prog_ops = {
4188
	.get_func_proto		= bpf_base_func_proto,
4189 4190 4191 4192
	.is_valid_access	= sock_filter_is_valid_access,
	.convert_ctx_access	= sock_filter_convert_ctx_access,
};

L
Lawrence Brakmo 已提交
4193
const struct bpf_verifier_ops sock_ops_prog_ops = {
4194
	.get_func_proto		= sock_ops_func_proto,
L
Lawrence Brakmo 已提交
4195 4196 4197 4198
	.is_valid_access	= sock_ops_is_valid_access,
	.convert_ctx_access	= sock_ops_convert_ctx_access,
};

4199 4200 4201 4202
const struct bpf_verifier_ops sk_skb_prog_ops = {
	.get_func_proto		= sk_skb_func_proto,
	.is_valid_access	= sk_skb_is_valid_access,
	.convert_ctx_access	= bpf_convert_ctx_access,
4203
	.gen_prologue		= sk_skb_prologue,
4204 4205
};

4206
int sk_detach_filter(struct sock *sk)
4207 4208 4209 4210
{
	int ret = -ENOENT;
	struct sk_filter *filter;

4211 4212 4213
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

4214 4215
	filter = rcu_dereference_protected(sk->sk_filter,
					   lockdep_sock_is_held(sk));
4216
	if (filter) {
4217
		RCU_INIT_POINTER(sk->sk_filter, NULL);
E
Eric Dumazet 已提交
4218
		sk_filter_uncharge(sk, filter);
4219 4220
		ret = 0;
	}
4221

4222 4223
	return ret;
}
4224
EXPORT_SYMBOL_GPL(sk_detach_filter);
4225

4226 4227
int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
		  unsigned int len)
4228
{
4229
	struct sock_fprog_kern *fprog;
4230
	struct sk_filter *filter;
4231
	int ret = 0;
4232 4233 4234

	lock_sock(sk);
	filter = rcu_dereference_protected(sk->sk_filter,
4235
					   lockdep_sock_is_held(sk));
4236 4237
	if (!filter)
		goto out;
4238 4239

	/* We're copying the filter that has been originally attached,
4240 4241
	 * so no conversion/decode needed anymore. eBPF programs that
	 * have no original program cannot be dumped through this.
4242
	 */
4243
	ret = -EACCES;
4244
	fprog = filter->prog->orig_prog;
4245 4246
	if (!fprog)
		goto out;
4247 4248

	ret = fprog->len;
4249
	if (!len)
4250
		/* User space only enquires number of filter blocks. */
4251
		goto out;
4252

4253
	ret = -EINVAL;
4254
	if (len < fprog->len)
4255 4256 4257
		goto out;

	ret = -EFAULT;
4258
	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
4259
		goto out;
4260

4261 4262 4263 4264
	/* Instead of bytes, the API requests to return the number
	 * of filter blocks.
	 */
	ret = fprog->len;
4265 4266 4267 4268
out:
	release_sock(sk);
	return ret;
}