filter.c 77.6 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 29 30 31 32
 */

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

S
Stephen Hemminger 已提交
55
/**
56
 *	sk_filter_trim_cap - run a packet through a socket filter
S
Stephen Hemminger 已提交
57 58
 *	@sk: sock associated with &sk_buff
 *	@skb: buffer to filter
59
 *	@cap: limit on how short the eBPF program may trim the packet
S
Stephen Hemminger 已提交
60
 *
61 62
 * 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 已提交
63
 * than pkt_len we keep whole skb->data. This is the socket level
64
 * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
S
Stephen Hemminger 已提交
65 66 67
 * be accepted or -EPERM if the packet should be tossed.
 *
 */
68
int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
S
Stephen Hemminger 已提交
69 70 71 72
{
	int err;
	struct sk_filter *filter;

73 74 75 76 77 78 79 80
	/*
	 * If the skb was allocated from pfmemalloc reserves, only
	 * allow SOCK_MEMALLOC sockets to use it as this socket is
	 * helping free memory
	 */
	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC))
		return -ENOMEM;

S
Stephen Hemminger 已提交
81 82 83 84
	err = security_sock_rcv_skb(sk, skb);
	if (err)
		return err;

85 86
	rcu_read_lock();
	filter = rcu_dereference(sk->sk_filter);
S
Stephen Hemminger 已提交
87
	if (filter) {
88
		unsigned int pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
89
		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
S
Stephen Hemminger 已提交
90
	}
91
	rcu_read_unlock();
S
Stephen Hemminger 已提交
92 93 94

	return err;
}
95
EXPORT_SYMBOL(sk_filter_trim_cap);
S
Stephen Hemminger 已提交
96

97
BPF_CALL_1(__skb_get_pay_offset, struct sk_buff *, skb)
98
{
99
	return skb_get_poff(skb);
100 101
}

102
BPF_CALL_3(__skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
103 104 105 106 107 108
{
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

109 110 111
	if (skb->len < sizeof(struct nlattr))
		return 0;

112
	if (a > skb->len - sizeof(struct nlattr))
113 114
		return 0;

115
	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
116 117 118 119 120 121
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

122
BPF_CALL_3(__skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
123 124 125 126 127 128
{
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

129 130 131
	if (skb->len < sizeof(struct nlattr))
		return 0;

132
	if (a > skb->len - sizeof(struct nlattr))
133 134
		return 0;

135 136
	nla = (struct nlattr *) &skb->data[a];
	if (nla->nla_len > skb->len - a)
137 138
		return 0;

139
	nla = nla_find_nested(nla, x);
140 141 142 143 144 145
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

146
BPF_CALL_0(__get_raw_cpu_id)
147 148 149 150
{
	return raw_smp_processor_id();
}

151 152 153 154 155 156
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,
};

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
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;
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

	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;
203 204 205 206 207
	}

	return insn - insn_buf;
}

208
static bool convert_bpf_extensions(struct sock_filter *fp,
209
				   struct bpf_insn **insnp)
210
{
211
	struct bpf_insn *insn = *insnp;
212
	u32 cnt;
213 214 215

	switch (fp->k) {
	case SKF_AD_OFF + SKF_AD_PROTOCOL:
216 217 218 219 220 221 222
		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);
223 224 225
		break;

	case SKF_AD_OFF + SKF_AD_PKTTYPE:
226 227
		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
228 229 230 231 232 233
		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);
234

235
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
236 237 238 239 240 241 242 243 244 245 246
				      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));
247 248 249
		break;

	case SKF_AD_OFF + SKF_AD_MARK:
250 251
		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
252 253 254 255 256
		break;

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

257 258
		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
				    offsetof(struct sk_buff, hash));
259 260 261
		break;

	case SKF_AD_OFF + SKF_AD_QUEUE:
262 263
		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
264 265 266
		break;

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

272 273 274 275
	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;
276 277
		break;

278 279 280 281 282 283 284 285 286 287
	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;

288 289 290 291
	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 已提交
292
	case SKF_AD_OFF + SKF_AD_RANDOM:
293
		/* arg1 = CTX */
294
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
295
		/* arg2 = A */
296
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
297
		/* arg3 = X */
298
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
299
		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
300 301
		switch (fp->k) {
		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
302
			*insn = BPF_EMIT_CALL(__skb_get_pay_offset);
303 304
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR:
305
			*insn = BPF_EMIT_CALL(__skb_get_nlattr);
306 307
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
308
			*insn = BPF_EMIT_CALL(__skb_get_nlattr_nest);
309 310
			break;
		case SKF_AD_OFF + SKF_AD_CPU:
311
			*insn = BPF_EMIT_CALL(__get_raw_cpu_id);
312
			break;
C
Chema Gonzalez 已提交
313
		case SKF_AD_OFF + SKF_AD_RANDOM:
314 315
			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
			bpf_user_rnd_init_once();
C
Chema Gonzalez 已提交
316
			break;
317 318 319 320
		}
		break;

	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
321 322
		/* A ^= X */
		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
		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;
}

/**
339
 *	bpf_convert_filter - convert filter program
340 341 342 343 344 345 346 347 348
 *	@prog: the user passed filter program
 *	@len: the length of the user passed filter program
 *	@new_prog: buffer where converted program will be stored
 *	@new_len: pointer to store length of converted program
 *
 * Remap 'sock_filter' style BPF instruction set to 'sock_filter_ext' style.
 * Conversion workflow:
 *
 * 1) First pass for calculating the new program length:
349
 *   bpf_convert_filter(old_prog, old_len, NULL, &new_len)
350 351 352
 *
 * 2) 2nd pass to remap in two passes: 1st pass finds new
 *    jump offsets, 2nd pass remapping:
353
 *   new_prog = kmalloc(sizeof(struct bpf_insn) * new_len);
354
 *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len);
355
 */
356 357
static int bpf_convert_filter(struct sock_filter *prog, int len,
			      struct bpf_insn *new_prog, int *new_len)
358 359
{
	int new_flen = 0, pass = 0, target, i;
360
	struct bpf_insn *new_insn;
361 362 363 364 365
	struct sock_filter *fp;
	int *addrs = NULL;
	u8 bpf_src;

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

368
	if (len <= 0 || len > BPF_MAXINSNS)
369 370 371
		return -EINVAL;

	if (new_prog) {
372 373
		addrs = kcalloc(len, sizeof(*addrs),
				GFP_KERNEL | __GFP_NOWARN);
374 375 376 377 378 379 380 381
		if (!addrs)
			return -ENOMEM;
	}

do_pass:
	new_insn = new_prog;
	fp = prog;

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
	/* Classic BPF related prologue emission. */
	if (new_insn) {
		/* 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;
	}
398 399

	for (i = 0; i < len; fp++, i++) {
400 401
		struct bpf_insn tmp_insns[6] = { };
		struct bpf_insn *insn = tmp_insns;
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

		if (addrs)
			addrs[i] = new_insn - new_prog;

		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;

444
			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
445 446
			break;

447 448 449 450 451 452 453
		/* 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							\
454 455 456 457 458 459 460 461
	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)

462 463 464 465
		case BPF_JMP | BPF_JA:
			target = i + fp->k + 1;
			insn->code = fp->code;
			BPF_EMIT_JMP;
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
			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.
				 */
481
				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
482

483 484
				insn->dst_reg = BPF_REG_A;
				insn->src_reg = BPF_REG_TMP;
485 486
				bpf_src = BPF_X;
			} else {
487
				insn->dst_reg = BPF_REG_A;
488 489
				insn->imm = fp->k;
				bpf_src = BPF_SRC(fp->code);
490
				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
L
Linus Torvalds 已提交
491
			}
492 493 494 495 496

			/* 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;
497
				BPF_EMIT_JMP;
498
				break;
L
Linus Torvalds 已提交
499
			}
500 501 502 503 504

			/* Convert JEQ into JNE when 'jump_true' is next insn. */
			if (fp->jt == 0 && BPF_OP(fp->code) == BPF_JEQ) {
				insn->code = BPF_JMP | BPF_JNE | bpf_src;
				target = i + fp->jf + 1;
505
				BPF_EMIT_JMP;
506
				break;
507
			}
508 509 510 511

			/* 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;
512
			BPF_EMIT_JMP;
513 514 515 516
			insn++;

			insn->code = BPF_JMP | BPF_JA;
			target = i + fp->jf + 1;
517
			BPF_EMIT_JMP;
518 519 520 521
			break;

		/* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
		case BPF_LDX | BPF_MSH | BPF_B:
522
			/* tmp = A */
523
			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_A);
