filter.c 41.2 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>
L
Linus Torvalds 已提交
49

S
Stephen Hemminger 已提交
50 51 52 53 54 55
/**
 *	sk_filter - run a packet through a socket filter
 *	@sk: sock associated with &sk_buff
 *	@skb: buffer to filter
 *
 * Run the filter code and then cut skb->data to correct size returned by
L
Li RongQing 已提交
56
 * SK_RUN_FILTER. If pkt_len is 0 we toss packet. If skb->len is smaller
S
Stephen Hemminger 已提交
57
 * than pkt_len we keep whole skb->data. This is the socket level
L
Li RongQing 已提交
58
 * wrapper to SK_RUN_FILTER. It returns 0 if the packet should
S
Stephen Hemminger 已提交
59 60 61 62 63 64 65 66
 * be accepted or -EPERM if the packet should be tossed.
 *
 */
int sk_filter(struct sock *sk, struct sk_buff *skb)
{
	int err;
	struct sk_filter *filter;

67 68 69 70 71 72 73 74
	/*
	 * 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 已提交
75 76 77 78
	err = security_sock_rcv_skb(sk, skb);
	if (err)
		return err;

79 80
	rcu_read_lock();
	filter = rcu_dereference(sk->sk_filter);
S
Stephen Hemminger 已提交
81
	if (filter) {
82
		unsigned int pkt_len = SK_RUN_FILTER(filter, skb);
83

S
Stephen Hemminger 已提交
84 85
		err = pkt_len ? pskb_trim(skb, pkt_len) : -EPERM;
	}
86
	rcu_read_unlock();
S
Stephen Hemminger 已提交
87 88 89 90 91

	return err;
}
EXPORT_SYMBOL(sk_filter);

92
static u64 __skb_get_pay_offset(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
93
{
94
	return skb_get_poff((struct sk_buff *)(unsigned long) ctx);
95 96
}

97
static u64 __skb_get_nlattr(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
98
{
99
	struct sk_buff *skb = (struct sk_buff *)(unsigned long) ctx;
100 101 102 103 104
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

105 106 107
	if (skb->len < sizeof(struct nlattr))
		return 0;

108
	if (a > skb->len - sizeof(struct nlattr))
109 110
		return 0;

111
	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
112 113 114 115 116 117
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

118
static u64 __skb_get_nlattr_nest(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
119
{
120
	struct sk_buff *skb = (struct sk_buff *)(unsigned long) ctx;
121 122 123 124 125
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

126 127 128
	if (skb->len < sizeof(struct nlattr))
		return 0;

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

132 133
	nla = (struct nlattr *) &skb->data[a];
	if (nla->nla_len > skb->len - a)
134 135
		return 0;

136
	nla = nla_find_nested(nla, x);
137 138 139 140 141 142
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

143
static u64 __get_raw_cpu_id(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
144 145 146 147
{
	return raw_smp_processor_id();
}

C
Chema Gonzalez 已提交
148
/* note that this only generates 32-bit random numbers */
149
static u64 __get_random_u32(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
C
Chema Gonzalez 已提交
150
{
151
	return prandom_u32();
C
Chema Gonzalez 已提交
152 153
}

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

	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;
200 201 202 203 204
	}

	return insn - insn_buf;
}

205
static bool convert_bpf_extensions(struct sock_filter *fp,
206
				   struct bpf_insn **insnp)
207
{
208
	struct bpf_insn *insn = *insnp;
209
	u32 cnt;
210 211 212

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

	case SKF_AD_OFF + SKF_AD_PKTTYPE:
223 224
		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
225 226 227 228 229 230
		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);
231 232 233 234 235 236 237 238 239 240 241 242 243 244
		BUILD_BUG_ON(bytes_to_bpf_size(FIELD_SIZEOF(struct sk_buff, dev)) < 0);

		*insn++ = BPF_LDX_MEM(bytes_to_bpf_size(FIELD_SIZEOF(struct sk_buff, dev)),
				      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));
245 246 247
		break;

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

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

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

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

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

270 271 272 273
	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;
274 275
		break;

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

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

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

