filter.c 59.3 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 57 58 59
/**
 *	sk_filter - run a packet through a socket filter
 *	@sk: sock associated with &sk_buff
 *	@skb: buffer to filter
 *
60 61
 * 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 已提交
62
 * than pkt_len we keep whole skb->data. This is the socket level
63
 * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
S
Stephen Hemminger 已提交
64 65 66 67 68 69 70 71
 * 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;

72 73 74 75 76 77 78 79
	/*
	 * 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 已提交
80 81 82 83
	err = security_sock_rcv_skb(sk, skb);
	if (err)
		return err;

84 85
	rcu_read_lock();
	filter = rcu_dereference(sk->sk_filter);
S
Stephen Hemminger 已提交
86
	if (filter) {
87
		unsigned int pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
88

S
Stephen Hemminger 已提交
89 90
		err = pkt_len ? pskb_trim(skb, pkt_len) : -EPERM;
	}
91
	rcu_read_unlock();
S
Stephen Hemminger 已提交
92 93 94 95 96

	return err;
}
EXPORT_SYMBOL(sk_filter);

97
static u64 __skb_get_pay_offset(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
98
{
99
	return skb_get_poff((struct sk_buff *)(unsigned long) ctx);
100 101
}

102
static u64 __skb_get_nlattr(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
103
{
104
	struct sk_buff *skb = (struct sk_buff *)(unsigned long) ctx;
105 106 107 108 109
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

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

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

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

	return 0;
}

123
static u64 __skb_get_nlattr_nest(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
124
{
125
	struct sk_buff *skb = (struct sk_buff *)(unsigned long) ctx;
126 127 128 129 130
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

131 132 133
	if (skb->len < sizeof(struct nlattr))
		return 0;

134
	if (a > skb->len - sizeof(struct nlattr))
135 136
		return 0;

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

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

	return 0;
}

148
static u64 __get_raw_cpu_id(u64 ctx, u64 a, u64 x, u64 r4, u64 r5)
149 150 151 152
{
	return raw_smp_processor_id();
}

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
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;
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

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

	return insn - insn_buf;
}

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

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

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

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

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

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

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

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

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

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

285 286 287 288
	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 已提交
289
	case SKF_AD_OFF + SKF_AD_RANDOM:
290
		/* arg1 = CTX */
291
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
292
		/* arg2 = A */
293
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
294
		/* arg3 = X */
295
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
296
		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
297 298
		switch (fp->k) {
		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
299
			*insn = BPF_EMIT_CALL(__skb_get_pay_offset);
300 301
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR:
302
			*insn = BPF_EMIT_CALL(__skb_get_nlattr);
303 304
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
305
			*insn = BPF_EMIT_CALL(__skb_get_nlattr_nest);
306 307
			break;
		case SKF_AD_OFF + SKF_AD_CPU:
308
			*insn = BPF_EMIT_CALL(__get_raw_cpu_id);
309
			break;
C
Chema Gonzalez 已提交
310
		case SKF_AD_OFF + SKF_AD_RANDOM:
311 312
			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
			bpf_user_rnd_init_once();
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
static int bpf_convert_filter(struct sock_filter *prog, int len,
			      struct bpf_insn *new_prog, int *new_len)
355 356
{
	int new_flen = 0, pass = 0, target, i;
357
	struct bpf_insn *new_insn;
358 359 360 361 362
	struct sock_filter *fp;
	int *addrs = NULL;
	u8 bpf_src;

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

365
	if (len <= 0 || len > BPF_MAXINSNS)
366 367 368
		return -EINVAL;

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

do_pass:
	new_insn = new_prog;
	fp = prog;

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
	/* 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;
	}
395 396

	for (i = 0; i < len; fp++, i++) {
397 398
		struct bpf_insn tmp_insns[6] = { };
		struct bpf_insn *insn = tmp_insns;
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 434 435 436 437 438 439 440

		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;

441
			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
442 443
			break;

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

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

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

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

			/* 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;
502
				BPF_EMIT_JMP;
503
				break;
504
			}
505 506 507 508

			/* 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;
509
			BPF_EMIT_JMP;
510 511 512 513
			insn++;

			insn->code = BPF_JMP | BPF_JA;
			target = i + fp->jf + 1;
514
			BPF_EMIT_JMP;
515 516 517 518
			break;

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

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

		/* Store to stack. */
		case BPF_ST:
		case BPF_STX:
547 548 549
			*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);
550 551 552 553 554
			break;

		/* Load from stack. */
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
555 556 557
			*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);
558 559 560 561 562
			break;

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

		/* X = A */
		case BPF_MISC | BPF_TAX:
569
			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