524
			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
525
			*insn++ = BPF_LD_ABS(BPF_B, fp->k);
526
			/* A &= 0xf */
527
			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
528
			/* A <<= 2 */
529
			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
530
			/* X = A */
531
			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
532
			/* A = tmp */
533
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
534 535
			break;

536 537 538
		/* 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.
		 */
539 540
		case BPF_RET | BPF_A:
		case BPF_RET | BPF_K:
541 542 543
			if (BPF_RVAL(fp->code) == BPF_K)
				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
							0, fp->k);
544
			*insn = BPF_EXIT_INSN();
545 546 547 548 549
			break;

		/* Store to stack. */
		case BPF_ST:
		case BPF_STX:
550 551 552
			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
					    BPF_ST ? BPF_REG_A : BPF_REG_X,
					    -(BPF_MEMWORDS - fp->k) * 4);
553 554 555 556 557
			break;

		/* Load from stack. */
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
558 559 560
			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
					    -(BPF_MEMWORDS - fp->k) * 4);
561 562 563 564 565
			break;

		/* A = K or X = K */
		case BPF_LD | BPF_IMM:
		case BPF_LDX | BPF_IMM:
566 567
			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
					      BPF_REG_A : BPF_REG_X, fp->k);
568 569 570 571
			break;

		/* X = A */
		case BPF_MISC | BPF_TAX:
572
			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
573 574 575 576
			break;

		/* A = X */
		case BPF_MISC | BPF_TXA:
577
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
578 579 580 581 582
			break;

		/* A = skb->len or X = skb->len */
		case BPF_LD | BPF_W | BPF_LEN:
		case BPF_LDX | BPF_W | BPF_LEN:
583 584 585
			*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));
586 587
			break;

588
		/* Access seccomp_data fields. */
589
		case BPF_LDX | BPF_ABS | BPF_W:
590 591
			/* A = *(u32 *) (ctx + K) */
			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
592 593
			break;

S
Stephen Hemminger 已提交
594
		/* Unknown instruction. */
L
Linus Torvalds 已提交
595
		default:
596
			goto err;
L
Linus Torvalds 已提交
597
		}
598 599 600 601 602 603

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

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
	if (!new_prog) {
		/* Only calculating new length. */
		*new_len = new_insn - new_prog;
		return 0;
	}

	pass++;
	if (new_flen != new_insn - new_prog) {
		new_flen = new_insn - new_prog;
		if (pass > 2)
			goto err;
		goto do_pass;
	}

	kfree(addrs);
	BUG_ON(*new_len != new_flen);
L
Linus Torvalds 已提交
622
	return 0;
623 624 625
err:
	kfree(addrs);
	return -EINVAL;
L
Linus Torvalds 已提交
626 627
}

628 629
/* Security:
 *
630
 * As we dont want to clear mem[] array for each packet going through
L
Li RongQing 已提交
631
 * __bpf_prog_run(), we check that filter loaded by user never try to read
632
 * a cell if not previously written, and we check all branches to be sure
L
Lucas De Marchi 已提交
633
 * a malicious user doesn't try to abuse us.
634
 */
635
static int check_load_and_stores(const struct sock_filter *filter, int flen)
636
{
637
	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
638 639 640
	int pc, ret = 0;

	BUILD_BUG_ON(BPF_MEMWORDS > 16);
641

642
	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
643 644
	if (!masks)
		return -ENOMEM;
645

646 647 648 649 650 651
	memset(masks, 0xff, flen * sizeof(*masks));

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

		switch (filter[pc].code) {
652 653
		case BPF_ST:
		case BPF_STX:
654 655
			memvalid |= (1 << filter[pc].k);
			break;
656 657
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
658 659 660 661 662
			if (!(memvalid & (1 << filter[pc].k))) {
				ret = -EINVAL;
				goto error;
			}
			break;
663 664
		case BPF_JMP | BPF_JA:
			/* A jump must set masks on target */
665 666 667
			masks[pc + 1 + filter[pc].k] &= memvalid;
			memvalid = ~0;
			break;
668 669 670 671 672 673 674 675 676
		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 */
677 678 679 680 681 682 683 684 685 686 687
			masks[pc + 1 + filter[pc].jt] &= memvalid;
			masks[pc + 1 + filter[pc].jf] &= memvalid;
			memvalid = ~0;
			break;
		}
	}
error:
	kfree(masks);
	return ret;
}

688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 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
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];
}

754 755 756 757 758 759 760 761 762 763 764
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 已提交
765
/**
766
 *	bpf_check_classic - verify socket filter code
L
Linus Torvalds 已提交
767 768 769 770 771
 *	@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
772 773
 * no references or jumps that are out of range, no illegal
 * instructions, and must end with a RET instruction.
L
Linus Torvalds 已提交
774
 *
775 776 777
 * All jumps are forward as they are not signed.
 *
 * Returns 0 if the rule set is legal or -EINVAL if not.
L
Linus Torvalds 已提交
778
 */
779 780
static int bpf_check_classic(const struct sock_filter *filter,
			     unsigned int flen)
L
Linus Torvalds 已提交
781
{
782
	bool anc_found;
783
	int pc;
L
Linus Torvalds 已提交
784

785
	/* Check the filter code now */
L
Linus Torvalds 已提交
786
	for (pc = 0; pc < flen; pc++) {
787
		const struct sock_filter *ftest = &filter[pc];
788

789 790
		/* May we actually operate on this code? */
		if (!chk_code_allowed(ftest->code))
791
			return -EINVAL;
792

793
		/* Some instructions need special checks */
794 795 796 797
		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 已提交
798 799 800
			if (ftest->k == 0)
				return -EINVAL;
			break;
R
Rabin Vincent 已提交
801 802 803 804 805
		case BPF_ALU | BPF_LSH | BPF_K:
		case BPF_ALU | BPF_RSH | BPF_K:
			if (ftest->k >= 32)
				return -EINVAL;
			break;
806 807 808 809 810
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
		case BPF_ST:
		case BPF_STX:
			/* Check for invalid memory addresses */
811 812 813
			if (ftest->k >= BPF_MEMWORDS)
				return -EINVAL;
			break;
814 815
		case BPF_JMP | BPF_JA:
			/* Note, the large ftest->k might cause loops.
816 817 818
			 * Compare this with conditional jumps below,
			 * where offsets are limited. --ANK (981016)
			 */
819
			if (ftest->k >= (unsigned int)(flen - pc - 1))
820
				return -EINVAL;
821
			break;
822 823 824 825 826 827 828 829 830
		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 */
831
			if (pc + ftest->jt + 1 >= flen ||
832 833
			    pc + ftest->jf + 1 >= flen)
				return -EINVAL;
834
			break;
835 836 837
		case BPF_LD | BPF_W | BPF_ABS:
		case BPF_LD | BPF_H | BPF_ABS:
		case BPF_LD | BPF_B | BPF_ABS:
838
			anc_found = false;
839 840 841
			if (bpf_anc_helper(ftest) & BPF_ANC)
				anc_found = true;
			/* Ancillary operation unknown or unsupported */
842 843
			if (anc_found == false && ftest->k >= SKF_AD_OFF)
				return -EINVAL;
844 845
		}
	}