/**
336
 *	bpf_convert_filter - convert filter program
337 338 339 340 341 342 343 344 345
 *	@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:
346
 *   bpf_convert_filter(old_prog, old_len, NULL, &new_len)
347 348 349
 *
 * 2) 2nd pass to remap in two passes: 1st pass finds new
 *    jump offsets, 2nd pass remapping:
350
 *   new_prog = kmalloc(sizeof(struct bpf_insn) * new_len);
351
 *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len);
352 353 354 355 356 357 358
 *
 * User BPF's register A is mapped to our BPF register 6, user BPF
 * register X is mapped to BPF register 7; frame pointer is always
 * register 10; Context 'void *ctx' is stored in register 1, that is,
 * for socket filters: ctx == 'struct sk_buff *', for seccomp:
 * ctx == 'struct seccomp_data *'.
 */
359 360
static int bpf_convert_filter(struct sock_filter *prog, int len,
			      struct bpf_insn *new_prog, int *new_len)
361 362
{
	int new_flen = 0, pass = 0, target, i;
363
	struct bpf_insn *new_insn;
364 365 366 367 368
	struct sock_filter *fp;
	int *addrs = NULL;
	u8 bpf_src;

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

371
	if (len <= 0 || len > BPF_MAXINSNS)
372 373 374
		return -EINVAL;

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

do_pass:
	new_insn = new_prog;
	fp = prog;

385 386
	if (new_insn)
		*new_insn = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
387 388 389
	new_insn++;

	for (i = 0; i < len; fp++, i++) {
390 391
		struct bpf_insn tmp_insns[6] = { };
		struct bpf_insn *insn = tmp_insns;
392 393 394 395 396 397 398 399 400 401 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

		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;

434
			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
435 436
			break;

437 438 439 440 441 442 443
		/* 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							\
444 445 446 447 448 449 450 451
	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)

452 453 454 455
		case BPF_JMP | BPF_JA:
			target = i + fp->k + 1;
			insn->code = fp->code;
			BPF_EMIT_JMP;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
			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.
				 */
471
				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
472

473 474
				insn->dst_reg = BPF_REG_A;
				insn->src_reg = BPF_REG_TMP;
475 476
				bpf_src = BPF_X;
			} else {
477 478
				insn->dst_reg = BPF_REG_A;
				insn->src_reg = BPF_REG_X;
479 480
				insn->imm = fp->k;
				bpf_src = BPF_SRC(fp->code);
L
Linus Torvalds 已提交
481
			}
482 483 484 485 486

			/* 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;
487
				BPF_EMIT_JMP;
488
				break;
L
Linus Torvalds 已提交
489
			}
490 491 492 493 494

			/* 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;
495
				BPF_EMIT_JMP;
496
				break;
497
			}
498 499 500 501

			/* 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;
502
			BPF_EMIT_JMP;
503 504 505 506
			insn++;

			insn->code = BPF_JMP | BPF_JA;
			target = i + fp->jf + 1;
507
			BPF_EMIT_JMP;
508 509 510 511
			break;

		/* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
		case BPF_LDX | BPF_MSH | BPF_B:
512
			/* tmp = A */
513
			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_A);
514
			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
515
			*insn++ = BPF_LD_ABS(BPF_B, fp->k);
516
			/* A &= 0xf */
517
			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
518
			/* A <<= 2 */
519
			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
520
			/* X = A */
521
			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
522
			/* A = tmp */
523
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
524 525 526 527 528
			break;

		/* RET_K, RET_A are remaped into 2 insns. */
		case BPF_RET | BPF_A:
		case BPF_RET | BPF_K:
529 530 531
			*insn++ = BPF_MOV32_RAW(BPF_RVAL(fp->code) == BPF_K ?
						BPF_K : BPF_X, BPF_REG_0,
						BPF_REG_A, fp->k);
532
			*insn = BPF_EXIT_INSN();
533 534 535 536 537
			break;

		/* Store to stack. */
		case BPF_ST:
		case BPF_STX:
538 539 540
			*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);
541 542 543 544 545
			break;

		/* Load from stack. */
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
546 547 548
			*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);
549 550 551 552 553
			break;

		/* A = K or X = K */
		case BPF_LD | BPF_IMM:
		case BPF_LDX | BPF_IMM:
554 555
			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
					      BPF_REG_A : BPF_REG_X, fp->k);
556 557 558 559
			break;

		/* X = A */
		case BPF_MISC | BPF_TAX:
560
			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
561 562 563 564
			break;

		/* A = X */
		case BPF_MISC | BPF_TXA:
565
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
566 567 568 569 570
			break;

		/* A = skb->len or X = skb->len */
		case BPF_LD | BPF_W | BPF_LEN:
		case BPF_LDX | BPF_W | BPF_LEN:
571 572 573
			*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));
574 575
			break;

576
		/* Access seccomp_data fields. */
577
		case BPF_LDX | BPF_ABS | BPF_W:
578 579
			/* A = *(u32 *) (ctx + K) */
			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
580 581
			break;

S
Stephen Hemminger 已提交
582
		/* Unknown instruction. */
L
Linus Torvalds 已提交
583
		default:
584
			goto err;
L
Linus Torvalds 已提交
585
		}
586 587 588 589 590 591

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

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
	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 已提交
610
	return 0;
611 612 613
err:
	kfree(addrs);
	return -EINVAL;
L
Linus Torvalds 已提交
614 615
}

616 617
/* Security:
 *
618
 * As we dont want to clear mem[] array for each packet going through
L
Li RongQing 已提交
619
 * __bpf_prog_run(), we check that filter loaded by user never try to read
620
 * a cell if not previously written, and we check all branches to be sure
L
Lucas De Marchi 已提交
621
 * a malicious user doesn't try to abuse us.
622
 */
623
static int check_load_and_stores(const struct sock_filter *filter, int flen)
624
{
625
	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
626 627 628
	int pc, ret = 0;

	BUILD_BUG_ON(BPF_MEMWORDS > 16);
629

630
	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
631 632
	if (!masks)
		return -ENOMEM;
633

634 635 636 637 638 639
	memset(masks, 0xff, flen * sizeof(*masks));

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

		switch (filter[pc].code) {
640 641
		case BPF_ST:
		case BPF_STX:
642 643
			memvalid |= (1 << filter[pc].k);
			break;
644 645
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
646 647 648 649 650
			if (!(memvalid & (1 << filter[pc].k))) {
				ret = -EINVAL;
				goto error;
			}
			break;
651 652
		case BPF_JMP | BPF_JA:
			/* A jump must set masks on target */
653 654 655
			masks[pc + 1 + filter[pc].k] &= memvalid;
			memvalid = ~0;
			break;
656 657 658 659 660 661 662 663 664
		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 */
665 666 667 668 669 670 671 672 673 674 675
			masks[pc + 1 + filter[pc].jt] &= memvalid;
			masks[pc + 1 + filter[pc].jf] &= memvalid;
			memvalid = ~0;
			break;
		}
	}
error:
	kfree(masks);
	return ret;
}

676 677 678 679 680 681 682 683 684 685 686 687 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
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];
}

L
Linus Torvalds 已提交
742
/**
743
 *	bpf_check_classic - verify socket filter code
L
Linus Torvalds 已提交
744 745 746 747 748
 *	@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
749 750
 * no references or jumps that are out of range, no illegal
 * instructions, and must end with a RET instruction.
L
Linus Torvalds 已提交
751
 *
752 753 754
 * All jumps are forward as they are not signed.
 *
 * Returns 0 if the rule set is legal or -EINVAL if not.
L
Linus Torvalds 已提交
755
 */
756 757
static int bpf_check_classic(const struct sock_filter *filter,
			     unsigned int flen)