570 571 572 573
			break;

		/* A = X */
		case BPF_MISC | BPF_TXA:
574
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
575 576 577 578 579
			break;

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

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

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

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

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
	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 已提交
619
	return 0;
620 621 622
err:
	kfree(addrs);
	return -EINVAL;
L
Linus Torvalds 已提交
623 624
}

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

	BUILD_BUG_ON(BPF_MEMWORDS > 16);
638

639
	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
640 641
	if (!masks)
		return -ENOMEM;
642

643 644 645 646 647 648
	memset(masks, 0xff, flen * sizeof(*masks));

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

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

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

771
	if (flen == 0 || flen > BPF_MAXINSNS)
L
Linus Torvalds 已提交
772 773
		return -EINVAL;

774
	/* Check the filter code now */
L
Linus Torvalds 已提交
775
	for (pc = 0; pc < flen; pc++) {
776
		const struct sock_filter *ftest = &filter[pc];
777

778 779
		/* May we actually operate on this code? */
		if (!chk_code_allowed(ftest->code))
780
			return -EINVAL;
781

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

836
	/* Last instruction must be a RET code */
837
	switch (filter[flen - 1].code) {
838 839
	case BPF_RET | BPF_K:
	case BPF_RET | BPF_A:
840
		return check_load_and_stores(filter, flen);
841
	}
842

843
	return -EINVAL;
L
Linus Torvalds 已提交
844 845
}

846 847
static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
				      const struct sock_fprog *fprog)
848
{
849
	unsigned int fsize = bpf_classic_proglen(fprog);
850 851 852 853 854 855 856 857
	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;
858 859 860

	fkprog->filter = kmemdup(fp->insns, fsize,
				 GFP_KERNEL | __GFP_NOWARN);
861 862 863 864 865 866 867 868
	if (!fkprog->filter) {
		kfree(fp->orig_prog);
		return -ENOMEM;
	}

	return 0;
}

869
static void bpf_release_orig_filter(struct bpf_prog *fp)
870 871 872 873 874 875 876 877 878
{
	struct sock_fprog_kern *fprog = fp->orig_prog;

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

879 880
static void __bpf_prog_release(struct bpf_prog *prog)
{
881
	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
882 883 884 885 886
		bpf_prog_put(prog);
	} else {
		bpf_release_orig_filter(prog);
		bpf_prog_free(prog);
	}
887 888
}

889 890
static void __sk_filter_release(struct sk_filter *fp)
{
891 892
	__bpf_prog_release(fp->prog);
	kfree(fp);
893 894
}

895
/**
E
Eric Dumazet 已提交
896
 * 	sk_filter_release_rcu - Release a socket filter by rcu_head
897 898
 *	@rcu: rcu_head that contains the sk_filter to free
 */
899
static void sk_filter_release_rcu(struct rcu_head *rcu)
900 901 902
{
	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);

903
	__sk_filter_release(fp);
904
}
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

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

922 923
	atomic_sub(filter_size, &sk->sk_omem_alloc);
	sk_filter_release(fp);
924
}
925

926 927 928 929
/* 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)
930
{
931
	u32 filter_size = bpf_prog_size(fp->prog->len);
932 933 934 935 936 937 938

	/* 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;
939
	}
940
	return false;
941 942
}

943
static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
944 945
{
	struct sock_filter *old_prog;
946
	struct bpf_prog *old_fp;
947
	int err, new_len, old_len = fp->len;
948 949 950 951 952 953 954

	/* 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) !=
955
		     sizeof(struct bpf_insn));
956 957 958 959 960 961

	/* 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),
962
			   GFP_KERNEL | __GFP_NOWARN);
963 964 965 966 967 968
	if (!old_prog) {
		err = -ENOMEM;
		goto out_err;
	}

	/* 1st pass: calculate the new program length. */
969
	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len);
970 971 972 973 974
	if (err)
		goto out_err_free;

	/* Expand fp for appending the new filter representation. */
	old_fp = fp;
975
	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
976 977 978 979 980 981 982 983 984 985 986
	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;

987
	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
988
	err = bpf_convert_filter(old_prog, old_len, fp->insnsi, &new_len);
989
	if (err)
990
		/* 2nd bpf_convert_filter() can fail only if it fails
991 992
		 * to allocate memory, remapping must succeed. Note,
		 * that at this time old_fp has already been released
993
		 * by krealloc().
994 995 996
		 */
		goto out_err_free;

997
	bpf_prog_select_runtime(fp);
998

999 1000 1001 1002 1003 1004
	kfree(old_prog);
	return fp;

out_err_free:
	kfree(old_prog);