846

847
	/* Last instruction must be a RET code */
848
	switch (filter[flen - 1].code) {
849 850
	case BPF_RET | BPF_K:
	case BPF_RET | BPF_A:
851
		return check_load_and_stores(filter, flen);
852
	}
853

854
	return -EINVAL;
L
Linus Torvalds 已提交
855 856
}

857 858
static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
				      const struct sock_fprog *fprog)
859
{
860
	unsigned int fsize = bpf_classic_proglen(fprog);
861 862 863 864 865 866 867 868
	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;
869 870 871

	fkprog->filter = kmemdup(fp->insns, fsize,
				 GFP_KERNEL | __GFP_NOWARN);
872 873 874 875 876 877 878 879
	if (!fkprog->filter) {
		kfree(fp->orig_prog);
		return -ENOMEM;
	}

	return 0;
}

880
static void bpf_release_orig_filter(struct bpf_prog *fp)
881 882 883 884 885 886 887 888 889
{
	struct sock_fprog_kern *fprog = fp->orig_prog;

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

890 891
static void __bpf_prog_release(struct bpf_prog *prog)
{
892
	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
893 894 895 896 897
		bpf_prog_put(prog);
	} else {
		bpf_release_orig_filter(prog);
		bpf_prog_free(prog);
	}
898 899
}

900 901
static void __sk_filter_release(struct sk_filter *fp)
{
902 903
	__bpf_prog_release(fp->prog);
	kfree(fp);
904 905
}

906
/**
E
Eric Dumazet 已提交
907
 * 	sk_filter_release_rcu - Release a socket filter by rcu_head
908 909
 *	@rcu: rcu_head that contains the sk_filter to free
 */
910
static void sk_filter_release_rcu(struct rcu_head *rcu)
911 912 913
{
	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);

914
	__sk_filter_release(fp);
915
}
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

/**
 *	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)
{
	if (atomic_dec_and_test(&fp->refcnt))
		call_rcu(&fp->rcu, sk_filter_release_rcu);
}

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

933 934
	atomic_sub(filter_size, &sk->sk_omem_alloc);
	sk_filter_release(fp);
935
}
936

937 938 939 940
/* try to charge the socket memory if there is space available
 * return true on success
 */
bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
941
{
942
	u32 filter_size = bpf_prog_size(fp->prog->len);
943 944 945 946 947 948 949

	/* same check as in sock_kmalloc() */
	if (filter_size <= sysctl_optmem_max &&
	    atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
		atomic_inc(&fp->refcnt);
		atomic_add(filter_size, &sk->sk_omem_alloc);
		return true;
950
	}
951
	return false;
952 953
}

954
static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
955 956
{
	struct sock_filter *old_prog;
957
	struct bpf_prog *old_fp;
958
	int err, new_len, old_len = fp->len;
959 960 961 962 963 964 965

	/* 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) !=
966
		     sizeof(struct bpf_insn));
967 968 969 970 971 972

	/* 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),
973
			   GFP_KERNEL | __GFP_NOWARN);
974 975 976 977 978 979
	if (!old_prog) {
		err = -ENOMEM;
		goto out_err;
	}

	/* 1st pass: calculate the new program length. */
980
	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
981 982 983 984 985
	if (err)
		goto out_err_free;

	/* Expand fp for appending the new filter representation. */
	old_fp = fp;
986
	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
987 988 989 990 991 992 993 994 995 996 997
	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;

998
	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
999
	err = bpf_convert_filter(old_prog, old_len, fp->insnsi, &new_len);
1000
	if (err)
1001
		/* 2nd bpf_convert_filter() can fail only if it fails
1002 1003
		 * to allocate memory, remapping must succeed. Note,
		 * that at this time old_fp has already been released
1004
		 * by krealloc().
1005 1006 1007
		 */
		goto out_err_free;

1008 1009 1010 1011 1012
	/* 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);
1013

1014 1015 1016 1017 1018 1019
	kfree(old_prog);
	return fp;

out_err_free:
	kfree(old_prog);
out_err:
1020
	__bpf_prog_release(fp);
1021 1022 1023
	return ERR_PTR(err);
}

1024 1025
static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
					   bpf_aux_classic_check_t trans)
1026 1027 1028
{
	int err;

1029
	fp->bpf_func = NULL;
1030
	fp->jited = 0;
1031

1032
	err = bpf_check_classic(fp->insns, fp->len);
1033
	if (err) {
1034
		__bpf_prog_release(fp);
1035
		return ERR_PTR(err);
1036
	}
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	/* 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);
		}
	}

1049 1050 1051
	/* Probe if we can JIT compile the filter and if so, do
	 * the compilation of the filter.
	 */
1052
	bpf_jit_compile(fp);
1053 1054 1055 1056

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

	return fp;
1061 1062 1063
}

/**
1064
 *	bpf_prog_create - create an unattached filter
R
Randy Dunlap 已提交
1065
 *	@pfp: the unattached filter that is created
1066
 *	@fprog: the filter program
1067
 *
R
Randy Dunlap 已提交
1068
 * Create a filter independent of any socket. We first run some
1069 1070 1071 1072
 * 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.
 */
1073
int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1074
{
1075
	unsigned int fsize = bpf_classic_proglen(fprog);
1076
	struct bpf_prog *fp;
1077 1078

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

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

1086 1087 1088
	memcpy(fp->insns, fprog->filter, fsize);

	fp->len = fprog->len;
1089 1090 1091 1092 1093
	/* 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;
1094

1095
	/* bpf_prepare_filter() already takes care of freeing
1096 1097
	 * memory in case something goes wrong.
	 */
1098
	fp = bpf_prepare_filter(fp, NULL);
1099 1100
	if (IS_ERR(fp))
		return PTR_ERR(fp);
1101 1102 1103 1104

	*pfp = fp;
	return 0;
}
1105
EXPORT_SYMBOL_GPL(bpf_prog_create);
1106

1107 1108 1109 1110 1111
/**
 *	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
1112
 *	@save_orig: save classic BPF program
1113 1114 1115 1116 1117 1118
 *
 * 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,
1119
			      bpf_aux_classic_check_t trans, bool save_orig)
1120 1121 1122
{
	unsigned int fsize = bpf_classic_proglen(fprog);
	struct bpf_prog *fp;
1123
	int err;
1124 1125

	/* Make sure new filter is there and in the right amounts. */
1126
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
		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;

