• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2  * Copyright (c) 2016 Facebook
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * General Public License for more details.
12  */
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
22 
23 /* bpf_check() is a static code analyzer that walks eBPF program
24  * instruction by instruction and updates register/stack state.
25  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
26  *
27  * The first pass is depth-first-search to check that the program is a DAG.
28  * It rejects the following programs:
29  * - larger than BPF_MAXINSNS insns
30  * - if loop is present (detected via back-edge)
31  * - unreachable insns exist (shouldn't be a forest. program = one function)
32  * - out of bounds or malformed jumps
33  * The second pass is all possible path descent from the 1st insn.
34  * Since it's analyzing all pathes through the program, the length of the
35  * analysis is limited to 32k insn, which may be hit even if total number of
36  * insn is less then 4K, but there are too many branches that change stack/regs.
37  * Number of 'branches to be analyzed' is limited to 1k
38  *
39  * On entry to each instruction, each register has a type, and the instruction
40  * changes the types of the registers depending on instruction semantics.
41  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
42  * copied to R1.
43  *
44  * All registers are 64-bit.
45  * R0 - return register
46  * R1-R5 argument passing registers
47  * R6-R9 callee saved registers
48  * R10 - frame pointer read-only
49  *
50  * At the start of BPF program the register R1 contains a pointer to bpf_context
51  * and has type PTR_TO_CTX.
52  *
53  * Verifier tracks arithmetic operations on pointers in case:
54  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
55  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
56  * 1st insn copies R10 (which has FRAME_PTR) type into R1
57  * and 2nd arithmetic instruction is pattern matched to recognize
58  * that it wants to construct a pointer to some element within stack.
59  * So after 2nd insn, the register R1 has type PTR_TO_STACK
60  * (and -20 constant is saved for further stack bounds checking).
61  * Meaning that this reg is a pointer to stack plus known immediate constant.
62  *
63  * Most of the time the registers have UNKNOWN_VALUE type, which
64  * means the register has some value, but it's not a valid pointer.
65  * (like pointer plus pointer becomes UNKNOWN_VALUE type)
66  *
67  * When verifier sees load or store instructions the type of base register
68  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
69  * types recognized by check_mem_access() function.
70  *
71  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
72  * and the range of [ptr, ptr + map's value_size) is accessible.
73  *
74  * registers used to pass values to function calls are checked against
75  * function argument constraints.
76  *
77  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
78  * It means that the register type passed to this function must be
79  * PTR_TO_STACK and it will be used inside the function as
80  * 'pointer to map element key'
81  *
82  * For example the argument constraints for bpf_map_lookup_elem():
83  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
84  *   .arg1_type = ARG_CONST_MAP_PTR,
85  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
86  *
87  * ret_type says that this function returns 'pointer to map elem value or null'
88  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
89  * 2nd argument should be a pointer to stack, which will be used inside
90  * the helper function as a pointer to map element key.
91  *
92  * On the kernel side the helper function looks like:
93  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
94  * {
95  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
96  *    void *key = (void *) (unsigned long) r2;
97  *    void *value;
98  *
99  *    here kernel can access 'key' and 'map' pointers safely, knowing that
100  *    [key, key + map->key_size) bytes are valid and were initialized on
101  *    the stack of eBPF program.
102  * }
103  *
104  * Corresponding eBPF program may look like:
105  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
106  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
107  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
108  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
109  * here verifier looks at prototype of map_lookup_elem() and sees:
110  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
111  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
112  *
113  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
114  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
115  * and were initialized prior to this call.
116  * If it's ok, then verifier allows this BPF_CALL insn and looks at
117  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
118  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
119  * returns ether pointer to map value or NULL.
120  *
121  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
122  * insn, the register holding that pointer in the true branch changes state to
123  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
124  * branch. See check_cond_jmp_op().
125  *
126  * After the call R0 is set to return type of the function and registers R1-R5
127  * are set to NOT_INIT to indicate that they are no longer readable.
128  */
129 
130 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
131 struct bpf_verifier_stack_elem {
132 	/* verifer state is 'st'
133 	 * before processing instruction 'insn_idx'
134 	 * and after processing instruction 'prev_insn_idx'
135 	 */
136 	struct bpf_verifier_state st;
137 	int insn_idx;
138 	int prev_insn_idx;
139 	struct bpf_verifier_stack_elem *next;
140 };
141 
142 #define BPF_COMPLEXITY_LIMIT_INSNS	98304
143 #define BPF_COMPLEXITY_LIMIT_STACK	1024
144 
145 struct bpf_call_arg_meta {
146 	struct bpf_map *map_ptr;
147 	bool raw_mode;
148 	bool pkt_access;
149 	int regno;
150 	int access_size;
151 };
152 
153 /* verbose verifier prints what it's seeing
154  * bpf_check() is called under lock, so no race to access these global vars
155  */
156 static u32 log_level, log_size, log_len;
157 static char *log_buf;
158 
159 static DEFINE_MUTEX(bpf_verifier_lock);
160 
161 /* log_level controls verbosity level of eBPF verifier.
162  * verbose() is used to dump the verification trace to the log, so the user
163  * can figure out what's wrong with the program
164  */
verbose(const char * fmt,...)165 static __printf(1, 2) void verbose(const char *fmt, ...)
166 {
167 	va_list args;
168 
169 	if (log_level == 0 || log_len >= log_size - 1)
170 		return;
171 
172 	va_start(args, fmt);
173 	log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
174 	va_end(args);
175 }
176 
177 /* string representation of 'enum bpf_reg_type' */
178 static const char * const reg_type_str[] = {
179 	[NOT_INIT]		= "?",
180 	[UNKNOWN_VALUE]		= "inv",
181 	[PTR_TO_CTX]		= "ctx",
182 	[CONST_PTR_TO_MAP]	= "map_ptr",
183 	[PTR_TO_MAP_VALUE]	= "map_value",
184 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
185 	[PTR_TO_MAP_VALUE_ADJ]	= "map_value_adj",
186 	[FRAME_PTR]		= "fp",
187 	[PTR_TO_STACK]		= "fp",
188 	[CONST_IMM]		= "imm",
189 	[PTR_TO_PACKET]		= "pkt",
190 	[PTR_TO_PACKET_END]	= "pkt_end",
191 };
192 
print_verifier_state(struct bpf_verifier_state * state)193 static void print_verifier_state(struct bpf_verifier_state *state)
194 {
195 	struct bpf_reg_state *reg;
196 	enum bpf_reg_type t;
197 	int i;
198 
199 	for (i = 0; i < MAX_BPF_REG; i++) {
200 		reg = &state->regs[i];
201 		t = reg->type;
202 		if (t == NOT_INIT)
203 			continue;
204 		verbose(" R%d=%s", i, reg_type_str[t]);
205 		if (t == CONST_IMM || t == PTR_TO_STACK)
206 			verbose("%lld", reg->imm);
207 		else if (t == PTR_TO_PACKET)
208 			verbose("(id=%d,off=%d,r=%d)",
209 				reg->id, reg->off, reg->range);
210 		else if (t == UNKNOWN_VALUE && reg->imm)
211 			verbose("%lld", reg->imm);
212 		else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
213 			 t == PTR_TO_MAP_VALUE_OR_NULL ||
214 			 t == PTR_TO_MAP_VALUE_ADJ)
215 			verbose("(ks=%d,vs=%d,id=%u)",
216 				reg->map_ptr->key_size,
217 				reg->map_ptr->value_size,
218 				reg->id);
219 		if (reg->min_value != BPF_REGISTER_MIN_RANGE)
220 			verbose(",min_value=%lld",
221 				(long long)reg->min_value);
222 		if (reg->max_value != BPF_REGISTER_MAX_RANGE)
223 			verbose(",max_value=%llu",
224 				(unsigned long long)reg->max_value);
225 	}
226 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
227 		if (state->stack_slot_type[i] == STACK_SPILL)
228 			verbose(" fp%d=%s", -MAX_BPF_STACK + i,
229 				reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
230 	}
231 	verbose("\n");
232 }
233 
234 static const char *const bpf_class_string[] = {
235 	[BPF_LD]    = "ld",
236 	[BPF_LDX]   = "ldx",
237 	[BPF_ST]    = "st",
238 	[BPF_STX]   = "stx",
239 	[BPF_ALU]   = "alu",
240 	[BPF_JMP]   = "jmp",
241 	[BPF_RET]   = "BUG",
242 	[BPF_ALU64] = "alu64",
243 };
244 
245 static const char *const bpf_alu_string[16] = {
246 	[BPF_ADD >> 4]  = "+=",
247 	[BPF_SUB >> 4]  = "-=",
248 	[BPF_MUL >> 4]  = "*=",
249 	[BPF_DIV >> 4]  = "/=",
250 	[BPF_OR  >> 4]  = "|=",
251 	[BPF_AND >> 4]  = "&=",
252 	[BPF_LSH >> 4]  = "<<=",
253 	[BPF_RSH >> 4]  = ">>=",
254 	[BPF_NEG >> 4]  = "neg",
255 	[BPF_MOD >> 4]  = "%=",
256 	[BPF_XOR >> 4]  = "^=",
257 	[BPF_MOV >> 4]  = "=",
258 	[BPF_ARSH >> 4] = "s>>=",
259 	[BPF_END >> 4]  = "endian",
260 };
261 
262 static const char *const bpf_ldst_string[] = {
263 	[BPF_W >> 3]  = "u32",
264 	[BPF_H >> 3]  = "u16",
265 	[BPF_B >> 3]  = "u8",
266 	[BPF_DW >> 3] = "u64",
267 };
268 
269 static const char *const bpf_jmp_string[16] = {
270 	[BPF_JA >> 4]   = "jmp",
271 	[BPF_JEQ >> 4]  = "==",
272 	[BPF_JGT >> 4]  = ">",
273 	[BPF_JGE >> 4]  = ">=",
274 	[BPF_JSET >> 4] = "&",
275 	[BPF_JNE >> 4]  = "!=",
276 	[BPF_JSGT >> 4] = "s>",
277 	[BPF_JSGE >> 4] = "s>=",
278 	[BPF_CALL >> 4] = "call",
279 	[BPF_EXIT >> 4] = "exit",
280 };
281 
print_bpf_insn(const struct bpf_verifier_env * env,const struct bpf_insn * insn)282 static void print_bpf_insn(const struct bpf_verifier_env *env,
283 			   const struct bpf_insn *insn)
284 {
285 	u8 class = BPF_CLASS(insn->code);
286 
287 	if (class == BPF_ALU || class == BPF_ALU64) {
288 		if (BPF_SRC(insn->code) == BPF_X)
289 			verbose("(%02x) %sr%d %s %sr%d\n",
290 				insn->code, class == BPF_ALU ? "(u32) " : "",
291 				insn->dst_reg,
292 				bpf_alu_string[BPF_OP(insn->code) >> 4],
293 				class == BPF_ALU ? "(u32) " : "",
294 				insn->src_reg);
295 		else
296 			verbose("(%02x) %sr%d %s %s%d\n",
297 				insn->code, class == BPF_ALU ? "(u32) " : "",
298 				insn->dst_reg,
299 				bpf_alu_string[BPF_OP(insn->code) >> 4],
300 				class == BPF_ALU ? "(u32) " : "",
301 				insn->imm);
302 	} else if (class == BPF_STX) {
303 		if (BPF_MODE(insn->code) == BPF_MEM)
304 			verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
305 				insn->code,
306 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
307 				insn->dst_reg,
308 				insn->off, insn->src_reg);
309 		else if (BPF_MODE(insn->code) == BPF_XADD)
310 			verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
311 				insn->code,
312 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
313 				insn->dst_reg, insn->off,
314 				insn->src_reg);
315 		else
316 			verbose("BUG_%02x\n", insn->code);
317 	} else if (class == BPF_ST) {
318 		if (BPF_MODE(insn->code) != BPF_MEM) {
319 			verbose("BUG_st_%02x\n", insn->code);
320 			return;
321 		}
322 		verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
323 			insn->code,
324 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
325 			insn->dst_reg,
326 			insn->off, insn->imm);
327 	} else if (class == BPF_LDX) {
328 		if (BPF_MODE(insn->code) != BPF_MEM) {
329 			verbose("BUG_ldx_%02x\n", insn->code);
330 			return;
331 		}
332 		verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
333 			insn->code, insn->dst_reg,
334 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
335 			insn->src_reg, insn->off);
336 	} else if (class == BPF_LD) {
337 		if (BPF_MODE(insn->code) == BPF_ABS) {
338 			verbose("(%02x) r0 = *(%s *)skb[%d]\n",
339 				insn->code,
340 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
341 				insn->imm);
342 		} else if (BPF_MODE(insn->code) == BPF_IND) {
343 			verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
344 				insn->code,
345 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
346 				insn->src_reg, insn->imm);
347 		} else if (BPF_MODE(insn->code) == BPF_IMM &&
348 			   BPF_SIZE(insn->code) == BPF_DW) {
349 			/* At this point, we already made sure that the second
350 			 * part of the ldimm64 insn is accessible.
351 			 */
352 			u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
353 			bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
354 
355 			if (map_ptr && !env->allow_ptr_leaks)
356 				imm = 0;
357 
358 			verbose("(%02x) r%d = 0x%llx\n", insn->code,
359 				insn->dst_reg, (unsigned long long)imm);
360 		} else {
361 			verbose("BUG_ld_%02x\n", insn->code);
362 			return;
363 		}
364 	} else if (class == BPF_JMP) {
365 		u8 opcode = BPF_OP(insn->code);
366 
367 		if (opcode == BPF_CALL) {
368 			verbose("(%02x) call %d\n", insn->code, insn->imm);
369 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
370 			verbose("(%02x) goto pc%+d\n",
371 				insn->code, insn->off);
372 		} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
373 			verbose("(%02x) exit\n", insn->code);
374 		} else if (BPF_SRC(insn->code) == BPF_X) {
375 			verbose("(%02x) if r%d %s r%d goto pc%+d\n",
376 				insn->code, insn->dst_reg,
377 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
378 				insn->src_reg, insn->off);
379 		} else {
380 			verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
381 				insn->code, insn->dst_reg,
382 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
383 				insn->imm, insn->off);
384 		}
385 	} else {
386 		verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
387 	}
388 }
389 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx)390 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
391 {
392 	struct bpf_verifier_stack_elem *elem;
393 	int insn_idx;
394 
395 	if (env->head == NULL)
396 		return -1;
397 
398 	memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
399 	insn_idx = env->head->insn_idx;
400 	if (prev_insn_idx)
401 		*prev_insn_idx = env->head->prev_insn_idx;
402 	elem = env->head->next;
403 	kfree(env->head);
404 	env->head = elem;
405 	env->stack_size--;
406 	return insn_idx;
407 }
408 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx)409 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
410 					     int insn_idx, int prev_insn_idx)
411 {
412 	struct bpf_verifier_stack_elem *elem;
413 
414 	elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
415 	if (!elem)
416 		goto err;
417 
418 	memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
419 	elem->insn_idx = insn_idx;
420 	elem->prev_insn_idx = prev_insn_idx;
421 	elem->next = env->head;
422 	env->head = elem;
423 	env->stack_size++;
424 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
425 		verbose("BPF program is too complex\n");
426 		goto err;
427 	}
428 	return &elem->st;
429 err:
430 	/* pop all elements and return */
431 	while (pop_stack(env, NULL) >= 0);
432 	return NULL;
433 }
434 
435 #define CALLER_SAVED_REGS 6
436 static const int caller_saved[CALLER_SAVED_REGS] = {
437 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
438 };
439 
init_reg_state(struct bpf_reg_state * regs)440 static void init_reg_state(struct bpf_reg_state *regs)
441 {
442 	int i;
443 
444 	for (i = 0; i < MAX_BPF_REG; i++) {
445 		regs[i].type = NOT_INIT;
446 		regs[i].imm = 0;
447 		regs[i].min_value = BPF_REGISTER_MIN_RANGE;
448 		regs[i].max_value = BPF_REGISTER_MAX_RANGE;
449 	}
450 
451 	/* frame pointer */
452 	regs[BPF_REG_FP].type = FRAME_PTR;
453 
454 	/* 1st arg to a function */
455 	regs[BPF_REG_1].type = PTR_TO_CTX;
456 }
457 
__mark_reg_unknown_value(struct bpf_reg_state * regs,u32 regno)458 static void __mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
459 {
460 	regs[regno].type = UNKNOWN_VALUE;
461 	regs[regno].id = 0;
462 	regs[regno].imm = 0;
463 }
464 
mark_reg_unknown_value(struct bpf_reg_state * regs,u32 regno)465 static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
466 {
467 	BUG_ON(regno >= MAX_BPF_REG);
468 	__mark_reg_unknown_value(regs, regno);
469 }
470 
reset_reg_range_values(struct bpf_reg_state * regs,u32 regno)471 static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
472 {
473 	regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
474 	regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
475 }
476 
477 enum reg_arg_type {
478 	SRC_OP,		/* register is used as source operand */
479 	DST_OP,		/* register is used as destination operand */
480 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
481 };
482 
check_reg_arg(struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)483 static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
484 			 enum reg_arg_type t)
485 {
486 	if (regno >= MAX_BPF_REG) {
487 		verbose("R%d is invalid\n", regno);
488 		return -EINVAL;
489 	}
490 
491 	if (t == SRC_OP) {
492 		/* check whether register used as source operand can be read */
493 		if (regs[regno].type == NOT_INIT) {
494 			verbose("R%d !read_ok\n", regno);
495 			return -EACCES;
496 		}
497 	} else {
498 		/* check whether register used as dest operand can be written to */
499 		if (regno == BPF_REG_FP) {
500 			verbose("frame pointer is read only\n");
501 			return -EACCES;
502 		}
503 		if (t == DST_OP)
504 			mark_reg_unknown_value(regs, regno);
505 	}
506 	return 0;
507 }
508 
bpf_size_to_bytes(int bpf_size)509 static int bpf_size_to_bytes(int bpf_size)
510 {
511 	if (bpf_size == BPF_W)
512 		return 4;
513 	else if (bpf_size == BPF_H)
514 		return 2;
515 	else if (bpf_size == BPF_B)
516 		return 1;
517 	else if (bpf_size == BPF_DW)
518 		return 8;
519 	else
520 		return -EINVAL;
521 }
522 
is_spillable_regtype(enum bpf_reg_type type)523 static bool is_spillable_regtype(enum bpf_reg_type type)
524 {
525 	switch (type) {
526 	case PTR_TO_MAP_VALUE:
527 	case PTR_TO_MAP_VALUE_OR_NULL:
528 	case PTR_TO_STACK:
529 	case PTR_TO_CTX:
530 	case PTR_TO_PACKET:
531 	case PTR_TO_PACKET_END:
532 	case FRAME_PTR:
533 	case CONST_PTR_TO_MAP:
534 		return true;
535 	default:
536 		return false;
537 	}
538 }
539 
540 /* check_stack_read/write functions track spill/fill of registers,
541  * stack boundary and alignment are checked in check_mem_access()
542  */
check_stack_write(struct bpf_verifier_state * state,int off,int size,int value_regno)543 static int check_stack_write(struct bpf_verifier_state *state, int off,
544 			     int size, int value_regno)
545 {
546 	int i;
547 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
548 	 * so it's aligned access and [off, off + size) are within stack limits
549 	 */
550 
551 	if (value_regno >= 0 &&
552 	    is_spillable_regtype(state->regs[value_regno].type)) {
553 
554 		/* register containing pointer is being spilled into stack */
555 		if (size != BPF_REG_SIZE) {
556 			verbose("invalid size of register spill\n");
557 			return -EACCES;
558 		}
559 
560 		/* save register state */
561 		state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
562 			state->regs[value_regno];
563 
564 		for (i = 0; i < BPF_REG_SIZE; i++)
565 			state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
566 	} else {
567 		/* regular write of data into stack */
568 		state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
569 			(struct bpf_reg_state) {};
570 
571 		for (i = 0; i < size; i++)
572 			state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
573 	}
574 	return 0;
575 }
576 
check_stack_read(struct bpf_verifier_state * state,int off,int size,int value_regno)577 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
578 			    int value_regno)
579 {
580 	u8 *slot_type;
581 	int i;
582 
583 	slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
584 
585 	if (slot_type[0] == STACK_SPILL) {
586 		if (size != BPF_REG_SIZE) {
587 			verbose("invalid size of register spill\n");
588 			return -EACCES;
589 		}
590 		for (i = 1; i < BPF_REG_SIZE; i++) {
591 			if (slot_type[i] != STACK_SPILL) {
592 				verbose("corrupted spill memory\n");
593 				return -EACCES;
594 			}
595 		}
596 
597 		if (value_regno >= 0)
598 			/* restore register state from stack */
599 			state->regs[value_regno] =
600 				state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
601 		return 0;
602 	} else {
603 		for (i = 0; i < size; i++) {
604 			if (slot_type[i] != STACK_MISC) {
605 				verbose("invalid read from stack off %d+%d size %d\n",
606 					off, i, size);
607 				return -EACCES;
608 			}
609 		}
610 		if (value_regno >= 0)
611 			/* have read misc data from the stack */
612 			mark_reg_unknown_value(state->regs, value_regno);
613 		return 0;
614 	}
615 }
616 
617 /* check read/write into map element returned by bpf_map_lookup_elem() */
check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size)618 static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
619 			    int size)
620 {
621 	struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
622 
623 	if (off < 0 || off + size > map->value_size) {
624 		verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
625 			map->value_size, off, size);
626 		return -EACCES;
627 	}
628 	return 0;
629 }
630 
631 #define MAX_PACKET_OFF 0xffff
632 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta)633 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
634 				       const struct bpf_call_arg_meta *meta)
635 {
636 	switch (env->prog->type) {
637 	case BPF_PROG_TYPE_SCHED_CLS:
638 	case BPF_PROG_TYPE_SCHED_ACT:
639 	case BPF_PROG_TYPE_XDP:
640 		if (meta)
641 			return meta->pkt_access;
642 
643 		env->seen_direct_write = true;
644 		return true;
645 	default:
646 		return false;
647 	}
648 }
649 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size)650 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
651 			       int size)
652 {
653 	struct bpf_reg_state *regs = env->cur_state.regs;
654 	struct bpf_reg_state *reg = &regs[regno];
655 
656 	off += reg->off;
657 	if (off < 0 || size <= 0 || off + size > reg->range) {
658 		verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
659 			off, size, regno, reg->id, reg->off, reg->range);
660 		return -EACCES;
661 	}
662 	return 0;
663 }
664 
665 /* check access to 'struct bpf_context' fields */
check_ctx_access(struct bpf_verifier_env * env,int off,int size,enum bpf_access_type t,enum bpf_reg_type * reg_type)666 static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
667 			    enum bpf_access_type t, enum bpf_reg_type *reg_type)
668 {
669 	/* for analyzer ctx accesses are already validated and converted */
670 	if (env->analyzer_ops)
671 		return 0;
672 
673 	if (env->prog->aux->ops->is_valid_access &&
674 	    env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
675 		/* remember the offset of last byte accessed in ctx */
676 		if (env->prog->aux->max_ctx_offset < off + size)
677 			env->prog->aux->max_ctx_offset = off + size;
678 		return 0;
679 	}
680 
681 	verbose("invalid bpf_context access off=%d size=%d\n", off, size);
682 	return -EACCES;
683 }
684 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)685 static bool __is_pointer_value(bool allow_ptr_leaks,
686 			       const struct bpf_reg_state *reg)
687 {
688 	if (allow_ptr_leaks)
689 		return false;
690 
691 	switch (reg->type) {
692 	case UNKNOWN_VALUE:
693 	case CONST_IMM:
694 		return false;
695 	default:
696 		return true;
697 	}
698 }
699 
is_pointer_value(struct bpf_verifier_env * env,int regno)700 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
701 {
702 	return __is_pointer_value(env->allow_ptr_leaks, &env->cur_state.regs[regno]);
703 }
704 
is_ctx_reg(struct bpf_verifier_env * env,int regno)705 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
706 {
707 	const struct bpf_reg_state *reg = &env->cur_state.regs[regno];
708 
709 	return reg->type == PTR_TO_CTX;
710 }
711 
check_ptr_alignment(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int off,int size)712 static int check_ptr_alignment(struct bpf_verifier_env *env,
713 			       struct bpf_reg_state *reg, int off, int size)
714 {
715 	if (reg->type != PTR_TO_PACKET && reg->type != PTR_TO_MAP_VALUE_ADJ) {
716 		if (off % size != 0) {
717 			verbose("misaligned access off %d size %d\n",
718 				off, size);
719 			return -EACCES;
720 		} else {
721 			return 0;
722 		}
723 	}
724 
725 	if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
726 		/* misaligned access to packet is ok on x86,arm,arm64 */
727 		return 0;
728 
729 	if (reg->id && size != 1) {
730 		verbose("Unknown packet alignment. Only byte-sized access allowed\n");
731 		return -EACCES;
732 	}
733 
734 	/* skb->data is NET_IP_ALIGN-ed */
735 	if (reg->type == PTR_TO_PACKET &&
736 	    (NET_IP_ALIGN + reg->off + off) % size != 0) {
737 		verbose("misaligned packet access off %d+%d+%d size %d\n",
738 			NET_IP_ALIGN, reg->off, off, size);
739 		return -EACCES;
740 	}
741 	return 0;
742 }
743 
744 /* check whether memory at (regno + off) is accessible for t = (read | write)
745  * if t==write, value_regno is a register which value is stored into memory
746  * if t==read, value_regno is a register which will receive the value from memory
747  * if t==write && value_regno==-1, some unknown value is stored into memory
748  * if t==read && value_regno==-1, don't care what we read from memory
749  */
check_mem_access(struct bpf_verifier_env * env,u32 regno,int off,int bpf_size,enum bpf_access_type t,int value_regno)750 static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
751 			    int bpf_size, enum bpf_access_type t,
752 			    int value_regno)
753 {
754 	struct bpf_verifier_state *state = &env->cur_state;
755 	struct bpf_reg_state *reg = &state->regs[regno];
756 	int size, err = 0;
757 
758 	if (reg->type == PTR_TO_STACK)
759 		off += reg->imm;
760 
761 	size = bpf_size_to_bytes(bpf_size);
762 	if (size < 0)
763 		return size;
764 
765 	err = check_ptr_alignment(env, reg, off, size);
766 	if (err)
767 		return err;
768 
769 	if (reg->type == PTR_TO_MAP_VALUE ||
770 	    reg->type == PTR_TO_MAP_VALUE_ADJ) {
771 		if (t == BPF_WRITE && value_regno >= 0 &&
772 		    is_pointer_value(env, value_regno)) {
773 			verbose("R%d leaks addr into map\n", value_regno);
774 			return -EACCES;
775 		}
776 
777 		/* If we adjusted the register to this map value at all then we
778 		 * need to change off and size to min_value and max_value
779 		 * respectively to make sure our theoretical access will be
780 		 * safe.
781 		 */
782 		if (reg->type == PTR_TO_MAP_VALUE_ADJ) {
783 			if (log_level)
784 				print_verifier_state(state);
785 			env->varlen_map_value_access = true;
786 			/* The minimum value is only important with signed
787 			 * comparisons where we can't assume the floor of a
788 			 * value is 0.  If we are using signed variables for our
789 			 * index'es we need to make sure that whatever we use
790 			 * will have a set floor within our range.
791 			 */
792 			if (reg->min_value < 0) {
793 				verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
794 					regno);
795 				return -EACCES;
796 			}
797 			err = check_map_access(env, regno, reg->min_value + off,
798 					       size);
799 			if (err) {
800 				verbose("R%d min value is outside of the array range\n",
801 					regno);
802 				return err;
803 			}
804 
805 			/* If we haven't set a max value then we need to bail
806 			 * since we can't be sure we won't do bad things.
807 			 */
808 			if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
809 				verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
810 					regno);
811 				return -EACCES;
812 			}
813 			off += reg->max_value;
814 		}
815 		err = check_map_access(env, regno, off, size);
816 		if (!err && t == BPF_READ && value_regno >= 0)
817 			mark_reg_unknown_value(state->regs, value_regno);
818 
819 	} else if (reg->type == PTR_TO_CTX) {
820 		enum bpf_reg_type reg_type = UNKNOWN_VALUE;
821 
822 		if (t == BPF_WRITE && value_regno >= 0 &&
823 		    is_pointer_value(env, value_regno)) {
824 			verbose("R%d leaks addr into ctx\n", value_regno);
825 			return -EACCES;
826 		}
827 		err = check_ctx_access(env, off, size, t, &reg_type);
828 		if (!err && t == BPF_READ && value_regno >= 0) {
829 			mark_reg_unknown_value(state->regs, value_regno);
830 			/* note that reg.[id|off|range] == 0 */
831 			state->regs[value_regno].type = reg_type;
832 		}
833 
834 	} else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
835 		if (off >= 0 || off < -MAX_BPF_STACK) {
836 			verbose("invalid stack off=%d size=%d\n", off, size);
837 			return -EACCES;
838 		}
839 		if (t == BPF_WRITE) {
840 			if (!env->allow_ptr_leaks &&
841 			    state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
842 			    size != BPF_REG_SIZE) {
843 				verbose("attempt to corrupt spilled pointer on stack\n");
844 				return -EACCES;
845 			}
846 			err = check_stack_write(state, off, size, value_regno);
847 		} else {
848 			err = check_stack_read(state, off, size, value_regno);
849 		}
850 	} else if (state->regs[regno].type == PTR_TO_PACKET) {
851 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL)) {
852 			verbose("cannot write into packet\n");
853 			return -EACCES;
854 		}
855 		if (t == BPF_WRITE && value_regno >= 0 &&
856 		    is_pointer_value(env, value_regno)) {
857 			verbose("R%d leaks addr into packet\n", value_regno);
858 			return -EACCES;
859 		}
860 		err = check_packet_access(env, regno, off, size);
861 		if (!err && t == BPF_READ && value_regno >= 0)
862 			mark_reg_unknown_value(state->regs, value_regno);
863 	} else {
864 		verbose("R%d invalid mem access '%s'\n",
865 			regno, reg_type_str[reg->type]);
866 		return -EACCES;
867 	}
868 
869 	if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
870 	    state->regs[value_regno].type == UNKNOWN_VALUE) {
871 		/* 1 or 2 byte load zero-extends, determine the number of
872 		 * zero upper bits. Not doing it fo 4 byte load, since
873 		 * such values cannot be added to ptr_to_packet anyway.
874 		 */
875 		state->regs[value_regno].imm = 64 - size * 8;
876 	}
877 	return err;
878 }
879 
check_xadd(struct bpf_verifier_env * env,struct bpf_insn * insn)880 static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
881 {
882 	struct bpf_reg_state *regs = env->cur_state.regs;
883 	int err;
884 
885 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
886 	    insn->imm != 0) {
887 		verbose("BPF_XADD uses reserved fields\n");
888 		return -EINVAL;
889 	}
890 
891 	/* check src1 operand */
892 	err = check_reg_arg(regs, insn->src_reg, SRC_OP);
893 	if (err)
894 		return err;
895 
896 	/* check src2 operand */
897 	err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
898 	if (err)
899 		return err;
900 
901 	if (is_pointer_value(env, insn->src_reg)) {
902 		verbose("R%d leaks addr into mem\n", insn->src_reg);
903 		return -EACCES;
904 	}
905 
906 	if (is_ctx_reg(env, insn->dst_reg)) {
907 		verbose("BPF_XADD stores into R%d context is not allowed\n",
908 			insn->dst_reg);
909 		return -EACCES;
910 	}
911 
912 	/* check whether atomic_add can read the memory */
913 	err = check_mem_access(env, insn->dst_reg, insn->off,
914 			       BPF_SIZE(insn->code), BPF_READ, -1);
915 	if (err)
916 		return err;
917 
918 	/* check whether atomic_add can write into the same memory */
919 	return check_mem_access(env, insn->dst_reg, insn->off,
920 				BPF_SIZE(insn->code), BPF_WRITE, -1);
921 }
922 
923 /* when register 'regno' is passed into function that will read 'access_size'
924  * bytes from that pointer, make sure that it's within stack boundary
925  * and all elements of stack are initialized
926  */
check_stack_boundary(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)927 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
928 				int access_size, bool zero_size_allowed,
929 				struct bpf_call_arg_meta *meta)
930 {
931 	struct bpf_verifier_state *state = &env->cur_state;
932 	struct bpf_reg_state *regs = state->regs;
933 	int off, i;
934 
935 	if (regs[regno].type != PTR_TO_STACK) {
936 		if (zero_size_allowed && access_size == 0 &&
937 		    regs[regno].type == CONST_IMM &&
938 		    regs[regno].imm  == 0)
939 			return 0;
940 
941 		verbose("R%d type=%s expected=%s\n", regno,
942 			reg_type_str[regs[regno].type],
943 			reg_type_str[PTR_TO_STACK]);
944 		return -EACCES;
945 	}
946 
947 	off = regs[regno].imm;
948 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
949 	    access_size <= 0) {
950 		verbose("invalid stack type R%d off=%d access_size=%d\n",
951 			regno, off, access_size);
952 		return -EACCES;
953 	}
954 
955 	if (meta && meta->raw_mode) {
956 		meta->access_size = access_size;
957 		meta->regno = regno;
958 		return 0;
959 	}
960 
961 	for (i = 0; i < access_size; i++) {
962 		if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
963 			verbose("invalid indirect read from stack off %d+%d size %d\n",
964 				off, i, access_size);
965 			return -EACCES;
966 		}
967 	}
968 	return 0;
969 }
970 
check_func_arg(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,struct bpf_call_arg_meta * meta)971 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
972 			  enum bpf_arg_type arg_type,
973 			  struct bpf_call_arg_meta *meta)
974 {
975 	struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
976 	enum bpf_reg_type expected_type, type = reg->type;
977 	int err = 0;
978 
979 	if (arg_type == ARG_DONTCARE)
980 		return 0;
981 
982 	if (type == NOT_INIT) {
983 		verbose("R%d !read_ok\n", regno);
984 		return -EACCES;
985 	}
986 
987 	if (arg_type == ARG_ANYTHING) {
988 		if (is_pointer_value(env, regno)) {
989 			verbose("R%d leaks addr into helper function\n", regno);
990 			return -EACCES;
991 		}
992 		return 0;
993 	}
994 
995 	if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta)) {
996 		verbose("helper access to the packet is not allowed\n");
997 		return -EACCES;
998 	}
999 
1000 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
1001 	    arg_type == ARG_PTR_TO_MAP_VALUE) {
1002 		expected_type = PTR_TO_STACK;
1003 		if (type != PTR_TO_PACKET && type != expected_type)
1004 			goto err_type;
1005 	} else if (arg_type == ARG_CONST_STACK_SIZE ||
1006 		   arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
1007 		expected_type = CONST_IMM;
1008 		if (type != expected_type)
1009 			goto err_type;
1010 	} else if (arg_type == ARG_CONST_MAP_PTR) {
1011 		expected_type = CONST_PTR_TO_MAP;
1012 		if (type != expected_type)
1013 			goto err_type;
1014 	} else if (arg_type == ARG_PTR_TO_CTX) {
1015 		expected_type = PTR_TO_CTX;
1016 		if (type != expected_type)
1017 			goto err_type;
1018 	} else if (arg_type == ARG_PTR_TO_STACK ||
1019 		   arg_type == ARG_PTR_TO_RAW_STACK) {
1020 		expected_type = PTR_TO_STACK;
1021 		/* One exception here. In case function allows for NULL to be
1022 		 * passed in as argument, it's a CONST_IMM type. Final test
1023 		 * happens during stack boundary checking.
1024 		 */
1025 		if (type == CONST_IMM && reg->imm == 0)
1026 			/* final test in check_stack_boundary() */;
1027 		else if (type != PTR_TO_PACKET && type != expected_type)
1028 			goto err_type;
1029 		meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
1030 	} else {
1031 		verbose("unsupported arg_type %d\n", arg_type);
1032 		return -EFAULT;
1033 	}
1034 
1035 	if (arg_type == ARG_CONST_MAP_PTR) {
1036 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1037 		meta->map_ptr = reg->map_ptr;
1038 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1039 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
1040 		 * check that [key, key + map->key_size) are within
1041 		 * stack limits and initialized
1042 		 */
1043 		if (!meta->map_ptr) {
1044 			/* in function declaration map_ptr must come before
1045 			 * map_key, so that it's verified and known before
1046 			 * we have to check map_key here. Otherwise it means
1047 			 * that kernel subsystem misconfigured verifier
1048 			 */
1049 			verbose("invalid map_ptr to access map->key\n");
1050 			return -EACCES;
1051 		}
1052 		if (type == PTR_TO_PACKET)
1053 			err = check_packet_access(env, regno, 0,
1054 						  meta->map_ptr->key_size);
1055 		else
1056 			err = check_stack_boundary(env, regno,
1057 						   meta->map_ptr->key_size,
1058 						   false, NULL);
1059 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1060 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
1061 		 * check [value, value + map->value_size) validity
1062 		 */
1063 		if (!meta->map_ptr) {
1064 			/* kernel subsystem misconfigured verifier */
1065 			verbose("invalid map_ptr to access map->value\n");
1066 			return -EACCES;
1067 		}
1068 		if (type == PTR_TO_PACKET)
1069 			err = check_packet_access(env, regno, 0,
1070 						  meta->map_ptr->value_size);
1071 		else
1072 			err = check_stack_boundary(env, regno,
1073 						   meta->map_ptr->value_size,
1074 						   false, NULL);
1075 	} else if (arg_type == ARG_CONST_STACK_SIZE ||
1076 		   arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
1077 		bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
1078 
1079 		/* bpf_xxx(..., buf, len) call will access 'len' bytes
1080 		 * from stack pointer 'buf'. Check it
1081 		 * note: regno == len, regno - 1 == buf
1082 		 */
1083 		if (regno == 0) {
1084 			/* kernel subsystem misconfigured verifier */
1085 			verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
1086 			return -EACCES;
1087 		}
1088 		if (regs[regno - 1].type == PTR_TO_PACKET)
1089 			err = check_packet_access(env, regno - 1, 0, reg->imm);
1090 		else
1091 			err = check_stack_boundary(env, regno - 1, reg->imm,
1092 						   zero_size_allowed, meta);
1093 	}
1094 
1095 	return err;
1096 err_type:
1097 	verbose("R%d type=%s expected=%s\n", regno,
1098 		reg_type_str[type], reg_type_str[expected_type]);
1099 	return -EACCES;
1100 }
1101 
check_map_func_compatibility(struct bpf_map * map,int func_id)1102 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1103 {
1104 	if (!map)
1105 		return 0;
1106 
1107 	/* We need a two way check, first is from map perspective ... */
1108 	switch (map->map_type) {
1109 	case BPF_MAP_TYPE_PROG_ARRAY:
1110 		if (func_id != BPF_FUNC_tail_call)
1111 			goto error;
1112 		break;
1113 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1114 		if (func_id != BPF_FUNC_perf_event_read &&
1115 		    func_id != BPF_FUNC_perf_event_output)
1116 			goto error;
1117 		break;
1118 	case BPF_MAP_TYPE_STACK_TRACE:
1119 		if (func_id != BPF_FUNC_get_stackid)
1120 			goto error;
1121 		break;
1122 	case BPF_MAP_TYPE_CGROUP_ARRAY:
1123 		if (func_id != BPF_FUNC_skb_under_cgroup &&
1124 		    func_id != BPF_FUNC_current_task_under_cgroup)
1125 			goto error;
1126 		break;
1127 	default:
1128 		break;
1129 	}
1130 
1131 	/* ... and second from the function itself. */
1132 	switch (func_id) {
1133 	case BPF_FUNC_tail_call:
1134 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1135 			goto error;
1136 		break;
1137 	case BPF_FUNC_perf_event_read:
1138 	case BPF_FUNC_perf_event_output:
1139 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1140 			goto error;
1141 		break;
1142 	case BPF_FUNC_get_stackid:
1143 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1144 			goto error;
1145 		break;
1146 	case BPF_FUNC_current_task_under_cgroup:
1147 	case BPF_FUNC_skb_under_cgroup:
1148 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1149 			goto error;
1150 		break;
1151 	default:
1152 		break;
1153 	}
1154 
1155 	return 0;
1156 error:
1157 	verbose("cannot pass map_type %d into func %d\n",
1158 		map->map_type, func_id);
1159 	return -EINVAL;
1160 }
1161 
check_raw_mode(const struct bpf_func_proto * fn)1162 static int check_raw_mode(const struct bpf_func_proto *fn)
1163 {
1164 	int count = 0;
1165 
1166 	if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1167 		count++;
1168 	if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1169 		count++;
1170 	if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1171 		count++;
1172 	if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1173 		count++;
1174 	if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1175 		count++;
1176 
1177 	return count > 1 ? -EINVAL : 0;
1178 }
1179 
clear_all_pkt_pointers(struct bpf_verifier_env * env)1180 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1181 {
1182 	struct bpf_verifier_state *state = &env->cur_state;
1183 	struct bpf_reg_state *regs = state->regs, *reg;
1184 	int i;
1185 
1186 	for (i = 0; i < MAX_BPF_REG; i++)
1187 		if (regs[i].type == PTR_TO_PACKET ||
1188 		    regs[i].type == PTR_TO_PACKET_END)
1189 			mark_reg_unknown_value(regs, i);
1190 
1191 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1192 		if (state->stack_slot_type[i] != STACK_SPILL)
1193 			continue;
1194 		reg = &state->spilled_regs[i / BPF_REG_SIZE];
1195 		if (reg->type != PTR_TO_PACKET &&
1196 		    reg->type != PTR_TO_PACKET_END)
1197 			continue;
1198 		reg->type = UNKNOWN_VALUE;
1199 		reg->imm = 0;
1200 	}
1201 }
1202 
check_call(struct bpf_verifier_env * env,int func_id,int insn_idx)1203 static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
1204 {
1205 	struct bpf_verifier_state *state = &env->cur_state;
1206 	const struct bpf_func_proto *fn = NULL;
1207 	struct bpf_reg_state *regs = state->regs;
1208 	struct bpf_reg_state *reg;
1209 	struct bpf_call_arg_meta meta;
1210 	bool changes_data;
1211 	int i, err;
1212 
1213 	/* find function prototype */
1214 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1215 		verbose("invalid func %d\n", func_id);
1216 		return -EINVAL;
1217 	}
1218 
1219 	if (env->prog->aux->ops->get_func_proto)
1220 		fn = env->prog->aux->ops->get_func_proto(func_id);
1221 
1222 	if (!fn) {
1223 		verbose("unknown func %d\n", func_id);
1224 		return -EINVAL;
1225 	}
1226 
1227 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
1228 	if (!env->prog->gpl_compatible && fn->gpl_only) {
1229 		verbose("cannot call GPL only function from proprietary program\n");
1230 		return -EINVAL;
1231 	}
1232 
1233 	changes_data = bpf_helper_changes_skb_data(fn->func);
1234 
1235 	memset(&meta, 0, sizeof(meta));
1236 	meta.pkt_access = fn->pkt_access;
1237 
1238 	/* We only support one arg being in raw mode at the moment, which
1239 	 * is sufficient for the helper functions we have right now.
1240 	 */
1241 	err = check_raw_mode(fn);
1242 	if (err) {
1243 		verbose("kernel subsystem misconfigured func %d\n", func_id);
1244 		return err;
1245 	}
1246 
1247 	/* check args */
1248 	err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1249 	if (err)
1250 		return err;
1251 	err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1252 	if (err)
1253 		return err;
1254 	if (func_id == BPF_FUNC_tail_call) {
1255 		if (meta.map_ptr == NULL) {
1256 			verbose("verifier bug\n");
1257 			return -EINVAL;
1258 		}
1259 		env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
1260 	}
1261 	err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1262 	if (err)
1263 		return err;
1264 	err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1265 	if (err)
1266 		return err;
1267 	err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1268 	if (err)
1269 		return err;
1270 
1271 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
1272 	 * is inferred from register state.
1273 	 */
1274 	for (i = 0; i < meta.access_size; i++) {
1275 		err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1276 		if (err)
1277 			return err;
1278 	}
1279 
1280 	/* reset caller saved regs */
1281 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
1282 		reg = regs + caller_saved[i];
1283 		reg->type = NOT_INIT;
1284 		reg->imm = 0;
1285 	}
1286 
1287 	/* update return register */
1288 	if (fn->ret_type == RET_INTEGER) {
1289 		regs[BPF_REG_0].type = UNKNOWN_VALUE;
1290 	} else if (fn->ret_type == RET_VOID) {
1291 		regs[BPF_REG_0].type = NOT_INIT;
1292 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1293 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1294 		regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
1295 		/* remember map_ptr, so that check_map_access()
1296 		 * can check 'value_size' boundary of memory access
1297 		 * to map element returned from bpf_map_lookup_elem()
1298 		 */
1299 		if (meta.map_ptr == NULL) {
1300 			verbose("kernel subsystem misconfigured verifier\n");
1301 			return -EINVAL;
1302 		}
1303 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
1304 		regs[BPF_REG_0].id = ++env->id_gen;
1305 	} else {
1306 		verbose("unknown return type %d of func %d\n",
1307 			fn->ret_type, func_id);
1308 		return -EINVAL;
1309 	}
1310 
1311 	err = check_map_func_compatibility(meta.map_ptr, func_id);
1312 	if (err)
1313 		return err;
1314 
1315 	if (changes_data)
1316 		clear_all_pkt_pointers(env);
1317 	return 0;
1318 }
1319 
check_packet_ptr_add(struct bpf_verifier_env * env,struct bpf_insn * insn)1320 static int check_packet_ptr_add(struct bpf_verifier_env *env,
1321 				struct bpf_insn *insn)
1322 {
1323 	struct bpf_reg_state *regs = env->cur_state.regs;
1324 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1325 	struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1326 	struct bpf_reg_state tmp_reg;
1327 	s32 imm;
1328 
1329 	if (BPF_SRC(insn->code) == BPF_K) {
1330 		/* pkt_ptr += imm */
1331 		imm = insn->imm;
1332 
1333 add_imm:
1334 		if (imm <= 0) {
1335 			verbose("addition of negative constant to packet pointer is not allowed\n");
1336 			return -EACCES;
1337 		}
1338 		if (imm >= MAX_PACKET_OFF ||
1339 		    imm + dst_reg->off >= MAX_PACKET_OFF) {
1340 			verbose("constant %d is too large to add to packet pointer\n",
1341 				imm);
1342 			return -EACCES;
1343 		}
1344 		/* a constant was added to pkt_ptr.
1345 		 * Remember it while keeping the same 'id'
1346 		 */
1347 		dst_reg->off += imm;
1348 	} else {
1349 		if (src_reg->type == PTR_TO_PACKET) {
1350 			/* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1351 			tmp_reg = *dst_reg;  /* save r7 state */
1352 			*dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1353 			src_reg = &tmp_reg;  /* pretend it's src_reg state */
1354 			/* if the checks below reject it, the copy won't matter,
1355 			 * since we're rejecting the whole program. If all ok,
1356 			 * then imm22 state will be added to r7
1357 			 * and r7 will be pkt(id=0,off=22,r=62) while
1358 			 * r6 will stay as pkt(id=0,off=0,r=62)
1359 			 */
1360 		}
1361 
1362 		if (src_reg->type == CONST_IMM) {
1363 			/* pkt_ptr += reg where reg is known constant */
1364 			imm = src_reg->imm;
1365 			goto add_imm;
1366 		}
1367 		/* disallow pkt_ptr += reg
1368 		 * if reg is not uknown_value with guaranteed zero upper bits
1369 		 * otherwise pkt_ptr may overflow and addition will become
1370 		 * subtraction which is not allowed
1371 		 */
1372 		if (src_reg->type != UNKNOWN_VALUE) {
1373 			verbose("cannot add '%s' to ptr_to_packet\n",
1374 				reg_type_str[src_reg->type]);
1375 			return -EACCES;
1376 		}
1377 		if (src_reg->imm < 48) {
1378 			verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1379 				src_reg->imm);
1380 			return -EACCES;
1381 		}
1382 		/* dst_reg stays as pkt_ptr type and since some positive
1383 		 * integer value was added to the pointer, increment its 'id'
1384 		 */
1385 		dst_reg->id = ++env->id_gen;
1386 
1387 		/* something was added to pkt_ptr, set range and off to zero */
1388 		dst_reg->off = 0;
1389 		dst_reg->range = 0;
1390 	}
1391 	return 0;
1392 }
1393 
evaluate_reg_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)1394 static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
1395 {
1396 	struct bpf_reg_state *regs = env->cur_state.regs;
1397 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1398 	u8 opcode = BPF_OP(insn->code);
1399 	s64 imm_log2;
1400 
1401 	/* for type == UNKNOWN_VALUE:
1402 	 * imm > 0 -> number of zero upper bits
1403 	 * imm == 0 -> don't track which is the same as all bits can be non-zero
1404 	 */
1405 
1406 	if (BPF_SRC(insn->code) == BPF_X) {
1407 		struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1408 
1409 		if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1410 		    dst_reg->imm && opcode == BPF_ADD) {
1411 			/* dreg += sreg
1412 			 * where both have zero upper bits. Adding them
1413 			 * can only result making one more bit non-zero
1414 			 * in the larger value.
1415 			 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1416 			 *     0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1417 			 */
1418 			dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1419 			dst_reg->imm--;
1420 			return 0;
1421 		}
1422 		if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1423 		    dst_reg->imm && opcode == BPF_ADD) {
1424 			/* dreg += sreg
1425 			 * where dreg has zero upper bits and sreg is const.
1426 			 * Adding them can only result making one more bit
1427 			 * non-zero in the larger value.
1428 			 */
1429 			imm_log2 = __ilog2_u64((long long)src_reg->imm);
1430 			dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1431 			dst_reg->imm--;
1432 			return 0;
1433 		}
1434 		/* all other cases non supported yet, just mark dst_reg */
1435 		dst_reg->imm = 0;
1436 		return 0;
1437 	}
1438 
1439 	/* sign extend 32-bit imm into 64-bit to make sure that
1440 	 * negative values occupy bit 63. Note ilog2() would have
1441 	 * been incorrect, since sizeof(insn->imm) == 4
1442 	 */
1443 	imm_log2 = __ilog2_u64((long long)insn->imm);
1444 
1445 	if (dst_reg->imm && opcode == BPF_LSH) {
1446 		/* reg <<= imm
1447 		 * if reg was a result of 2 byte load, then its imm == 48
1448 		 * which means that upper 48 bits are zero and shifting this reg
1449 		 * left by 4 would mean that upper 44 bits are still zero
1450 		 */
1451 		dst_reg->imm -= insn->imm;
1452 	} else if (dst_reg->imm && opcode == BPF_MUL) {
1453 		/* reg *= imm
1454 		 * if multiplying by 14 subtract 4
1455 		 * This is conservative calculation of upper zero bits.
1456 		 * It's not trying to special case insn->imm == 1 or 0 cases
1457 		 */
1458 		dst_reg->imm -= imm_log2 + 1;
1459 	} else if (opcode == BPF_AND) {
1460 		/* reg &= imm */
1461 		dst_reg->imm = 63 - imm_log2;
1462 	} else if (dst_reg->imm && opcode == BPF_ADD) {
1463 		/* reg += imm */
1464 		dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1465 		dst_reg->imm--;
1466 	} else if (opcode == BPF_RSH) {
1467 		/* reg >>= imm
1468 		 * which means that after right shift, upper bits will be zero
1469 		 * note that verifier already checked that
1470 		 * 0 <= imm < 64 for shift insn
1471 		 */
1472 		dst_reg->imm += insn->imm;
1473 		if (unlikely(dst_reg->imm > 64))
1474 			/* some dumb code did:
1475 			 * r2 = *(u32 *)mem;
1476 			 * r2 >>= 32;
1477 			 * and all bits are zero now */
1478 			dst_reg->imm = 64;
1479 	} else {
1480 		/* all other alu ops, means that we don't know what will
1481 		 * happen to the value, mark it with unknown number of zero bits
1482 		 */
1483 		dst_reg->imm = 0;
1484 	}
1485 
1486 	if (dst_reg->imm < 0) {
1487 		/* all 64 bits of the register can contain non-zero bits
1488 		 * and such value cannot be added to ptr_to_packet, since it
1489 		 * may overflow, mark it as unknown to avoid further eval
1490 		 */
1491 		dst_reg->imm = 0;
1492 	}
1493 	return 0;
1494 }
1495 
evaluate_reg_imm_alu_unknown(struct bpf_verifier_env * env,struct bpf_insn * insn)1496 static int evaluate_reg_imm_alu_unknown(struct bpf_verifier_env *env,
1497 					struct bpf_insn *insn)
1498 {
1499 	struct bpf_reg_state *regs = env->cur_state.regs;
1500 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1501 	struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1502 	u8 opcode = BPF_OP(insn->code);
1503 	s64 imm_log2 = __ilog2_u64((long long)dst_reg->imm);
1504 
1505 	/* BPF_X code with src_reg->type UNKNOWN_VALUE here. */
1506 	if (src_reg->imm > 0 && dst_reg->imm) {
1507 		switch (opcode) {
1508 		case BPF_ADD:
1509 			/* dreg += sreg
1510 			 * where both have zero upper bits. Adding them
1511 			 * can only result making one more bit non-zero
1512 			 * in the larger value.
1513 			 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1514 			 *     0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1515 			 */
1516 			dst_reg->imm = min(src_reg->imm, 63 - imm_log2);
1517 			dst_reg->imm--;
1518 			break;
1519 		case BPF_AND:
1520 			/* dreg &= sreg
1521 			 * AND can not extend zero bits only shrink
1522 			 * Ex.  0x00..00ffffff
1523 			 *    & 0x0f..ffffffff
1524 			 *     ----------------
1525 			 *      0x00..00ffffff
1526 			 */
1527 			dst_reg->imm = max(src_reg->imm, 63 - imm_log2);
1528 			break;
1529 		case BPF_OR:
1530 			/* dreg |= sreg
1531 			 * OR can only extend zero bits
1532 			 * Ex.  0x00..00ffffff
1533 			 *    | 0x0f..ffffffff
1534 			 *     ----------------
1535 			 *      0x0f..00ffffff
1536 			 */
1537 			dst_reg->imm = min(src_reg->imm, 63 - imm_log2);
1538 			break;
1539 		case BPF_SUB:
1540 		case BPF_MUL:
1541 		case BPF_RSH:
1542 		case BPF_LSH:
1543 			/* These may be flushed out later */
1544 		default:
1545 			mark_reg_unknown_value(regs, insn->dst_reg);
1546 		}
1547 	} else {
1548 		mark_reg_unknown_value(regs, insn->dst_reg);
1549 	}
1550 
1551 	dst_reg->type = UNKNOWN_VALUE;
1552 	return 0;
1553 }
1554 
evaluate_reg_imm_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)1555 static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1556 				struct bpf_insn *insn)
1557 {
1558 	struct bpf_reg_state *regs = env->cur_state.regs;
1559 	struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1560 	struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1561 	u8 opcode = BPF_OP(insn->code);
1562 
1563 	if (BPF_SRC(insn->code) == BPF_X && src_reg->type == UNKNOWN_VALUE)
1564 		return evaluate_reg_imm_alu_unknown(env, insn);
1565 
1566 	/* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1567 	 * Don't care about overflow or negative values, just add them
1568 	 */
1569 	if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1570 		dst_reg->imm += insn->imm;
1571 	else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1572 		 src_reg->type == CONST_IMM)
1573 		dst_reg->imm += src_reg->imm;
1574 	else
1575 		mark_reg_unknown_value(regs, insn->dst_reg);
1576 	return 0;
1577 }
1578 
check_reg_overflow(struct bpf_reg_state * reg)1579 static void check_reg_overflow(struct bpf_reg_state *reg)
1580 {
1581 	if (reg->max_value > BPF_REGISTER_MAX_RANGE)
1582 		reg->max_value = BPF_REGISTER_MAX_RANGE;
1583 	if (reg->min_value < BPF_REGISTER_MIN_RANGE ||
1584 	    reg->min_value > BPF_REGISTER_MAX_RANGE)
1585 		reg->min_value = BPF_REGISTER_MIN_RANGE;
1586 }
1587 
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)1588 static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
1589 				    struct bpf_insn *insn)
1590 {
1591 	struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1592 	s64 min_val = BPF_REGISTER_MIN_RANGE;
1593 	u64 max_val = BPF_REGISTER_MAX_RANGE;
1594 	bool min_set = false, max_set = false;
1595 	u8 opcode = BPF_OP(insn->code);
1596 
1597 	dst_reg = &regs[insn->dst_reg];
1598 	if (BPF_SRC(insn->code) == BPF_X) {
1599 		check_reg_overflow(&regs[insn->src_reg]);
1600 		min_val = regs[insn->src_reg].min_value;
1601 		max_val = regs[insn->src_reg].max_value;
1602 
1603 		/* If the source register is a random pointer then the
1604 		 * min_value/max_value values represent the range of the known
1605 		 * accesses into that value, not the actual min/max value of the
1606 		 * register itself.  In this case we have to reset the reg range
1607 		 * values so we know it is not safe to look at.
1608 		 */
1609 		if (regs[insn->src_reg].type != CONST_IMM &&
1610 		    regs[insn->src_reg].type != UNKNOWN_VALUE) {
1611 			min_val = BPF_REGISTER_MIN_RANGE;
1612 			max_val = BPF_REGISTER_MAX_RANGE;
1613 		}
1614 	} else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
1615 		   (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
1616 		min_val = max_val = insn->imm;
1617 		min_set = max_set = true;
1618 	}
1619 
1620 	/* We don't know anything about what was done to this register, mark it
1621 	 * as unknown. Also, if both derived bounds came from signed/unsigned
1622 	 * mixed compares and one side is unbounded, we cannot really do anything
1623 	 * with them as boundaries cannot be trusted. Thus, arithmetic of two
1624 	 * regs of such kind will get invalidated bounds on the dst side.
1625 	 */
1626 	if ((min_val == BPF_REGISTER_MIN_RANGE &&
1627 	     max_val == BPF_REGISTER_MAX_RANGE) ||
1628 	    (BPF_SRC(insn->code) == BPF_X &&
1629 	     ((min_val != BPF_REGISTER_MIN_RANGE &&
1630 	       max_val == BPF_REGISTER_MAX_RANGE) ||
1631 	      (min_val == BPF_REGISTER_MIN_RANGE &&
1632 	       max_val != BPF_REGISTER_MAX_RANGE) ||
1633 	      (dst_reg->min_value != BPF_REGISTER_MIN_RANGE &&
1634 	       dst_reg->max_value == BPF_REGISTER_MAX_RANGE) ||
1635 	      (dst_reg->min_value == BPF_REGISTER_MIN_RANGE &&
1636 	       dst_reg->max_value != BPF_REGISTER_MAX_RANGE)) &&
1637 	     regs[insn->dst_reg].value_from_signed !=
1638 	     regs[insn->src_reg].value_from_signed)) {
1639 		reset_reg_range_values(regs, insn->dst_reg);
1640 		return;
1641 	}
1642 
1643 	/* If one of our values was at the end of our ranges then we can't just
1644 	 * do our normal operations to the register, we need to set the values
1645 	 * to the min/max since they are undefined.
1646 	 */
1647 	if (opcode != BPF_SUB) {
1648 		if (min_val == BPF_REGISTER_MIN_RANGE)
1649 			dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1650 		if (max_val == BPF_REGISTER_MAX_RANGE)
1651 			dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1652 	}
1653 
1654 	switch (opcode) {
1655 	case BPF_ADD:
1656 		if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1657 			dst_reg->min_value += min_val;
1658 		if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1659 			dst_reg->max_value += max_val;
1660 		break;
1661 	case BPF_SUB:
1662 		/* If one of our values was at the end of our ranges, then the
1663 		 * _opposite_ value in the dst_reg goes to the end of our range.
1664 		 */
1665 		if (min_val == BPF_REGISTER_MIN_RANGE)
1666 			dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1667 		if (max_val == BPF_REGISTER_MAX_RANGE)
1668 			dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1669 		if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1670 			dst_reg->min_value -= max_val;
1671 		if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1672 			dst_reg->max_value -= min_val;
1673 		break;
1674 	case BPF_MUL:
1675 		if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1676 			dst_reg->min_value *= min_val;
1677 		if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1678 			dst_reg->max_value *= max_val;
1679 		break;
1680 	case BPF_AND:
1681 		/* Disallow AND'ing of negative numbers, ain't nobody got time
1682 		 * for that.  Otherwise the minimum is 0 and the max is the max
1683 		 * value we could AND against.
1684 		 */
1685 		if (min_val < 0)
1686 			dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1687 		else
1688 			dst_reg->min_value = 0;
1689 		dst_reg->max_value = max_val;
1690 		break;
1691 	case BPF_LSH:
1692 		/* Gotta have special overflow logic here, if we're shifting
1693 		 * more than MAX_RANGE then just assume we have an invalid
1694 		 * range.
1695 		 */
1696 		if (min_val > ilog2(BPF_REGISTER_MAX_RANGE))
1697 			dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1698 		else if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1699 			dst_reg->min_value <<= min_val;
1700 
1701 		if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
1702 			dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1703 		else if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1704 			dst_reg->max_value <<= max_val;
1705 		break;
1706 	case BPF_RSH:
1707 		/* RSH by a negative number is undefined, and the BPF_RSH is an
1708 		 * unsigned shift, so make the appropriate casts.
1709 		 */
1710 		if (min_val < 0 || dst_reg->min_value < 0)
1711 			dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1712 		else
1713 			dst_reg->min_value =
1714 				(u64)(dst_reg->min_value) >> min_val;
1715 		if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1716 			dst_reg->max_value >>= max_val;
1717 		break;
1718 	default:
1719 		reset_reg_range_values(regs, insn->dst_reg);
1720 		break;
1721 	}
1722 
1723 	check_reg_overflow(dst_reg);
1724 }
1725 
1726 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)1727 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
1728 {
1729 	struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1730 	u8 opcode = BPF_OP(insn->code);
1731 	int err;
1732 
1733 	if (opcode == BPF_END || opcode == BPF_NEG) {
1734 		if (opcode == BPF_NEG) {
1735 			if (BPF_SRC(insn->code) != 0 ||
1736 			    insn->src_reg != BPF_REG_0 ||
1737 			    insn->off != 0 || insn->imm != 0) {
1738 				verbose("BPF_NEG uses reserved fields\n");
1739 				return -EINVAL;
1740 			}
1741 		} else {
1742 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1743 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
1744 			    BPF_CLASS(insn->code) == BPF_ALU64) {
1745 				verbose("BPF_END uses reserved fields\n");
1746 				return -EINVAL;
1747 			}
1748 		}
1749 
1750 		/* check src operand */
1751 		err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1752 		if (err)
1753 			return err;
1754 
1755 		if (is_pointer_value(env, insn->dst_reg)) {
1756 			verbose("R%d pointer arithmetic prohibited\n",
1757 				insn->dst_reg);
1758 			return -EACCES;
1759 		}
1760 
1761 		/* check dest operand */
1762 		err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1763 		if (err)
1764 			return err;
1765 
1766 	} else if (opcode == BPF_MOV) {
1767 
1768 		if (BPF_SRC(insn->code) == BPF_X) {
1769 			if (insn->imm != 0 || insn->off != 0) {
1770 				verbose("BPF_MOV uses reserved fields\n");
1771 				return -EINVAL;
1772 			}
1773 
1774 			/* check src operand */
1775 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1776 			if (err)
1777 				return err;
1778 		} else {
1779 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1780 				verbose("BPF_MOV uses reserved fields\n");
1781 				return -EINVAL;
1782 			}
1783 		}
1784 
1785 		/* check dest operand */
1786 		err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1787 		if (err)
1788 			return err;
1789 
1790 		/* we are setting our register to something new, we need to
1791 		 * reset its range values.
1792 		 */
1793 		reset_reg_range_values(regs, insn->dst_reg);
1794 
1795 		if (BPF_SRC(insn->code) == BPF_X) {
1796 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
1797 				/* case: R1 = R2
1798 				 * copy register state to dest reg
1799 				 */
1800 				regs[insn->dst_reg] = regs[insn->src_reg];
1801 			} else {
1802 				if (is_pointer_value(env, insn->src_reg)) {
1803 					verbose("R%d partial copy of pointer\n",
1804 						insn->src_reg);
1805 					return -EACCES;
1806 				}
1807 				mark_reg_unknown_value(regs, insn->dst_reg);
1808 			}
1809 		} else {
1810 			/* case: R = imm
1811 			 * remember the value we stored into this reg
1812 			 */
1813 			u64 imm;
1814 
1815 			if (BPF_CLASS(insn->code) == BPF_ALU64)
1816 				imm = insn->imm;
1817 			else
1818 				imm = (u32)insn->imm;
1819 
1820 			regs[insn->dst_reg].type = CONST_IMM;
1821 			regs[insn->dst_reg].imm = imm;
1822 			regs[insn->dst_reg].max_value = imm;
1823 			regs[insn->dst_reg].min_value = imm;
1824 		}
1825 
1826 	} else if (opcode > BPF_END) {
1827 		verbose("invalid BPF_ALU opcode %x\n", opcode);
1828 		return -EINVAL;
1829 
1830 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
1831 
1832 		if (BPF_SRC(insn->code) == BPF_X) {
1833 			if (insn->imm != 0 || insn->off != 0) {
1834 				verbose("BPF_ALU uses reserved fields\n");
1835 				return -EINVAL;
1836 			}
1837 			/* check src1 operand */
1838 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1839 			if (err)
1840 				return err;
1841 		} else {
1842 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1843 				verbose("BPF_ALU uses reserved fields\n");
1844 				return -EINVAL;
1845 			}
1846 		}
1847 
1848 		/* check src2 operand */
1849 		err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1850 		if (err)
1851 			return err;
1852 
1853 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1854 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1855 			verbose("div by zero\n");
1856 			return -EINVAL;
1857 		}
1858 
1859 		if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
1860 			verbose("BPF_ARSH not supported for 32 bit ALU\n");
1861 			return -EINVAL;
1862 		}
1863 
1864 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1865 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1866 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1867 
1868 			if (insn->imm < 0 || insn->imm >= size) {
1869 				verbose("invalid shift %d\n", insn->imm);
1870 				return -EINVAL;
1871 			}
1872 		}
1873 
1874 		/* check dest operand */
1875 		err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1876 		if (err)
1877 			return err;
1878 
1879 		dst_reg = &regs[insn->dst_reg];
1880 
1881 		/* first we want to adjust our ranges. */
1882 		adjust_reg_min_max_vals(env, insn);
1883 
1884 		/* pattern match 'bpf_add Rx, imm' instruction */
1885 		if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1886 		    dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1887 			dst_reg->type = PTR_TO_STACK;
1888 			dst_reg->imm = insn->imm;
1889 			return 0;
1890 		} else if (opcode == BPF_ADD &&
1891 			   BPF_CLASS(insn->code) == BPF_ALU64 &&
1892 			   dst_reg->type == PTR_TO_STACK &&
1893 			   ((BPF_SRC(insn->code) == BPF_X &&
1894 			     regs[insn->src_reg].type == CONST_IMM) ||
1895 			    BPF_SRC(insn->code) == BPF_K)) {
1896 			if (BPF_SRC(insn->code) == BPF_X) {
1897 				/* check in case the register contains a big
1898 				 * 64-bit value
1899 				 */
1900 				if (regs[insn->src_reg].imm < -MAX_BPF_STACK ||
1901 				    regs[insn->src_reg].imm > MAX_BPF_STACK) {
1902 					verbose("R%d value too big in R%d pointer arithmetic\n",
1903 						insn->src_reg, insn->dst_reg);
1904 					return -EACCES;
1905 				}
1906 				dst_reg->imm += regs[insn->src_reg].imm;
1907 			} else {
1908 				/* safe against overflow: addition of 32-bit
1909 				 * numbers in 64-bit representation
1910 				 */
1911 				dst_reg->imm += insn->imm;
1912 			}
1913 			if (dst_reg->imm > 0 || dst_reg->imm < -MAX_BPF_STACK) {
1914 				verbose("R%d out-of-bounds pointer arithmetic\n",
1915 					insn->dst_reg);
1916 				return -EACCES;
1917 			}
1918 			return 0;
1919 		} else if (opcode == BPF_ADD &&
1920 			   BPF_CLASS(insn->code) == BPF_ALU64 &&
1921 			   (dst_reg->type == PTR_TO_PACKET ||
1922 			    (BPF_SRC(insn->code) == BPF_X &&
1923 			     regs[insn->src_reg].type == PTR_TO_PACKET))) {
1924 			/* ptr_to_packet += K|X */
1925 			return check_packet_ptr_add(env, insn);
1926 		} else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1927 			   dst_reg->type == UNKNOWN_VALUE &&
1928 			   env->allow_ptr_leaks) {
1929 			/* unknown += K|X */
1930 			return evaluate_reg_alu(env, insn);
1931 		} else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1932 			   dst_reg->type == CONST_IMM &&
1933 			   env->allow_ptr_leaks) {
1934 			/* reg_imm += K|X */
1935 			return evaluate_reg_imm_alu(env, insn);
1936 		} else if (is_pointer_value(env, insn->dst_reg)) {
1937 			verbose("R%d pointer arithmetic prohibited\n",
1938 				insn->dst_reg);
1939 			return -EACCES;
1940 		} else if (BPF_SRC(insn->code) == BPF_X &&
1941 			   is_pointer_value(env, insn->src_reg)) {
1942 			verbose("R%d pointer arithmetic prohibited\n",
1943 				insn->src_reg);
1944 			return -EACCES;
1945 		}
1946 
1947 		/* If we did pointer math on a map value then just set it to our
1948 		 * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
1949 		 * loads to this register appropriately, otherwise just mark the
1950 		 * register as unknown.
1951 		 */
1952 		if (env->allow_ptr_leaks &&
1953 		    BPF_CLASS(insn->code) == BPF_ALU64 && opcode == BPF_ADD &&
1954 		    (dst_reg->type == PTR_TO_MAP_VALUE ||
1955 		     dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
1956 			dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
1957 		else
1958 			mark_reg_unknown_value(regs, insn->dst_reg);
1959 	}
1960 
1961 	return 0;
1962 }
1963 
find_good_pkt_pointers(struct bpf_verifier_state * state,struct bpf_reg_state * dst_reg)1964 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
1965 				   struct bpf_reg_state *dst_reg)
1966 {
1967 	struct bpf_reg_state *regs = state->regs, *reg;
1968 	int i;
1969 
1970 	/* LLVM can generate two kind of checks:
1971 	 *
1972 	 * Type 1:
1973 	 *
1974 	 *   r2 = r3;
1975 	 *   r2 += 8;
1976 	 *   if (r2 > pkt_end) goto <handle exception>
1977 	 *   <access okay>
1978 	 *
1979 	 *   Where:
1980 	 *     r2 == dst_reg, pkt_end == src_reg
1981 	 *     r2=pkt(id=n,off=8,r=0)
1982 	 *     r3=pkt(id=n,off=0,r=0)
1983 	 *
1984 	 * Type 2:
1985 	 *
1986 	 *   r2 = r3;
1987 	 *   r2 += 8;
1988 	 *   if (pkt_end >= r2) goto <access okay>
1989 	 *   <handle exception>
1990 	 *
1991 	 *   Where:
1992 	 *     pkt_end == dst_reg, r2 == src_reg
1993 	 *     r2=pkt(id=n,off=8,r=0)
1994 	 *     r3=pkt(id=n,off=0,r=0)
1995 	 *
1996 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1997 	 * so that range of bytes [r3, r3 + 8) is safe to access.
1998 	 */
1999 
2000 	for (i = 0; i < MAX_BPF_REG; i++)
2001 		if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
2002 			/* keep the maximum range already checked */
2003 			regs[i].range = max(regs[i].range, dst_reg->off);
2004 
2005 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2006 		if (state->stack_slot_type[i] != STACK_SPILL)
2007 			continue;
2008 		reg = &state->spilled_regs[i / BPF_REG_SIZE];
2009 		if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
2010 			reg->range = max(reg->range, dst_reg->off);
2011 	}
2012 }
2013 
2014 /* Adjusts the register min/max values in the case that the dst_reg is the
2015  * variable register that we are working on, and src_reg is a constant or we're
2016  * simply doing a BPF_K check.
2017  */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode)2018 static void reg_set_min_max(struct bpf_reg_state *true_reg,
2019 			    struct bpf_reg_state *false_reg, u64 val,
2020 			    u8 opcode)
2021 {
2022 	bool value_from_signed = true;
2023 	bool is_range = true;
2024 
2025 	switch (opcode) {
2026 	case BPF_JEQ:
2027 		/* If this is false then we know nothing Jon Snow, but if it is
2028 		 * true then we know for sure.
2029 		 */
2030 		true_reg->max_value = true_reg->min_value = val;
2031 		is_range = false;
2032 		break;
2033 	case BPF_JNE:
2034 		/* If this is true we know nothing Jon Snow, but if it is false
2035 		 * we know the value for sure;
2036 		 */
2037 		false_reg->max_value = false_reg->min_value = val;
2038 		is_range = false;
2039 		break;
2040 	case BPF_JGT:
2041 		value_from_signed = false;
2042 		/* fallthrough */
2043 	case BPF_JSGT:
2044 		if (true_reg->value_from_signed != value_from_signed)
2045 			reset_reg_range_values(true_reg, 0);
2046 		if (false_reg->value_from_signed != value_from_signed)
2047 			reset_reg_range_values(false_reg, 0);
2048 		if (opcode == BPF_JGT) {
2049 			/* Unsigned comparison, the minimum value is 0. */
2050 			false_reg->min_value = 0;
2051 		}
2052 		/* If this is false then we know the maximum val is val,
2053 		 * otherwise we know the min val is val+1.
2054 		 */
2055 		false_reg->max_value = val;
2056 		false_reg->value_from_signed = value_from_signed;
2057 		true_reg->min_value = val + 1;
2058 		true_reg->value_from_signed = value_from_signed;
2059 		break;
2060 	case BPF_JGE:
2061 		value_from_signed = false;
2062 		/* fallthrough */
2063 	case BPF_JSGE:
2064 		if (true_reg->value_from_signed != value_from_signed)
2065 			reset_reg_range_values(true_reg, 0);
2066 		if (false_reg->value_from_signed != value_from_signed)
2067 			reset_reg_range_values(false_reg, 0);
2068 		if (opcode == BPF_JGE) {
2069 			/* Unsigned comparison, the minimum value is 0. */
2070 			false_reg->min_value = 0;
2071 		}
2072 		/* If this is false then we know the maximum value is val - 1,
2073 		 * otherwise we know the mimimum value is val.
2074 		 */
2075 		false_reg->max_value = val - 1;
2076 		false_reg->value_from_signed = value_from_signed;
2077 		true_reg->min_value = val;
2078 		true_reg->value_from_signed = value_from_signed;
2079 		break;
2080 	default:
2081 		break;
2082 	}
2083 
2084 	check_reg_overflow(false_reg);
2085 	check_reg_overflow(true_reg);
2086 	if (is_range) {
2087 		if (__is_pointer_value(false, false_reg))
2088 			reset_reg_range_values(false_reg, 0);
2089 		if (__is_pointer_value(false, true_reg))
2090 			reset_reg_range_values(true_reg, 0);
2091 	}
2092 }
2093 
2094 /* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
2095  * is the variable reg.
2096  */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode)2097 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
2098 				struct bpf_reg_state *false_reg, u64 val,
2099 				u8 opcode)
2100 {
2101 	bool value_from_signed = true;
2102 	bool is_range = true;
2103 
2104 	switch (opcode) {
2105 	case BPF_JEQ:
2106 		/* If this is false then we know nothing Jon Snow, but if it is
2107 		 * true then we know for sure.
2108 		 */
2109 		true_reg->max_value = true_reg->min_value = val;
2110 		is_range = false;
2111 		break;
2112 	case BPF_JNE:
2113 		/* If this is true we know nothing Jon Snow, but if it is false
2114 		 * we know the value for sure;
2115 		 */
2116 		false_reg->max_value = false_reg->min_value = val;
2117 		is_range = false;
2118 		break;
2119 	case BPF_JGT:
2120 		value_from_signed = false;
2121 		/* fallthrough */
2122 	case BPF_JSGT:
2123 		if (true_reg->value_from_signed != value_from_signed)
2124 			reset_reg_range_values(true_reg, 0);
2125 		if (false_reg->value_from_signed != value_from_signed)
2126 			reset_reg_range_values(false_reg, 0);
2127 		if (opcode == BPF_JGT) {
2128 			/* Unsigned comparison, the minimum value is 0. */
2129 			true_reg->min_value = 0;
2130 		}
2131 		/*
2132 		 * If this is false, then the val is <= the register, if it is
2133 		 * true the register <= to the val.
2134 		 */
2135 		false_reg->min_value = val;
2136 		false_reg->value_from_signed = value_from_signed;
2137 		true_reg->max_value = val - 1;
2138 		true_reg->value_from_signed = value_from_signed;
2139 		break;
2140 	case BPF_JGE:
2141 		value_from_signed = false;
2142 		/* fallthrough */
2143 	case BPF_JSGE:
2144 		if (true_reg->value_from_signed != value_from_signed)
2145 			reset_reg_range_values(true_reg, 0);
2146 		if (false_reg->value_from_signed != value_from_signed)
2147 			reset_reg_range_values(false_reg, 0);
2148 		if (opcode == BPF_JGE) {
2149 			/* Unsigned comparison, the minimum value is 0. */
2150 			true_reg->min_value = 0;
2151 		}
2152 		/* If this is false then constant < register, if it is true then
2153 		 * the register < constant.
2154 		 */
2155 		false_reg->min_value = val + 1;
2156 		false_reg->value_from_signed = value_from_signed;
2157 		true_reg->max_value = val;
2158 		true_reg->value_from_signed = value_from_signed;
2159 		break;
2160 	default:
2161 		break;
2162 	}
2163 
2164 	check_reg_overflow(false_reg);
2165 	check_reg_overflow(true_reg);
2166 	if (is_range) {
2167 		if (__is_pointer_value(false, false_reg))
2168 			reset_reg_range_values(false_reg, 0);
2169 		if (__is_pointer_value(false, true_reg))
2170 			reset_reg_range_values(true_reg, 0);
2171 	}
2172 }
2173 
mark_map_reg(struct bpf_reg_state * regs,u32 regno,u32 id,enum bpf_reg_type type)2174 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
2175 			 enum bpf_reg_type type)
2176 {
2177 	struct bpf_reg_state *reg = &regs[regno];
2178 
2179 	if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
2180 		reg->type = type;
2181 		/* We don't need id from this point onwards anymore, thus we
2182 		 * should better reset it, so that state pruning has chances
2183 		 * to take effect.
2184 		 */
2185 		reg->id = 0;
2186 		if (type == UNKNOWN_VALUE)
2187 			__mark_reg_unknown_value(regs, regno);
2188 	}
2189 }
2190 
2191 /* The logic is similar to find_good_pkt_pointers(), both could eventually
2192  * be folded together at some point.
2193  */
mark_map_regs(struct bpf_verifier_state * state,u32 regno,enum bpf_reg_type type)2194 static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
2195 			  enum bpf_reg_type type)
2196 {
2197 	struct bpf_reg_state *regs = state->regs;
2198 	u32 id = regs[regno].id;
2199 	int i;
2200 
2201 	for (i = 0; i < MAX_BPF_REG; i++)
2202 		mark_map_reg(regs, i, id, type);
2203 
2204 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2205 		if (state->stack_slot_type[i] != STACK_SPILL)
2206 			continue;
2207 		mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, type);
2208 	}
2209 }
2210 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)2211 static int check_cond_jmp_op(struct bpf_verifier_env *env,
2212 			     struct bpf_insn *insn, int *insn_idx)
2213 {
2214 	struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
2215 	struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
2216 	u8 opcode = BPF_OP(insn->code);
2217 	int err;
2218 
2219 	if (opcode > BPF_EXIT) {
2220 		verbose("invalid BPF_JMP opcode %x\n", opcode);
2221 		return -EINVAL;
2222 	}
2223 
2224 	if (BPF_SRC(insn->code) == BPF_X) {
2225 		if (insn->imm != 0) {
2226 			verbose("BPF_JMP uses reserved fields\n");
2227 			return -EINVAL;
2228 		}
2229 
2230 		/* check src1 operand */
2231 		err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2232 		if (err)
2233 			return err;
2234 
2235 		if (is_pointer_value(env, insn->src_reg)) {
2236 			verbose("R%d pointer comparison prohibited\n",
2237 				insn->src_reg);
2238 			return -EACCES;
2239 		}
2240 	} else {
2241 		if (insn->src_reg != BPF_REG_0) {
2242 			verbose("BPF_JMP uses reserved fields\n");
2243 			return -EINVAL;
2244 		}
2245 	}
2246 
2247 	/* check src2 operand */
2248 	err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2249 	if (err)
2250 		return err;
2251 
2252 	dst_reg = &regs[insn->dst_reg];
2253 
2254 	/* detect if R == 0 where R was initialized to zero earlier */
2255 	if (BPF_SRC(insn->code) == BPF_K &&
2256 	    (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2257 	    dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
2258 		if (opcode == BPF_JEQ) {
2259 			/* if (imm == imm) goto pc+off;
2260 			 * only follow the goto, ignore fall-through
2261 			 */
2262 			*insn_idx += insn->off;
2263 			return 0;
2264 		} else {
2265 			/* if (imm != imm) goto pc+off;
2266 			 * only follow fall-through branch, since
2267 			 * that's where the program will go
2268 			 */
2269 			return 0;
2270 		}
2271 	}
2272 
2273 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
2274 	if (!other_branch)
2275 		return -EFAULT;
2276 
2277 	/* detect if we are comparing against a constant value so we can adjust
2278 	 * our min/max values for our dst register.
2279 	 */
2280 	if (BPF_SRC(insn->code) == BPF_X) {
2281 		if (regs[insn->src_reg].type == CONST_IMM)
2282 			reg_set_min_max(&other_branch->regs[insn->dst_reg],
2283 					dst_reg, regs[insn->src_reg].imm,
2284 					opcode);
2285 		else if (dst_reg->type == CONST_IMM)
2286 			reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
2287 					    &regs[insn->src_reg], dst_reg->imm,
2288 					    opcode);
2289 	} else {
2290 		reg_set_min_max(&other_branch->regs[insn->dst_reg],
2291 					dst_reg, insn->imm, opcode);
2292 	}
2293 
2294 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
2295 	if (BPF_SRC(insn->code) == BPF_K &&
2296 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2297 	    dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2298 		/* Mark all identical map registers in each branch as either
2299 		 * safe or unknown depending R == 0 or R != 0 conditional.
2300 		 */
2301 		mark_map_regs(this_branch, insn->dst_reg,
2302 			      opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE);
2303 		mark_map_regs(other_branch, insn->dst_reg,
2304 			      opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE);
2305 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2306 		   dst_reg->type == PTR_TO_PACKET &&
2307 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
2308 		find_good_pkt_pointers(this_branch, dst_reg);
2309 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2310 		   dst_reg->type == PTR_TO_PACKET_END &&
2311 		   regs[insn->src_reg].type == PTR_TO_PACKET) {
2312 		find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
2313 	} else if (is_pointer_value(env, insn->dst_reg)) {
2314 		verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
2315 		return -EACCES;
2316 	}
2317 	if (log_level)
2318 		print_verifier_state(this_branch);
2319 	return 0;
2320 }
2321 
2322 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
ld_imm64_to_map_ptr(struct bpf_insn * insn)2323 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2324 {
2325 	u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2326 
2327 	return (struct bpf_map *) (unsigned long) imm64;
2328 }
2329 
2330 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)2331 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
2332 {
2333 	struct bpf_reg_state *regs = env->cur_state.regs;
2334 	int err;
2335 
2336 	if (BPF_SIZE(insn->code) != BPF_DW) {
2337 		verbose("invalid BPF_LD_IMM insn\n");
2338 		return -EINVAL;
2339 	}
2340 	if (insn->off != 0) {
2341 		verbose("BPF_LD_IMM64 uses reserved fields\n");
2342 		return -EINVAL;
2343 	}
2344 
2345 	err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2346 	if (err)
2347 		return err;
2348 
2349 	if (insn->src_reg == 0) {
2350 		/* generic move 64-bit immediate into a register,
2351 		 * only analyzer needs to collect the ld_imm value.
2352 		 */
2353 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
2354 
2355 		if (!env->analyzer_ops)
2356 			return 0;
2357 
2358 		regs[insn->dst_reg].type = CONST_IMM;
2359 		regs[insn->dst_reg].imm = imm;
2360 		return 0;
2361 	}
2362 
2363 	/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
2364 	BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
2365 
2366 	regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
2367 	regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
2368 	return 0;
2369 }
2370 
may_access_skb(enum bpf_prog_type type)2371 static bool may_access_skb(enum bpf_prog_type type)
2372 {
2373 	switch (type) {
2374 	case BPF_PROG_TYPE_SOCKET_FILTER:
2375 	case BPF_PROG_TYPE_SCHED_CLS:
2376 	case BPF_PROG_TYPE_SCHED_ACT:
2377 		return true;
2378 	default:
2379 		return false;
2380 	}
2381 }
2382 
2383 /* verify safety of LD_ABS|LD_IND instructions:
2384  * - they can only appear in the programs where ctx == skb
2385  * - since they are wrappers of function calls, they scratch R1-R5 registers,
2386  *   preserve R6-R9, and store return value into R0
2387  *
2388  * Implicit input:
2389  *   ctx == skb == R6 == CTX
2390  *
2391  * Explicit input:
2392  *   SRC == any register
2393  *   IMM == 32-bit immediate
2394  *
2395  * Output:
2396  *   R0 - 8/16/32-bit skb data converted to cpu endianness
2397  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)2398 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
2399 {
2400 	struct bpf_reg_state *regs = env->cur_state.regs;
2401 	u8 mode = BPF_MODE(insn->code);
2402 	struct bpf_reg_state *reg;
2403 	int i, err;
2404 
2405 	if (!may_access_skb(env->prog->type)) {
2406 		verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
2407 		return -EINVAL;
2408 	}
2409 
2410 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
2411 	    BPF_SIZE(insn->code) == BPF_DW ||
2412 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
2413 		verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
2414 		return -EINVAL;
2415 	}
2416 
2417 	/* check whether implicit source operand (register R6) is readable */
2418 	err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
2419 	if (err)
2420 		return err;
2421 
2422 	if (regs[BPF_REG_6].type != PTR_TO_CTX) {
2423 		verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
2424 		return -EINVAL;
2425 	}
2426 
2427 	if (mode == BPF_IND) {
2428 		/* check explicit source operand */
2429 		err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2430 		if (err)
2431 			return err;
2432 	}
2433 
2434 	/* reset caller saved regs to unreadable */
2435 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
2436 		reg = regs + caller_saved[i];
2437 		reg->type = NOT_INIT;
2438 		reg->imm = 0;
2439 	}
2440 
2441 	/* mark destination R0 register as readable, since it contains
2442 	 * the value fetched from the packet
2443 	 */
2444 	regs[BPF_REG_0].type = UNKNOWN_VALUE;
2445 	return 0;
2446 }
2447 
2448 /* non-recursive DFS pseudo code
2449  * 1  procedure DFS-iterative(G,v):
2450  * 2      label v as discovered
2451  * 3      let S be a stack
2452  * 4      S.push(v)
2453  * 5      while S is not empty
2454  * 6            t <- S.pop()
2455  * 7            if t is what we're looking for:
2456  * 8                return t
2457  * 9            for all edges e in G.adjacentEdges(t) do
2458  * 10               if edge e is already labelled
2459  * 11                   continue with the next edge
2460  * 12               w <- G.adjacentVertex(t,e)
2461  * 13               if vertex w is not discovered and not explored
2462  * 14                   label e as tree-edge
2463  * 15                   label w as discovered
2464  * 16                   S.push(w)
2465  * 17                   continue at 5
2466  * 18               else if vertex w is discovered
2467  * 19                   label e as back-edge
2468  * 20               else
2469  * 21                   // vertex w is explored
2470  * 22                   label e as forward- or cross-edge
2471  * 23           label t as explored
2472  * 24           S.pop()
2473  *
2474  * convention:
2475  * 0x10 - discovered
2476  * 0x11 - discovered and fall-through edge labelled
2477  * 0x12 - discovered and fall-through and branch edges labelled
2478  * 0x20 - explored
2479  */
2480 
2481 enum {
2482 	DISCOVERED = 0x10,
2483 	EXPLORED = 0x20,
2484 	FALLTHROUGH = 1,
2485 	BRANCH = 2,
2486 };
2487 
2488 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
2489 
2490 static int *insn_stack;	/* stack of insns to process */
2491 static int cur_stack;	/* current stack index */
2492 static int *insn_state;
2493 
2494 /* t, w, e - match pseudo-code above:
2495  * t - index of current instruction
2496  * w - next instruction
2497  * e - edge
2498  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)2499 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
2500 {
2501 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
2502 		return 0;
2503 
2504 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
2505 		return 0;
2506 
2507 	if (w < 0 || w >= env->prog->len) {
2508 		verbose("jump out of range from insn %d to %d\n", t, w);
2509 		return -EINVAL;
2510 	}
2511 
2512 	if (e == BRANCH)
2513 		/* mark branch target for state pruning */
2514 		env->explored_states[w] = STATE_LIST_MARK;
2515 
2516 	if (insn_state[w] == 0) {
2517 		/* tree-edge */
2518 		insn_state[t] = DISCOVERED | e;
2519 		insn_state[w] = DISCOVERED;
2520 		if (cur_stack >= env->prog->len)
2521 			return -E2BIG;
2522 		insn_stack[cur_stack++] = w;
2523 		return 1;
2524 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2525 		verbose("back-edge from insn %d to %d\n", t, w);
2526 		return -EINVAL;
2527 	} else if (insn_state[w] == EXPLORED) {
2528 		/* forward- or cross-edge */
2529 		insn_state[t] = DISCOVERED | e;
2530 	} else {
2531 		verbose("insn state internal bug\n");
2532 		return -EFAULT;
2533 	}
2534 	return 0;
2535 }
2536 
2537 /* non-recursive depth-first-search to detect loops in BPF program
2538  * loop == back-edge in directed graph
2539  */
check_cfg(struct bpf_verifier_env * env)2540 static int check_cfg(struct bpf_verifier_env *env)
2541 {
2542 	struct bpf_insn *insns = env->prog->insnsi;
2543 	int insn_cnt = env->prog->len;
2544 	int ret = 0;
2545 	int i, t;
2546 
2547 	insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2548 	if (!insn_state)
2549 		return -ENOMEM;
2550 
2551 	insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2552 	if (!insn_stack) {
2553 		kfree(insn_state);
2554 		return -ENOMEM;
2555 	}
2556 
2557 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
2558 	insn_stack[0] = 0; /* 0 is the first instruction */
2559 	cur_stack = 1;
2560 
2561 peek_stack:
2562 	if (cur_stack == 0)
2563 		goto check_state;
2564 	t = insn_stack[cur_stack - 1];
2565 
2566 	if (BPF_CLASS(insns[t].code) == BPF_JMP) {
2567 		u8 opcode = BPF_OP(insns[t].code);
2568 
2569 		if (opcode == BPF_EXIT) {
2570 			goto mark_explored;
2571 		} else if (opcode == BPF_CALL) {
2572 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
2573 			if (ret == 1)
2574 				goto peek_stack;
2575 			else if (ret < 0)
2576 				goto err_free;
2577 			if (t + 1 < insn_cnt)
2578 				env->explored_states[t + 1] = STATE_LIST_MARK;
2579 		} else if (opcode == BPF_JA) {
2580 			if (BPF_SRC(insns[t].code) != BPF_K) {
2581 				ret = -EINVAL;
2582 				goto err_free;
2583 			}
2584 			/* unconditional jump with single edge */
2585 			ret = push_insn(t, t + insns[t].off + 1,
2586 					FALLTHROUGH, env);
2587 			if (ret == 1)
2588 				goto peek_stack;
2589 			else if (ret < 0)
2590 				goto err_free;
2591 			/* tell verifier to check for equivalent states
2592 			 * after every call and jump
2593 			 */
2594 			if (t + 1 < insn_cnt)
2595 				env->explored_states[t + 1] = STATE_LIST_MARK;
2596 		} else {
2597 			/* conditional jump with two edges */
2598 			env->explored_states[t] = STATE_LIST_MARK;
2599 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
2600 			if (ret == 1)
2601 				goto peek_stack;
2602 			else if (ret < 0)
2603 				goto err_free;
2604 
2605 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2606 			if (ret == 1)
2607 				goto peek_stack;
2608 			else if (ret < 0)
2609 				goto err_free;
2610 		}
2611 	} else {
2612 		/* all other non-branch instructions with single
2613 		 * fall-through edge
2614 		 */
2615 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
2616 		if (ret == 1)
2617 			goto peek_stack;
2618 		else if (ret < 0)
2619 			goto err_free;
2620 	}
2621 
2622 mark_explored:
2623 	insn_state[t] = EXPLORED;
2624 	if (cur_stack-- <= 0) {
2625 		verbose("pop stack internal bug\n");
2626 		ret = -EFAULT;
2627 		goto err_free;
2628 	}
2629 	goto peek_stack;
2630 
2631 check_state:
2632 	for (i = 0; i < insn_cnt; i++) {
2633 		if (insn_state[i] != EXPLORED) {
2634 			verbose("unreachable insn %d\n", i);
2635 			ret = -EINVAL;
2636 			goto err_free;
2637 		}
2638 	}
2639 	ret = 0; /* cfg looks good */
2640 
2641 err_free:
2642 	kfree(insn_state);
2643 	kfree(insn_stack);
2644 	return ret;
2645 }
2646 
2647 /* the following conditions reduce the number of explored insns
2648  * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2649  */
compare_ptrs_to_packet(struct bpf_reg_state * old,struct bpf_reg_state * cur)2650 static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
2651 				   struct bpf_reg_state *cur)
2652 {
2653 	if (old->id != cur->id)
2654 		return false;
2655 
2656 	/* old ptr_to_packet is more conservative, since it allows smaller
2657 	 * range. Ex:
2658 	 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2659 	 * old(off=0,r=10) means that with range=10 the verifier proceeded
2660 	 * further and found no issues with the program. Now we're in the same
2661 	 * spot with cur(off=0,r=20), so we're safe too, since anything further
2662 	 * will only be looking at most 10 bytes after this pointer.
2663 	 */
2664 	if (old->off == cur->off && old->range < cur->range)
2665 		return true;
2666 
2667 	/* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2668 	 * since both cannot be used for packet access and safe(old)
2669 	 * pointer has smaller off that could be used for further
2670 	 * 'if (ptr > data_end)' check
2671 	 * Ex:
2672 	 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2673 	 * that we cannot access the packet.
2674 	 * The safe range is:
2675 	 * [ptr, ptr + range - off)
2676 	 * so whenever off >=range, it means no safe bytes from this pointer.
2677 	 * When comparing old->off <= cur->off, it means that older code
2678 	 * went with smaller offset and that offset was later
2679 	 * used to figure out the safe range after 'if (ptr > data_end)' check
2680 	 * Say, 'old' state was explored like:
2681 	 * ... R3(off=0, r=0)
2682 	 * R4 = R3 + 20
2683 	 * ... now R4(off=20,r=0)  <-- here
2684 	 * if (R4 > data_end)
2685 	 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2686 	 * ... the code further went all the way to bpf_exit.
2687 	 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2688 	 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2689 	 * goes further, such cur_R4 will give larger safe packet range after
2690 	 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2691 	 * so they will be good with r=30 and we can prune the search.
2692 	 */
2693 	if (old->off <= cur->off &&
2694 	    old->off >= old->range && cur->off >= cur->range)
2695 		return true;
2696 
2697 	return false;
2698 }
2699 
2700 /* compare two verifier states
2701  *
2702  * all states stored in state_list are known to be valid, since
2703  * verifier reached 'bpf_exit' instruction through them
2704  *
2705  * this function is called when verifier exploring different branches of
2706  * execution popped from the state stack. If it sees an old state that has
2707  * more strict register state and more strict stack state then this execution
2708  * branch doesn't need to be explored further, since verifier already
2709  * concluded that more strict state leads to valid finish.
2710  *
2711  * Therefore two states are equivalent if register state is more conservative
2712  * and explored stack state is more conservative than the current one.
2713  * Example:
2714  *       explored                   current
2715  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2716  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2717  *
2718  * In other words if current stack state (one being explored) has more
2719  * valid slots than old one that already passed validation, it means
2720  * the verifier can stop exploring and conclude that current state is valid too
2721  *
2722  * Similarly with registers. If explored state has register type as invalid
2723  * whereas register type in current state is meaningful, it means that
2724  * the current state will reach 'bpf_exit' instruction safely
2725  */
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)2726 static bool states_equal(struct bpf_verifier_env *env,
2727 			 struct bpf_verifier_state *old,
2728 			 struct bpf_verifier_state *cur)
2729 {
2730 	bool varlen_map_access = env->varlen_map_value_access;
2731 	struct bpf_reg_state *rold, *rcur;
2732 	int i;
2733 
2734 	for (i = 0; i < MAX_BPF_REG; i++) {
2735 		rold = &old->regs[i];
2736 		rcur = &cur->regs[i];
2737 
2738 		if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2739 			continue;
2740 
2741 		/* If the ranges were not the same, but everything else was and
2742 		 * we didn't do a variable access into a map then we are a-ok.
2743 		 */
2744 		if (!varlen_map_access &&
2745 		    memcmp(rold, rcur, offsetofend(struct bpf_reg_state, id)) == 0)
2746 			continue;
2747 
2748 		/* If we didn't map access then again we don't care about the
2749 		 * mismatched range values and it's ok if our old type was
2750 		 * UNKNOWN and we didn't go to a NOT_INIT'ed or pointer reg.
2751 		 */
2752 		if (rold->type == NOT_INIT ||
2753 		    (!varlen_map_access && rold->type == UNKNOWN_VALUE &&
2754 		     rcur->type != NOT_INIT &&
2755 		     !__is_pointer_value(env->allow_ptr_leaks, rcur)))
2756 			continue;
2757 
2758 		/* Don't care about the reg->id in this case. */
2759 		if (rold->type == PTR_TO_MAP_VALUE_OR_NULL &&
2760 		    rcur->type == PTR_TO_MAP_VALUE_OR_NULL &&
2761 		    rold->map_ptr == rcur->map_ptr)
2762 			continue;
2763 
2764 		if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2765 		    compare_ptrs_to_packet(rold, rcur))
2766 			continue;
2767 
2768 		return false;
2769 	}
2770 
2771 	for (i = 0; i < MAX_BPF_STACK; i++) {
2772 		if (old->stack_slot_type[i] == STACK_INVALID)
2773 			continue;
2774 		if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2775 			/* Ex: old explored (safe) state has STACK_SPILL in
2776 			 * this stack slot, but current has has STACK_MISC ->
2777 			 * this verifier states are not equivalent,
2778 			 * return false to continue verification of this path
2779 			 */
2780 			return false;
2781 		if (i % BPF_REG_SIZE)
2782 			continue;
2783 		if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2784 			   &cur->spilled_regs[i / BPF_REG_SIZE],
2785 			   sizeof(old->spilled_regs[0])))
2786 			/* when explored and current stack slot types are
2787 			 * the same, check that stored pointers types
2788 			 * are the same as well.
2789 			 * Ex: explored safe path could have stored
2790 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
2791 			 * but current path has stored:
2792 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
2793 			 * such verifier states are not equivalent.
2794 			 * return false to continue verification of this path
2795 			 */
2796 			return false;
2797 		else
2798 			continue;
2799 	}
2800 	return true;
2801 }
2802 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)2803 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
2804 {
2805 	struct bpf_verifier_state_list *new_sl;
2806 	struct bpf_verifier_state_list *sl;
2807 
2808 	sl = env->explored_states[insn_idx];
2809 	if (!sl)
2810 		/* this 'insn_idx' instruction wasn't marked, so we will not
2811 		 * be doing state search here
2812 		 */
2813 		return 0;
2814 
2815 	while (sl != STATE_LIST_MARK) {
2816 		if (states_equal(env, &sl->state, &env->cur_state))
2817 			/* reached equivalent register/stack state,
2818 			 * prune the search
2819 			 */
2820 			return 1;
2821 		sl = sl->next;
2822 	}
2823 
2824 	/* there were no equivalent states, remember current one.
2825 	 * technically the current state is not proven to be safe yet,
2826 	 * but it will either reach bpf_exit (which means it's safe) or
2827 	 * it will be rejected. Since there are no loops, we won't be
2828 	 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2829 	 */
2830 	new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
2831 	if (!new_sl)
2832 		return -ENOMEM;
2833 
2834 	/* add new state to the head of linked list */
2835 	memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2836 	new_sl->next = env->explored_states[insn_idx];
2837 	env->explored_states[insn_idx] = new_sl;
2838 	return 0;
2839 }
2840 
ext_analyzer_insn_hook(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx)2841 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2842 				  int insn_idx, int prev_insn_idx)
2843 {
2844 	if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2845 		return 0;
2846 
2847 	return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2848 }
2849 
do_check(struct bpf_verifier_env * env)2850 static int do_check(struct bpf_verifier_env *env)
2851 {
2852 	struct bpf_verifier_state *state = &env->cur_state;
2853 	struct bpf_insn *insns = env->prog->insnsi;
2854 	struct bpf_reg_state *regs = state->regs;
2855 	int insn_cnt = env->prog->len;
2856 	int insn_idx, prev_insn_idx = 0;
2857 	int insn_processed = 0;
2858 	bool do_print_state = false;
2859 
2860 	init_reg_state(regs);
2861 	insn_idx = 0;
2862 	env->varlen_map_value_access = false;
2863 	for (;;) {
2864 		struct bpf_insn *insn;
2865 		u8 class;
2866 		int err;
2867 
2868 		if (insn_idx >= insn_cnt) {
2869 			verbose("invalid insn idx %d insn_cnt %d\n",
2870 				insn_idx, insn_cnt);
2871 			return -EFAULT;
2872 		}
2873 
2874 		insn = &insns[insn_idx];
2875 		class = BPF_CLASS(insn->code);
2876 
2877 		if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2878 			verbose("BPF program is too large. Proccessed %d insn\n",
2879 				insn_processed);
2880 			return -E2BIG;
2881 		}
2882 
2883 		err = is_state_visited(env, insn_idx);
2884 		if (err < 0)
2885 			return err;
2886 		if (err == 1) {
2887 			/* found equivalent state, can prune the search */
2888 			if (log_level) {
2889 				if (do_print_state)
2890 					verbose("\nfrom %d to %d: safe\n",
2891 						prev_insn_idx, insn_idx);
2892 				else
2893 					verbose("%d: safe\n", insn_idx);
2894 			}
2895 			goto process_bpf_exit;
2896 		}
2897 
2898 		if (need_resched())
2899 			cond_resched();
2900 
2901 		if (log_level && do_print_state) {
2902 			verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
2903 			print_verifier_state(&env->cur_state);
2904 			do_print_state = false;
2905 		}
2906 
2907 		if (log_level) {
2908 			verbose("%d: ", insn_idx);
2909 			print_bpf_insn(env, insn);
2910 		}
2911 
2912 		err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2913 		if (err)
2914 			return err;
2915 
2916 		env->insn_aux_data[insn_idx].seen = true;
2917 		if (class == BPF_ALU || class == BPF_ALU64) {
2918 			err = check_alu_op(env, insn);
2919 			if (err)
2920 				return err;
2921 
2922 		} else if (class == BPF_LDX) {
2923 			enum bpf_reg_type *prev_src_type, src_reg_type;
2924 
2925 			/* check for reserved fields is already done */
2926 
2927 			/* check src operand */
2928 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2929 			if (err)
2930 				return err;
2931 
2932 			err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2933 			if (err)
2934 				return err;
2935 
2936 			src_reg_type = regs[insn->src_reg].type;
2937 
2938 			/* check that memory (src_reg + off) is readable,
2939 			 * the state of dst_reg will be updated by this func
2940 			 */
2941 			err = check_mem_access(env, insn->src_reg, insn->off,
2942 					       BPF_SIZE(insn->code), BPF_READ,
2943 					       insn->dst_reg);
2944 			if (err)
2945 				return err;
2946 
2947 			reset_reg_range_values(regs, insn->dst_reg);
2948 			if (BPF_SIZE(insn->code) != BPF_W &&
2949 			    BPF_SIZE(insn->code) != BPF_DW) {
2950 				insn_idx++;
2951 				continue;
2952 			}
2953 
2954 			prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
2955 
2956 			if (*prev_src_type == NOT_INIT) {
2957 				/* saw a valid insn
2958 				 * dst_reg = *(u32 *)(src_reg + off)
2959 				 * save type to validate intersecting paths
2960 				 */
2961 				*prev_src_type = src_reg_type;
2962 
2963 			} else if (src_reg_type != *prev_src_type &&
2964 				   (src_reg_type == PTR_TO_CTX ||
2965 				    *prev_src_type == PTR_TO_CTX)) {
2966 				/* ABuser program is trying to use the same insn
2967 				 * dst_reg = *(u32*) (src_reg + off)
2968 				 * with different pointer types:
2969 				 * src_reg == ctx in one branch and
2970 				 * src_reg == stack|map in some other branch.
2971 				 * Reject it.
2972 				 */
2973 				verbose("same insn cannot be used with different pointers\n");
2974 				return -EINVAL;
2975 			}
2976 
2977 		} else if (class == BPF_STX) {
2978 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
2979 
2980 			if (BPF_MODE(insn->code) == BPF_XADD) {
2981 				err = check_xadd(env, insn);
2982 				if (err)
2983 					return err;
2984 				insn_idx++;
2985 				continue;
2986 			}
2987 
2988 			/* check src1 operand */
2989 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2990 			if (err)
2991 				return err;
2992 			/* check src2 operand */
2993 			err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2994 			if (err)
2995 				return err;
2996 
2997 			dst_reg_type = regs[insn->dst_reg].type;
2998 
2999 			/* check that memory (dst_reg + off) is writeable */
3000 			err = check_mem_access(env, insn->dst_reg, insn->off,
3001 					       BPF_SIZE(insn->code), BPF_WRITE,
3002 					       insn->src_reg);
3003 			if (err)
3004 				return err;
3005 
3006 			prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
3007 
3008 			if (*prev_dst_type == NOT_INIT) {
3009 				*prev_dst_type = dst_reg_type;
3010 			} else if (dst_reg_type != *prev_dst_type &&
3011 				   (dst_reg_type == PTR_TO_CTX ||
3012 				    *prev_dst_type == PTR_TO_CTX)) {
3013 				verbose("same insn cannot be used with different pointers\n");
3014 				return -EINVAL;
3015 			}
3016 
3017 		} else if (class == BPF_ST) {
3018 			if (BPF_MODE(insn->code) != BPF_MEM ||
3019 			    insn->src_reg != BPF_REG_0) {
3020 				verbose("BPF_ST uses reserved fields\n");
3021 				return -EINVAL;
3022 			}
3023 			/* check src operand */
3024 			err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3025 			if (err)
3026 				return err;
3027 
3028 			if (is_ctx_reg(env, insn->dst_reg)) {
3029 				verbose("BPF_ST stores into R%d context is not allowed\n",
3030 					insn->dst_reg);
3031 				return -EACCES;
3032 			}
3033 
3034 			/* check that memory (dst_reg + off) is writeable */
3035 			err = check_mem_access(env, insn->dst_reg, insn->off,
3036 					       BPF_SIZE(insn->code), BPF_WRITE,
3037 					       -1);
3038 			if (err)
3039 				return err;
3040 
3041 		} else if (class == BPF_JMP) {
3042 			u8 opcode = BPF_OP(insn->code);
3043 
3044 			if (opcode == BPF_CALL) {
3045 				if (BPF_SRC(insn->code) != BPF_K ||
3046 				    insn->off != 0 ||
3047 				    insn->src_reg != BPF_REG_0 ||
3048 				    insn->dst_reg != BPF_REG_0) {
3049 					verbose("BPF_CALL uses reserved fields\n");
3050 					return -EINVAL;
3051 				}
3052 
3053 				err = check_call(env, insn->imm, insn_idx);
3054 				if (err)
3055 					return err;
3056 
3057 			} else if (opcode == BPF_JA) {
3058 				if (BPF_SRC(insn->code) != BPF_K ||
3059 				    insn->imm != 0 ||
3060 				    insn->src_reg != BPF_REG_0 ||
3061 				    insn->dst_reg != BPF_REG_0) {
3062 					verbose("BPF_JA uses reserved fields\n");
3063 					return -EINVAL;
3064 				}
3065 
3066 				insn_idx += insn->off + 1;
3067 				continue;
3068 
3069 			} else if (opcode == BPF_EXIT) {
3070 				if (BPF_SRC(insn->code) != BPF_K ||
3071 				    insn->imm != 0 ||
3072 				    insn->src_reg != BPF_REG_0 ||
3073 				    insn->dst_reg != BPF_REG_0) {
3074 					verbose("BPF_EXIT uses reserved fields\n");
3075 					return -EINVAL;
3076 				}
3077 
3078 				/* eBPF calling convetion is such that R0 is used
3079 				 * to return the value from eBPF program.
3080 				 * Make sure that it's readable at this time
3081 				 * of bpf_exit, which means that program wrote
3082 				 * something into it earlier
3083 				 */
3084 				err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
3085 				if (err)
3086 					return err;
3087 
3088 				if (is_pointer_value(env, BPF_REG_0)) {
3089 					verbose("R0 leaks addr as return value\n");
3090 					return -EACCES;
3091 				}
3092 
3093 process_bpf_exit:
3094 				insn_idx = pop_stack(env, &prev_insn_idx);
3095 				if (insn_idx < 0) {
3096 					break;
3097 				} else {
3098 					do_print_state = true;
3099 					continue;
3100 				}
3101 			} else {
3102 				err = check_cond_jmp_op(env, insn, &insn_idx);
3103 				if (err)
3104 					return err;
3105 			}
3106 		} else if (class == BPF_LD) {
3107 			u8 mode = BPF_MODE(insn->code);
3108 
3109 			if (mode == BPF_ABS || mode == BPF_IND) {
3110 				err = check_ld_abs(env, insn);
3111 				if (err)
3112 					return err;
3113 
3114 			} else if (mode == BPF_IMM) {
3115 				err = check_ld_imm(env, insn);
3116 				if (err)
3117 					return err;
3118 
3119 				insn_idx++;
3120 				env->insn_aux_data[insn_idx].seen = true;
3121 			} else {
3122 				verbose("invalid BPF_LD mode\n");
3123 				return -EINVAL;
3124 			}
3125 			reset_reg_range_values(regs, insn->dst_reg);
3126 		} else {
3127 			verbose("unknown insn class %d\n", class);
3128 			return -EINVAL;
3129 		}
3130 
3131 		insn_idx++;
3132 	}
3133 
3134 	verbose("processed %d insns\n", insn_processed);
3135 	return 0;
3136 }
3137 
check_map_prog_compatibility(struct bpf_map * map,struct bpf_prog * prog)3138 static int check_map_prog_compatibility(struct bpf_map *map,
3139 					struct bpf_prog *prog)
3140 
3141 {
3142 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
3143 	    (map->map_type == BPF_MAP_TYPE_HASH ||
3144 	     map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
3145 	    (map->map_flags & BPF_F_NO_PREALLOC)) {
3146 		verbose("perf_event programs can only use preallocated hash map\n");
3147 		return -EINVAL;
3148 	}
3149 	return 0;
3150 }
3151 
3152 /* look for pseudo eBPF instructions that access map FDs and
3153  * replace them with actual map pointers
3154  */
replace_map_fd_with_map_ptr(struct bpf_verifier_env * env)3155 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
3156 {
3157 	struct bpf_insn *insn = env->prog->insnsi;
3158 	int insn_cnt = env->prog->len;
3159 	int i, j, err;
3160 
3161 	for (i = 0; i < insn_cnt; i++, insn++) {
3162 		if (BPF_CLASS(insn->code) == BPF_LDX &&
3163 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
3164 			verbose("BPF_LDX uses reserved fields\n");
3165 			return -EINVAL;
3166 		}
3167 
3168 		if (BPF_CLASS(insn->code) == BPF_STX &&
3169 		    ((BPF_MODE(insn->code) != BPF_MEM &&
3170 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
3171 			verbose("BPF_STX uses reserved fields\n");
3172 			return -EINVAL;
3173 		}
3174 
3175 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
3176 			struct bpf_map *map;
3177 			struct fd f;
3178 
3179 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
3180 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
3181 			    insn[1].off != 0) {
3182 				verbose("invalid bpf_ld_imm64 insn\n");
3183 				return -EINVAL;
3184 			}
3185 
3186 			if (insn->src_reg == 0)
3187 				/* valid generic load 64-bit imm */
3188 				goto next_insn;
3189 
3190 			if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
3191 				verbose("unrecognized bpf_ld_imm64 insn\n");
3192 				return -EINVAL;
3193 			}
3194 
3195 			f = fdget(insn->imm);
3196 			map = __bpf_map_get(f);
3197 			if (IS_ERR(map)) {
3198 				verbose("fd %d is not pointing to valid bpf_map\n",
3199 					insn->imm);
3200 				return PTR_ERR(map);
3201 			}
3202 
3203 			err = check_map_prog_compatibility(map, env->prog);
3204 			if (err) {
3205 				fdput(f);
3206 				return err;
3207 			}
3208 
3209 			/* store map pointer inside BPF_LD_IMM64 instruction */
3210 			insn[0].imm = (u32) (unsigned long) map;
3211 			insn[1].imm = ((u64) (unsigned long) map) >> 32;
3212 
3213 			/* check whether we recorded this map already */
3214 			for (j = 0; j < env->used_map_cnt; j++)
3215 				if (env->used_maps[j] == map) {
3216 					fdput(f);
3217 					goto next_insn;
3218 				}
3219 
3220 			if (env->used_map_cnt >= MAX_USED_MAPS) {
3221 				fdput(f);
3222 				return -E2BIG;
3223 			}
3224 
3225 			/* hold the map. If the program is rejected by verifier,
3226 			 * the map will be released by release_maps() or it
3227 			 * will be used by the valid program until it's unloaded
3228 			 * and all maps are released in free_bpf_prog_info()
3229 			 */
3230 			map = bpf_map_inc(map, false);
3231 			if (IS_ERR(map)) {
3232 				fdput(f);
3233 				return PTR_ERR(map);
3234 			}
3235 			env->used_maps[env->used_map_cnt++] = map;
3236 
3237 			fdput(f);
3238 next_insn:
3239 			insn++;
3240 			i++;
3241 		}
3242 	}
3243 
3244 	/* now all pseudo BPF_LD_IMM64 instructions load valid
3245 	 * 'struct bpf_map *' into a register instead of user map_fd.
3246 	 * These pointers will be used later by verifier to validate map access.
3247 	 */
3248 	return 0;
3249 }
3250 
3251 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)3252 static void release_maps(struct bpf_verifier_env *env)
3253 {
3254 	int i;
3255 
3256 	for (i = 0; i < env->used_map_cnt; i++)
3257 		bpf_map_put(env->used_maps[i]);
3258 }
3259 
3260 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)3261 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
3262 {
3263 	struct bpf_insn *insn = env->prog->insnsi;
3264 	int insn_cnt = env->prog->len;
3265 	int i;
3266 
3267 	for (i = 0; i < insn_cnt; i++, insn++)
3268 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
3269 			insn->src_reg = 0;
3270 }
3271 
3272 /* single env->prog->insni[off] instruction was replaced with the range
3273  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
3274  * [0, off) and [off, end) to new locations, so the patched range stays zero
3275  */
adjust_insn_aux_data(struct bpf_verifier_env * env,u32 prog_len,u32 off,u32 cnt)3276 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
3277 				u32 off, u32 cnt)
3278 {
3279 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
3280 	int i;
3281 
3282 	if (cnt == 1)
3283 		return 0;
3284 	new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
3285 	if (!new_data)
3286 		return -ENOMEM;
3287 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
3288 	memcpy(new_data + off + cnt - 1, old_data + off,
3289 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
3290 	for (i = off; i < off + cnt - 1; i++)
3291 		new_data[i].seen = true;
3292 	env->insn_aux_data = new_data;
3293 	vfree(old_data);
3294 	return 0;
3295 }
3296 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)3297 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
3298 					    const struct bpf_insn *patch, u32 len)
3299 {
3300 	struct bpf_prog *new_prog;
3301 
3302 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
3303 	if (!new_prog)
3304 		return NULL;
3305 	if (adjust_insn_aux_data(env, new_prog->len, off, len))
3306 		return NULL;
3307 	return new_prog;
3308 }
3309 
3310 /* The verifier does more data flow analysis than llvm and will not explore
3311  * branches that are dead at run time. Malicious programs can have dead code
3312  * too. Therefore replace all dead at-run-time code with nops.
3313  */
sanitize_dead_code(struct bpf_verifier_env * env)3314 static void sanitize_dead_code(struct bpf_verifier_env *env)
3315 {
3316 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
3317 	struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
3318 	struct bpf_insn *insn = env->prog->insnsi;
3319 	const int insn_cnt = env->prog->len;
3320 	int i;
3321 
3322 	for (i = 0; i < insn_cnt; i++) {
3323 		if (aux_data[i].seen)
3324 			continue;
3325 		memcpy(insn + i, &nop, sizeof(nop));
3326 	}
3327 }
3328 
3329 /* convert load instructions that access fields of 'struct __sk_buff'
3330  * into sequence of instructions that access fields of 'struct sk_buff'
3331  */
convert_ctx_accesses(struct bpf_verifier_env * env)3332 static int convert_ctx_accesses(struct bpf_verifier_env *env)
3333 {
3334 	const struct bpf_verifier_ops *ops = env->prog->aux->ops;
3335 	const int insn_cnt = env->prog->len;
3336 	struct bpf_insn insn_buf[16], *insn;
3337 	struct bpf_prog *new_prog;
3338 	enum bpf_access_type type;
3339 	int i, cnt, delta = 0;
3340 
3341 	if (ops->gen_prologue) {
3342 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
3343 					env->prog);
3344 		if (cnt >= ARRAY_SIZE(insn_buf)) {
3345 			verbose("bpf verifier is misconfigured\n");
3346 			return -EINVAL;
3347 		} else if (cnt) {
3348 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
3349 			if (!new_prog)
3350 				return -ENOMEM;
3351 
3352 			env->prog = new_prog;
3353 			delta += cnt - 1;
3354 		}
3355 	}
3356 
3357 	if (!ops->convert_ctx_access)
3358 		return 0;
3359 
3360 	insn = env->prog->insnsi + delta;
3361 
3362 	for (i = 0; i < insn_cnt; i++, insn++) {
3363 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
3364 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
3365 			type = BPF_READ;
3366 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
3367 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
3368 			type = BPF_WRITE;
3369 		else
3370 			continue;
3371 
3372 		if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
3373 			continue;
3374 
3375 		cnt = ops->convert_ctx_access(type, insn->dst_reg, insn->src_reg,
3376 					      insn->off, insn_buf, env->prog);
3377 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3378 			verbose("bpf verifier is misconfigured\n");
3379 			return -EINVAL;
3380 		}
3381 
3382 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
3383 		if (!new_prog)
3384 			return -ENOMEM;
3385 
3386 		delta += cnt - 1;
3387 
3388 		/* keep walking new program and skip insns we just inserted */
3389 		env->prog = new_prog;
3390 		insn      = new_prog->insnsi + i + delta;
3391 	}
3392 
3393 	return 0;
3394 }
3395 
3396 /* fixup insn->imm field of bpf_call instructions
3397  *
3398  * this function is called after eBPF program passed verification
3399  */
fixup_bpf_calls(struct bpf_verifier_env * env)3400 static int fixup_bpf_calls(struct bpf_verifier_env *env)
3401 {
3402 	struct bpf_prog *prog = env->prog;
3403 	struct bpf_insn *insn = prog->insnsi;
3404 	const struct bpf_func_proto *fn;
3405 	const int insn_cnt = prog->len;
3406 	struct bpf_insn insn_buf[16];
3407 	struct bpf_prog *new_prog;
3408 	struct bpf_map *map_ptr;
3409 	int i, cnt, delta = 0;
3410 
3411 
3412 	for (i = 0; i < insn_cnt; i++, insn++) {
3413 		if (insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
3414 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
3415 			/* due to JIT bugs clear upper 32-bits of src register
3416 			 * before div/mod operation
3417 			 */
3418 			insn_buf[0] = BPF_MOV32_REG(insn->src_reg, insn->src_reg);
3419 			insn_buf[1] = *insn;
3420 			cnt = 2;
3421 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
3422 			if (!new_prog)
3423 				return -ENOMEM;
3424 
3425 			delta    += cnt - 1;
3426 			env->prog = prog = new_prog;
3427 			insn      = new_prog->insnsi + i + delta;
3428 			continue;
3429 		}
3430 
3431 		if (insn->code != (BPF_JMP | BPF_CALL))
3432 			continue;
3433 
3434 		if (insn->imm == BPF_FUNC_get_route_realm)
3435 			prog->dst_needed = 1;
3436 		if (insn->imm == BPF_FUNC_get_prandom_u32)
3437 			bpf_user_rnd_init_once();
3438 		if (insn->imm == BPF_FUNC_tail_call) {
3439 			/* mark bpf_tail_call as different opcode to avoid
3440 			 * conditional branch in the interpeter for every normal
3441 			 * call and to prevent accidental JITing by JIT compiler
3442 			 * that doesn't support bpf_tail_call yet
3443  			 */
3444 			insn->imm = 0;
3445 			insn->code |= BPF_X;
3446 
3447 			/* instead of changing every JIT dealing with tail_call
3448 			 * emit two extra insns:
3449 			 * if (index >= max_entries) goto out;
3450 			 * index &= array->index_mask;
3451 			 * to avoid out-of-bounds cpu speculation
3452 			 */
3453 			map_ptr = env->insn_aux_data[i + delta].map_ptr;
3454 			if (!map_ptr->unpriv_array)
3455 				continue;
3456 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
3457 						  map_ptr->max_entries, 2);
3458 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
3459 						    container_of(map_ptr,
3460 								 struct bpf_array,
3461 								 map)->index_mask);
3462 			insn_buf[2] = *insn;
3463 			cnt = 3;
3464 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
3465 			if (!new_prog)
3466 				return -ENOMEM;
3467 
3468 			delta    += cnt - 1;
3469 			env->prog = prog = new_prog;
3470 			insn      = new_prog->insnsi + i + delta;
3471 			continue;
3472 		}
3473 
3474 		fn = prog->aux->ops->get_func_proto(insn->imm);
3475 		/* all functions that have prototype and verifier allowed
3476 		 * programs to call them, must be real in-kernel functions
3477 		 */
3478 		if (!fn->func) {
3479 			verbose("kernel subsystem misconfigured func %d\n",
3480 				insn->imm);
3481 			return -EFAULT;
3482 		}
3483 		insn->imm = fn->func - __bpf_call_base;
3484 	}
3485 
3486 	return 0;
3487 }
3488 
free_states(struct bpf_verifier_env * env)3489 static void free_states(struct bpf_verifier_env *env)
3490 {
3491 	struct bpf_verifier_state_list *sl, *sln;
3492 	int i;
3493 
3494 	if (!env->explored_states)
3495 		return;
3496 
3497 	for (i = 0; i < env->prog->len; i++) {
3498 		sl = env->explored_states[i];
3499 
3500 		if (sl)
3501 			while (sl != STATE_LIST_MARK) {
3502 				sln = sl->next;
3503 				kfree(sl);
3504 				sl = sln;
3505 			}
3506 	}
3507 
3508 	kfree(env->explored_states);
3509 }
3510 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr)3511 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
3512 {
3513 	char __user *log_ubuf = NULL;
3514 	struct bpf_verifier_env *env;
3515 	int ret = -EINVAL;
3516 
3517 	if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
3518 		return -E2BIG;
3519 
3520 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
3521 	 * allocate/free it every time bpf_check() is called
3522 	 */
3523 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3524 	if (!env)
3525 		return -ENOMEM;
3526 
3527 	env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3528 				     (*prog)->len);
3529 	ret = -ENOMEM;
3530 	if (!env->insn_aux_data)
3531 		goto err_free_env;
3532 	env->prog = *prog;
3533 
3534 	/* grab the mutex to protect few globals used by verifier */
3535 	mutex_lock(&bpf_verifier_lock);
3536 
3537 	if (attr->log_level || attr->log_buf || attr->log_size) {
3538 		/* user requested verbose verifier output
3539 		 * and supplied buffer to store the verification trace
3540 		 */
3541 		log_level = attr->log_level;
3542 		log_ubuf = (char __user *) (unsigned long) attr->log_buf;
3543 		log_size = attr->log_size;
3544 		log_len = 0;
3545 
3546 		ret = -EINVAL;
3547 		/* log_* values have to be sane */
3548 		if (log_size < 128 || log_size > UINT_MAX >> 8 ||
3549 		    log_level == 0 || log_ubuf == NULL)
3550 			goto err_unlock;
3551 
3552 		ret = -ENOMEM;
3553 		log_buf = vmalloc(log_size);
3554 		if (!log_buf)
3555 			goto err_unlock;
3556 	} else {
3557 		log_level = 0;
3558 	}
3559 
3560 	ret = replace_map_fd_with_map_ptr(env);
3561 	if (ret < 0)
3562 		goto skip_full_check;
3563 
3564 	env->explored_states = kcalloc(env->prog->len,
3565 				       sizeof(struct bpf_verifier_state_list *),
3566 				       GFP_USER);
3567 	ret = -ENOMEM;
3568 	if (!env->explored_states)
3569 		goto skip_full_check;
3570 
3571 	ret = check_cfg(env);
3572 	if (ret < 0)
3573 		goto skip_full_check;
3574 
3575 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3576 
3577 	ret = do_check(env);
3578 
3579 skip_full_check:
3580 	while (pop_stack(env, NULL) >= 0);
3581 	free_states(env);
3582 
3583 	if (ret == 0)
3584 		sanitize_dead_code(env);
3585 
3586 	if (ret == 0)
3587 		/* program is valid, convert *(u32*)(ctx + off) accesses */
3588 		ret = convert_ctx_accesses(env);
3589 
3590 	if (ret == 0)
3591 		ret = fixup_bpf_calls(env);
3592 
3593 	if (log_level && log_len >= log_size - 1) {
3594 		BUG_ON(log_len >= log_size);
3595 		/* verifier log exceeded user supplied buffer */
3596 		ret = -ENOSPC;
3597 		/* fall through to return what was recorded */
3598 	}
3599 
3600 	/* copy verifier log back to user space including trailing zero */
3601 	if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
3602 		ret = -EFAULT;
3603 		goto free_log_buf;
3604 	}
3605 
3606 	if (ret == 0 && env->used_map_cnt) {
3607 		/* if program passed verifier, update used_maps in bpf_prog_info */
3608 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
3609 							  sizeof(env->used_maps[0]),
3610 							  GFP_KERNEL);
3611 
3612 		if (!env->prog->aux->used_maps) {
3613 			ret = -ENOMEM;
3614 			goto free_log_buf;
3615 		}
3616 
3617 		memcpy(env->prog->aux->used_maps, env->used_maps,
3618 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
3619 		env->prog->aux->used_map_cnt = env->used_map_cnt;
3620 
3621 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
3622 		 * bpf_ld_imm64 instructions
3623 		 */
3624 		convert_pseudo_ld_imm64(env);
3625 	}
3626 
3627 free_log_buf:
3628 	if (log_level)
3629 		vfree(log_buf);
3630 	if (!env->prog->aux->used_maps)
3631 		/* if we didn't copy map pointers into bpf_prog_info, release
3632 		 * them now. Otherwise free_bpf_prog_info() will release them.
3633 		 */
3634 		release_maps(env);
3635 	*prog = env->prog;
3636 err_unlock:
3637 	mutex_unlock(&bpf_verifier_lock);
3638 	vfree(env->insn_aux_data);
3639 err_free_env:
3640 	kfree(env);
3641 	return ret;
3642 }
3643 
bpf_analyzer(struct bpf_prog * prog,const struct bpf_ext_analyzer_ops * ops,void * priv)3644 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
3645 		 void *priv)
3646 {
3647 	struct bpf_verifier_env *env;
3648 	int ret;
3649 
3650 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3651 	if (!env)
3652 		return -ENOMEM;
3653 
3654 	env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3655 				     prog->len);
3656 	ret = -ENOMEM;
3657 	if (!env->insn_aux_data)
3658 		goto err_free_env;
3659 	env->prog = prog;
3660 	env->analyzer_ops = ops;
3661 	env->analyzer_priv = priv;
3662 
3663 	/* grab the mutex to protect few globals used by verifier */
3664 	mutex_lock(&bpf_verifier_lock);
3665 
3666 	log_level = 0;
3667 
3668 	env->explored_states = kcalloc(env->prog->len,
3669 				       sizeof(struct bpf_verifier_state_list *),
3670 				       GFP_KERNEL);
3671 	ret = -ENOMEM;
3672 	if (!env->explored_states)
3673 		goto skip_full_check;
3674 
3675 	ret = check_cfg(env);
3676 	if (ret < 0)
3677 		goto skip_full_check;
3678 
3679 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3680 
3681 	ret = do_check(env);
3682 
3683 skip_full_check:
3684 	while (pop_stack(env, NULL) >= 0);
3685 	free_states(env);
3686 
3687 	mutex_unlock(&bpf_verifier_lock);
3688 	vfree(env->insn_aux_data);
3689 err_free_env:
3690 	kfree(env);
3691 	return ret;
3692 }
3693 EXPORT_SYMBOL_GPL(bpf_analyzer);
3694