out_err:
1005
	__bpf_prog_release(fp);
1006 1007 1008
	return ERR_PTR(err);
}

1009 1010
static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
					   bpf_aux_classic_check_t trans)
1011 1012 1013
{
	int err;

1014
	fp->bpf_func = NULL;
1015
	fp->jited = 0;
1016

1017
	err = bpf_check_classic(fp->insns, fp->len);
1018
	if (err) {
1019
		__bpf_prog_release(fp);
1020
		return ERR_PTR(err);
1021
	}
1022

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
	/* 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);
		}
	}

1034 1035 1036
	/* Probe if we can JIT compile the filter and if so, do
	 * the compilation of the filter.
	 */
1037
	bpf_jit_compile(fp);
1038 1039 1040 1041

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

	return fp;
1046 1047 1048
}

/**
1049
 *	bpf_prog_create - create an unattached filter
R
Randy Dunlap 已提交
1050
 *	@pfp: the unattached filter that is created
1051
 *	@fprog: the filter program
1052
 *
R
Randy Dunlap 已提交
1053
 * Create a filter independent of any socket. We first run some
1054 1055 1056 1057
 * 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.
 */
1058
int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1059
{
1060
	unsigned int fsize = bpf_classic_proglen(fprog);
1061
	struct bpf_prog *fp;
1062 1063 1064 1065 1066

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

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

1071 1072 1073
	memcpy(fp->insns, fprog->filter, fsize);

	fp->len = fprog->len;
1074 1075 1076 1077 1078
	/* 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;
1079

1080
	/* bpf_prepare_filter() already takes care of freeing
1081 1082
	 * memory in case something goes wrong.
	 */
1083
	fp = bpf_prepare_filter(fp, NULL);
1084 1085
	if (IS_ERR(fp))
		return PTR_ERR(fp);
1086 1087 1088 1089

	*pfp = fp;
	return 0;
}
1090
EXPORT_SYMBOL_GPL(bpf_prog_create);
1091

1092 1093 1094 1095 1096
/**
 *	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
1097
 *	@save_orig: save classic BPF program
1098 1099 1100 1101 1102 1103
 *
 * 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,
1104
			      bpf_aux_classic_check_t trans, bool save_orig)
1105 1106 1107
{
	unsigned int fsize = bpf_classic_proglen(fprog);
	struct bpf_prog *fp;
1108
	int err;
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125

	/* 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;
	fp->orig_prog = NULL;

1126 1127 1128 1129 1130 1131 1132 1133
	if (save_orig) {
		err = bpf_prog_store_orig_filter(fp, fprog);
		if (err) {
			__bpf_prog_free(fp);
			return -ENOMEM;
		}
	}

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
	/* 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;
}
1144
EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1145

1146
void bpf_prog_destroy(struct bpf_prog *fp)
1147
{
1148
	__bpf_prog_release(fp);
1149
}
1150
EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
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;
}

1178 1179 1180 1181 1182 1183 1184 1185
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;

1186
	if (sk_unhashed(sk) && sk->sk_reuseport) {
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
		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 已提交
1204
{
1205
	unsigned int fsize = bpf_classic_proglen(fprog);
1206 1207
	unsigned int bpf_fsize = bpf_prog_size(fprog->len);
	struct bpf_prog *prog;
L
Linus Torvalds 已提交
1208 1209
	int err;

1210
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1211
		return ERR_PTR(-EPERM);
1212

L
Linus Torvalds 已提交
1213
	/* Make sure new filter is there and in the right amounts. */
1214
	if (fprog->filter == NULL)
1215
		return ERR_PTR(-EINVAL);
L
Linus Torvalds 已提交
1216

1217
	prog = bpf_prog_alloc(bpf_fsize, 0);
1218
	if (!prog)
1219
		return ERR_PTR(-ENOMEM);
1220

1221
	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1222
		__bpf_prog_free(prog);
1223
		return ERR_PTR(-EFAULT);
L
Linus Torvalds 已提交
1224 1225
	}

1226
	prog->len = fprog->len;
L
Linus Torvalds 已提交
1227

1228
	err = bpf_prog_store_orig_filter(prog, fprog);
1229
	if (err) {
1230
		__bpf_prog_free(prog);
1231
		return ERR_PTR(-ENOMEM);
1232 1233
	}

1234
	/* bpf_prepare_filter() already takes care of freeing
1235 1236
	 * memory in case something goes wrong.
	 */
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
	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.
 */