1141 1142 1143 1144 1145 1146 1147 1148
	if (save_orig) {
		err = bpf_prog_store_orig_filter(fp, fprog);
		if (err) {
			__bpf_prog_free(fp);
			return -ENOMEM;
		}
	}

1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
	/* 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;
}
1159
EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1160

1161
void bpf_prog_destroy(struct bpf_prog *fp)
1162
{
1163
	__bpf_prog_release(fp);
1164
}
1165
EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1166

1167
static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
{
	struct sk_filter *fp, *old_fp;

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

	fp->prog = prog;
	atomic_set(&fp->refcnt, 0);

	if (!sk_filter_charge(sk, fp)) {
		kfree(fp);
		return -ENOMEM;
	}

1183 1184
	old_fp = rcu_dereference_protected(sk->sk_filter,
					   lockdep_sock_is_held(sk));
1185
	rcu_assign_pointer(sk->sk_filter, fp);
1186

1187 1188 1189 1190 1191 1192
	if (old_fp)
		sk_filter_uncharge(sk, old_fp);

	return 0;
}

1193 1194 1195 1196 1197 1198 1199 1200
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;

1201
	if (sk_unhashed(sk) && sk->sk_reuseport) {
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
		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 已提交
1219
{
1220
	unsigned int fsize = bpf_classic_proglen(fprog);
1221
	struct bpf_prog *prog;
L
Linus Torvalds 已提交
1222 1223
	int err;

1224
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1225
		return ERR_PTR(-EPERM);
1226

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

1231
	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1232
	if (!prog)
1233
		return ERR_PTR(-ENOMEM);
1234

1235
	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1236
		__bpf_prog_free(prog);
1237
		return ERR_PTR(-EFAULT);
L
Linus Torvalds 已提交
1238 1239
	}

1240
	prog->len = fprog->len;
L
Linus Torvalds 已提交
1241

1242
	err = bpf_prog_store_orig_filter(prog, fprog);
1243
	if (err) {
1244
		__bpf_prog_free(prog);
1245
		return ERR_PTR(-ENOMEM);
1246 1247
	}

1248
	/* bpf_prepare_filter() already takes care of freeing
1249 1250
	 * memory in case something goes wrong.
	 */
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	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.
 */
1264
int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1265 1266 1267 1268
{
	struct bpf_prog *prog = __get_filter(fprog, sk);
	int err;

1269 1270 1271
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1272
	err = __sk_attach_prog(prog, sk);
1273
	if (err < 0) {
1274
		__bpf_prog_release(prog);
1275
		return err;
1276 1277
	}

1278
	return 0;
L
Linus Torvalds 已提交
1279
}
1280
EXPORT_SYMBOL_GPL(sk_attach_filter);
L
Linus Torvalds 已提交
1281

1282
int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1283
{
1284
	struct bpf_prog *prog = __get_filter(fprog, sk);
1285
	int err;
1286

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
	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)
{
1301
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1302
		return ERR_PTR(-EPERM);
1303

1304
	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
}

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);

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

	return 0;
}

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
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;
}

1341 1342 1343 1344 1345 1346 1347 1348
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);
1349

1350 1351 1352 1353 1354 1355
static inline int __bpf_try_make_writable(struct sk_buff *skb,
					  unsigned int write_len)
{
	return skb_ensure_writable(skb, write_len);
}

1356 1357 1358
static inline int bpf_try_make_writable(struct sk_buff *skb,
					unsigned int write_len)
{
1359
	int err = __bpf_try_make_writable(skb, write_len);
1360

1361
	bpf_compute_data_end(skb);
1362 1363 1364
	return err;
}

1365 1366 1367 1368 1369
static int bpf_try_make_head_writable(struct sk_buff *skb)
{
	return bpf_try_make_writable(skb, skb_headlen(skb));
}

1370 1371 1372 1373 1374 1375
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);
}

1376 1377 1378 1379 1380 1381
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);
}

1382 1383
BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
	   const void *, from, u32, len, u64, flags)
1384 1385 1386
{
	void *ptr;

1387
	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1388
		return -EINVAL;
1389
	if (unlikely(offset > 0xffff))
1390
		return -EFAULT;
1391
	if (unlikely(bpf_try_make_writable(skb, offset + len)))
1392 1393
		return -EFAULT;

1394
	ptr = skb->data + offset;
1395
	if (flags & BPF_F_RECOMPUTE_CSUM)
1396
		__skb_postpull_rcsum(skb, ptr, len, offset);
1397 1398 1399

	memcpy(ptr, from, len);

1400
	if (flags & BPF_F_RECOMPUTE_CSUM)
1401
		__skb_postpush_rcsum(skb, ptr, len, offset);
1402 1403
	if (flags & BPF_F_INVALIDATE_HASH)
		skb_clear_hash(skb);
1404

1405 1406 1407
	return 0;
}

1408
static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1409 1410 1411 1412 1413 1414 1415
	.func		= bpf_skb_store_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_STACK,
	.arg4_type	= ARG_CONST_STACK_SIZE,
1416 1417 1418
	.arg5_type	= ARG_ANYTHING,
};

1419 1420
BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
	   void *, to, u32, len)
1421 1422 1423
{
	void *ptr;

1424
	if (unlikely(offset > 0xffff))
1425
		goto err_clear;
1426 1427 1428

	ptr = skb_header_pointer(skb, offset, len, to);
	if (unlikely(!ptr))
1429
		goto err_clear;
1430 1431 1432 1433
	if (ptr != to)
		memcpy(to, ptr, len);

	return 0;
1434 1435 1436
err_clear:
	memset(to, 0, len);
	return -EFAULT;
1437 1438
}

1439
static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1440 1441 1442 1443 1444
	.func		= bpf_skb_load_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
1445
	.arg3_type	= ARG_PTR_TO_RAW_STACK,
1446 1447 1448
	.arg4_type	= ARG_CONST_STACK_SIZE,
};

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
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,
};

1471 1472
BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
	   u64, from, u64, to, u64, flags)
1473
{
1474
	__sum16 *ptr;
1475

1476 1477
	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
		return -EINVAL;
1478
	if (unlikely(offset > 0xffff || offset & 1))
1479
		return -EFAULT;
1480
	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1481 1482
		return -EFAULT;

1483
	ptr = (__sum16 *)(skb->data + offset);
1484
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1485 1486 1487 1488 1489 1490
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		csum_replace_by_diff(ptr, to);
		break;
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	case 2:
		csum_replace2(ptr, from, to);
		break;
	case 4:
		csum_replace4(ptr, from, to);
		break;
	default:
		return -EINVAL;
	}

	return 0;
}

1504
static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
	.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,
};

1515 1516
BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
	   u64, from, u64, to, u64, flags)
1517
{
1518
	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1519
	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1520
	__sum16 *ptr;
1521

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

1530
	ptr = (__sum16 *)(skb->data + offset);
1531 1532
	if (is_mmzero && !*ptr)
		return 0;
1533

1534
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1535 1536 1537 1538 1539 1540
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
		break;
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
	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;
	}

1551 1552
	if (is_mmzero && !*ptr)
		*ptr = CSUM_MANGLED_0;
1553 1554 1555
	return 0;
}

1556
static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1557 1558 1559 1560 1561 1562 1563 1564
	.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,
1565 1566
};

1567 1568
BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
	   __be32 *, to, u32, to_size, __wsum, seed)
1569
{
1570
	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1571
	u32 diff_size = from_size + to_size;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
	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);
}