L
Linus Torvalds 已提交
758
{
759
	bool anc_found;
760
	int pc;
L
Linus Torvalds 已提交
761

762
	if (flen == 0 || flen > BPF_MAXINSNS)
L
Linus Torvalds 已提交
763 764
		return -EINVAL;

765
	/* Check the filter code now */
L
Linus Torvalds 已提交
766
	for (pc = 0; pc < flen; pc++) {
767
		const struct sock_filter *ftest = &filter[pc];
768

769 770
		/* May we actually operate on this code? */
		if (!chk_code_allowed(ftest->code))
771
			return -EINVAL;
772

773
		/* Some instructions need special checks */
774 775 776 777
		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 已提交
778 779 780
			if (ftest->k == 0)
				return -EINVAL;
			break;
781 782 783 784 785
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
		case BPF_ST:
		case BPF_STX:
			/* Check for invalid memory addresses */
786 787 788
			if (ftest->k >= BPF_MEMWORDS)
				return -EINVAL;
			break;
789 790
		case BPF_JMP | BPF_JA:
			/* Note, the large ftest->k might cause loops.
791 792 793
			 * Compare this with conditional jumps below,
			 * where offsets are limited. --ANK (981016)
			 */
794
			if (ftest->k >= (unsigned int)(flen - pc - 1))
795
				return -EINVAL;
796
			break;
797 798 799 800 801 802 803 804 805
		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 */
806
			if (pc + ftest->jt + 1 >= flen ||
807 808
			    pc + ftest->jf + 1 >= flen)
				return -EINVAL;
809
			break;
810 811 812
		case BPF_LD | BPF_W | BPF_ABS:
		case BPF_LD | BPF_H | BPF_ABS:
		case BPF_LD | BPF_B | BPF_ABS:
813
			anc_found = false;
814 815 816
			if (bpf_anc_helper(ftest) & BPF_ANC)
				anc_found = true;
			/* Ancillary operation unknown or unsupported */
817 818
			if (anc_found == false && ftest->k >= SKF_AD_OFF)
				return -EINVAL;
819 820
		}
	}
821

822
	/* Last instruction must be a RET code */
823
	switch (filter[flen - 1].code) {
824 825
	case BPF_RET | BPF_K:
	case BPF_RET | BPF_A:
826
		return check_load_and_stores(filter, flen);
827
	}
828

829
	return -EINVAL;
L
Linus Torvalds 已提交
830 831
}

832 833
static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
				      const struct sock_fprog *fprog)
834
{
835
	unsigned int fsize = bpf_classic_proglen(fprog);
836 837 838 839 840 841 842 843
	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;
844 845 846

	fkprog->filter = kmemdup(fp->insns, fsize,
				 GFP_KERNEL | __GFP_NOWARN);
847 848 849 850 851 852 853 854
	if (!fkprog->filter) {
		kfree(fp->orig_prog);
		return -ENOMEM;
	}

	return 0;
}

855
static void bpf_release_orig_filter(struct bpf_prog *fp)
856 857 858 859 860 861 862 863 864
{
	struct sock_fprog_kern *fprog = fp->orig_prog;

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

865 866
static void __bpf_prog_release(struct bpf_prog *prog)
{
867
	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
868 869 870 871 872
		bpf_prog_put(prog);
	} else {
		bpf_release_orig_filter(prog);
		bpf_prog_free(prog);
	}
873 874
}

875 876
static void __sk_filter_release(struct sk_filter *fp)
{
877 878
	__bpf_prog_release(fp->prog);
	kfree(fp);
879 880
}

881
/**
E
Eric Dumazet 已提交
882
 * 	sk_filter_release_rcu - Release a socket filter by rcu_head
883 884
 *	@rcu: rcu_head that contains the sk_filter to free
 */
885
static void sk_filter_release_rcu(struct rcu_head *rcu)
886 887 888
{
	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);

889
	__sk_filter_release(fp);
890
}
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905

/**
 *	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)
{
906
	u32 filter_size = bpf_prog_size(fp->prog->len);
907

908 909
	atomic_sub(filter_size, &sk->sk_omem_alloc);
	sk_filter_release(fp);
910
}
911

912 913 914 915
/* 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)
916
{
917
	u32 filter_size = bpf_prog_size(fp->prog->len);
918 919 920 921 922 923 924

	/* 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;
925
	}
926
	return false;
927 928
}

929
static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
930 931
{
	struct sock_filter *old_prog;
932
	struct bpf_prog *old_fp;
933
	int err, new_len, old_len = fp->len;
934 935 936 937 938 939 940

	/* 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) !=
941
		     sizeof(struct bpf_insn));
942 943 944 945 946 947

	/* 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),
948
			   GFP_KERNEL | __GFP_NOWARN);
949 950 951 952 953 954
	if (!old_prog) {
		err = -ENOMEM;
		goto out_err;
	}

	/* 1st pass: calculate the new program length. */