int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
{
	struct bpf_prog *prog = __get_filter(fprog, sk);
	int err;

1255 1256 1257
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1258 1259
	err = __sk_attach_prog(prog, sk);
	if (err < 0) {
1260
		__bpf_prog_release(prog);
1261
		return err;
1262 1263
	}

1264
	return 0;
L
Linus Torvalds 已提交
1265
}
1266
EXPORT_SYMBOL_GPL(sk_attach_filter);
L
Linus Torvalds 已提交
1267

1268
int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1269
{
1270
	struct bpf_prog *prog = __get_filter(fprog, sk);
1271
	int err;
1272

1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
	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)
{
	struct bpf_prog *prog;

1289
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1290
		return ERR_PTR(-EPERM);
1291 1292

	prog = bpf_prog_get(ufd);
1293
	if (IS_ERR(prog))
1294
		return prog;
1295

1296
	if (prog->type != BPF_PROG_TYPE_SOCKET_FILTER) {
1297
		bpf_prog_put(prog);
1298
		return ERR_PTR(-EINVAL);
1299 1300
	}

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	return prog;
}

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

1312 1313
	err = __sk_attach_prog(prog, sk);
	if (err < 0) {
1314
		bpf_prog_put(prog);
1315
		return err;
1316 1317 1318 1319 1320
	}

	return 0;
}

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

1338 1339 1340 1341 1342 1343 1344 1345
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);
1346 1347

static u64 bpf_skb_store_bytes(u64 r1, u64 r2, u64 r3, u64 r4, u64 flags)
1348
{
1349
	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1350
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
1351
	int offset = (int) r2;
1352 1353 1354 1355
	void *from = (void *) (long) r3;
	unsigned int len = (unsigned int) r4;
	void *ptr;

1356
	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1357 1358
		return -EINVAL;

1359 1360 1361 1362 1363 1364 1365 1366
	/* 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'
	 */
1367
	if (unlikely((u32) offset > 0xffff || len > sizeof(sp->buff)))
1368
		return -EFAULT;
1369
	if (unlikely(skb_try_make_writable(skb, offset + len)))
1370 1371
		return -EFAULT;

1372
	ptr = skb_header_pointer(skb, offset, len, sp->buff);
1373 1374 1375
	if (unlikely(!ptr))
		return -EFAULT;

1376
	if (flags & BPF_F_RECOMPUTE_CSUM)
1377
		skb_postpull_rcsum(skb, ptr, len);
1378 1379 1380

	memcpy(ptr, from, len);

1381
	if (ptr == sp->buff)
1382 1383 1384
		/* skb_store_bits cannot return -EFAULT here */
		skb_store_bits(skb, offset, ptr, len);

1385
	if (flags & BPF_F_RECOMPUTE_CSUM)
1386
		skb_postpush_rcsum(skb, ptr, len);
1387 1388
	if (flags & BPF_F_INVALIDATE_HASH)
		skb_clear_hash(skb);
1389

1390 1391 1392
	return 0;
}

1393
static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1394 1395 1396 1397 1398 1399 1400
	.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,
1401 1402 1403
	.arg5_type	= ARG_ANYTHING,
};

1404 1405 1406 1407 1408 1409 1410 1411
static u64 bpf_skb_load_bytes(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
{
	const struct sk_buff *skb = (const struct sk_buff *)(unsigned long) r1;
	int offset = (int) r2;
	void *to = (void *)(unsigned long) r3;
	unsigned int len = (unsigned int) r4;
	void *ptr;

1412
	if (unlikely((u32) offset > 0xffff || len > MAX_BPF_STACK))
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
		return -EFAULT;

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

	return 0;
}

1424
static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1425 1426 1427 1428 1429 1430 1431 1432 1433
	.func		= bpf_skb_load_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,
};

1434
static u64 bpf_l3_csum_replace(u64 r1, u64 r2, u64 from, u64 to, u64 flags)
1435 1436
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
1437
	int offset = (int) r2;
1438 1439
	__sum16 sum, *ptr;

1440 1441
	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
		return -EINVAL;
1442
	if (unlikely((u32) offset > 0xffff))
1443
		return -EFAULT;
1444
	if (unlikely(skb_try_make_writable(skb, offset + sizeof(sum))))
1445 1446 1447 1448 1449 1450
		return -EFAULT;

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

1451
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1452 1453 1454 1455 1456 1457
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		csum_replace_by_diff(ptr, to);
		break;
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
	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;
}

1475
static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
	.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,
};

1486
static u64 bpf_l4_csum_replace(u64 r1, u64 r2, u64 from, u64 to, u64 flags)
1487 1488
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
1489
	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1490
	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1491
	int offset = (int) r2;
1492 1493
	__sum16 sum, *ptr;

1494 1495
	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_PSEUDO_HDR |
			       BPF_F_HDR_FIELD_MASK)))