1594
static const struct bpf_func_proto bpf_csum_diff_proto = {
1595 1596
	.func		= bpf_csum_diff,
	.gpl_only	= false,
1597
	.pkt_access	= true,
1598 1599 1600 1601 1602 1603 1604 1605
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_STACK,
	.arg2_type	= ARG_CONST_STACK_SIZE_OR_ZERO,
	.arg3_type	= ARG_PTR_TO_STACK,
	.arg4_type	= ARG_CONST_STACK_SIZE_OR_ZERO,
	.arg5_type	= ARG_ANYTHING,
};

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
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,
};

1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
{
	return dev_forward_skb(dev, skb);
}

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;
}

1650
BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
1651 1652
{
	struct net_device *dev;
1653 1654
	struct sk_buff *clone;
	int ret;
1655

1656 1657 1658
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return -EINVAL;

1659 1660 1661 1662
	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
	if (unlikely(!dev))
		return -EINVAL;

1663 1664
	clone = skb_clone(skb, GFP_ATOMIC);
	if (unlikely(!clone))
1665 1666
		return -ENOMEM;

1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
	/* 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;
	}

	bpf_push_mac_rcsum(clone);
1679

1680
	return flags & BPF_F_INGRESS ?
1681
	       __bpf_rx_skb(dev, clone) : __bpf_tx_skb(dev, clone);
1682 1683
}

1684
static const struct bpf_func_proto bpf_clone_redirect_proto = {
1685 1686 1687 1688 1689 1690 1691 1692
	.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,
};

1693 1694 1695 1696 1697 1698
struct redirect_info {
	u32 ifindex;
	u32 flags;
};

static DEFINE_PER_CPU(struct redirect_info, redirect_info);
1699

1700
BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
1701 1702 1703
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);

1704 1705 1706
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return TC_ACT_SHOT;

1707 1708
	ri->ifindex = ifindex;
	ri->flags = flags;
1709

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
	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;
	}

1725 1726
	bpf_push_mac_rcsum(skb);

1727 1728
	return ri->flags & BPF_F_INGRESS ?
	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
1729 1730
}

1731
static const struct bpf_func_proto bpf_redirect_proto = {
1732 1733 1734 1735 1736 1737 1738
	.func           = bpf_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_ANYTHING,
	.arg2_type      = ARG_ANYTHING,
};

1739
BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
1740
{
1741
	return task_get_classid(skb);
1742 1743 1744 1745 1746 1747 1748 1749 1750
}

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,
};

1751
BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
1752
{
1753
	return dst_tclassid(skb);
1754 1755 1756 1757 1758 1759 1760 1761 1762
}

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,
};

1763
BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
1764 1765 1766 1767 1768 1769
{
	/* 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.
	 */
1770
	return skb_get_hash(skb);
1771 1772 1773 1774 1775 1776 1777 1778 1779
}

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,
};

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
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,
};

1796 1797
BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
	   u16, vlan_tci)
1798
{
1799
	int ret;
1800 1801 1802 1803 1804

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

1805
	bpf_push_mac_rcsum(skb);
1806
	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
1807 1808
	bpf_pull_mac_rcsum(skb);

1809 1810
	bpf_compute_data_end(skb);
	return ret;
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
}

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,
};
1821
EXPORT_SYMBOL_GPL(bpf_skb_vlan_push_proto);
1822

1823
BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
1824
{
1825
	int ret;
1826

1827
	bpf_push_mac_rcsum(skb);
1828
	ret = skb_vlan_pop(skb);
1829 1830
	bpf_pull_mac_rcsum(skb);

1831 1832
	bpf_compute_data_end(skb);
	return ret;
1833 1834 1835 1836 1837 1838 1839 1840
}

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,
};
1841
EXPORT_SYMBOL_GPL(bpf_skb_vlan_pop_proto);
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 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
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);
	u32 off = skb->network_header - skb->mac_header;
	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)) {
		/* SKB_GSO_UDP stays as is. SKB_GSO_TCPV4 needs to
		 * be changed into SKB_GSO_TCPV6.
		 */
		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);
	u32 off = skb->network_header - skb->mac_header;
	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)) {
		/* SKB_GSO_UDP stays as is. SKB_GSO_TCPV6 needs to
		 * be changed into SKB_GSO_TCPV4.
		 */
		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;
}

1999 2000
BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
	   u64, flags)
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
{
	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,
};

2038
BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2039 2040
{
	/* We only allow a restricted subset to be changed for now. */
2041 2042
	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
		     !skb_pkt_type_ok(pkt_type)))
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
		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,
};

2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
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 u32 __bpf_skb_max_len(const struct sk_buff *skb)
{
D
Daniel Borkmann 已提交
2071
	return skb->dev->mtu + skb->dev->hard_header_len;
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
}

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);
}

2090 2091
BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
	   u64, flags)
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
{
	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,
};

2141 2142
bool bpf_helper_changes_skb_data(void *func)
{
2143 2144 2145 2146 2147 2148 2149 2150
	if (func == bpf_skb_vlan_push ||
	    func == bpf_skb_vlan_pop ||
	    func == bpf_skb_store_bytes ||
	    func == bpf_skb_change_proto ||
	    func == bpf_skb_change_tail ||
	    func == bpf_skb_pull_data ||
	    func == bpf_l3_csum_replace ||
	    func == bpf_l4_csum_replace)
2151 2152
		return true;

2153 2154 2155
	return false;
}

2156
static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
2157
				  unsigned long off, unsigned long len)
2158
{
2159
	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
2160 2161 2162 2163 2164 2165 2166 2167 2168

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

	return 0;
}

2169 2170
BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
	   u64, flags, void *, meta, u64, meta_size)
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
{
	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,
	.arg4_type	= ARG_PTR_TO_STACK,
	.arg5_type	= ARG_CONST_STACK_SIZE,
};

2194 2195 2196 2197 2198
static unsigned short bpf_tunnel_key_af(u64 flags)
{
	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
}

2199 2200
BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
	   u32, size, u64, flags)
2201
{
2202 2203
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
	u8 compat[sizeof(struct bpf_tunnel_key)];
2204 2205
	void *to_orig = to;
	int err;
2206

2207 2208 2209 2210 2211 2212 2213 2214
	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;
	}
2215
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
2216
		err = -EINVAL;
2217
		switch (size) {
2218
		case offsetof(struct bpf_tunnel_key, tunnel_label):
2219
		case offsetof(struct bpf_tunnel_key, tunnel_ext):
2220
			goto set_compat;
2221 2222 2223 2224 2225
		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)
2226
				goto err_clear;
2227
set_compat:
2228 2229 2230
			to = (struct bpf_tunnel_key *)compat;
			break;
		default:
2231
			goto err_clear;
2232 2233
		}
	}
2234 2235

	to->tunnel_id = be64_to_cpu(info->key.tun_id);
2236 2237 2238
	to->tunnel_tos = info->key.tos;
	to->tunnel_ttl = info->key.ttl;

2239
	if (flags & BPF_F_TUNINFO_IPV6) {
2240 2241
		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
		       sizeof(to->remote_ipv6));
2242 2243
		to->tunnel_label = be32_to_cpu(info->key.label);
	} else {
2244
		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
2245
	}
2246 2247

	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
2248
		memcpy(to_orig, to, size);
2249 2250

	return 0;
2251 2252 2253
err_clear:
	memset(to_orig, 0, size);
	return err;
2254 2255
}