955
	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
956 957 958 959 960
	if (err)
		goto out_err_free;

	/* Expand fp for appending the new filter representation. */
	old_fp = fp;
961
	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
962 963 964 965 966 967 968 969 970 971 972
	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;

973
	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
974
	err = bpf_convert_filter(old_prog, old_len, fp->insnsi, &new_len);
975
	if (err)
976
		/* 2nd bpf_convert_filter() can fail only if it fails
977 978
		 * to allocate memory, remapping must succeed. Note,
		 * that at this time old_fp has already been released
979
		 * by krealloc().
980 981 982
		 */
		goto out_err_free;

983
	bpf_prog_select_runtime(fp);
984

985 986 987 988 989 990
	kfree(old_prog);
	return fp;

out_err_free:
	kfree(old_prog);
out_err:
991
	__bpf_prog_release(fp);
992 993 994
	return ERR_PTR(err);
}

995 996
static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
					   bpf_aux_classic_check_t trans)
997 998 999
{
	int err;

1000
	fp->bpf_func = NULL;
1001
	fp->jited = false;
1002

1003
	err = bpf_check_classic(fp->insns, fp->len);
1004
	if (err) {
1005
		__bpf_prog_release(fp);
1006
		return ERR_PTR(err);
1007
	}
1008

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	/* 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);
		}
	}

1020 1021 1022
	/* Probe if we can JIT compile the filter and if so, do
	 * the compilation of the filter.
	 */
1023
	bpf_jit_compile(fp);
1024 1025 1026 1027

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

	return fp;
1032 1033 1034
}

/**
1035
 *	bpf_prog_create - create an unattached filter
R
Randy Dunlap 已提交
1036
 *	@pfp: the unattached filter that is created
1037
 *	@fprog: the filter program
1038
 *
R
Randy Dunlap 已提交
1039
 * Create a filter independent of any socket. We first run some
1040 1041 1042 1043
 * 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.
 */
1044
int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1045
{
1046
	unsigned int fsize = bpf_classic_proglen(fprog);
1047
	struct bpf_prog *fp;
1048 1049 1050 1051 1052

	/* Make sure new filter is there and in the right amounts. */
	if (fprog->filter == NULL)
		return -EINVAL;

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

1057 1058 1059
	memcpy(fp->insns, fprog->filter, fsize);

	fp->len = fprog->len;
1060 1061 1062 1063 1064
	/* 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;
1065

1066
	/* bpf_prepare_filter() already takes care of freeing
1067 1068
	 * memory in case something goes wrong.
	 */
1069
	fp = bpf_prepare_filter(fp, NULL);
1070 1071
	if (IS_ERR(fp))
		return PTR_ERR(fp);
1072 1073 1074 1075

	*pfp = fp;
	return 0;
}
1076
EXPORT_SYMBOL_GPL(bpf_prog_create);
1077

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
/**
 *	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
 *
 * 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,
			      bpf_aux_classic_check_t trans)
{
	unsigned int fsize = bpf_classic_proglen(fprog);
	struct bpf_prog *fp;

	/* Make sure new filter is there and in the right amounts. */
	if (fprog->filter == NULL)
		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;
	/* 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;

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

1125
void bpf_prog_destroy(struct bpf_prog *fp)
1126
{
1127
	__bpf_prog_release(fp);
1128
}
1129
EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1130

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
{
	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;
	}

	old_fp = rcu_dereference_protected(sk->sk_filter,
					   sock_owned_by_user(sk));
	rcu_assign_pointer(sk->sk_filter, fp);

	if (old_fp)
		sk_filter_uncharge(sk, old_fp);

	return 0;
}

L
Linus Torvalds 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
/**
 *	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.
 */