1496
		return -EINVAL;
1497
	if (unlikely((u32) offset > 0xffff))
1498
		return -EFAULT;
1499
	if (unlikely(skb_try_make_writable(skb, offset + sizeof(sum))))
1500 1501 1502 1503 1504
		return -EFAULT;

	ptr = skb_header_pointer(skb, offset, sizeof(sum), &sum);
	if (unlikely(!ptr))
		return -EFAULT;
1505 1506
	if (is_mmzero && !*ptr)
		return 0;
1507

1508
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1509 1510 1511 1512 1513 1514
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
		break;
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
	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;
	}

1525 1526
	if (is_mmzero && !*ptr)
		*ptr = CSUM_MANGLED_0;
1527 1528 1529 1530 1531 1532 1533
	if (ptr == &sum)
		/* skb_store_bits guaranteed to not return -EFAULT here */
		skb_store_bits(skb, offset, ptr, sizeof(sum));

	return 0;
}

1534
static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1535 1536 1537 1538 1539 1540 1541 1542
	.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,
1543 1544
};

1545 1546
static u64 bpf_csum_diff(u64 r1, u64 from_size, u64 r3, u64 to_size, u64 seed)
{
1547
	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
	u64 diff_size = from_size + to_size;
	__be32 *from = (__be32 *) (long) r1;
	__be32 *to   = (__be32 *) (long) r3;
	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);
}

1573
static const struct bpf_func_proto bpf_csum_diff_proto = {
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
	.func		= bpf_csum_diff,
	.gpl_only	= false,
	.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,
};

1584 1585 1586 1587 1588
static u64 bpf_clone_redirect(u64 r1, u64 ifindex, u64 flags, u64 r4, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1, *skb2;
	struct net_device *dev;

1589 1590 1591
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return -EINVAL;

1592 1593 1594 1595 1596 1597 1598 1599
	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
	if (unlikely(!dev))
		return -EINVAL;

	skb2 = skb_clone(skb, GFP_ATOMIC);
	if (unlikely(!skb2))
		return -ENOMEM;

1600
	if (flags & BPF_F_INGRESS) {
1601 1602 1603
		if (skb_at_tc_ingress(skb2))
			skb_postpush_rcsum(skb2, skb_mac_header(skb2),
					   skb2->mac_len);
1604
		return dev_forward_skb(dev, skb2);
1605
	}
1606 1607 1608 1609 1610

	skb2->dev = dev;
	return dev_queue_xmit(skb2);
}

1611
static const struct bpf_func_proto bpf_clone_redirect_proto = {
1612 1613 1614 1615 1616 1617 1618 1619
	.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,
};

1620 1621 1622 1623 1624 1625
struct redirect_info {
	u32 ifindex;
	u32 flags;
};

static DEFINE_PER_CPU(struct redirect_info, redirect_info);
1626

1627 1628 1629 1630
static u64 bpf_redirect(u64 ifindex, u64 flags, u64 r3, u64 r4, u64 r5)
{
	struct redirect_info *ri = this_cpu_ptr(&redirect_info);

1631 1632 1633
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return TC_ACT_SHOT;

1634 1635
	ri->ifindex = ifindex;
	ri->flags = flags;
1636

1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
	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;
	}

1652
	if (ri->flags & BPF_F_INGRESS) {
1653 1654 1655
		if (skb_at_tc_ingress(skb))
			skb_postpush_rcsum(skb, skb_mac_header(skb),
					   skb->mac_len);
1656
		return dev_forward_skb(dev, skb);
1657
	}
1658 1659 1660 1661 1662

	skb->dev = dev;
	return dev_queue_xmit(skb);
}

1663
static const struct bpf_func_proto bpf_redirect_proto = {
1664 1665 1666 1667 1668 1669 1670
	.func           = bpf_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_ANYTHING,
	.arg2_type      = ARG_ANYTHING,
};

1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
static u64 bpf_get_cgroup_classid(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
{
	return task_get_classid((struct sk_buff *) (unsigned long) r1);
}

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

1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
static u64 bpf_get_route_realm(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
{
#ifdef CONFIG_IP_ROUTE_CLASSID
	const struct dst_entry *dst;

	dst = skb_dst((struct sk_buff *) (unsigned long) r1);
	if (dst)
		return dst->tclassid;
#endif
	return 0;
}

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

1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
static u64 bpf_skb_vlan_push(u64 r1, u64 r2, u64 vlan_tci, u64 r4, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
	__be16 vlan_proto = (__force __be16) r2;

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

	return skb_vlan_push(skb, vlan_proto, vlan_tci);
}

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,
};
1722
EXPORT_SYMBOL_GPL(bpf_skb_vlan_push_proto);
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736

static u64 bpf_skb_vlan_pop(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;

	return skb_vlan_pop(skb);
}

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,
};
1737
EXPORT_SYMBOL_GPL(bpf_skb_vlan_pop_proto);
1738 1739 1740 1741 1742 1743 1744