2256
static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
2257 2258 2259 2260
	.func		= bpf_skb_get_tunnel_key,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
2261
	.arg2_type	= ARG_PTR_TO_RAW_STACK,
2262 2263 2264 2265
	.arg3_type	= ARG_CONST_STACK_SIZE,
	.arg4_type	= ARG_ANYTHING,
};

2266
BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
2267 2268
{
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
2269
	int err;
2270 2271

	if (unlikely(!info ||
2272 2273 2274 2275 2276 2277 2278 2279
		     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
		err = -ENOENT;
		goto err_clear;
	}
	if (unlikely(size < info->options_len)) {
		err = -ENOMEM;
		goto err_clear;
	}
2280 2281

	ip_tunnel_info_opts_get(to, info);
2282 2283
	if (size > info->options_len)
		memset(to + info->options_len, 0, size - info->options_len);
2284 2285

	return info->options_len;
2286 2287 2288
err_clear:
	memset(to, 0, size);
	return err;
2289 2290 2291 2292 2293 2294 2295
}

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,
2296
	.arg2_type	= ARG_PTR_TO_RAW_STACK,
2297 2298 2299
	.arg3_type	= ARG_CONST_STACK_SIZE,
};

2300 2301
static struct metadata_dst __percpu *md_dst;

2302 2303
BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
2304 2305
{
	struct metadata_dst *md = this_cpu_ptr(md_dst);
2306
	u8 compat[sizeof(struct bpf_tunnel_key)];
2307 2308
	struct ip_tunnel_info *info;

2309 2310
	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
			       BPF_F_DONT_FRAGMENT)))
2311
		return -EINVAL;
2312 2313
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
		switch (size) {
2314
		case offsetof(struct bpf_tunnel_key, tunnel_label):
2315
		case offsetof(struct bpf_tunnel_key, tunnel_ext):
2316 2317 2318 2319 2320 2321
		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);
2322
			from = (const struct bpf_tunnel_key *) compat;
2323 2324 2325 2326 2327
			break;
		default:
			return -EINVAL;
		}
	}
2328 2329
	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
		     from->tunnel_ext))
2330
		return -EINVAL;
2331 2332 2333 2334 2335 2336 2337

	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;
2338

2339
	info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
2340 2341 2342
	if (flags & BPF_F_DONT_FRAGMENT)
		info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;

2343
	info->key.tun_id = cpu_to_be64(from->tunnel_id);
2344 2345 2346 2347 2348 2349 2350
	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));
2351 2352
		info->key.label = cpu_to_be32(from->tunnel_label) &
				  IPV6_FLOWLABEL_MASK;
2353 2354
	} else {
		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
2355 2356
		if (flags & BPF_F_ZERO_CSUM_TX)
			info->key.tun_flags &= ~TUNNEL_CSUM;
2357
	}
2358 2359 2360 2361

	return 0;
}

2362
static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
2363 2364 2365 2366 2367 2368 2369 2370 2371
	.func		= bpf_skb_set_tunnel_key,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_PTR_TO_STACK,
	.arg3_type	= ARG_CONST_STACK_SIZE,
	.arg4_type	= ARG_ANYTHING,
};

2372 2373
BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
	   const u8 *, from, u32, size)
2374 2375 2376 2377 2378 2379
{
	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;
2380
	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
		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,
	.arg2_type	= ARG_PTR_TO_STACK,
	.arg3_type	= ARG_CONST_STACK_SIZE,
};

static const struct bpf_func_proto *
bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
2399 2400
{
	if (!md_dst) {
2401 2402
		/* Race is not possible, since it's called from verifier
		 * that is holding verifier mutex.
2403
		 */
2404
		md_dst = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
2405
						   GFP_KERNEL);
2406 2407 2408
		if (!md_dst)
			return NULL;
	}
2409 2410 2411 2412 2413 2414 2415 2416 2417

	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;
	}
2418 2419
}

2420 2421
BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
	   u32, idx)
2422 2423 2424 2425 2426
{
	struct bpf_array *array = container_of(map, struct bpf_array, map);
	struct cgroup *cgrp;
	struct sock *sk;

2427
	sk = skb_to_full_sk(skb);
2428 2429
	if (!sk || !sk_fullsock(sk))
		return -ENOENT;
2430
	if (unlikely(idx >= array->map.max_entries))
2431 2432
		return -E2BIG;

2433
	cgrp = READ_ONCE(array->ptrs[idx]);
2434 2435 2436
	if (unlikely(!cgrp))
		return -EAGAIN;

2437
	return sk_under_cgroup_hierarchy(sk, cgrp);
2438 2439
}

2440 2441
static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
	.func		= bpf_skb_under_cgroup,
2442 2443 2444 2445 2446 2447 2448
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
};

2449 2450 2451 2452 2453 2454 2455
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;
}

2456 2457
BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
	   u64, flags, void *, meta, u64, meta_size)
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
{
	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;

	return bpf_event_output(map, flags, meta, meta_size, xdp, xdp_size,
				bpf_xdp_copy);
}

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,
	.arg4_type	= ARG_PTR_TO_STACK,
	.arg5_type	= ARG_CONST_STACK_SIZE,
};

2481 2482
static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id)
2483 2484 2485 2486 2487 2488 2489 2490
{
	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;
2491 2492
	case BPF_FUNC_get_prandom_u32:
		return &bpf_get_prandom_u32_proto;
2493
	case BPF_FUNC_get_smp_processor_id:
2494
		return &bpf_get_raw_smp_processor_id_proto;
2495 2496
	case BPF_FUNC_tail_call:
		return &bpf_tail_call_proto;
2497 2498
	case BPF_FUNC_ktime_get_ns:
		return &bpf_ktime_get_ns_proto;
2499
	case BPF_FUNC_trace_printk:
2500 2501
		if (capable(CAP_SYS_ADMIN))
			return bpf_get_trace_printk_proto();
2502 2503 2504 2505 2506
	default:
		return NULL;
	}
}

2507 2508 2509 2510 2511 2512
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;
2513 2514
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
2515 2516
	case BPF_FUNC_skb_pull_data:
		return &bpf_skb_pull_data_proto;
2517 2518
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
2519 2520
	case BPF_FUNC_csum_update:
		return &bpf_csum_update_proto;
2521 2522 2523 2524
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
2525 2526
	case BPF_FUNC_clone_redirect:
		return &bpf_clone_redirect_proto;
2527 2528
	case BPF_FUNC_get_cgroup_classid:
		return &bpf_get_cgroup_classid_proto;
2529 2530 2531 2532
	case BPF_FUNC_skb_vlan_push:
		return &bpf_skb_vlan_push_proto;
	case BPF_FUNC_skb_vlan_pop:
		return &bpf_skb_vlan_pop_proto;
2533 2534
	case BPF_FUNC_skb_change_proto:
		return &bpf_skb_change_proto_proto;
2535 2536
	case BPF_FUNC_skb_change_type:
		return &bpf_skb_change_type_proto;
2537 2538
	case BPF_FUNC_skb_change_tail:
		return &bpf_skb_change_tail_proto;
2539 2540 2541
	case BPF_FUNC_skb_get_tunnel_key:
		return &bpf_skb_get_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_key:
2542 2543 2544 2545 2546
		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);
2547 2548
	case BPF_FUNC_redirect:
		return &bpf_redirect_proto;
2549 2550
	case BPF_FUNC_get_route_realm:
		return &bpf_get_route_realm_proto;