int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
{
1169
	unsigned int fsize = bpf_classic_proglen(fprog);
1170 1171
	unsigned int bpf_fsize = bpf_prog_size(fprog->len);
	struct bpf_prog *prog;
L
Linus Torvalds 已提交
1172 1173
	int err;

1174 1175 1176
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

L
Linus Torvalds 已提交
1177
	/* Make sure new filter is there and in the right amounts. */
1178 1179
	if (fprog->filter == NULL)
		return -EINVAL;
L
Linus Torvalds 已提交
1180

1181
	prog = bpf_prog_alloc(bpf_fsize, 0);
1182
	if (!prog)
L
Linus Torvalds 已提交
1183
		return -ENOMEM;
1184

1185
	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1186
		__bpf_prog_free(prog);
L
Linus Torvalds 已提交
1187 1188 1189
		return -EFAULT;
	}

1190
	prog->len = fprog->len;
L
Linus Torvalds 已提交
1191

1192
	err = bpf_prog_store_orig_filter(prog, fprog);
1193
	if (err) {
1194
		__bpf_prog_free(prog);
1195 1196 1197
		return -ENOMEM;
	}

1198
	/* bpf_prepare_filter() already takes care of freeing
1199 1200
	 * memory in case something goes wrong.
	 */
1201
	prog = bpf_prepare_filter(prog, NULL);
1202 1203 1204
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1205 1206
	err = __sk_attach_prog(prog, sk);
	if (err < 0) {
1207
		__bpf_prog_release(prog);
1208
		return err;
1209 1210
	}

1211
	return 0;
L
Linus Torvalds 已提交
1212
}
1213
EXPORT_SYMBOL_GPL(sk_attach_filter);
L
Linus Torvalds 已提交
1214

1215 1216 1217
int sk_attach_bpf(u32 ufd, struct sock *sk)
{
	struct bpf_prog *prog;
1218
	int err;
1219 1220 1221 1222 1223

	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

	prog = bpf_prog_get(ufd);
1224 1225
	if (IS_ERR(prog))
		return PTR_ERR(prog);
1226

1227
	if (prog->type != BPF_PROG_TYPE_SOCKET_FILTER) {
1228 1229 1230 1231
		bpf_prog_put(prog);
		return -EINVAL;
	}

1232 1233
	err = __sk_attach_prog(prog, sk);
	if (err < 0) {
1234
		bpf_prog_put(prog);
1235
		return err;
1236 1237 1238 1239 1240
	}

	return 0;
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
/**
 *	bpf_skb_clone_not_writable - is the header of a clone not writable
 *	@skb: buffer to check
 *	@len: length up to which to write, can be negative
 *
 *	Returns true if modifying the header part of the cloned buffer
 *	does require the data to be copied. I.e. this version works with
 *	negative lengths needed for eBPF case!
 */
static bool bpf_skb_clone_unwritable(const struct sk_buff *skb, int len)
{
	return skb_header_cloned(skb) ||
	       (int) skb_headroom(skb) + len > skb->hdr_len;
}

1256 1257 1258
#define BPF_RECOMPUTE_CSUM(flags)	((flags) & 1)

static u64 bpf_skb_store_bytes(u64 r1, u64 r2, u64 r3, u64 r4, u64 flags)
1259 1260
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
1261
	int offset = (int) r2;
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
	void *from = (void *) (long) r3;
	unsigned int len = (unsigned int) r4;
	char buf[16];
	void *ptr;

	/* bpf verifier guarantees that:
	 * 'from' pointer points to bpf program stack
	 * 'len' bytes of it were initialized
	 * 'len' > 0
	 * 'skb' is a valid pointer to 'struct sk_buff'
	 *
	 * so check for invalid 'offset' and too large 'len'
	 */
1275
	if (unlikely((u32) offset > 0xffff || len > sizeof(buf)))
1276 1277
		return -EFAULT;

1278 1279 1280
	offset -= skb->data - skb_mac_header(skb);
	if (unlikely(skb_cloned(skb) &&
		     bpf_skb_clone_unwritable(skb, offset + len)))
1281 1282 1283 1284 1285 1286
		return -EFAULT;

	ptr = skb_header_pointer(skb, offset, len, buf);
	if (unlikely(!ptr))
		return -EFAULT;

1287 1288
	if (BPF_RECOMPUTE_CSUM(flags))
		skb_postpull_rcsum(skb, ptr, len);
1289 1290 1291 1292 1293 1294 1295

	memcpy(ptr, from, len);

	if (ptr == buf)
		/* skb_store_bits cannot return -EFAULT here */
		skb_store_bits(skb, offset, ptr, len);

1296
	if (BPF_RECOMPUTE_CSUM(flags) && skb->ip_summed == CHECKSUM_COMPLETE)
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
		skb->csum = csum_add(skb->csum, csum_partial(ptr, len, 0));
	return 0;
}