bool bpf_helper_changes_skb_data(void *func)
{
	if (func == bpf_skb_vlan_push)
		return true;
	if (func == bpf_skb_vlan_pop)
		return true;
1745 1746 1747 1748 1749 1750 1751
	if (func == bpf_skb_store_bytes)
		return true;
	if (func == bpf_l3_csum_replace)
		return true;
	if (func == bpf_l4_csum_replace)
		return true;

1752 1753 1754
	return false;
}

1755 1756 1757 1758 1759
static unsigned short bpf_tunnel_key_af(u64 flags)
{
	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
}

1760 1761 1762 1763
static u64 bpf_skb_get_tunnel_key(u64 r1, u64 r2, u64 size, u64 flags, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
	struct bpf_tunnel_key *to = (struct bpf_tunnel_key *) (long) r2;
1764 1765
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
	u8 compat[sizeof(struct bpf_tunnel_key)];
1766

1767
	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6))))
1768
		return -EINVAL;
1769 1770 1771 1772
	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags))
		return -EPROTO;
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
		switch (size) {
1773 1774
		case offsetof(struct bpf_tunnel_key, tunnel_label):
			goto set_compat;
1775 1776 1777 1778 1779 1780
		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)
				return -EINVAL;
1781
set_compat:
1782 1783 1784 1785 1786 1787
			to = (struct bpf_tunnel_key *)compat;
			break;
		default:
			return -EINVAL;
		}
	}
1788 1789

	to->tunnel_id = be64_to_cpu(info->key.tun_id);
1790 1791 1792
	to->tunnel_tos = info->key.tos;
	to->tunnel_ttl = info->key.ttl;

1793
	if (flags & BPF_F_TUNINFO_IPV6) {
1794 1795
		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
		       sizeof(to->remote_ipv6));
1796 1797
		to->tunnel_label = be32_to_cpu(info->key.label);
	} else {
1798
		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
1799
	}
1800 1801 1802

	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
		memcpy((void *)(long) r2, to, size);
1803 1804 1805 1806

	return 0;
}

1807
static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
1808 1809 1810 1811 1812 1813 1814 1815 1816
	.func		= bpf_skb_get_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,
};

1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
static u64 bpf_skb_get_tunnel_opt(u64 r1, u64 r2, u64 size, u64 r4, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
	u8 *to = (u8 *) (long) r2;
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);

	if (unlikely(!info ||
		     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT)))
		return -ENOENT;
	if (unlikely(size < info->options_len))
		return -ENOMEM;

	ip_tunnel_info_opts_get(to, info);

	return info->options_len;
}

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,
	.arg2_type	= ARG_PTR_TO_STACK,
	.arg3_type	= ARG_CONST_STACK_SIZE,
};

1843 1844 1845 1846 1847 1848 1849
static struct metadata_dst __percpu *md_dst;

static u64 bpf_skb_set_tunnel_key(u64 r1, u64 r2, u64 size, u64 flags, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
	struct bpf_tunnel_key *from = (struct bpf_tunnel_key *) (long) r2;
	struct metadata_dst *md = this_cpu_ptr(md_dst);
1850
	u8 compat[sizeof(struct bpf_tunnel_key)];
1851 1852
	struct ip_tunnel_info *info;

1853 1854
	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
			       BPF_F_DONT_FRAGMENT)))
1855
		return -EINVAL;
1856 1857
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
		switch (size) {
1858
		case offsetof(struct bpf_tunnel_key, tunnel_label):
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870
		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);
			from = (struct bpf_tunnel_key *)compat;
			break;
		default:
			return -EINVAL;
		}
	}
1871 1872
	if (unlikely(!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label))
		return -EINVAL;
1873 1874 1875 1876 1877 1878 1879

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

1881
	info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
1882 1883 1884
	if (flags & BPF_F_DONT_FRAGMENT)
		info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;

1885
	info->key.tun_id = cpu_to_be64(from->tunnel_id);
1886 1887 1888 1889 1890 1891 1892
	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));
1893 1894
		info->key.label = cpu_to_be32(from->tunnel_label) &
				  IPV6_FLOWLABEL_MASK;
1895 1896
	} else {
		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
1897 1898
		if (flags & BPF_F_ZERO_CSUM_TX)
			info->key.tun_flags &= ~TUNNEL_CSUM;
1899
	}