2551 2552
	case BPF_FUNC_get_hash_recalc:
		return &bpf_get_hash_recalc_proto;
2553 2554
	case BPF_FUNC_set_hash_invalid:
		return &bpf_set_hash_invalid_proto;
2555
	case BPF_FUNC_perf_event_output:
2556
		return &bpf_skb_event_output_proto;
2557 2558
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
2559 2560
	case BPF_FUNC_skb_under_cgroup:
		return &bpf_skb_under_cgroup_proto;
2561 2562 2563 2564 2565
	default:
		return sk_filter_func_proto(func_id);
	}
}

2566 2567 2568
static const struct bpf_func_proto *
xdp_func_proto(enum bpf_func_id func_id)
{
2569 2570 2571
	switch (func_id) {
	case BPF_FUNC_perf_event_output:
		return &bpf_xdp_event_output_proto;
2572 2573
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
2574 2575 2576
	default:
		return sk_filter_func_proto(func_id);
	}
2577 2578
}

2579
static bool __is_valid_access(int off, int size, enum bpf_access_type type)
2580
{
2581 2582
	if (off < 0 || off >= sizeof(struct __sk_buff))
		return false;
2583
	/* The verifier guarantees that size > 0. */
2584 2585
	if (off % size != 0)
		return false;
2586
	if (size != sizeof(__u32))
2587 2588 2589 2590 2591
		return false;

	return true;
}

2592
static bool sk_filter_is_valid_access(int off, int size,
2593 2594
				      enum bpf_access_type type,
				      enum bpf_reg_type *reg_type)
2595
{
2596 2597 2598 2599
	switch (off) {
	case offsetof(struct __sk_buff, tc_classid):
	case offsetof(struct __sk_buff, data):
	case offsetof(struct __sk_buff, data_end):
2600
		return false;
2601
	}
2602

2603 2604 2605
	if (type == BPF_WRITE) {
		switch (off) {
		case offsetof(struct __sk_buff, cb[0]) ...
2606
		     offsetof(struct __sk_buff, cb[4]):
2607 2608 2609 2610 2611 2612 2613 2614 2615
			break;
		default:
			return false;
		}
	}

	return __is_valid_access(off, size, type);
}

2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
			       const struct bpf_prog *prog)
{
	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);
	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, TC_ACT_SHOT);
	*insn++ = BPF_EXIT_INSN();

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

	return insn - insn_buf;
}

2655
static bool tc_cls_act_is_valid_access(int off, int size,
2656 2657
				       enum bpf_access_type type,
				       enum bpf_reg_type *reg_type)
2658 2659 2660 2661 2662
{
	if (type == BPF_WRITE) {
		switch (off) {
		case offsetof(struct __sk_buff, mark):
		case offsetof(struct __sk_buff, tc_index):
2663
		case offsetof(struct __sk_buff, priority):
2664
		case offsetof(struct __sk_buff, cb[0]) ...
2665 2666
		     offsetof(struct __sk_buff, cb[4]):
		case offsetof(struct __sk_buff, tc_classid):
2667 2668 2669 2670 2671
			break;
		default:
			return false;
		}
	}
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681

	switch (off) {
	case offsetof(struct __sk_buff, data):
		*reg_type = PTR_TO_PACKET;
		break;
	case offsetof(struct __sk_buff, data_end):
		*reg_type = PTR_TO_PACKET_END;
		break;
	}

2682 2683 2684
	return __is_valid_access(off, size, type);
}

2685 2686 2687 2688 2689 2690 2691
static bool __is_valid_xdp_access(int off, int size,
				  enum bpf_access_type type)
{
	if (off < 0 || off >= sizeof(struct xdp_md))
		return false;
	if (off % size != 0)
		return false;
D
Daniel Borkmann 已提交
2692
	if (size != sizeof(__u32))
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722
		return false;

	return true;
}

static bool xdp_is_valid_access(int off, int size,
				enum bpf_access_type type,
				enum bpf_reg_type *reg_type)
{
	if (type == BPF_WRITE)
		return false;

	switch (off) {
	case offsetof(struct xdp_md, data):
		*reg_type = PTR_TO_PACKET;
		break;
	case offsetof(struct xdp_md, data_end):
		*reg_type = PTR_TO_PACKET_END;
		break;
	}

	return __is_valid_xdp_access(off, size, type);
}

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);

2723 2724 2725 2726
static u32 sk_filter_convert_ctx_access(enum bpf_access_type type, int dst_reg,
					int src_reg, int ctx_off,
					struct bpf_insn *insn_buf,
					struct bpf_prog *prog)
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
{
	struct bpf_insn *insn = insn_buf;

	switch (ctx_off) {
	case offsetof(struct __sk_buff, len):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, len) != 4);

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

2738 2739 2740 2741 2742 2743 2744
	case offsetof(struct __sk_buff, protocol):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);

		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
				      offsetof(struct sk_buff, protocol));
		break;

2745 2746 2747 2748 2749 2750 2751
	case offsetof(struct __sk_buff, vlan_proto):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);

		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
				      offsetof(struct sk_buff, vlan_proto));
		break;

2752 2753 2754
	case offsetof(struct __sk_buff, priority):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, priority) != 4);

2755 2756 2757 2758 2759 2760
		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, dst_reg, src_reg,
					      offsetof(struct sk_buff, priority));
		else
			*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
					      offsetof(struct sk_buff, priority));
2761 2762
		break;

2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
	case offsetof(struct __sk_buff, ingress_ifindex):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, skb_iif) != 4);

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

	case offsetof(struct __sk_buff, ifindex):
		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);

2773
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
2774 2775 2776 2777 2778 2779 2780
				      dst_reg, src_reg,
				      offsetof(struct sk_buff, dev));
		*insn++ = BPF_JMP_IMM(BPF_JEQ, dst_reg, 0, 1);
		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, dst_reg,
				      offsetof(struct net_device, ifindex));
		break;

2781 2782 2783 2784 2785 2786 2787
	case offsetof(struct __sk_buff, hash):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);

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

2788
	case offsetof(struct __sk_buff, mark):
2789 2790 2791 2792 2793 2794 2795 2796 2797
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);

		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, dst_reg, src_reg,
					      offsetof(struct sk_buff, mark));
		else
			*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
					      offsetof(struct sk_buff, mark));
		break;
2798 2799 2800 2801 2802 2803

	case offsetof(struct __sk_buff, pkt_type):
		return convert_skb_access(SKF_AD_PKTTYPE, dst_reg, src_reg, insn);

	case offsetof(struct __sk_buff, queue_mapping):
		return convert_skb_access(SKF_AD_QUEUE, dst_reg, src_reg, insn);
2804 2805 2806 2807 2808 2809 2810 2811

	case offsetof(struct __sk_buff, vlan_present):
		return convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
					  dst_reg, src_reg, insn);

	case offsetof(struct __sk_buff, vlan_tci):
		return convert_skb_access(SKF_AD_VLAN_TAG,
					  dst_reg, src_reg, insn);
2812 2813

	case offsetof(struct __sk_buff, cb[0]) ...
D
Daniel Borkmann 已提交
2814
	     offsetof(struct __sk_buff, cb[4]):
2815 2816
		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);

2817
		prog->cb_access = 1;
2818 2819 2820 2821 2822 2823 2824 2825 2826
		ctx_off -= offsetof(struct __sk_buff, cb[0]);
		ctx_off += offsetof(struct sk_buff, cb);
		ctx_off += offsetof(struct qdisc_skb_cb, data);
		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, dst_reg, src_reg, ctx_off);
		else
			*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg, ctx_off);
		break;