const struct bpf_func_proto bpf_skb_store_bytes_proto = {
	.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,
1309 1310 1311 1312 1313 1314
	.arg5_type	= ARG_ANYTHING,
};

#define BPF_HEADER_FIELD_SIZE(flags)	((flags) & 0x0f)
#define BPF_IS_PSEUDO_HEADER(flags)	((flags) & 0x10)

1315
static u64 bpf_l3_csum_replace(u64 r1, u64 r2, u64 from, u64 to, u64 flags)
1316 1317
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
1318
	int offset = (int) r2;
1319 1320
	__sum16 sum, *ptr;

1321
	if (unlikely((u32) offset > 0xffff))
1322 1323
		return -EFAULT;

1324 1325 1326
	offset -= skb->data - skb_mac_header(skb);
	if (unlikely(skb_cloned(skb) &&
		     bpf_skb_clone_unwritable(skb, offset + sizeof(sum))))
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
		return -EFAULT;

	ptr = skb_header_pointer(skb, offset, sizeof(sum), &sum);
	if (unlikely(!ptr))
		return -EFAULT;

	switch (BPF_HEADER_FIELD_SIZE(flags)) {
	case 2:
		csum_replace2(ptr, from, to);
		break;
	case 4:
		csum_replace4(ptr, from, to);
		break;
	default:
		return -EINVAL;
	}

	if (ptr == &sum)
		/* skb_store_bits guaranteed to not return -EFAULT here */
		skb_store_bits(skb, offset, ptr, sizeof(sum));

	return 0;
}

const struct bpf_func_proto bpf_l3_csum_replace_proto = {
	.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,
};

1362
static u64 bpf_l4_csum_replace(u64 r1, u64 r2, u64 from, u64 to, u64 flags)
1363 1364 1365
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
	u32 is_pseudo = BPF_IS_PSEUDO_HEADER(flags);
1366
	int offset = (int) r2;
1367 1368
	__sum16 sum, *ptr;

1369
	if (unlikely((u32) offset > 0xffff))
1370 1371
		return -EFAULT;

1372 1373 1374
	offset -= skb->data - skb_mac_header(skb);
	if (unlikely(skb_cloned(skb) &&
		     bpf_skb_clone_unwritable(skb, offset + sizeof(sum))))
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
		return -EFAULT;

	ptr = skb_header_pointer(skb, offset, sizeof(sum), &sum);
	if (unlikely(!ptr))
		return -EFAULT;

	switch (BPF_HEADER_FIELD_SIZE(flags)) {
	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;
	}

	if (ptr == &sum)
		/* skb_store_bits guaranteed to not return -EFAULT here */
		skb_store_bits(skb, offset, ptr, sizeof(sum));

	return 0;
}

const struct bpf_func_proto bpf_l4_csum_replace_proto = {
	.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,
1408 1409
};

1410 1411
static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id)
1412 1413 1414 1415 1416 1417 1418 1419
{
	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;
1420 1421
	case BPF_FUNC_get_prandom_u32:
		return &bpf_get_prandom_u32_proto;
1422 1423
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
1424 1425 1426 1427 1428
	default:
		return NULL;
	}
}

1429 1430 1431 1432 1433 1434
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;
1435 1436 1437 1438
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
1439 1440 1441 1442 1443
	default:
		return sk_filter_func_proto(func_id);
	}
}

1444 1445
static bool sk_filter_is_valid_access(int off, int size,
				      enum bpf_access_type type)
1446
{
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
	/* only read is allowed */
	if (type != BPF_READ)
		return false;

	/* check bounds */
	if (off < 0 || off >= sizeof(struct __sk_buff))
		return false;

	/* disallow misaligned access */
	if (off % size != 0)
		return false;

	/* all __sk_buff fields are __u32 */
	if (size != 4)
		return false;

	return true;
}