1900 1901 1902 1903

	return 0;
}

1904
static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
1905 1906 1907 1908 1909 1910 1911 1912 1913
	.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,
};

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
#define BPF_TUNLEN_MAX	255

static u64 bpf_skb_set_tunnel_opt(u64 r1, u64 r2, u64 size, u64 r4, u64 r5)
{
	struct sk_buff *skb = (struct sk_buff *) (long) r1;
	u8 *from = (u8 *) (long) r2;
	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;
	if (unlikely(size > BPF_TUNLEN_MAX))
		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)
1944 1945
{
	if (!md_dst) {
1946 1947 1948 1949 1950
		BUILD_BUG_ON(FIELD_SIZEOF(struct ip_tunnel_info,
					  options_len) != 1);

		/* Race is not possible, since it's called from verifier
		 * that is holding verifier mutex.
1951
		 */
1952 1953
		md_dst = metadata_dst_alloc_percpu(BPF_TUNLEN_MAX,
						   GFP_KERNEL);
1954 1955 1956
		if (!md_dst)
			return NULL;
	}
1957 1958 1959 1960 1961 1962 1963 1964 1965

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

1968 1969
static const struct bpf_func_proto *
sk_filter_func_proto(enum bpf_func_id func_id)
1970 1971 1972 1973 1974 1975 1976 1977
{
	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;
1978 1979
	case BPF_FUNC_get_prandom_u32:
		return &bpf_get_prandom_u32_proto;
1980 1981
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
1982 1983
	case BPF_FUNC_tail_call:
		return &bpf_tail_call_proto;
1984 1985
	case BPF_FUNC_ktime_get_ns:
		return &bpf_ktime_get_ns_proto;
1986
	case BPF_FUNC_trace_printk:
1987 1988
		if (capable(CAP_SYS_ADMIN))
			return bpf_get_trace_printk_proto();
1989 1990 1991 1992 1993
	default:
		return NULL;
	}
}

1994 1995 1996 1997 1998 1999
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;
2000 2001
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
2002 2003
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
2004 2005 2006 2007
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
2008 2009
	case BPF_FUNC_clone_redirect:
		return &bpf_clone_redirect_proto;
2010 2011
	case BPF_FUNC_get_cgroup_classid:
		return &bpf_get_cgroup_classid_proto;
2012 2013 2014 2015
	case BPF_FUNC_skb_vlan_push:
		return &bpf_skb_vlan_push_proto;
	case BPF_FUNC_skb_vlan_pop:
		return &bpf_skb_vlan_pop_proto;
2016 2017 2018
	case BPF_FUNC_skb_get_tunnel_key:
		return &bpf_skb_get_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_key:
2019 2020 2021 2022 2023
		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);
2024 2025
	case BPF_FUNC_redirect:
		return &bpf_redirect_proto;
2026 2027
	case BPF_FUNC_get_route_realm:
		return &bpf_get_route_realm_proto;
2028 2029 2030 2031 2032
	default:
		return sk_filter_func_proto(func_id);
	}
}