2827 2828 2829 2830
	case offsetof(struct __sk_buff, tc_classid):
		ctx_off -= offsetof(struct __sk_buff, tc_classid);
		ctx_off += offsetof(struct sk_buff, cb);
		ctx_off += offsetof(struct qdisc_skb_cb, tc_classid);
2831 2832 2833 2834
		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_H, dst_reg, src_reg, ctx_off);
		else
			*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg, ctx_off);
2835 2836
		break;

2837
	case offsetof(struct __sk_buff, data):
2838
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
2839 2840 2841 2842 2843 2844 2845 2846
				      dst_reg, src_reg,
				      offsetof(struct sk_buff, data));
		break;

	case offsetof(struct __sk_buff, data_end):
		ctx_off -= offsetof(struct __sk_buff, data_end);
		ctx_off += offsetof(struct sk_buff, cb);
		ctx_off += offsetof(struct bpf_skb_data_end, data_end);
2847 2848
		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), dst_reg, src_reg,
				      ctx_off);
2849 2850
		break;

2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868
	case offsetof(struct __sk_buff, tc_index):
#ifdef CONFIG_NET_SCHED
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tc_index) != 2);

		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_H, dst_reg, src_reg,
					      offsetof(struct sk_buff, tc_index));
		else
			*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
					      offsetof(struct sk_buff, tc_index));
		break;
#else
		if (type == BPF_WRITE)
			*insn++ = BPF_MOV64_REG(dst_reg, dst_reg);
		else
			*insn++ = BPF_MOV64_IMM(dst_reg, 0);
		break;
#endif
2869 2870 2871
	}

	return insn - insn_buf;
2872 2873
}

2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type, int dst_reg,
					 int src_reg, int ctx_off,
					 struct bpf_insn *insn_buf,
					 struct bpf_prog *prog)
{
	struct bpf_insn *insn = insn_buf;

	switch (ctx_off) {
	case offsetof(struct __sk_buff, ifindex):
		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
				      dst_reg, src_reg,
				      offsetof(struct sk_buff, dev));
		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, dst_reg,
				      offsetof(struct net_device, ifindex));
		break;
	default:
		return sk_filter_convert_ctx_access(type, dst_reg, src_reg,
						    ctx_off, insn_buf, prog);
	}

	return insn - insn_buf;
}

2899 2900 2901 2902 2903 2904 2905 2906 2907
static u32 xdp_convert_ctx_access(enum bpf_access_type type, int dst_reg,
				  int src_reg, int ctx_off,
				  struct bpf_insn *insn_buf,
				  struct bpf_prog *prog)
{
	struct bpf_insn *insn = insn_buf;

	switch (ctx_off) {
	case offsetof(struct xdp_md, data):
2908
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
2909 2910 2911 2912
				      dst_reg, src_reg,
				      offsetof(struct xdp_buff, data));
		break;
	case offsetof(struct xdp_md, data_end):
2913
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
2914 2915 2916 2917 2918 2919 2920 2921
				      dst_reg, src_reg,
				      offsetof(struct xdp_buff, data_end));
		break;
	}

	return insn - insn_buf;
}

2922
static const struct bpf_verifier_ops sk_filter_ops = {
2923 2924
	.get_func_proto		= sk_filter_func_proto,
	.is_valid_access	= sk_filter_is_valid_access,
2925
	.convert_ctx_access	= sk_filter_convert_ctx_access,
2926 2927
};

2928
static const struct bpf_verifier_ops tc_cls_act_ops = {
2929 2930
	.get_func_proto		= tc_cls_act_func_proto,
	.is_valid_access	= tc_cls_act_is_valid_access,
2931
	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
2932
	.gen_prologue		= tc_cls_act_prologue,
2933 2934
};

2935 2936 2937 2938 2939 2940
static const struct bpf_verifier_ops xdp_ops = {
	.get_func_proto		= xdp_func_proto,
	.is_valid_access	= xdp_is_valid_access,
	.convert_ctx_access	= xdp_convert_ctx_access,
};

2941
static struct bpf_prog_type_list sk_filter_type __read_mostly = {
2942 2943
	.ops	= &sk_filter_ops,
	.type	= BPF_PROG_TYPE_SOCKET_FILTER,
2944 2945
};

2946
static struct bpf_prog_type_list sched_cls_type __read_mostly = {
2947 2948
	.ops	= &tc_cls_act_ops,
	.type	= BPF_PROG_TYPE_SCHED_CLS,
2949 2950
};

2951
static struct bpf_prog_type_list sched_act_type __read_mostly = {
2952 2953
	.ops	= &tc_cls_act_ops,
	.type	= BPF_PROG_TYPE_SCHED_ACT,
2954 2955
};

2956 2957 2958 2959 2960
static struct bpf_prog_type_list xdp_type __read_mostly = {
	.ops	= &xdp_ops,
	.type	= BPF_PROG_TYPE_XDP,
};

2961
static int __init register_sk_filter_ops(void)
2962
{
2963
	bpf_register_prog_type(&sk_filter_type);
2964
	bpf_register_prog_type(&sched_cls_type);
2965
	bpf_register_prog_type(&sched_act_type);
2966
	bpf_register_prog_type(&xdp_type);
2967

2968 2969
	return 0;
}
2970 2971
late_initcall(register_sk_filter_ops);

2972
int sk_detach_filter(struct sock *sk)
2973 2974 2975 2976
{
	int ret = -ENOENT;
	struct sk_filter *filter;

2977 2978 2979
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

2980 2981
	filter = rcu_dereference_protected(sk->sk_filter,
					   lockdep_sock_is_held(sk));
2982
	if (filter) {
2983
		RCU_INIT_POINTER(sk->sk_filter, NULL);
E
Eric Dumazet 已提交
2984
		sk_filter_uncharge(sk, filter);
2985 2986
		ret = 0;
	}
2987

2988 2989
	return ret;
}
2990
EXPORT_SYMBOL_GPL(sk_detach_filter);
2991

2992 2993
int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
		  unsigned int len)
2994
{
2995
	struct sock_fprog_kern *fprog;
2996
	struct sk_filter *filter;
2997
	int ret = 0;
2998 2999 3000

	lock_sock(sk);
	filter = rcu_dereference_protected(sk->sk_filter,
3001
					   lockdep_sock_is_held(sk));
3002 3003
	if (!filter)
		goto out;
3004 3005

	/* We're copying the filter that has been originally attached,
3006 3007
	 * so no conversion/decode needed anymore. eBPF programs that
	 * have no original program cannot be dumped through this.
3008
	 */
3009
	ret = -EACCES;
3010
	fprog = filter->prog->orig_prog;
3011 3012
	if (!fprog)
		goto out;
3013 3014

	ret = fprog->len;
3015
	if (!len)
3016
		/* User space only enquires number of filter blocks. */
3017
		goto out;
3018

3019
	ret = -EINVAL;
3020
	if (len < fprog->len)
3021 3022 3023
		goto out;

	ret = -EFAULT;
3024
	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
3025
		goto out;
3026

3027 3028 3029 3030
	/* Instead of bytes, the API requests to return the number
	 * of filter blocks.
	 */
	ret = fprog->len;
3031 3032 3033 3034
out:
	release_sock(sk);
	return ret;
}