static u32 sk_filter_convert_ctx_access(int dst_reg, int src_reg, int ctx_off,
					struct bpf_insn *insn_buf)
{
	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;

1479 1480 1481 1482 1483 1484 1485
	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;

1486 1487 1488 1489 1490 1491 1492
	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;

1493 1494 1495 1496 1497 1498 1499
	case offsetof(struct __sk_buff, priority):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, priority) != 4);

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

1500 1501 1502 1503 1504 1505 1506 1507
	case offsetof(struct __sk_buff, mark):
		return convert_skb_access(SKF_AD_MARK, dst_reg, src_reg, insn);

	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);
1508 1509 1510 1511 1512 1513 1514 1515

	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);
1516 1517 1518
	}

	return insn - insn_buf;
1519 1520
}

1521 1522 1523
static const struct bpf_verifier_ops sk_filter_ops = {
	.get_func_proto = sk_filter_func_proto,
	.is_valid_access = sk_filter_is_valid_access,
1524
	.convert_ctx_access = sk_filter_convert_ctx_access,
1525 1526
};

1527 1528 1529 1530 1531 1532
static const struct bpf_verifier_ops tc_cls_act_ops = {
	.get_func_proto = tc_cls_act_func_proto,
	.is_valid_access = sk_filter_is_valid_access,
	.convert_ctx_access = sk_filter_convert_ctx_access,
};

1533 1534
static struct bpf_prog_type_list sk_filter_type __read_mostly = {
	.ops = &sk_filter_ops,
1535 1536 1537
	.type = BPF_PROG_TYPE_SOCKET_FILTER,
};

1538
static struct bpf_prog_type_list sched_cls_type __read_mostly = {
1539
	.ops = &tc_cls_act_ops,
1540 1541 1542
	.type = BPF_PROG_TYPE_SCHED_CLS,
};

1543
static struct bpf_prog_type_list sched_act_type __read_mostly = {
1544
	.ops = &tc_cls_act_ops,
1545 1546 1547
	.type = BPF_PROG_TYPE_SCHED_ACT,
};

1548
static int __init register_sk_filter_ops(void)
1549
{
1550
	bpf_register_prog_type(&sk_filter_type);
1551
	bpf_register_prog_type(&sched_cls_type);
1552
	bpf_register_prog_type(&sched_act_type);
1553

1554 1555
	return 0;
}
1556 1557
late_initcall(register_sk_filter_ops);

1558 1559 1560 1561 1562
int sk_detach_filter(struct sock *sk)
{
	int ret = -ENOENT;
	struct sk_filter *filter;

1563 1564 1565
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

1566 1567
	filter = rcu_dereference_protected(sk->sk_filter,
					   sock_owned_by_user(sk));
1568
	if (filter) {
1569
		RCU_INIT_POINTER(sk->sk_filter, NULL);
E
Eric Dumazet 已提交
1570
		sk_filter_uncharge(sk, filter);
1571 1572
		ret = 0;
	}
1573

1574 1575
	return ret;
}
1576
EXPORT_SYMBOL_GPL(sk_detach_filter);
1577

1578 1579
int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
		  unsigned int len)
1580
{
1581
	struct sock_fprog_kern *fprog;
1582
	struct sk_filter *filter;
1583
	int ret = 0;
1584 1585 1586

	lock_sock(sk);
	filter = rcu_dereference_protected(sk->sk_filter,
1587
					   sock_owned_by_user(sk));
1588 1589
	if (!filter)
		goto out;
1590 1591 1592 1593

	/* We're copying the filter that has been originally attached,
	 * so no conversion/decode needed anymore.
	 */
1594
	fprog = filter->prog->orig_prog;
1595 1596

	ret = fprog->len;
1597
	if (!len)
1598
		/* User space only enquires number of filter blocks. */
1599
		goto out;
1600

1601
	ret = -EINVAL;
1602
	if (len < fprog->len)
1603 1604 1605
		goto out;

	ret = -EFAULT;
1606
	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
1607
		goto out;
1608

1609 1610 1611 1612
	/* Instead of bytes, the API requests to return the number
	 * of filter blocks.
	 */
	ret = fprog->len;
1613 1614 1615 1616
out:
	release_sock(sk);
	return ret;
}