2033
static bool __is_valid_access(int off, int size, enum bpf_access_type type)
2034
{
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
	/* 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;
}

2050 2051 2052
static bool sk_filter_is_valid_access(int off, int size,
				      enum bpf_access_type type)
{
2053 2054 2055
	if (off == offsetof(struct __sk_buff, tc_classid))
		return false;

2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
	if (type == BPF_WRITE) {
		switch (off) {
		case offsetof(struct __sk_buff, cb[0]) ...
			offsetof(struct __sk_buff, cb[4]):
			break;
		default:
			return false;
		}
	}

	return __is_valid_access(off, size, type);
}

static bool tc_cls_act_is_valid_access(int off, int size,
				       enum bpf_access_type type)
{
	if (type == BPF_WRITE) {
		switch (off) {
		case offsetof(struct __sk_buff, mark):
		case offsetof(struct __sk_buff, tc_index):
2076
		case offsetof(struct __sk_buff, priority):
2077
		case offsetof(struct __sk_buff, cb[0]) ...
2078 2079
		     offsetof(struct __sk_buff, cb[4]):
		case offsetof(struct __sk_buff, tc_classid):
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
			break;
		default:
			return false;
		}
	}
	return __is_valid_access(off, size, type);
}

static u32 bpf_net_convert_ctx_access(enum bpf_access_type type, int dst_reg,
				      int src_reg, int ctx_off,
2090 2091
				      struct bpf_insn *insn_buf,
				      struct bpf_prog *prog)
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
{
	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;

2103 2104 2105 2106 2107 2108 2109
	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;

2110 2111 2112 2113 2114 2115 2116
	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;

2117 2118 2119
	case offsetof(struct __sk_buff, priority):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, priority) != 4);

2120 2121 2122 2123 2124 2125
		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));
2126 2127
		break;

2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
	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);

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

2146 2147 2148 2149 2150 2151 2152
	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;

2153
	case offsetof(struct __sk_buff, mark):
2154 2155 2156 2157 2158 2159 2160 2161 2162
		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;
2163 2164 2165 2166 2167 2168

	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);
2169 2170 2171 2172 2173 2174 2175 2176

	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);
2177 2178 2179 2180 2181

	case offsetof(struct __sk_buff, cb[0]) ...
		offsetof(struct __sk_buff, cb[4]):
		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);

2182
		prog->cb_access = 1;
2183 2184 2185 2186 2187 2188 2189 2190 2191
		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;

2192 2193 2194 2195
	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);
2196 2197 2198 2199
		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);
2200 2201
		break;

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
	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
2220 2221 2222
	}

	return insn - insn_buf;
2223 2224
}

2225 2226 2227
static const struct bpf_verifier_ops sk_filter_ops = {
	.get_func_proto = sk_filter_func_proto,
	.is_valid_access = sk_filter_is_valid_access,
2228
	.convert_ctx_access = bpf_net_convert_ctx_access,
2229 2230
};

2231 2232
static const struct bpf_verifier_ops tc_cls_act_ops = {
	.get_func_proto = tc_cls_act_func_proto,
2233 2234
	.is_valid_access = tc_cls_act_is_valid_access,
	.convert_ctx_access = bpf_net_convert_ctx_access,
2235 2236
};

2237 2238
static struct bpf_prog_type_list sk_filter_type __read_mostly = {
	.ops = &sk_filter_ops,
2239 2240 2241
	.type = BPF_PROG_TYPE_SOCKET_FILTER,
};

2242
static struct bpf_prog_type_list sched_cls_type __read_mostly = {
2243
	.ops = &tc_cls_act_ops,
2244 2245 2246
	.type = BPF_PROG_TYPE_SCHED_CLS,
};

2247
static struct bpf_prog_type_list sched_act_type __read_mostly = {
2248
	.ops = &tc_cls_act_ops,
2249 2250 2251
	.type = BPF_PROG_TYPE_SCHED_ACT,
};

2252
static int __init register_sk_filter_ops(void)
2253
{
2254
	bpf_register_prog_type(&sk_filter_type);
2255
	bpf_register_prog_type(&sched_cls_type);
2256
	bpf_register_prog_type(&sched_act_type);
2257

2258 2259
	return 0;
}
2260 2261
late_initcall(register_sk_filter_ops);

2262 2263 2264 2265 2266
int sk_detach_filter(struct sock *sk)
{
	int ret = -ENOENT;
	struct sk_filter *filter;

2267 2268 2269
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

2270 2271
	filter = rcu_dereference_protected(sk->sk_filter,
					   sock_owned_by_user(sk));
2272
	if (filter) {
2273
		RCU_INIT_POINTER(sk->sk_filter, NULL);
E
Eric Dumazet 已提交
2274
		sk_filter_uncharge(sk, filter);
2275 2276
		ret = 0;
	}
2277

2278 2279
	return ret;
}
2280
EXPORT_SYMBOL_GPL(sk_detach_filter);
2281

2282 2283
int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
		  unsigned int len)
2284
{
2285
	struct sock_fprog_kern *fprog;
2286
	struct sk_filter *filter;
2287
	int ret = 0;
2288 2289 2290

	lock_sock(sk);
	filter = rcu_dereference_protected(sk->sk_filter,
2291
					   sock_owned_by_user(sk));
2292 2293
	if (!filter)
		goto out;
2294 2295

	/* We're copying the filter that has been originally attached,
2296 2297
	 * so no conversion/decode needed anymore. eBPF programs that
	 * have no original program cannot be dumped through this.
2298
	 */
2299
	ret = -EACCES;
2300
	fprog = filter->prog->orig_prog;
2301 2302
	if (!fprog)
		goto out;
2303 2304

	ret = fprog->len;
2305
	if (!len)
2306
		/* User space only enquires number of filter blocks. */
2307
		goto out;
2308

2309
	ret = -EINVAL;
2310
	if (len < fprog->len)
2311 2312 2313
		goto out;

	ret = -EFAULT;
2314
	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
2315
		goto out;
2316

2317 2318 2319 2320
	/* Instead of bytes, the API requests to return the number
	 * of filter blocks.
	 */
	ret = fprog->len;
2321 2322 2323 2324
out:
	release_sock(sk);
	return ret;
}