• 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 #include <linux/stringify.h>
23 
24 /* bpf_check() is a static code analyzer that walks eBPF program
25  * instruction by instruction and updates register/stack state.
26  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
27  *
28  * The first pass is depth-first-search to check that the program is a DAG.
29  * It rejects the following programs:
30  * - larger than BPF_MAXINSNS insns
31  * - if loop is present (detected via back-edge)
32  * - unreachable insns exist (shouldn't be a forest. program = one function)
33  * - out of bounds or malformed jumps
34  * The second pass is all possible path descent from the 1st insn.
35  * Since it's analyzing all pathes through the program, the length of the
36  * analysis is limited to 64k insn, which may be hit even if total number of
37  * insn is less then 4K, but there are too many branches that change stack/regs.
38  * Number of 'branches to be analyzed' is limited to 1k
39  *
40  * On entry to each instruction, each register has a type, and the instruction
41  * changes the types of the registers depending on instruction semantics.
42  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
43  * copied to R1.
44  *
45  * All registers are 64-bit.
46  * R0 - return register
47  * R1-R5 argument passing registers
48  * R6-R9 callee saved registers
49  * R10 - frame pointer read-only
50  *
51  * At the start of BPF program the register R1 contains a pointer to bpf_context
52  * and has type PTR_TO_CTX.
53  *
54  * Verifier tracks arithmetic operations on pointers in case:
55  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
56  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
57  * 1st insn copies R10 (which has FRAME_PTR) type into R1
58  * and 2nd arithmetic instruction is pattern matched to recognize
59  * that it wants to construct a pointer to some element within stack.
60  * So after 2nd insn, the register R1 has type PTR_TO_STACK
61  * (and -20 constant is saved for further stack bounds checking).
62  * Meaning that this reg is a pointer to stack plus known immediate constant.
63  *
64  * Most of the time the registers have SCALAR_VALUE type, which
65  * means the register has some value, but it's not a valid pointer.
66  * (like pointer plus pointer becomes SCALAR_VALUE type)
67  *
68  * When verifier sees load or store instructions the type of base register
69  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
70  * types recognized by check_mem_access() function.
71  *
72  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
73  * and the range of [ptr, ptr + map's value_size) is accessible.
74  *
75  * registers used to pass values to function calls are checked against
76  * function argument constraints.
77  *
78  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
79  * It means that the register type passed to this function must be
80  * PTR_TO_STACK and it will be used inside the function as
81  * 'pointer to map element key'
82  *
83  * For example the argument constraints for bpf_map_lookup_elem():
84  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
85  *   .arg1_type = ARG_CONST_MAP_PTR,
86  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
87  *
88  * ret_type says that this function returns 'pointer to map elem value or null'
89  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
90  * 2nd argument should be a pointer to stack, which will be used inside
91  * the helper function as a pointer to map element key.
92  *
93  * On the kernel side the helper function looks like:
94  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
95  * {
96  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
97  *    void *key = (void *) (unsigned long) r2;
98  *    void *value;
99  *
100  *    here kernel can access 'key' and 'map' pointers safely, knowing that
101  *    [key, key + map->key_size) bytes are valid and were initialized on
102  *    the stack of eBPF program.
103  * }
104  *
105  * Corresponding eBPF program may look like:
106  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
107  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
108  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
109  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
110  * here verifier looks at prototype of map_lookup_elem() and sees:
111  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
112  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
113  *
114  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
115  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
116  * and were initialized prior to this call.
117  * If it's ok, then verifier allows this BPF_CALL insn and looks at
118  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
119  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
120  * returns ether pointer to map value or NULL.
121  *
122  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
123  * insn, the register holding that pointer in the true branch changes state to
124  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
125  * branch. See check_cond_jmp_op().
126  *
127  * After the call R0 is set to return type of the function and registers R1-R5
128  * are set to NOT_INIT to indicate that they are no longer readable.
129  */
130 
131 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
132 struct bpf_verifier_stack_elem {
133 	/* verifer state is 'st'
134 	 * before processing instruction 'insn_idx'
135 	 * and after processing instruction 'prev_insn_idx'
136 	 */
137 	struct bpf_verifier_state st;
138 	int insn_idx;
139 	int prev_insn_idx;
140 	struct bpf_verifier_stack_elem *next;
141 };
142 
143 #define BPF_COMPLEXITY_LIMIT_INSNS	131072
144 #define BPF_COMPLEXITY_LIMIT_STACK	1024
145 
146 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
147 
148 struct bpf_call_arg_meta {
149 	struct bpf_map *map_ptr;
150 	bool raw_mode;
151 	bool pkt_access;
152 	int regno;
153 	int access_size;
154 };
155 
156 /* verbose verifier prints what it's seeing
157  * bpf_check() is called under lock, so no race to access these global vars
158  */
159 static u32 log_level, log_size, log_len;
160 static char *log_buf;
161 
162 static DEFINE_MUTEX(bpf_verifier_lock);
163 
164 /* log_level controls verbosity level of eBPF verifier.
165  * verbose() is used to dump the verification trace to the log, so the user
166  * can figure out what's wrong with the program
167  */
verbose(const char * fmt,...)168 static __printf(1, 2) void verbose(const char *fmt, ...)
169 {
170 	va_list args;
171 
172 	if (log_level == 0 || log_len >= log_size - 1)
173 		return;
174 
175 	va_start(args, fmt);
176 	log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
177 	va_end(args);
178 }
179 
180 /* string representation of 'enum bpf_reg_type' */
181 static const char * const reg_type_str[] = {
182 	[NOT_INIT]		= "?",
183 	[SCALAR_VALUE]		= "inv",
184 	[PTR_TO_CTX]		= "ctx",
185 	[CONST_PTR_TO_MAP]	= "map_ptr",
186 	[PTR_TO_MAP_VALUE]	= "map_value",
187 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
188 	[PTR_TO_STACK]		= "fp",
189 	[PTR_TO_PACKET]		= "pkt",
190 	[PTR_TO_PACKET_END]	= "pkt_end",
191 };
192 
193 #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
194 static const char * const func_id_str[] = {
195 	__BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
196 };
197 #undef __BPF_FUNC_STR_FN
198 
func_id_name(int id)199 static const char *func_id_name(int id)
200 {
201 	BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
202 
203 	if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
204 		return func_id_str[id];
205 	else
206 		return "unknown";
207 }
208 
print_verifier_state(struct bpf_verifier_state * state)209 static void print_verifier_state(struct bpf_verifier_state *state)
210 {
211 	struct bpf_reg_state *reg;
212 	enum bpf_reg_type t;
213 	int i;
214 
215 	for (i = 0; i < MAX_BPF_REG; i++) {
216 		reg = &state->regs[i];
217 		t = reg->type;
218 		if (t == NOT_INIT)
219 			continue;
220 		verbose(" R%d=%s", i, reg_type_str[t]);
221 		if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
222 		    tnum_is_const(reg->var_off)) {
223 			/* reg->off should be 0 for SCALAR_VALUE */
224 			verbose("%lld", reg->var_off.value + reg->off);
225 		} else {
226 			verbose("(id=%d", reg->id);
227 			if (t != SCALAR_VALUE)
228 				verbose(",off=%d", reg->off);
229 			if (t == PTR_TO_PACKET)
230 				verbose(",r=%d", reg->range);
231 			else if (t == CONST_PTR_TO_MAP ||
232 				 t == PTR_TO_MAP_VALUE ||
233 				 t == PTR_TO_MAP_VALUE_OR_NULL)
234 				verbose(",ks=%d,vs=%d",
235 					reg->map_ptr->key_size,
236 					reg->map_ptr->value_size);
237 			if (tnum_is_const(reg->var_off)) {
238 				/* Typically an immediate SCALAR_VALUE, but
239 				 * could be a pointer whose offset is too big
240 				 * for reg->off
241 				 */
242 				verbose(",imm=%llx", reg->var_off.value);
243 			} else {
244 				if (reg->smin_value != reg->umin_value &&
245 				    reg->smin_value != S64_MIN)
246 					verbose(",smin_value=%lld",
247 						(long long)reg->smin_value);
248 				if (reg->smax_value != reg->umax_value &&
249 				    reg->smax_value != S64_MAX)
250 					verbose(",smax_value=%lld",
251 						(long long)reg->smax_value);
252 				if (reg->umin_value != 0)
253 					verbose(",umin_value=%llu",
254 						(unsigned long long)reg->umin_value);
255 				if (reg->umax_value != U64_MAX)
256 					verbose(",umax_value=%llu",
257 						(unsigned long long)reg->umax_value);
258 				if (!tnum_is_unknown(reg->var_off)) {
259 					char tn_buf[48];
260 
261 					tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
262 					verbose(",var_off=%s", tn_buf);
263 				}
264 			}
265 			verbose(")");
266 		}
267 	}
268 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
269 		if (state->stack[i].slot_type[0] == STACK_SPILL)
270 			verbose(" fp%d=%s",
271 				(-i - 1) * BPF_REG_SIZE,
272 				reg_type_str[state->stack[i].spilled_ptr.type]);
273 	}
274 	verbose("\n");
275 }
276 
277 static const char *const bpf_class_string[] = {
278 	[BPF_LD]    = "ld",
279 	[BPF_LDX]   = "ldx",
280 	[BPF_ST]    = "st",
281 	[BPF_STX]   = "stx",
282 	[BPF_ALU]   = "alu",
283 	[BPF_JMP]   = "jmp",
284 	[BPF_RET]   = "BUG",
285 	[BPF_ALU64] = "alu64",
286 };
287 
288 static const char *const bpf_alu_string[16] = {
289 	[BPF_ADD >> 4]  = "+=",
290 	[BPF_SUB >> 4]  = "-=",
291 	[BPF_MUL >> 4]  = "*=",
292 	[BPF_DIV >> 4]  = "/=",
293 	[BPF_OR  >> 4]  = "|=",
294 	[BPF_AND >> 4]  = "&=",
295 	[BPF_LSH >> 4]  = "<<=",
296 	[BPF_RSH >> 4]  = ">>=",
297 	[BPF_NEG >> 4]  = "neg",
298 	[BPF_MOD >> 4]  = "%=",
299 	[BPF_XOR >> 4]  = "^=",
300 	[BPF_MOV >> 4]  = "=",
301 	[BPF_ARSH >> 4] = "s>>=",
302 	[BPF_END >> 4]  = "endian",
303 };
304 
305 static const char *const bpf_ldst_string[] = {
306 	[BPF_W >> 3]  = "u32",
307 	[BPF_H >> 3]  = "u16",
308 	[BPF_B >> 3]  = "u8",
309 	[BPF_DW >> 3] = "u64",
310 };
311 
312 static const char *const bpf_jmp_string[16] = {
313 	[BPF_JA >> 4]   = "jmp",
314 	[BPF_JEQ >> 4]  = "==",
315 	[BPF_JGT >> 4]  = ">",
316 	[BPF_JLT >> 4]  = "<",
317 	[BPF_JGE >> 4]  = ">=",
318 	[BPF_JLE >> 4]  = "<=",
319 	[BPF_JSET >> 4] = "&",
320 	[BPF_JNE >> 4]  = "!=",
321 	[BPF_JSGT >> 4] = "s>",
322 	[BPF_JSLT >> 4] = "s<",
323 	[BPF_JSGE >> 4] = "s>=",
324 	[BPF_JSLE >> 4] = "s<=",
325 	[BPF_CALL >> 4] = "call",
326 	[BPF_EXIT >> 4] = "exit",
327 };
328 
print_bpf_insn(const struct bpf_verifier_env * env,const struct bpf_insn * insn)329 static void print_bpf_insn(const struct bpf_verifier_env *env,
330 			   const struct bpf_insn *insn)
331 {
332 	u8 class = BPF_CLASS(insn->code);
333 
334 	if (class == BPF_ALU || class == BPF_ALU64) {
335 		if (BPF_SRC(insn->code) == BPF_X)
336 			verbose("(%02x) %sr%d %s %sr%d\n",
337 				insn->code, class == BPF_ALU ? "(u32) " : "",
338 				insn->dst_reg,
339 				bpf_alu_string[BPF_OP(insn->code) >> 4],
340 				class == BPF_ALU ? "(u32) " : "",
341 				insn->src_reg);
342 		else
343 			verbose("(%02x) %sr%d %s %s%d\n",
344 				insn->code, class == BPF_ALU ? "(u32) " : "",
345 				insn->dst_reg,
346 				bpf_alu_string[BPF_OP(insn->code) >> 4],
347 				class == BPF_ALU ? "(u32) " : "",
348 				insn->imm);
349 	} else if (class == BPF_STX) {
350 		if (BPF_MODE(insn->code) == BPF_MEM)
351 			verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
352 				insn->code,
353 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
354 				insn->dst_reg,
355 				insn->off, insn->src_reg);
356 		else if (BPF_MODE(insn->code) == BPF_XADD)
357 			verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
358 				insn->code,
359 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
360 				insn->dst_reg, insn->off,
361 				insn->src_reg);
362 		else
363 			verbose("BUG_%02x\n", insn->code);
364 	} else if (class == BPF_ST) {
365 		if (BPF_MODE(insn->code) != BPF_MEM) {
366 			verbose("BUG_st_%02x\n", insn->code);
367 			return;
368 		}
369 		verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
370 			insn->code,
371 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
372 			insn->dst_reg,
373 			insn->off, insn->imm);
374 	} else if (class == BPF_LDX) {
375 		if (BPF_MODE(insn->code) != BPF_MEM) {
376 			verbose("BUG_ldx_%02x\n", insn->code);
377 			return;
378 		}
379 		verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
380 			insn->code, insn->dst_reg,
381 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
382 			insn->src_reg, insn->off);
383 	} else if (class == BPF_LD) {
384 		if (BPF_MODE(insn->code) == BPF_ABS) {
385 			verbose("(%02x) r0 = *(%s *)skb[%d]\n",
386 				insn->code,
387 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
388 				insn->imm);
389 		} else if (BPF_MODE(insn->code) == BPF_IND) {
390 			verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
391 				insn->code,
392 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
393 				insn->src_reg, insn->imm);
394 		} else if (BPF_MODE(insn->code) == BPF_IMM &&
395 			   BPF_SIZE(insn->code) == BPF_DW) {
396 			/* At this point, we already made sure that the second
397 			 * part of the ldimm64 insn is accessible.
398 			 */
399 			u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
400 			bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
401 
402 			if (map_ptr && !env->allow_ptr_leaks)
403 				imm = 0;
404 
405 			verbose("(%02x) r%d = 0x%llx\n", insn->code,
406 				insn->dst_reg, (unsigned long long)imm);
407 		} else {
408 			verbose("BUG_ld_%02x\n", insn->code);
409 			return;
410 		}
411 	} else if (class == BPF_JMP) {
412 		u8 opcode = BPF_OP(insn->code);
413 
414 		if (opcode == BPF_CALL) {
415 			verbose("(%02x) call %s#%d\n", insn->code,
416 				func_id_name(insn->imm), insn->imm);
417 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
418 			verbose("(%02x) goto pc%+d\n",
419 				insn->code, insn->off);
420 		} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
421 			verbose("(%02x) exit\n", insn->code);
422 		} else if (BPF_SRC(insn->code) == BPF_X) {
423 			verbose("(%02x) if r%d %s r%d goto pc%+d\n",
424 				insn->code, insn->dst_reg,
425 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
426 				insn->src_reg, insn->off);
427 		} else {
428 			verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
429 				insn->code, insn->dst_reg,
430 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
431 				insn->imm, insn->off);
432 		}
433 	} else {
434 		verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
435 	}
436 }
437 
copy_stack_state(struct bpf_verifier_state * dst,const struct bpf_verifier_state * src)438 static int copy_stack_state(struct bpf_verifier_state *dst,
439 			    const struct bpf_verifier_state *src)
440 {
441 	if (!src->stack)
442 		return 0;
443 	if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
444 		/* internal bug, make state invalid to reject the program */
445 		memset(dst, 0, sizeof(*dst));
446 		return -EFAULT;
447 	}
448 	memcpy(dst->stack, src->stack,
449 	       sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
450 	return 0;
451 }
452 
453 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
454  * make it consume minimal amount of memory. check_stack_write() access from
455  * the program calls into realloc_verifier_state() to grow the stack size.
456  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
457  * which this function copies over. It points to previous bpf_verifier_state
458  * which is never reallocated
459  */
realloc_verifier_state(struct bpf_verifier_state * state,int size,bool copy_old)460 static int realloc_verifier_state(struct bpf_verifier_state *state, int size,
461 				  bool copy_old)
462 {
463 	u32 old_size = state->allocated_stack;
464 	struct bpf_stack_state *new_stack;
465 	int slot = size / BPF_REG_SIZE;
466 
467 	if (size <= old_size || !size) {
468 		if (copy_old)
469 			return 0;
470 		state->allocated_stack = slot * BPF_REG_SIZE;
471 		if (!size && old_size) {
472 			kfree(state->stack);
473 			state->stack = NULL;
474 		}
475 		return 0;
476 	}
477 	new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
478 				  GFP_KERNEL);
479 	if (!new_stack)
480 		return -ENOMEM;
481 	if (copy_old) {
482 		if (state->stack)
483 			memcpy(new_stack, state->stack,
484 			       sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
485 		memset(new_stack + old_size / BPF_REG_SIZE, 0,
486 		       sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
487 	}
488 	state->allocated_stack = slot * BPF_REG_SIZE;
489 	kfree(state->stack);
490 	state->stack = new_stack;
491 	return 0;
492 }
493 
free_verifier_state(struct bpf_verifier_state * state,bool free_self)494 static void free_verifier_state(struct bpf_verifier_state *state,
495 				bool free_self)
496 {
497 	kfree(state->stack);
498 	if (free_self)
499 		kfree(state);
500 }
501 
502 /* copy verifier state from src to dst growing dst stack space
503  * when necessary to accommodate larger src stack
504  */
copy_verifier_state(struct bpf_verifier_state * dst,const struct bpf_verifier_state * src)505 static int copy_verifier_state(struct bpf_verifier_state *dst,
506 			       const struct bpf_verifier_state *src)
507 {
508 	int err;
509 
510 	err = realloc_verifier_state(dst, src->allocated_stack, false);
511 	if (err)
512 		return err;
513 	memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack));
514 	return copy_stack_state(dst, src);
515 }
516 
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx)517 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
518 		     int *insn_idx)
519 {
520 	struct bpf_verifier_state *cur = env->cur_state;
521 	struct bpf_verifier_stack_elem *elem, *head = env->head;
522 	int err;
523 
524 	if (env->head == NULL)
525 		return -ENOENT;
526 
527 	if (cur) {
528 		err = copy_verifier_state(cur, &head->st);
529 		if (err)
530 			return err;
531 	}
532 	if (insn_idx)
533 		*insn_idx = head->insn_idx;
534 	if (prev_insn_idx)
535 		*prev_insn_idx = head->prev_insn_idx;
536 	elem = head->next;
537 	free_verifier_state(&head->st, false);
538 	kfree(head);
539 	env->head = elem;
540 	env->stack_size--;
541 	return 0;
542 }
543 
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)544 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
545 					     int insn_idx, int prev_insn_idx,
546 					     bool speculative)
547 {
548 	struct bpf_verifier_stack_elem *elem;
549 	struct bpf_verifier_state *cur = env->cur_state;
550 	int err;
551 
552 	elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
553 	if (!elem)
554 		goto err;
555 
556 	elem->insn_idx = insn_idx;
557 	elem->prev_insn_idx = prev_insn_idx;
558 	elem->next = env->head;
559 	elem->st.speculative |= speculative;
560 	env->head = elem;
561 	env->stack_size++;
562 	err = copy_verifier_state(&elem->st, cur);
563 	if (err)
564 		goto err;
565 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
566 		verbose("BPF program is too complex\n");
567 		goto err;
568 	}
569 	return &elem->st;
570 err:
571 	/* pop all elements and return */
572 	while (!pop_stack(env, NULL, NULL));
573 	return NULL;
574 }
575 
576 #define CALLER_SAVED_REGS 6
577 static const int caller_saved[CALLER_SAVED_REGS] = {
578 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
579 };
580 
581 static void __mark_reg_not_init(struct bpf_reg_state *reg);
582 
583 /* Mark the unknown part of a register (variable offset or scalar value) as
584  * known to have the value @imm.
585  */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)586 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
587 {
588 	reg->id = 0;
589 	reg->var_off = tnum_const(imm);
590 	reg->smin_value = (s64)imm;
591 	reg->smax_value = (s64)imm;
592 	reg->umin_value = imm;
593 	reg->umax_value = imm;
594 }
595 
596 /* Mark the 'variable offset' part of a register as zero.  This should be
597  * used only on registers holding a pointer type.
598  */
__mark_reg_known_zero(struct bpf_reg_state * reg)599 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
600 {
601 	__mark_reg_known(reg, 0);
602 }
603 
mark_reg_known_zero(struct bpf_reg_state * regs,u32 regno)604 static void mark_reg_known_zero(struct bpf_reg_state *regs, u32 regno)
605 {
606 	if (WARN_ON(regno >= MAX_BPF_REG)) {
607 		verbose("mark_reg_known_zero(regs, %u)\n", regno);
608 		/* Something bad happened, let's kill all regs */
609 		for (regno = 0; regno < MAX_BPF_REG; regno++)
610 			__mark_reg_not_init(regs + regno);
611 		return;
612 	}
613 	__mark_reg_known_zero(regs + regno);
614 }
615 
616 /* Attempts to improve min/max values based on var_off information */
__update_reg_bounds(struct bpf_reg_state * reg)617 static void __update_reg_bounds(struct bpf_reg_state *reg)
618 {
619 	/* min signed is max(sign bit) | min(other bits) */
620 	reg->smin_value = max_t(s64, reg->smin_value,
621 				reg->var_off.value | (reg->var_off.mask & S64_MIN));
622 	/* max signed is min(sign bit) | max(other bits) */
623 	reg->smax_value = min_t(s64, reg->smax_value,
624 				reg->var_off.value | (reg->var_off.mask & S64_MAX));
625 	reg->umin_value = max(reg->umin_value, reg->var_off.value);
626 	reg->umax_value = min(reg->umax_value,
627 			      reg->var_off.value | reg->var_off.mask);
628 }
629 
630 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg_deduce_bounds(struct bpf_reg_state * reg)631 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
632 {
633 	/* Learn sign from signed bounds.
634 	 * If we cannot cross the sign boundary, then signed and unsigned bounds
635 	 * are the same, so combine.  This works even in the negative case, e.g.
636 	 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
637 	 */
638 	if (reg->smin_value >= 0 || reg->smax_value < 0) {
639 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
640 							  reg->umin_value);
641 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
642 							  reg->umax_value);
643 		return;
644 	}
645 	/* Learn sign from unsigned bounds.  Signed bounds cross the sign
646 	 * boundary, so we must be careful.
647 	 */
648 	if ((s64)reg->umax_value >= 0) {
649 		/* Positive.  We can't learn anything from the smin, but smax
650 		 * is positive, hence safe.
651 		 */
652 		reg->smin_value = reg->umin_value;
653 		reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
654 							  reg->umax_value);
655 	} else if ((s64)reg->umin_value < 0) {
656 		/* Negative.  We can't learn anything from the smax, but smin
657 		 * is negative, hence safe.
658 		 */
659 		reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
660 							  reg->umin_value);
661 		reg->smax_value = reg->umax_value;
662 	}
663 }
664 
665 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)666 static void __reg_bound_offset(struct bpf_reg_state *reg)
667 {
668 	reg->var_off = tnum_intersect(reg->var_off,
669 				      tnum_range(reg->umin_value,
670 						 reg->umax_value));
671 }
672 
673 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)674 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
675 {
676 	reg->smin_value = S64_MIN;
677 	reg->smax_value = S64_MAX;
678 	reg->umin_value = 0;
679 	reg->umax_value = U64_MAX;
680 }
681 
682 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(struct bpf_reg_state * reg)683 static void __mark_reg_unknown(struct bpf_reg_state *reg)
684 {
685 	reg->type = SCALAR_VALUE;
686 	reg->id = 0;
687 	reg->off = 0;
688 	reg->var_off = tnum_unknown;
689 	__mark_reg_unbounded(reg);
690 }
691 
mark_reg_unknown(struct bpf_reg_state * regs,u32 regno)692 static void mark_reg_unknown(struct bpf_reg_state *regs, u32 regno)
693 {
694 	if (WARN_ON(regno >= MAX_BPF_REG)) {
695 		verbose("mark_reg_unknown(regs, %u)\n", regno);
696 		/* Something bad happened, let's kill all regs */
697 		for (regno = 0; regno < MAX_BPF_REG; regno++)
698 			__mark_reg_not_init(regs + regno);
699 		return;
700 	}
701 	__mark_reg_unknown(regs + regno);
702 }
703 
__mark_reg_not_init(struct bpf_reg_state * reg)704 static void __mark_reg_not_init(struct bpf_reg_state *reg)
705 {
706 	__mark_reg_unknown(reg);
707 	reg->type = NOT_INIT;
708 }
709 
mark_reg_not_init(struct bpf_reg_state * regs,u32 regno)710 static void mark_reg_not_init(struct bpf_reg_state *regs, u32 regno)
711 {
712 	if (WARN_ON(regno >= MAX_BPF_REG)) {
713 		verbose("mark_reg_not_init(regs, %u)\n", regno);
714 		/* Something bad happened, let's kill all regs */
715 		for (regno = 0; regno < MAX_BPF_REG; regno++)
716 			__mark_reg_not_init(regs + regno);
717 		return;
718 	}
719 	__mark_reg_not_init(regs + regno);
720 }
721 
init_reg_state(struct bpf_reg_state * regs)722 static void init_reg_state(struct bpf_reg_state *regs)
723 {
724 	int i;
725 
726 	for (i = 0; i < MAX_BPF_REG; i++) {
727 		mark_reg_not_init(regs, i);
728 		regs[i].live = REG_LIVE_NONE;
729 	}
730 
731 	/* frame pointer */
732 	regs[BPF_REG_FP].type = PTR_TO_STACK;
733 	mark_reg_known_zero(regs, BPF_REG_FP);
734 
735 	/* 1st arg to a function */
736 	regs[BPF_REG_1].type = PTR_TO_CTX;
737 	mark_reg_known_zero(regs, BPF_REG_1);
738 }
739 
740 enum reg_arg_type {
741 	SRC_OP,		/* register is used as source operand */
742 	DST_OP,		/* register is used as destination operand */
743 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
744 };
745 
mark_reg_read(const struct bpf_verifier_state * state,u32 regno)746 static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
747 {
748 	struct bpf_verifier_state *parent = state->parent;
749 
750 	if (regno == BPF_REG_FP)
751 		/* We don't need to worry about FP liveness because it's read-only */
752 		return;
753 
754 	while (parent) {
755 		/* if read wasn't screened by an earlier write ... */
756 		if (state->regs[regno].live & REG_LIVE_WRITTEN)
757 			break;
758 		/* ... then we depend on parent's value */
759 		parent->regs[regno].live |= REG_LIVE_READ;
760 		state = parent;
761 		parent = state->parent;
762 	}
763 }
764 
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)765 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
766 			 enum reg_arg_type t)
767 {
768 	struct bpf_reg_state *regs = env->cur_state->regs;
769 
770 	if (regno >= MAX_BPF_REG) {
771 		verbose("R%d is invalid\n", regno);
772 		return -EINVAL;
773 	}
774 
775 	if (t == SRC_OP) {
776 		/* check whether register used as source operand can be read */
777 		if (regs[regno].type == NOT_INIT) {
778 			verbose("R%d !read_ok\n", regno);
779 			return -EACCES;
780 		}
781 		mark_reg_read(env->cur_state, regno);
782 	} else {
783 		/* check whether register used as dest operand can be written to */
784 		if (regno == BPF_REG_FP) {
785 			verbose("frame pointer is read only\n");
786 			return -EACCES;
787 		}
788 		regs[regno].live |= REG_LIVE_WRITTEN;
789 		if (t == DST_OP)
790 			mark_reg_unknown(regs, regno);
791 	}
792 	return 0;
793 }
794 
is_spillable_regtype(enum bpf_reg_type type)795 static bool is_spillable_regtype(enum bpf_reg_type type)
796 {
797 	switch (type) {
798 	case PTR_TO_MAP_VALUE:
799 	case PTR_TO_MAP_VALUE_OR_NULL:
800 	case PTR_TO_STACK:
801 	case PTR_TO_CTX:
802 	case PTR_TO_PACKET:
803 	case PTR_TO_PACKET_END:
804 	case CONST_PTR_TO_MAP:
805 		return true;
806 	default:
807 		return false;
808 	}
809 }
810 
811 /* check_stack_read/write functions track spill/fill of registers,
812  * stack boundary and alignment are checked in check_mem_access()
813  */
check_stack_write(struct bpf_verifier_env * env,struct bpf_verifier_state * state,int off,int size,int value_regno,int insn_idx)814 static int check_stack_write(struct bpf_verifier_env *env,
815 			     struct bpf_verifier_state *state, int off,
816 			     int size, int value_regno, int insn_idx)
817 {
818 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
819 
820 	err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE),
821 				     true);
822 	if (err)
823 		return err;
824 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
825 	 * so it's aligned access and [off, off + size) are within stack limits
826 	 */
827 	if (!env->allow_ptr_leaks &&
828 	    state->stack[spi].slot_type[0] == STACK_SPILL &&
829 	    size != BPF_REG_SIZE) {
830 		verbose("attempt to corrupt spilled pointer on stack\n");
831 		return -EACCES;
832 	}
833 
834 	if (value_regno >= 0 &&
835 	    is_spillable_regtype(state->regs[value_regno].type)) {
836 
837 		/* register containing pointer is being spilled into stack */
838 		if (size != BPF_REG_SIZE) {
839 			verbose("invalid size of register spill\n");
840 			return -EACCES;
841 		}
842 
843 		/* save register state */
844 		state->stack[spi].spilled_ptr = state->regs[value_regno];
845 		state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
846 
847 		for (i = 0; i < BPF_REG_SIZE; i++) {
848 			if (state->stack[spi].slot_type[i] == STACK_MISC &&
849 			    !env->allow_ptr_leaks) {
850 				int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
851 				int soff = (-spi - 1) * BPF_REG_SIZE;
852 
853 				/* detected reuse of integer stack slot with a pointer
854 				 * which means either llvm is reusing stack slot or
855 				 * an attacker is trying to exploit CVE-2018-3639
856 				 * (speculative store bypass)
857 				 * Have to sanitize that slot with preemptive
858 				 * store of zero.
859 				 */
860 				if (*poff && *poff != soff) {
861 					/* disallow programs where single insn stores
862 					 * into two different stack slots, since verifier
863 					 * cannot sanitize them
864 					 */
865 					verbose("insn %d cannot access two stack slots fp%d and fp%d",
866 						insn_idx, *poff, soff);
867 					return -EINVAL;
868 				}
869 				*poff = soff;
870 			}
871 			state->stack[spi].slot_type[i] = STACK_SPILL;
872 		}
873 	} else {
874 		/* regular write of data into stack */
875 		state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
876 
877 		for (i = 0; i < size; i++)
878 			state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
879 				STACK_MISC;
880 	}
881 	return 0;
882 }
883 
mark_stack_slot_read(const struct bpf_verifier_state * state,int slot)884 static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
885 {
886 	struct bpf_verifier_state *parent = state->parent;
887 
888 	while (parent) {
889 		/* if read wasn't screened by an earlier write ... */
890 		if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
891 			break;
892 		/* ... then we depend on parent's value */
893 		parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
894 		state = parent;
895 		parent = state->parent;
896 	}
897 }
898 
check_stack_read(struct bpf_verifier_state * state,int off,int size,int value_regno)899 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
900 			    int value_regno)
901 {
902 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
903 	u8 *stype;
904 
905 	if (state->allocated_stack <= slot) {
906 		verbose("invalid read from stack off %d+0 size %d\n",
907 			off, size);
908 		return -EACCES;
909 	}
910 	stype = state->stack[spi].slot_type;
911 
912 	if (stype[0] == STACK_SPILL) {
913 		if (size != BPF_REG_SIZE) {
914 			verbose("invalid size of register spill\n");
915 			return -EACCES;
916 		}
917 		for (i = 1; i < BPF_REG_SIZE; i++) {
918 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
919 				verbose("corrupted spill memory\n");
920 				return -EACCES;
921 			}
922 		}
923 
924 		if (value_regno >= 0) {
925 			/* restore register state from stack */
926 			state->regs[value_regno] = state->stack[spi].spilled_ptr;
927 			mark_stack_slot_read(state, spi);
928 		}
929 		return 0;
930 	} else {
931 		for (i = 0; i < size; i++) {
932 			if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) {
933 				verbose("invalid read from stack off %d+%d size %d\n",
934 					off, i, size);
935 				return -EACCES;
936 			}
937 		}
938 		if (value_regno >= 0)
939 			/* have read misc data from the stack */
940 			mark_reg_unknown(state->regs, value_regno);
941 		return 0;
942 	}
943 }
944 
check_stack_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size)945 static int check_stack_access(struct bpf_verifier_env *env,
946 			      const struct bpf_reg_state *reg,
947 			      int off, int size)
948 {
949 	/* Stack accesses must be at a fixed offset, so that we
950 	 * can determine what type of data were returned. See
951 	 * check_stack_read().
952 	 */
953 	if (!tnum_is_const(reg->var_off)) {
954 		char tn_buf[48];
955 
956 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
957 		verbose("variable stack access var_off=%s off=%d size=%d",
958 			tn_buf, off, size);
959 		return -EACCES;
960 	}
961 
962 	if (off >= 0 || off < -MAX_BPF_STACK) {
963 		verbose("invalid stack off=%d size=%d\n", off, size);
964 		return -EACCES;
965 	}
966 
967 	return 0;
968 }
969 
970 /* 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)971 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
972 			    int size)
973 {
974 	struct bpf_reg_state *regs = cur_regs(env);
975 	struct bpf_map *map = regs[regno].map_ptr;
976 
977 	if (off < 0 || size <= 0 || off + size > map->value_size) {
978 		verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
979 			map->value_size, off, size);
980 		return -EACCES;
981 	}
982 	return 0;
983 }
984 
985 /* check read/write into a map element with possible variable offset */
check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size)986 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
987 			    int off, int size)
988 {
989 	struct bpf_verifier_state *state = env->cur_state;
990 	struct bpf_reg_state *reg = &state->regs[regno];
991 	int err;
992 
993 	/* We may have adjusted the register to this map value, so we
994 	 * need to try adding each of min_value and max_value to off
995 	 * to make sure our theoretical access will be safe.
996 	 */
997 	if (log_level)
998 		print_verifier_state(state);
999 
1000 	/* The minimum value is only important with signed
1001 	 * comparisons where we can't assume the floor of a
1002 	 * value is 0.  If we are using signed variables for our
1003 	 * index'es we need to make sure that whatever we use
1004 	 * will have a set floor within our range.
1005 	 */
1006 	if (reg->smin_value < 0 &&
1007 	    (reg->smin_value == S64_MIN ||
1008 	     (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1009 	      reg->smin_value + off < 0)) {
1010 		verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1011 			regno);
1012 		return -EACCES;
1013 	}
1014 	err = __check_map_access(env, regno, reg->smin_value + off, size);
1015 	if (err) {
1016 		verbose("R%d min value is outside of the array range\n", regno);
1017 		return err;
1018 	}
1019 
1020 	/* If we haven't set a max value then we need to bail since we can't be
1021 	 * sure we won't do bad things.
1022 	 * If reg->umax_value + off could overflow, treat that as unbounded too.
1023 	 */
1024 	if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1025 		verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1026 			regno);
1027 		return -EACCES;
1028 	}
1029 	err = __check_map_access(env, regno, reg->umax_value + off, size);
1030 	if (err)
1031 		verbose("R%d max value is outside of the array range\n", regno);
1032 	return err;
1033 }
1034 
1035 #define MAX_PACKET_OFF 0xffff
1036 
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)1037 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1038 				       const struct bpf_call_arg_meta *meta,
1039 				       enum bpf_access_type t)
1040 {
1041 	switch (env->prog->type) {
1042 	case BPF_PROG_TYPE_LWT_IN:
1043 	case BPF_PROG_TYPE_LWT_OUT:
1044 		/* dst_input() and dst_output() can't write for now */
1045 		if (t == BPF_WRITE)
1046 			return false;
1047 		/* fallthrough */
1048 	case BPF_PROG_TYPE_SCHED_CLS:
1049 	case BPF_PROG_TYPE_SCHED_ACT:
1050 	case BPF_PROG_TYPE_XDP:
1051 	case BPF_PROG_TYPE_LWT_XMIT:
1052 	case BPF_PROG_TYPE_SK_SKB:
1053 		if (meta)
1054 			return meta->pkt_access;
1055 
1056 		env->seen_direct_write = true;
1057 		return true;
1058 	default:
1059 		return false;
1060 	}
1061 }
1062 
__check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size)1063 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1064 				 int off, int size)
1065 {
1066 	struct bpf_reg_state *regs = cur_regs(env);
1067 	struct bpf_reg_state *reg = &regs[regno];
1068 
1069 	if (off < 0 || size <= 0 || (u64)off + size > reg->range) {
1070 		verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1071 			off, size, regno, reg->id, reg->off, reg->range);
1072 		return -EACCES;
1073 	}
1074 	return 0;
1075 }
1076 
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size)1077 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1078 			       int size)
1079 {
1080 	struct bpf_reg_state *regs = cur_regs(env);
1081 	struct bpf_reg_state *reg = &regs[regno];
1082 	int err;
1083 
1084 	/* We may have added a variable offset to the packet pointer; but any
1085 	 * reg->range we have comes after that.  We are only checking the fixed
1086 	 * offset.
1087 	 */
1088 
1089 	/* We don't allow negative numbers, because we aren't tracking enough
1090 	 * detail to prove they're safe.
1091 	 */
1092 	if (reg->smin_value < 0) {
1093 		verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1094 			regno);
1095 		return -EACCES;
1096 	}
1097 	err = __check_packet_access(env, regno, off, size);
1098 	if (err) {
1099 		verbose("R%d offset is outside of the packet\n", regno);
1100 		return err;
1101 	}
1102 	return err;
1103 }
1104 
1105 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,enum bpf_reg_type * reg_type)1106 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1107 			    enum bpf_access_type t, enum bpf_reg_type *reg_type)
1108 {
1109 	struct bpf_insn_access_aux info = {
1110 		.reg_type = *reg_type,
1111 	};
1112 
1113 	/* for analyzer ctx accesses are already validated and converted */
1114 	if (env->analyzer_ops)
1115 		return 0;
1116 
1117 	if (env->prog->aux->ops->is_valid_access &&
1118 	    env->prog->aux->ops->is_valid_access(off, size, t, &info)) {
1119 		/* A non zero info.ctx_field_size indicates that this field is a
1120 		 * candidate for later verifier transformation to load the whole
1121 		 * field and then apply a mask when accessed with a narrower
1122 		 * access than actual ctx access size. A zero info.ctx_field_size
1123 		 * will only allow for whole field access and rejects any other
1124 		 * type of narrower access.
1125 		 */
1126 		env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1127 		*reg_type = info.reg_type;
1128 
1129 		/* remember the offset of last byte accessed in ctx */
1130 		if (env->prog->aux->max_ctx_offset < off + size)
1131 			env->prog->aux->max_ctx_offset = off + size;
1132 		return 0;
1133 	}
1134 
1135 	verbose("invalid bpf_context access off=%d size=%d\n", off, size);
1136 	return -EACCES;
1137 }
1138 
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)1139 static bool __is_pointer_value(bool allow_ptr_leaks,
1140 			       const struct bpf_reg_state *reg)
1141 {
1142 	if (allow_ptr_leaks)
1143 		return false;
1144 
1145 	return reg->type != SCALAR_VALUE;
1146 }
1147 
is_pointer_value(struct bpf_verifier_env * env,int regno)1148 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1149 {
1150 	return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1151 }
1152 
is_ctx_reg(struct bpf_verifier_env * env,int regno)1153 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1154 {
1155 	const struct bpf_reg_state *reg = cur_regs(env) + regno;
1156 
1157 	return reg->type == PTR_TO_CTX;
1158 }
1159 
is_pkt_reg(struct bpf_verifier_env * env,int regno)1160 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1161 {
1162 	const struct bpf_reg_state *reg = cur_regs(env) + regno;
1163 
1164 	return reg->type == PTR_TO_PACKET;
1165 }
1166 
check_pkt_ptr_alignment(const struct bpf_reg_state * reg,int off,int size,bool strict)1167 static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
1168 				   int off, int size, bool strict)
1169 {
1170 	struct tnum reg_off;
1171 	int ip_align;
1172 
1173 	/* Byte size accesses are always allowed. */
1174 	if (!strict || size == 1)
1175 		return 0;
1176 
1177 	/* For platforms that do not have a Kconfig enabling
1178 	 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1179 	 * NET_IP_ALIGN is universally set to '2'.  And on platforms
1180 	 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1181 	 * to this code only in strict mode where we want to emulate
1182 	 * the NET_IP_ALIGN==2 checking.  Therefore use an
1183 	 * unconditional IP align value of '2'.
1184 	 */
1185 	ip_align = 2;
1186 
1187 	reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1188 	if (!tnum_is_aligned(reg_off, size)) {
1189 		char tn_buf[48];
1190 
1191 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1192 		verbose("misaligned packet access off %d+%s+%d+%d size %d\n",
1193 			ip_align, tn_buf, reg->off, off, size);
1194 		return -EACCES;
1195 	}
1196 
1197 	return 0;
1198 }
1199 
check_generic_ptr_alignment(const struct bpf_reg_state * reg,const char * pointer_desc,int off,int size,bool strict)1200 static int check_generic_ptr_alignment(const struct bpf_reg_state *reg,
1201 				       const char *pointer_desc,
1202 				       int off, int size, bool strict)
1203 {
1204 	struct tnum reg_off;
1205 
1206 	/* Byte size accesses are always allowed. */
1207 	if (!strict || size == 1)
1208 		return 0;
1209 
1210 	reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1211 	if (!tnum_is_aligned(reg_off, size)) {
1212 		char tn_buf[48];
1213 
1214 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1215 		verbose("misaligned %saccess off %s+%d+%d size %d\n",
1216 			pointer_desc, tn_buf, reg->off, off, size);
1217 		return -EACCES;
1218 	}
1219 
1220 	return 0;
1221 }
1222 
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)1223 static int check_ptr_alignment(struct bpf_verifier_env *env,
1224 			       const struct bpf_reg_state *reg, int off,
1225 			       int size, bool strict_alignment_once)
1226 {
1227 	bool strict = env->strict_alignment || strict_alignment_once;
1228 	const char *pointer_desc = "";
1229 
1230 	switch (reg->type) {
1231 	case PTR_TO_PACKET:
1232 		/* special case, because of NET_IP_ALIGN */
1233 		return check_pkt_ptr_alignment(reg, off, size, strict);
1234 	case PTR_TO_MAP_VALUE:
1235 		pointer_desc = "value ";
1236 		break;
1237 	case PTR_TO_CTX:
1238 		pointer_desc = "context ";
1239 		break;
1240 	case PTR_TO_STACK:
1241 		pointer_desc = "stack ";
1242 		/* The stack spill tracking logic in check_stack_write()
1243 		 * and check_stack_read() relies on stack accesses being
1244 		 * aligned.
1245 		 */
1246 		strict = true;
1247 		break;
1248 	default:
1249 		break;
1250 	}
1251 	return check_generic_ptr_alignment(reg, pointer_desc, off, size, strict);
1252 }
1253 
check_ctx_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)1254 static int check_ctx_reg(struct bpf_verifier_env *env,
1255 			 const struct bpf_reg_state *reg, int regno)
1256 {
1257 	/* Access to ctx or passing it to a helper is only allowed in
1258 	 * its original, unmodified form.
1259 	 */
1260 
1261 	if (reg->off) {
1262 		verbose("dereference of modified ctx ptr R%d off=%d disallowed\n",
1263 			regno, reg->off);
1264 		return -EACCES;
1265 	}
1266 
1267 	if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1268 		char tn_buf[48];
1269 
1270 		tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1271 		verbose("variable ctx access var_off=%s disallowed\n", tn_buf);
1272 		return -EACCES;
1273 	}
1274 
1275 	return 0;
1276 }
1277 
1278 /* truncate register to smaller size (in bytes)
1279  * must be called with size < BPF_REG_SIZE
1280  */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)1281 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1282 {
1283 	u64 mask;
1284 
1285 	/* clear high bits in bit representation */
1286 	reg->var_off = tnum_cast(reg->var_off, size);
1287 
1288 	/* fix arithmetic bounds */
1289 	mask = ((u64)1 << (size * 8)) - 1;
1290 	if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1291 		reg->umin_value &= mask;
1292 		reg->umax_value &= mask;
1293 	} else {
1294 		reg->umin_value = 0;
1295 		reg->umax_value = mask;
1296 	}
1297 	reg->smin_value = reg->umin_value;
1298 	reg->smax_value = reg->umax_value;
1299 }
1300 
1301 /* check whether memory at (regno + off) is accessible for t = (read | write)
1302  * if t==write, value_regno is a register which value is stored into memory
1303  * if t==read, value_regno is a register which will receive the value from memory
1304  * if t==write && value_regno==-1, some unknown value is stored into memory
1305  * if t==read && value_regno==-1, don't care what we read from memory
1306  */
check_mem_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int bpf_size,enum bpf_access_type t,int value_regno,bool strict_alignment_once)1307 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1308 			    int off, int bpf_size, enum bpf_access_type t,
1309 			    int value_regno, bool strict_alignment_once)
1310 {
1311 	struct bpf_verifier_state *state = env->cur_state;
1312 	struct bpf_reg_state *regs = cur_regs(env);
1313 	struct bpf_reg_state *reg = regs + regno;
1314 	int size, err = 0;
1315 
1316 	size = bpf_size_to_bytes(bpf_size);
1317 	if (size < 0)
1318 		return size;
1319 
1320 	/* alignment checks will add in reg->off themselves */
1321 	err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1322 	if (err)
1323 		return err;
1324 
1325 	/* for access checks, reg->off is just part of off */
1326 	off += reg->off;
1327 
1328 	if (reg->type == PTR_TO_MAP_VALUE) {
1329 		if (t == BPF_WRITE && value_regno >= 0 &&
1330 		    is_pointer_value(env, value_regno)) {
1331 			verbose("R%d leaks addr into map\n", value_regno);
1332 			return -EACCES;
1333 		}
1334 
1335 		err = check_map_access(env, regno, off, size);
1336 		if (!err && t == BPF_READ && value_regno >= 0)
1337 			mark_reg_unknown(regs, value_regno);
1338 
1339 	} else if (reg->type == PTR_TO_CTX) {
1340 		enum bpf_reg_type reg_type = SCALAR_VALUE;
1341 
1342 		if (t == BPF_WRITE && value_regno >= 0 &&
1343 		    is_pointer_value(env, value_regno)) {
1344 			verbose("R%d leaks addr into ctx\n", value_regno);
1345 			return -EACCES;
1346 		}
1347 		err = check_ctx_reg(env, reg, regno);
1348 		if (err < 0)
1349 			return err;
1350 
1351 		err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
1352 		if (!err && t == BPF_READ && value_regno >= 0) {
1353 			/* ctx access returns either a scalar, or a
1354 			 * PTR_TO_PACKET[_END].  In the latter case, we know
1355 			 * the offset is zero.
1356 			 */
1357 			if (reg_type == SCALAR_VALUE)
1358 				mark_reg_unknown(regs, value_regno);
1359 			else
1360 				mark_reg_known_zero(regs, value_regno);
1361 			regs[value_regno].id = 0;
1362 			regs[value_regno].off = 0;
1363 			regs[value_regno].range = 0;
1364 			regs[value_regno].type = reg_type;
1365 		}
1366 
1367 	} else if (reg->type == PTR_TO_STACK) {
1368 		off += reg->var_off.value;
1369 		err = check_stack_access(env, reg, off, size);
1370 		if (err)
1371 			return err;
1372 
1373 		if (env->prog->aux->stack_depth < -off)
1374 			env->prog->aux->stack_depth = -off;
1375 
1376 		if (t == BPF_WRITE)
1377 			err = check_stack_write(env, state, off, size,
1378 						value_regno, insn_idx);
1379 		else
1380 			err = check_stack_read(state, off, size, value_regno);
1381 	} else if (reg->type == PTR_TO_PACKET) {
1382 		if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1383 			verbose("cannot write into packet\n");
1384 			return -EACCES;
1385 		}
1386 		if (t == BPF_WRITE && value_regno >= 0 &&
1387 		    is_pointer_value(env, value_regno)) {
1388 			verbose("R%d leaks addr into packet\n", value_regno);
1389 			return -EACCES;
1390 		}
1391 		err = check_packet_access(env, regno, off, size);
1392 		if (!err && t == BPF_READ && value_regno >= 0)
1393 			mark_reg_unknown(regs, value_regno);
1394 	} else {
1395 		verbose("R%d invalid mem access '%s'\n",
1396 			regno, reg_type_str[reg->type]);
1397 		return -EACCES;
1398 	}
1399 
1400 	if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1401 	    regs[value_regno].type == SCALAR_VALUE) {
1402 		/* b/h/w load zero-extends, mark upper bits as known 0 */
1403 		coerce_reg_to_size(&regs[value_regno], size);
1404 	}
1405 	return err;
1406 }
1407 
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)1408 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1409 {
1410 	int err;
1411 
1412 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1413 	    insn->imm != 0) {
1414 		verbose("BPF_XADD uses reserved fields\n");
1415 		return -EINVAL;
1416 	}
1417 
1418 	/* check src1 operand */
1419 	err = check_reg_arg(env, insn->src_reg, SRC_OP);
1420 	if (err)
1421 		return err;
1422 
1423 	/* check src2 operand */
1424 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1425 	if (err)
1426 		return err;
1427 
1428 	if (is_pointer_value(env, insn->src_reg)) {
1429 		verbose("R%d leaks addr into mem\n", insn->src_reg);
1430 		return -EACCES;
1431 	}
1432 
1433 	if (is_ctx_reg(env, insn->dst_reg) ||
1434 	    is_pkt_reg(env, insn->dst_reg)) {
1435 		verbose("BPF_XADD stores into R%d %s is not allowed\n",
1436 			insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1437 			"context" : "packet");
1438 		return -EACCES;
1439 	}
1440 
1441 	/* check whether atomic_add can read the memory */
1442 	err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1443 			       BPF_SIZE(insn->code), BPF_READ, -1, true);
1444 	if (err)
1445 		return err;
1446 
1447 	/* check whether atomic_add can write into the same memory */
1448 	return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1449 				BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1450 }
1451 
1452 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state reg)1453 static bool register_is_null(struct bpf_reg_state reg)
1454 {
1455 	return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
1456 }
1457 
1458 /* when register 'regno' is passed into function that will read 'access_size'
1459  * bytes from that pointer, make sure that it's within stack boundary
1460  * and all elements of stack are initialized.
1461  * Unlike most pointer bounds-checking functions, this one doesn't take an
1462  * 'off' argument, so it has to add in reg->off itself.
1463  */
check_stack_boundary(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)1464 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1465 				int access_size, bool zero_size_allowed,
1466 				struct bpf_call_arg_meta *meta)
1467 {
1468 	struct bpf_verifier_state *state = env->cur_state;
1469 	struct bpf_reg_state *regs = state->regs;
1470 	int off, i, slot, spi;
1471 
1472 	if (regs[regno].type != PTR_TO_STACK) {
1473 		/* Allow zero-byte read from NULL, regardless of pointer type */
1474 		if (zero_size_allowed && access_size == 0 &&
1475 		    register_is_null(regs[regno]))
1476 			return 0;
1477 
1478 		verbose("R%d type=%s expected=%s\n", regno,
1479 			reg_type_str[regs[regno].type],
1480 			reg_type_str[PTR_TO_STACK]);
1481 		return -EACCES;
1482 	}
1483 
1484 	/* Only allow fixed-offset stack reads */
1485 	if (!tnum_is_const(regs[regno].var_off)) {
1486 		char tn_buf[48];
1487 
1488 		tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
1489 		verbose("invalid variable stack read R%d var_off=%s\n",
1490 			regno, tn_buf);
1491 		return -EACCES;
1492 	}
1493 	off = regs[regno].off + regs[regno].var_off.value;
1494 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1495 	    access_size <= 0) {
1496 		verbose("invalid stack type R%d off=%d access_size=%d\n",
1497 			regno, off, access_size);
1498 		return -EACCES;
1499 	}
1500 
1501 	if (env->prog->aux->stack_depth < -off)
1502 		env->prog->aux->stack_depth = -off;
1503 
1504 	if (meta && meta->raw_mode) {
1505 		meta->access_size = access_size;
1506 		meta->regno = regno;
1507 		return 0;
1508 	}
1509 
1510 	for (i = 0; i < access_size; i++) {
1511 		slot = -(off + i) - 1;
1512 		spi = slot / BPF_REG_SIZE;
1513 		if (state->allocated_stack <= slot ||
1514 		    state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
1515 			STACK_MISC) {
1516 			verbose("invalid indirect read from stack off %d+%d size %d\n",
1517 				off, i, access_size);
1518 			return -EACCES;
1519 		}
1520 	}
1521 	return 0;
1522 }
1523 
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)1524 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1525 				   int access_size, bool zero_size_allowed,
1526 				   struct bpf_call_arg_meta *meta)
1527 {
1528 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1529 
1530 	switch (reg->type) {
1531 	case PTR_TO_PACKET:
1532 		return check_packet_access(env, regno, reg->off, access_size);
1533 	case PTR_TO_MAP_VALUE:
1534 		return check_map_access(env, regno, reg->off, access_size);
1535 	default: /* scalar_value|ptr_to_stack or invalid ptr */
1536 		return check_stack_boundary(env, regno, access_size,
1537 					    zero_size_allowed, meta);
1538 	}
1539 }
1540 
check_func_arg(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,struct bpf_call_arg_meta * meta)1541 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1542 			  enum bpf_arg_type arg_type,
1543 			  struct bpf_call_arg_meta *meta)
1544 {
1545 	struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1546 	enum bpf_reg_type expected_type, type = reg->type;
1547 	int err = 0;
1548 
1549 	if (arg_type == ARG_DONTCARE)
1550 		return 0;
1551 
1552 	err = check_reg_arg(env, regno, SRC_OP);
1553 	if (err)
1554 		return err;
1555 
1556 	if (arg_type == ARG_ANYTHING) {
1557 		if (is_pointer_value(env, regno)) {
1558 			verbose("R%d leaks addr into helper function\n", regno);
1559 			return -EACCES;
1560 		}
1561 		return 0;
1562 	}
1563 
1564 	if (type == PTR_TO_PACKET &&
1565 	    !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1566 		verbose("helper access to the packet is not allowed\n");
1567 		return -EACCES;
1568 	}
1569 
1570 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
1571 	    arg_type == ARG_PTR_TO_MAP_VALUE) {
1572 		expected_type = PTR_TO_STACK;
1573 		if (type != PTR_TO_PACKET && type != expected_type)
1574 			goto err_type;
1575 	} else if (arg_type == ARG_CONST_SIZE ||
1576 		   arg_type == ARG_CONST_SIZE_OR_ZERO) {
1577 		expected_type = SCALAR_VALUE;
1578 		if (type != expected_type)
1579 			goto err_type;
1580 	} else if (arg_type == ARG_CONST_MAP_PTR) {
1581 		expected_type = CONST_PTR_TO_MAP;
1582 		if (type != expected_type)
1583 			goto err_type;
1584 	} else if (arg_type == ARG_PTR_TO_CTX) {
1585 		expected_type = PTR_TO_CTX;
1586 		if (type != expected_type)
1587 			goto err_type;
1588 		err = check_ctx_reg(env, reg, regno);
1589 		if (err < 0)
1590 			return err;
1591 	} else if (arg_type == ARG_PTR_TO_MEM ||
1592 		   arg_type == ARG_PTR_TO_UNINIT_MEM) {
1593 		expected_type = PTR_TO_STACK;
1594 		/* One exception here. In case function allows for NULL to be
1595 		 * passed in as argument, it's a SCALAR_VALUE type. Final test
1596 		 * happens during stack boundary checking.
1597 		 */
1598 		if (register_is_null(*reg))
1599 			/* final test in check_stack_boundary() */;
1600 		else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
1601 			 type != expected_type)
1602 			goto err_type;
1603 		meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1604 	} else {
1605 		verbose("unsupported arg_type %d\n", arg_type);
1606 		return -EFAULT;
1607 	}
1608 
1609 	if (arg_type == ARG_CONST_MAP_PTR) {
1610 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1611 		meta->map_ptr = reg->map_ptr;
1612 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1613 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
1614 		 * check that [key, key + map->key_size) are within
1615 		 * stack limits and initialized
1616 		 */
1617 		if (!meta->map_ptr) {
1618 			/* in function declaration map_ptr must come before
1619 			 * map_key, so that it's verified and known before
1620 			 * we have to check map_key here. Otherwise it means
1621 			 * that kernel subsystem misconfigured verifier
1622 			 */
1623 			verbose("invalid map_ptr to access map->key\n");
1624 			return -EACCES;
1625 		}
1626 		if (type == PTR_TO_PACKET)
1627 			err = check_packet_access(env, regno, reg->off,
1628 						  meta->map_ptr->key_size);
1629 		else
1630 			err = check_stack_boundary(env, regno,
1631 						   meta->map_ptr->key_size,
1632 						   false, NULL);
1633 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1634 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
1635 		 * check [value, value + map->value_size) validity
1636 		 */
1637 		if (!meta->map_ptr) {
1638 			/* kernel subsystem misconfigured verifier */
1639 			verbose("invalid map_ptr to access map->value\n");
1640 			return -EACCES;
1641 		}
1642 		if (type == PTR_TO_PACKET)
1643 			err = check_packet_access(env, regno, reg->off,
1644 						  meta->map_ptr->value_size);
1645 		else
1646 			err = check_stack_boundary(env, regno,
1647 						   meta->map_ptr->value_size,
1648 						   false, NULL);
1649 	} else if (arg_type == ARG_CONST_SIZE ||
1650 		   arg_type == ARG_CONST_SIZE_OR_ZERO) {
1651 		bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1652 
1653 		/* bpf_xxx(..., buf, len) call will access 'len' bytes
1654 		 * from stack pointer 'buf'. Check it
1655 		 * note: regno == len, regno - 1 == buf
1656 		 */
1657 		if (regno == 0) {
1658 			/* kernel subsystem misconfigured verifier */
1659 			verbose("ARG_CONST_SIZE cannot be first argument\n");
1660 			return -EACCES;
1661 		}
1662 
1663 		/* The register is SCALAR_VALUE; the access check
1664 		 * happens using its boundaries.
1665 		 */
1666 
1667 		if (!tnum_is_const(reg->var_off))
1668 			/* For unprivileged variable accesses, disable raw
1669 			 * mode so that the program is required to
1670 			 * initialize all the memory that the helper could
1671 			 * just partially fill up.
1672 			 */
1673 			meta = NULL;
1674 
1675 		if (reg->smin_value < 0) {
1676 			verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
1677 				regno);
1678 			return -EACCES;
1679 		}
1680 
1681 		if (reg->umin_value == 0) {
1682 			err = check_helper_mem_access(env, regno - 1, 0,
1683 						      zero_size_allowed,
1684 						      meta);
1685 			if (err)
1686 				return err;
1687 		}
1688 
1689 		if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
1690 			verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
1691 				regno);
1692 			return -EACCES;
1693 		}
1694 		err = check_helper_mem_access(env, regno - 1,
1695 					      reg->umax_value,
1696 					      zero_size_allowed, meta);
1697 	}
1698 
1699 	return err;
1700 err_type:
1701 	verbose("R%d type=%s expected=%s\n", regno,
1702 		reg_type_str[type], reg_type_str[expected_type]);
1703 	return -EACCES;
1704 }
1705 
check_map_func_compatibility(struct bpf_map * map,int func_id)1706 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1707 {
1708 	if (!map)
1709 		return 0;
1710 
1711 	/* We need a two way check, first is from map perspective ... */
1712 	switch (map->map_type) {
1713 	case BPF_MAP_TYPE_PROG_ARRAY:
1714 		if (func_id != BPF_FUNC_tail_call)
1715 			goto error;
1716 		break;
1717 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1718 		if (func_id != BPF_FUNC_perf_event_read &&
1719 		    func_id != BPF_FUNC_perf_event_output)
1720 			goto error;
1721 		break;
1722 	case BPF_MAP_TYPE_STACK_TRACE:
1723 		if (func_id != BPF_FUNC_get_stackid)
1724 			goto error;
1725 		break;
1726 	case BPF_MAP_TYPE_CGROUP_ARRAY:
1727 		if (func_id != BPF_FUNC_skb_under_cgroup &&
1728 		    func_id != BPF_FUNC_current_task_under_cgroup)
1729 			goto error;
1730 		break;
1731 	/* devmap returns a pointer to a live net_device ifindex that we cannot
1732 	 * allow to be modified from bpf side. So do not allow lookup elements
1733 	 * for now.
1734 	 */
1735 	case BPF_MAP_TYPE_DEVMAP:
1736 		if (func_id != BPF_FUNC_redirect_map)
1737 			goto error;
1738 		break;
1739 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1740 	case BPF_MAP_TYPE_HASH_OF_MAPS:
1741 		if (func_id != BPF_FUNC_map_lookup_elem)
1742 			goto error;
1743 		break;
1744 	case BPF_MAP_TYPE_SOCKMAP:
1745 		if (func_id != BPF_FUNC_sk_redirect_map &&
1746 		    func_id != BPF_FUNC_sock_map_update &&
1747 		    func_id != BPF_FUNC_map_delete_elem)
1748 			goto error;
1749 		break;
1750 	default:
1751 		break;
1752 	}
1753 
1754 	/* ... and second from the function itself. */
1755 	switch (func_id) {
1756 	case BPF_FUNC_tail_call:
1757 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1758 			goto error;
1759 		break;
1760 	case BPF_FUNC_perf_event_read:
1761 	case BPF_FUNC_perf_event_output:
1762 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1763 			goto error;
1764 		break;
1765 	case BPF_FUNC_get_stackid:
1766 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1767 			goto error;
1768 		break;
1769 	case BPF_FUNC_current_task_under_cgroup:
1770 	case BPF_FUNC_skb_under_cgroup:
1771 		if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1772 			goto error;
1773 		break;
1774 	case BPF_FUNC_redirect_map:
1775 		if (map->map_type != BPF_MAP_TYPE_DEVMAP)
1776 			goto error;
1777 		break;
1778 	case BPF_FUNC_sk_redirect_map:
1779 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
1780 			goto error;
1781 		break;
1782 	case BPF_FUNC_sock_map_update:
1783 		if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
1784 			goto error;
1785 		break;
1786 	default:
1787 		break;
1788 	}
1789 
1790 	return 0;
1791 error:
1792 	verbose("cannot pass map_type %d into func %s#%d\n",
1793 		map->map_type, func_id_name(func_id), func_id);
1794 	return -EINVAL;
1795 }
1796 
check_raw_mode(const struct bpf_func_proto * fn)1797 static int check_raw_mode(const struct bpf_func_proto *fn)
1798 {
1799 	int count = 0;
1800 
1801 	if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
1802 		count++;
1803 	if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
1804 		count++;
1805 	if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
1806 		count++;
1807 	if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
1808 		count++;
1809 	if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
1810 		count++;
1811 
1812 	return count > 1 ? -EINVAL : 0;
1813 }
1814 
1815 /* Packet data might have moved, any old PTR_TO_PACKET[_END] are now invalid,
1816  * so turn them into unknown SCALAR_VALUE.
1817  */
clear_all_pkt_pointers(struct bpf_verifier_env * env)1818 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1819 {
1820 	struct bpf_verifier_state *state = env->cur_state;
1821 	struct bpf_reg_state *regs = state->regs, *reg;
1822 	int i;
1823 
1824 	for (i = 0; i < MAX_BPF_REG; i++)
1825 		if (regs[i].type == PTR_TO_PACKET ||
1826 		    regs[i].type == PTR_TO_PACKET_END)
1827 			mark_reg_unknown(regs, i);
1828 
1829 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1830 		if (state->stack[i].slot_type[0] != STACK_SPILL)
1831 			continue;
1832 		reg = &state->stack[i].spilled_ptr;
1833 		if (reg->type != PTR_TO_PACKET &&
1834 		    reg->type != PTR_TO_PACKET_END)
1835 			continue;
1836 		__mark_reg_unknown(reg);
1837 	}
1838 }
1839 
check_call(struct bpf_verifier_env * env,int func_id,int insn_idx)1840 static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
1841 {
1842 	const struct bpf_func_proto *fn = NULL;
1843 	struct bpf_reg_state *regs;
1844 	struct bpf_call_arg_meta meta;
1845 	bool changes_data;
1846 	int i, err;
1847 
1848 	/* find function prototype */
1849 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1850 		verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
1851 		return -EINVAL;
1852 	}
1853 
1854 	if (env->prog->aux->ops->get_func_proto)
1855 		fn = env->prog->aux->ops->get_func_proto(func_id);
1856 
1857 	if (!fn) {
1858 		verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
1859 		return -EINVAL;
1860 	}
1861 
1862 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
1863 	if (!env->prog->gpl_compatible && fn->gpl_only) {
1864 		verbose("cannot call GPL only function from proprietary program\n");
1865 		return -EINVAL;
1866 	}
1867 
1868 	changes_data = bpf_helper_changes_pkt_data(fn->func);
1869 
1870 	memset(&meta, 0, sizeof(meta));
1871 	meta.pkt_access = fn->pkt_access;
1872 
1873 	/* We only support one arg being in raw mode at the moment, which
1874 	 * is sufficient for the helper functions we have right now.
1875 	 */
1876 	err = check_raw_mode(fn);
1877 	if (err) {
1878 		verbose("kernel subsystem misconfigured func %s#%d\n",
1879 			func_id_name(func_id), func_id);
1880 		return err;
1881 	}
1882 
1883 	/* check args */
1884 	err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1885 	if (err)
1886 		return err;
1887 	err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1888 	if (err)
1889 		return err;
1890 	if (func_id == BPF_FUNC_tail_call) {
1891 		if (meta.map_ptr == NULL) {
1892 			verbose("verifier bug\n");
1893 			return -EINVAL;
1894 		}
1895 		env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
1896 	}
1897 	err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1898 	if (err)
1899 		return err;
1900 	err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1901 	if (err)
1902 		return err;
1903 	err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1904 	if (err)
1905 		return err;
1906 
1907 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
1908 	 * is inferred from register state.
1909 	 */
1910 	for (i = 0; i < meta.access_size; i++) {
1911 		err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
1912 				       BPF_WRITE, -1, false);
1913 		if (err)
1914 			return err;
1915 	}
1916 
1917 	regs = cur_regs(env);
1918 	/* reset caller saved regs */
1919 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
1920 		mark_reg_not_init(regs, caller_saved[i]);
1921 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
1922 	}
1923 
1924 	/* update return register (already marked as written above) */
1925 	if (fn->ret_type == RET_INTEGER) {
1926 		/* sets type to SCALAR_VALUE */
1927 		mark_reg_unknown(regs, BPF_REG_0);
1928 	} else if (fn->ret_type == RET_VOID) {
1929 		regs[BPF_REG_0].type = NOT_INIT;
1930 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1931 		struct bpf_insn_aux_data *insn_aux;
1932 
1933 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1934 		/* There is no offset yet applied, variable or fixed */
1935 		mark_reg_known_zero(regs, BPF_REG_0);
1936 		regs[BPF_REG_0].off = 0;
1937 		/* remember map_ptr, so that check_map_access()
1938 		 * can check 'value_size' boundary of memory access
1939 		 * to map element returned from bpf_map_lookup_elem()
1940 		 */
1941 		if (meta.map_ptr == NULL) {
1942 			verbose("kernel subsystem misconfigured verifier\n");
1943 			return -EINVAL;
1944 		}
1945 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
1946 		regs[BPF_REG_0].id = ++env->id_gen;
1947 		insn_aux = &env->insn_aux_data[insn_idx];
1948 		if (!insn_aux->map_ptr)
1949 			insn_aux->map_ptr = meta.map_ptr;
1950 		else if (insn_aux->map_ptr != meta.map_ptr)
1951 			insn_aux->map_ptr = BPF_MAP_PTR_POISON;
1952 	} else {
1953 		verbose("unknown return type %d of func %s#%d\n",
1954 			fn->ret_type, func_id_name(func_id), func_id);
1955 		return -EINVAL;
1956 	}
1957 
1958 	err = check_map_func_compatibility(meta.map_ptr, func_id);
1959 	if (err)
1960 		return err;
1961 
1962 	if (changes_data)
1963 		clear_all_pkt_pointers(env);
1964 	return 0;
1965 }
1966 
signed_add_overflows(s64 a,s64 b)1967 static bool signed_add_overflows(s64 a, s64 b)
1968 {
1969 	/* Do the add in u64, where overflow is well-defined */
1970 	s64 res = (s64)((u64)a + (u64)b);
1971 
1972 	if (b < 0)
1973 		return res > a;
1974 	return res < a;
1975 }
1976 
signed_sub_overflows(s64 a,s64 b)1977 static bool signed_sub_overflows(s64 a, s64 b)
1978 {
1979 	/* Do the sub in u64, where overflow is well-defined */
1980 	s64 res = (s64)((u64)a - (u64)b);
1981 
1982 	if (b < 0)
1983 		return res < a;
1984 	return res > a;
1985 }
1986 
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)1987 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
1988 				  const struct bpf_reg_state *reg,
1989 				  enum bpf_reg_type type)
1990 {
1991 	bool known = tnum_is_const(reg->var_off);
1992 	s64 val = reg->var_off.value;
1993 	s64 smin = reg->smin_value;
1994 
1995 	if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
1996 		verbose("math between %s pointer and %lld is not allowed\n",
1997 			reg_type_str[type], val);
1998 		return false;
1999 	}
2000 
2001 	if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2002 		verbose("%s pointer offset %d is not allowed\n",
2003 			reg_type_str[type], reg->off);
2004 		return false;
2005 	}
2006 
2007 	if (smin == S64_MIN) {
2008 		verbose("math between %s pointer and register with unbounded min value is not allowed\n",
2009 			reg_type_str[type]);
2010 		return false;
2011 	}
2012 
2013 	if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2014 		verbose("value %lld makes %s pointer be out of bounds\n",
2015 			smin, reg_type_str[type]);
2016 		return false;
2017 	}
2018 
2019 	return true;
2020 }
2021 
cur_aux(struct bpf_verifier_env * env)2022 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
2023 {
2024 	return &env->insn_aux_data[env->insn_idx];
2025 }
2026 
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * ptr_limit,u8 opcode,bool off_is_neg)2027 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
2028 			      u32 *ptr_limit, u8 opcode, bool off_is_neg)
2029 {
2030 	bool mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
2031 			    (opcode == BPF_SUB && !off_is_neg);
2032 	u32 off;
2033 
2034 	switch (ptr_reg->type) {
2035 	case PTR_TO_STACK:
2036 		off = ptr_reg->off + ptr_reg->var_off.value;
2037 		if (mask_to_left)
2038 			*ptr_limit = MAX_BPF_STACK + off;
2039 		else
2040 			*ptr_limit = -off;
2041 		return 0;
2042 	case PTR_TO_MAP_VALUE:
2043 		if (mask_to_left) {
2044 			*ptr_limit = ptr_reg->umax_value + ptr_reg->off;
2045 		} else {
2046 			off = ptr_reg->smin_value + ptr_reg->off;
2047 			*ptr_limit = ptr_reg->map_ptr->value_size - off;
2048 		}
2049 		return 0;
2050 	default:
2051 		return -EINVAL;
2052 	}
2053 }
2054 
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)2055 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
2056 				    const struct bpf_insn *insn)
2057 {
2058 	return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
2059 }
2060 
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)2061 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
2062 				       u32 alu_state, u32 alu_limit)
2063 {
2064 	/* If we arrived here from different branches with different
2065 	 * state or limits to sanitize, then this won't work.
2066 	 */
2067 	if (aux->alu_state &&
2068 	    (aux->alu_state != alu_state ||
2069 	     aux->alu_limit != alu_limit))
2070 		return -EACCES;
2071 
2072 	/* Corresponding fixup done in fixup_bpf_calls(). */
2073 	aux->alu_state = alu_state;
2074 	aux->alu_limit = alu_limit;
2075 	return 0;
2076 }
2077 
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)2078 static int sanitize_val_alu(struct bpf_verifier_env *env,
2079 			    struct bpf_insn *insn)
2080 {
2081 	struct bpf_insn_aux_data *aux = cur_aux(env);
2082 
2083 	if (can_skip_alu_sanitation(env, insn))
2084 		return 0;
2085 
2086 	return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
2087 }
2088 
sanitize_ptr_alu(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,struct bpf_reg_state * dst_reg,bool off_is_neg)2089 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
2090 			    struct bpf_insn *insn,
2091 			    const struct bpf_reg_state *ptr_reg,
2092 			    struct bpf_reg_state *dst_reg,
2093 			    bool off_is_neg)
2094 {
2095 	struct bpf_verifier_state *vstate = env->cur_state;
2096 	struct bpf_insn_aux_data *aux = cur_aux(env);
2097 	bool ptr_is_dst_reg = ptr_reg == dst_reg;
2098 	u8 opcode = BPF_OP(insn->code);
2099 	u32 alu_state, alu_limit;
2100 	struct bpf_reg_state tmp;
2101 	bool ret;
2102 
2103 	if (can_skip_alu_sanitation(env, insn))
2104 		return 0;
2105 
2106 	/* We already marked aux for masking from non-speculative
2107 	 * paths, thus we got here in the first place. We only care
2108 	 * to explore bad access from here.
2109 	 */
2110 	if (vstate->speculative)
2111 		goto do_sim;
2112 
2113 	alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
2114 	alu_state |= ptr_is_dst_reg ?
2115 		     BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
2116 
2117 	if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
2118 		return 0;
2119 	if (update_alu_sanitation_state(aux, alu_state, alu_limit))
2120 		return -EACCES;
2121 do_sim:
2122 	/* Simulate and find potential out-of-bounds access under
2123 	 * speculative execution from truncation as a result of
2124 	 * masking when off was not within expected range. If off
2125 	 * sits in dst, then we temporarily need to move ptr there
2126 	 * to simulate dst (== 0) +/-= ptr. Needed, for example,
2127 	 * for cases where we use K-based arithmetic in one direction
2128 	 * and truncated reg-based in the other in order to explore
2129 	 * bad access.
2130 	 */
2131 	if (!ptr_is_dst_reg) {
2132 		tmp = *dst_reg;
2133 		*dst_reg = *ptr_reg;
2134 	}
2135 	ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
2136 	if (!ptr_is_dst_reg && ret)
2137 		*dst_reg = tmp;
2138 	return !ret ? -EFAULT : 0;
2139 }
2140 
2141 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2142  * Caller should also handle BPF_MOV case separately.
2143  * If we return -EACCES, caller may want to try again treating pointer as a
2144  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
2145  */
adjust_ptr_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg)2146 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2147 				   struct bpf_insn *insn,
2148 				   const struct bpf_reg_state *ptr_reg,
2149 				   const struct bpf_reg_state *off_reg)
2150 {
2151 	struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
2152 	bool known = tnum_is_const(off_reg->var_off);
2153 	s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2154 	    smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2155 	u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2156 	    umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2157 	u32 dst = insn->dst_reg, src = insn->src_reg;
2158 	u8 opcode = BPF_OP(insn->code);
2159 	int ret;
2160 
2161 	dst_reg = &regs[dst];
2162 
2163 	if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2164 	    smin_val > smax_val || umin_val > umax_val) {
2165 		/* Taint dst register if offset had invalid bounds derived from
2166 		 * e.g. dead branches.
2167 		 */
2168 		__mark_reg_unknown(dst_reg);
2169 		return 0;
2170 	}
2171 
2172 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
2173 		/* 32-bit ALU ops on pointers produce (meaningless) scalars */
2174 		if (!env->allow_ptr_leaks)
2175 			verbose("R%d 32-bit pointer arithmetic prohibited\n",
2176 				dst);
2177 		return -EACCES;
2178 	}
2179 
2180 	if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2181 		if (!env->allow_ptr_leaks)
2182 			verbose("R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2183 				dst);
2184 		return -EACCES;
2185 	}
2186 	if (ptr_reg->type == CONST_PTR_TO_MAP) {
2187 		if (!env->allow_ptr_leaks)
2188 			verbose("R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2189 				dst);
2190 		return -EACCES;
2191 	}
2192 	if (ptr_reg->type == PTR_TO_PACKET_END) {
2193 		if (!env->allow_ptr_leaks)
2194 			verbose("R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2195 				dst);
2196 		return -EACCES;
2197 	}
2198 
2199 	/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2200 	 * The id may be overwritten later if we create a new variable offset.
2201 	 */
2202 	dst_reg->type = ptr_reg->type;
2203 	dst_reg->id = ptr_reg->id;
2204 
2205 	if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2206 	    !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2207 		return -EINVAL;
2208 
2209 	switch (opcode) {
2210 	case BPF_ADD:
2211 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
2212 		if (ret < 0) {
2213 			verbose("R%d tried to add from different maps or paths\n", dst);
2214 			return ret;
2215 		}
2216 		/* We can take a fixed offset as long as it doesn't overflow
2217 		 * the s32 'off' field
2218 		 */
2219 		if (known && (ptr_reg->off + smin_val ==
2220 			      (s64)(s32)(ptr_reg->off + smin_val))) {
2221 			/* pointer += K.  Accumulate it into fixed offset */
2222 			dst_reg->smin_value = smin_ptr;
2223 			dst_reg->smax_value = smax_ptr;
2224 			dst_reg->umin_value = umin_ptr;
2225 			dst_reg->umax_value = umax_ptr;
2226 			dst_reg->var_off = ptr_reg->var_off;
2227 			dst_reg->off = ptr_reg->off + smin_val;
2228 			dst_reg->raw = ptr_reg->raw;
2229 			break;
2230 		}
2231 		/* A new variable offset is created.  Note that off_reg->off
2232 		 * == 0, since it's a scalar.
2233 		 * dst_reg gets the pointer type and since some positive
2234 		 * integer value was added to the pointer, give it a new 'id'
2235 		 * if it's a PTR_TO_PACKET.
2236 		 * this creates a new 'base' pointer, off_reg (variable) gets
2237 		 * added into the variable offset, and we copy the fixed offset
2238 		 * from ptr_reg.
2239 		 */
2240 		if (signed_add_overflows(smin_ptr, smin_val) ||
2241 		    signed_add_overflows(smax_ptr, smax_val)) {
2242 			dst_reg->smin_value = S64_MIN;
2243 			dst_reg->smax_value = S64_MAX;
2244 		} else {
2245 			dst_reg->smin_value = smin_ptr + smin_val;
2246 			dst_reg->smax_value = smax_ptr + smax_val;
2247 		}
2248 		if (umin_ptr + umin_val < umin_ptr ||
2249 		    umax_ptr + umax_val < umax_ptr) {
2250 			dst_reg->umin_value = 0;
2251 			dst_reg->umax_value = U64_MAX;
2252 		} else {
2253 			dst_reg->umin_value = umin_ptr + umin_val;
2254 			dst_reg->umax_value = umax_ptr + umax_val;
2255 		}
2256 		dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2257 		dst_reg->off = ptr_reg->off;
2258 		dst_reg->raw = ptr_reg->raw;
2259 		if (ptr_reg->type == PTR_TO_PACKET) {
2260 			dst_reg->id = ++env->id_gen;
2261 			/* something was added to pkt_ptr, set range to zero */
2262 			dst_reg->raw = 0;
2263 		}
2264 		break;
2265 	case BPF_SUB:
2266 		ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
2267 		if (ret < 0) {
2268 			verbose("R%d tried to sub from different maps or paths\n", dst);
2269 			return ret;
2270 		}
2271 		if (dst_reg == off_reg) {
2272 			/* scalar -= pointer.  Creates an unknown scalar */
2273 			if (!env->allow_ptr_leaks)
2274 				verbose("R%d tried to subtract pointer from scalar\n",
2275 					dst);
2276 			return -EACCES;
2277 		}
2278 		/* We don't allow subtraction from FP, because (according to
2279 		 * test_verifier.c test "invalid fp arithmetic", JITs might not
2280 		 * be able to deal with it.
2281 		 */
2282 		if (ptr_reg->type == PTR_TO_STACK) {
2283 			if (!env->allow_ptr_leaks)
2284 				verbose("R%d subtraction from stack pointer prohibited\n",
2285 					dst);
2286 			return -EACCES;
2287 		}
2288 		if (known && (ptr_reg->off - smin_val ==
2289 			      (s64)(s32)(ptr_reg->off - smin_val))) {
2290 			/* pointer -= K.  Subtract it from fixed offset */
2291 			dst_reg->smin_value = smin_ptr;
2292 			dst_reg->smax_value = smax_ptr;
2293 			dst_reg->umin_value = umin_ptr;
2294 			dst_reg->umax_value = umax_ptr;
2295 			dst_reg->var_off = ptr_reg->var_off;
2296 			dst_reg->id = ptr_reg->id;
2297 			dst_reg->off = ptr_reg->off - smin_val;
2298 			dst_reg->raw = ptr_reg->raw;
2299 			break;
2300 		}
2301 		/* A new variable offset is created.  If the subtrahend is known
2302 		 * nonnegative, then any reg->range we had before is still good.
2303 		 */
2304 		if (signed_sub_overflows(smin_ptr, smax_val) ||
2305 		    signed_sub_overflows(smax_ptr, smin_val)) {
2306 			/* Overflow possible, we know nothing */
2307 			dst_reg->smin_value = S64_MIN;
2308 			dst_reg->smax_value = S64_MAX;
2309 		} else {
2310 			dst_reg->smin_value = smin_ptr - smax_val;
2311 			dst_reg->smax_value = smax_ptr - smin_val;
2312 		}
2313 		if (umin_ptr < umax_val) {
2314 			/* Overflow possible, we know nothing */
2315 			dst_reg->umin_value = 0;
2316 			dst_reg->umax_value = U64_MAX;
2317 		} else {
2318 			/* Cannot overflow (as long as bounds are consistent) */
2319 			dst_reg->umin_value = umin_ptr - umax_val;
2320 			dst_reg->umax_value = umax_ptr - umin_val;
2321 		}
2322 		dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2323 		dst_reg->off = ptr_reg->off;
2324 		dst_reg->raw = ptr_reg->raw;
2325 		if (ptr_reg->type == PTR_TO_PACKET) {
2326 			dst_reg->id = ++env->id_gen;
2327 			/* something was added to pkt_ptr, set range to zero */
2328 			if (smin_val < 0)
2329 				dst_reg->raw = 0;
2330 		}
2331 		break;
2332 	case BPF_AND:
2333 	case BPF_OR:
2334 	case BPF_XOR:
2335 		/* bitwise ops on pointers are troublesome, prohibit for now.
2336 		 * (However, in principle we could allow some cases, e.g.
2337 		 * ptr &= ~3 which would reduce min_value by 3.)
2338 		 */
2339 		if (!env->allow_ptr_leaks)
2340 			verbose("R%d bitwise operator %s on pointer prohibited\n",
2341 				dst, bpf_alu_string[opcode >> 4]);
2342 		return -EACCES;
2343 	case PTR_TO_MAP_VALUE:
2344 		if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
2345 			verbose("R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
2346 				off_reg == dst_reg ? dst : src);
2347 			return -EACCES;
2348 		}
2349 		/* fall-through */
2350 	default:
2351 		/* other operators (e.g. MUL,LSH) produce non-pointer results */
2352 		if (!env->allow_ptr_leaks)
2353 			verbose("R%d pointer arithmetic with %s operator prohibited\n",
2354 				dst, bpf_alu_string[opcode >> 4]);
2355 		return -EACCES;
2356 	}
2357 
2358 	if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2359 		return -EINVAL;
2360 
2361 	__update_reg_bounds(dst_reg);
2362 	__reg_deduce_bounds(dst_reg);
2363 	__reg_bound_offset(dst_reg);
2364 
2365 	/* For unprivileged we require that resulting offset must be in bounds
2366 	 * in order to be able to sanitize access later on.
2367 	 */
2368 	if (!env->allow_ptr_leaks) {
2369 		if (dst_reg->type == PTR_TO_MAP_VALUE &&
2370 		    check_map_access(env, dst, dst_reg->off, 1)) {
2371 			verbose("R%d pointer arithmetic of map value goes out of range, "
2372 				"prohibited for !root\n", dst);
2373 			return -EACCES;
2374 		} else if (dst_reg->type == PTR_TO_STACK &&
2375 			   check_stack_access(env, dst_reg, dst_reg->off +
2376 					      dst_reg->var_off.value, 1)) {
2377 			verbose("R%d stack pointer arithmetic goes out of range, "
2378 				"prohibited for !root\n", dst);
2379 			return -EACCES;
2380 		}
2381 	}
2382 
2383 	return 0;
2384 }
2385 
2386 /* WARNING: This function does calculations on 64-bit values, but the actual
2387  * execution may occur on 32-bit values. Therefore, things like bitshifts
2388  * need extra checks in the 32-bit case.
2389  */
adjust_scalar_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state src_reg)2390 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2391 				      struct bpf_insn *insn,
2392 				      struct bpf_reg_state *dst_reg,
2393 				      struct bpf_reg_state src_reg)
2394 {
2395 	struct bpf_reg_state *regs = cur_regs(env);
2396 	u8 opcode = BPF_OP(insn->code);
2397 	bool src_known, dst_known;
2398 	s64 smin_val, smax_val;
2399 	u64 umin_val, umax_val;
2400 	u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2401 	u32 dst = insn->dst_reg;
2402 	int ret;
2403 
2404 	if (insn_bitness == 32) {
2405 		/* Relevant for 32-bit RSH: Information can propagate towards
2406 		 * LSB, so it isn't sufficient to only truncate the output to
2407 		 * 32 bits.
2408 		 */
2409 		coerce_reg_to_size(dst_reg, 4);
2410 		coerce_reg_to_size(&src_reg, 4);
2411 	}
2412 
2413 	smin_val = src_reg.smin_value;
2414 	smax_val = src_reg.smax_value;
2415 	umin_val = src_reg.umin_value;
2416 	umax_val = src_reg.umax_value;
2417 	src_known = tnum_is_const(src_reg.var_off);
2418 	dst_known = tnum_is_const(dst_reg->var_off);
2419 
2420 	if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2421 	    smin_val > smax_val || umin_val > umax_val) {
2422 		/* Taint dst register if offset had invalid bounds derived from
2423 		 * e.g. dead branches.
2424 		 */
2425 		__mark_reg_unknown(dst_reg);
2426 		return 0;
2427 	}
2428 
2429 	if (!src_known &&
2430 	    opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2431 		__mark_reg_unknown(dst_reg);
2432 		return 0;
2433 	}
2434 
2435 	switch (opcode) {
2436 	case BPF_ADD:
2437 		ret = sanitize_val_alu(env, insn);
2438 		if (ret < 0) {
2439 			verbose("R%d tried to add from different pointers or scalars\n", dst);
2440 			return ret;
2441 		}
2442 		if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2443 		    signed_add_overflows(dst_reg->smax_value, smax_val)) {
2444 			dst_reg->smin_value = S64_MIN;
2445 			dst_reg->smax_value = S64_MAX;
2446 		} else {
2447 			dst_reg->smin_value += smin_val;
2448 			dst_reg->smax_value += smax_val;
2449 		}
2450 		if (dst_reg->umin_value + umin_val < umin_val ||
2451 		    dst_reg->umax_value + umax_val < umax_val) {
2452 			dst_reg->umin_value = 0;
2453 			dst_reg->umax_value = U64_MAX;
2454 		} else {
2455 			dst_reg->umin_value += umin_val;
2456 			dst_reg->umax_value += umax_val;
2457 		}
2458 		dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2459 		break;
2460 	case BPF_SUB:
2461 		ret = sanitize_val_alu(env, insn);
2462 		if (ret < 0) {
2463 			verbose("R%d tried to sub from different pointers or scalars\n", dst);
2464 			return ret;
2465 		}
2466 		if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2467 		    signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2468 			/* Overflow possible, we know nothing */
2469 			dst_reg->smin_value = S64_MIN;
2470 			dst_reg->smax_value = S64_MAX;
2471 		} else {
2472 			dst_reg->smin_value -= smax_val;
2473 			dst_reg->smax_value -= smin_val;
2474 		}
2475 		if (dst_reg->umin_value < umax_val) {
2476 			/* Overflow possible, we know nothing */
2477 			dst_reg->umin_value = 0;
2478 			dst_reg->umax_value = U64_MAX;
2479 		} else {
2480 			/* Cannot overflow (as long as bounds are consistent) */
2481 			dst_reg->umin_value -= umax_val;
2482 			dst_reg->umax_value -= umin_val;
2483 		}
2484 		dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2485 		break;
2486 	case BPF_MUL:
2487 		dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2488 		if (smin_val < 0 || dst_reg->smin_value < 0) {
2489 			/* Ain't nobody got time to multiply that sign */
2490 			__mark_reg_unbounded(dst_reg);
2491 			__update_reg_bounds(dst_reg);
2492 			break;
2493 		}
2494 		/* Both values are positive, so we can work with unsigned and
2495 		 * copy the result to signed (unless it exceeds S64_MAX).
2496 		 */
2497 		if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2498 			/* Potential overflow, we know nothing */
2499 			__mark_reg_unbounded(dst_reg);
2500 			/* (except what we can learn from the var_off) */
2501 			__update_reg_bounds(dst_reg);
2502 			break;
2503 		}
2504 		dst_reg->umin_value *= umin_val;
2505 		dst_reg->umax_value *= umax_val;
2506 		if (dst_reg->umax_value > S64_MAX) {
2507 			/* Overflow possible, we know nothing */
2508 			dst_reg->smin_value = S64_MIN;
2509 			dst_reg->smax_value = S64_MAX;
2510 		} else {
2511 			dst_reg->smin_value = dst_reg->umin_value;
2512 			dst_reg->smax_value = dst_reg->umax_value;
2513 		}
2514 		break;
2515 	case BPF_AND:
2516 		if (src_known && dst_known) {
2517 			__mark_reg_known(dst_reg, dst_reg->var_off.value &
2518 						  src_reg.var_off.value);
2519 			break;
2520 		}
2521 		/* We get our minimum from the var_off, since that's inherently
2522 		 * bitwise.  Our maximum is the minimum of the operands' maxima.
2523 		 */
2524 		dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2525 		dst_reg->umin_value = dst_reg->var_off.value;
2526 		dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2527 		if (dst_reg->smin_value < 0 || smin_val < 0) {
2528 			/* Lose signed bounds when ANDing negative numbers,
2529 			 * ain't nobody got time for that.
2530 			 */
2531 			dst_reg->smin_value = S64_MIN;
2532 			dst_reg->smax_value = S64_MAX;
2533 		} else {
2534 			/* ANDing two positives gives a positive, so safe to
2535 			 * cast result into s64.
2536 			 */
2537 			dst_reg->smin_value = dst_reg->umin_value;
2538 			dst_reg->smax_value = dst_reg->umax_value;
2539 		}
2540 		/* We may learn something more from the var_off */
2541 		__update_reg_bounds(dst_reg);
2542 		break;
2543 	case BPF_OR:
2544 		if (src_known && dst_known) {
2545 			__mark_reg_known(dst_reg, dst_reg->var_off.value |
2546 						  src_reg.var_off.value);
2547 			break;
2548 		}
2549 		/* We get our maximum from the var_off, and our minimum is the
2550 		 * maximum of the operands' minima
2551 		 */
2552 		dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2553 		dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2554 		dst_reg->umax_value = dst_reg->var_off.value |
2555 				      dst_reg->var_off.mask;
2556 		if (dst_reg->smin_value < 0 || smin_val < 0) {
2557 			/* Lose signed bounds when ORing negative numbers,
2558 			 * ain't nobody got time for that.
2559 			 */
2560 			dst_reg->smin_value = S64_MIN;
2561 			dst_reg->smax_value = S64_MAX;
2562 		} else {
2563 			/* ORing two positives gives a positive, so safe to
2564 			 * cast result into s64.
2565 			 */
2566 			dst_reg->smin_value = dst_reg->umin_value;
2567 			dst_reg->smax_value = dst_reg->umax_value;
2568 		}
2569 		/* We may learn something more from the var_off */
2570 		__update_reg_bounds(dst_reg);
2571 		break;
2572 	case BPF_LSH:
2573 		if (umax_val >= insn_bitness) {
2574 			/* Shifts greater than 31 or 63 are undefined.
2575 			 * This includes shifts by a negative number.
2576 			 */
2577 			mark_reg_unknown(regs, insn->dst_reg);
2578 			break;
2579 		}
2580 		/* We lose all sign bit information (except what we can pick
2581 		 * up from var_off)
2582 		 */
2583 		dst_reg->smin_value = S64_MIN;
2584 		dst_reg->smax_value = S64_MAX;
2585 		/* If we might shift our top bit out, then we know nothing */
2586 		if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2587 			dst_reg->umin_value = 0;
2588 			dst_reg->umax_value = U64_MAX;
2589 		} else {
2590 			dst_reg->umin_value <<= umin_val;
2591 			dst_reg->umax_value <<= umax_val;
2592 		}
2593 		if (src_known)
2594 			dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2595 		else
2596 			dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2597 		/* We may learn something more from the var_off */
2598 		__update_reg_bounds(dst_reg);
2599 		break;
2600 	case BPF_RSH:
2601 		if (umax_val >= insn_bitness) {
2602 			/* Shifts greater than 31 or 63 are undefined.
2603 			 * This includes shifts by a negative number.
2604 			 */
2605 			mark_reg_unknown(regs, insn->dst_reg);
2606 			break;
2607 		}
2608 		/* BPF_RSH is an unsigned shift.  If the value in dst_reg might
2609 		 * be negative, then either:
2610 		 * 1) src_reg might be zero, so the sign bit of the result is
2611 		 *    unknown, so we lose our signed bounds
2612 		 * 2) it's known negative, thus the unsigned bounds capture the
2613 		 *    signed bounds
2614 		 * 3) the signed bounds cross zero, so they tell us nothing
2615 		 *    about the result
2616 		 * If the value in dst_reg is known nonnegative, then again the
2617 		 * unsigned bounts capture the signed bounds.
2618 		 * Thus, in all cases it suffices to blow away our signed bounds
2619 		 * and rely on inferring new ones from the unsigned bounds and
2620 		 * var_off of the result.
2621 		 */
2622 		dst_reg->smin_value = S64_MIN;
2623 		dst_reg->smax_value = S64_MAX;
2624 		if (src_known)
2625 			dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2626 						       umin_val);
2627 		else
2628 			dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2629 		dst_reg->umin_value >>= umax_val;
2630 		dst_reg->umax_value >>= umin_val;
2631 		/* We may learn something more from the var_off */
2632 		__update_reg_bounds(dst_reg);
2633 		break;
2634 	default:
2635 		mark_reg_unknown(regs, insn->dst_reg);
2636 		break;
2637 	}
2638 
2639 	if (BPF_CLASS(insn->code) != BPF_ALU64) {
2640 		/* 32-bit ALU ops are (32,32)->32 */
2641 		coerce_reg_to_size(dst_reg, 4);
2642 	}
2643 
2644 	__reg_deduce_bounds(dst_reg);
2645 	__reg_bound_offset(dst_reg);
2646 	return 0;
2647 }
2648 
2649 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2650  * and var_off.
2651  */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)2652 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2653 				   struct bpf_insn *insn)
2654 {
2655 	struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
2656 	struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2657 	u8 opcode = BPF_OP(insn->code);
2658 	int rc;
2659 
2660 	dst_reg = &regs[insn->dst_reg];
2661 	src_reg = NULL;
2662 	if (dst_reg->type != SCALAR_VALUE)
2663 		ptr_reg = dst_reg;
2664 	if (BPF_SRC(insn->code) == BPF_X) {
2665 		src_reg = &regs[insn->src_reg];
2666 		if (src_reg->type != SCALAR_VALUE) {
2667 			if (dst_reg->type != SCALAR_VALUE) {
2668 				/* Combining two pointers by any ALU op yields
2669 				 * an arbitrary scalar.
2670 				 */
2671 				if (!env->allow_ptr_leaks) {
2672 					verbose("R%d pointer %s pointer prohibited\n",
2673 						insn->dst_reg,
2674 						bpf_alu_string[opcode >> 4]);
2675 					return -EACCES;
2676 				}
2677 				mark_reg_unknown(regs, insn->dst_reg);
2678 				return 0;
2679 			} else {
2680 				/* scalar += pointer
2681 				 * This is legal, but we have to reverse our
2682 				 * src/dest handling in computing the range
2683 				 */
2684 				rc = adjust_ptr_min_max_vals(env, insn,
2685 							     src_reg, dst_reg);
2686 				if (rc == -EACCES && env->allow_ptr_leaks) {
2687 					/* scalar += unknown scalar */
2688 					__mark_reg_unknown(&off_reg);
2689 					return adjust_scalar_min_max_vals(
2690 							env, insn,
2691 							dst_reg, off_reg);
2692 				}
2693 				return rc;
2694 			}
2695 		} else if (ptr_reg) {
2696 			/* pointer += scalar */
2697 			rc = adjust_ptr_min_max_vals(env, insn,
2698 						     dst_reg, src_reg);
2699 			if (rc == -EACCES && env->allow_ptr_leaks) {
2700 				/* unknown scalar += scalar */
2701 				__mark_reg_unknown(dst_reg);
2702 				return adjust_scalar_min_max_vals(
2703 						env, insn, dst_reg, *src_reg);
2704 			}
2705 			return rc;
2706 		}
2707 	} else {
2708 		/* Pretend the src is a reg with a known value, since we only
2709 		 * need to be able to read from this state.
2710 		 */
2711 		off_reg.type = SCALAR_VALUE;
2712 		__mark_reg_known(&off_reg, insn->imm);
2713 		src_reg = &off_reg;
2714 		if (ptr_reg) { /* pointer += K */
2715 			rc = adjust_ptr_min_max_vals(env, insn,
2716 						     ptr_reg, src_reg);
2717 			if (rc == -EACCES && env->allow_ptr_leaks) {
2718 				/* unknown scalar += K */
2719 				__mark_reg_unknown(dst_reg);
2720 				return adjust_scalar_min_max_vals(
2721 						env, insn, dst_reg, off_reg);
2722 			}
2723 			return rc;
2724 		}
2725 	}
2726 
2727 	/* Got here implies adding two SCALAR_VALUEs */
2728 	if (WARN_ON_ONCE(ptr_reg)) {
2729 		print_verifier_state(env->cur_state);
2730 		verbose("verifier internal error: unexpected ptr_reg\n");
2731 		return -EINVAL;
2732 	}
2733 	if (WARN_ON(!src_reg)) {
2734 		print_verifier_state(env->cur_state);
2735 		verbose("verifier internal error: no src_reg\n");
2736 		return -EINVAL;
2737 	}
2738 	return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
2739 }
2740 
2741 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)2742 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
2743 {
2744 	struct bpf_reg_state *regs = cur_regs(env);
2745 	u8 opcode = BPF_OP(insn->code);
2746 	int err;
2747 
2748 	if (opcode == BPF_END || opcode == BPF_NEG) {
2749 		if (opcode == BPF_NEG) {
2750 			if (BPF_SRC(insn->code) != 0 ||
2751 			    insn->src_reg != BPF_REG_0 ||
2752 			    insn->off != 0 || insn->imm != 0) {
2753 				verbose("BPF_NEG uses reserved fields\n");
2754 				return -EINVAL;
2755 			}
2756 		} else {
2757 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
2758 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
2759 			    BPF_CLASS(insn->code) == BPF_ALU64) {
2760 				verbose("BPF_END uses reserved fields\n");
2761 				return -EINVAL;
2762 			}
2763 		}
2764 
2765 		/* check src operand */
2766 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2767 		if (err)
2768 			return err;
2769 
2770 		if (is_pointer_value(env, insn->dst_reg)) {
2771 			verbose("R%d pointer arithmetic prohibited\n",
2772 				insn->dst_reg);
2773 			return -EACCES;
2774 		}
2775 
2776 		/* check dest operand */
2777 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
2778 		if (err)
2779 			return err;
2780 
2781 	} else if (opcode == BPF_MOV) {
2782 
2783 		if (BPF_SRC(insn->code) == BPF_X) {
2784 			if (insn->imm != 0 || insn->off != 0) {
2785 				verbose("BPF_MOV uses reserved fields\n");
2786 				return -EINVAL;
2787 			}
2788 
2789 			/* check src operand */
2790 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
2791 			if (err)
2792 				return err;
2793 		} else {
2794 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2795 				verbose("BPF_MOV uses reserved fields\n");
2796 				return -EINVAL;
2797 			}
2798 		}
2799 
2800 		/* check dest operand */
2801 		err = check_reg_arg(env, insn->dst_reg, DST_OP);
2802 		if (err)
2803 			return err;
2804 
2805 		if (BPF_SRC(insn->code) == BPF_X) {
2806 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
2807 				/* case: R1 = R2
2808 				 * copy register state to dest reg
2809 				 */
2810 				regs[insn->dst_reg] = regs[insn->src_reg];
2811 				regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
2812 			} else {
2813 				/* R1 = (u32) R2 */
2814 				if (is_pointer_value(env, insn->src_reg)) {
2815 					verbose("R%d partial copy of pointer\n",
2816 						insn->src_reg);
2817 					return -EACCES;
2818 				}
2819 				mark_reg_unknown(regs, insn->dst_reg);
2820 				coerce_reg_to_size(&regs[insn->dst_reg], 4);
2821 			}
2822 		} else {
2823 			/* case: R = imm
2824 			 * remember the value we stored into this reg
2825 			 */
2826 			regs[insn->dst_reg].type = SCALAR_VALUE;
2827 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
2828 				__mark_reg_known(regs + insn->dst_reg,
2829 						 insn->imm);
2830 			} else {
2831 				__mark_reg_known(regs + insn->dst_reg,
2832 						 (u32)insn->imm);
2833 			}
2834 		}
2835 
2836 	} else if (opcode > BPF_END) {
2837 		verbose("invalid BPF_ALU opcode %x\n", opcode);
2838 		return -EINVAL;
2839 
2840 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
2841 
2842 		if (BPF_SRC(insn->code) == BPF_X) {
2843 			if (insn->imm != 0 || insn->off != 0) {
2844 				verbose("BPF_ALU uses reserved fields\n");
2845 				return -EINVAL;
2846 			}
2847 			/* check src1 operand */
2848 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
2849 			if (err)
2850 				return err;
2851 		} else {
2852 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2853 				verbose("BPF_ALU uses reserved fields\n");
2854 				return -EINVAL;
2855 			}
2856 		}
2857 
2858 		/* check src2 operand */
2859 		err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2860 		if (err)
2861 			return err;
2862 
2863 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
2864 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
2865 			verbose("div by zero\n");
2866 			return -EINVAL;
2867 		}
2868 
2869 		if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
2870 			verbose("BPF_ARSH not supported for 32 bit ALU\n");
2871 			return -EINVAL;
2872 		}
2873 
2874 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
2875 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
2876 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
2877 
2878 			if (insn->imm < 0 || insn->imm >= size) {
2879 				verbose("invalid shift %d\n", insn->imm);
2880 				return -EINVAL;
2881 			}
2882 		}
2883 
2884 		/* check dest operand */
2885 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
2886 		if (err)
2887 			return err;
2888 
2889 		return adjust_reg_min_max_vals(env, insn);
2890 	}
2891 
2892 	return 0;
2893 }
2894 
find_good_pkt_pointers(struct bpf_verifier_state * state,struct bpf_reg_state * dst_reg,bool range_right_open)2895 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
2896 				   struct bpf_reg_state *dst_reg,
2897 				   bool range_right_open)
2898 {
2899 	struct bpf_reg_state *regs = state->regs, *reg;
2900 	u16 new_range;
2901 	int i;
2902 
2903 	if (dst_reg->off < 0 ||
2904 	    (dst_reg->off == 0 && range_right_open))
2905 		/* This doesn't give us any range */
2906 		return;
2907 
2908 	if (dst_reg->umax_value > MAX_PACKET_OFF ||
2909 	    dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
2910 		/* Risk of overflow.  For instance, ptr + (1<<63) may be less
2911 		 * than pkt_end, but that's because it's also less than pkt.
2912 		 */
2913 		return;
2914 
2915 	new_range = dst_reg->off;
2916 	if (range_right_open)
2917 		new_range--;
2918 
2919 	/* Examples for register markings:
2920 	 *
2921 	 * pkt_data in dst register:
2922 	 *
2923 	 *   r2 = r3;
2924 	 *   r2 += 8;
2925 	 *   if (r2 > pkt_end) goto <handle exception>
2926 	 *   <access okay>
2927 	 *
2928 	 *   r2 = r3;
2929 	 *   r2 += 8;
2930 	 *   if (r2 < pkt_end) goto <access okay>
2931 	 *   <handle exception>
2932 	 *
2933 	 *   Where:
2934 	 *     r2 == dst_reg, pkt_end == src_reg
2935 	 *     r2=pkt(id=n,off=8,r=0)
2936 	 *     r3=pkt(id=n,off=0,r=0)
2937 	 *
2938 	 * pkt_data in src register:
2939 	 *
2940 	 *   r2 = r3;
2941 	 *   r2 += 8;
2942 	 *   if (pkt_end >= r2) goto <access okay>
2943 	 *   <handle exception>
2944 	 *
2945 	 *   r2 = r3;
2946 	 *   r2 += 8;
2947 	 *   if (pkt_end <= r2) goto <handle exception>
2948 	 *   <access okay>
2949 	 *
2950 	 *   Where:
2951 	 *     pkt_end == dst_reg, r2 == src_reg
2952 	 *     r2=pkt(id=n,off=8,r=0)
2953 	 *     r3=pkt(id=n,off=0,r=0)
2954 	 *
2955 	 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
2956 	 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
2957 	 * and [r3, r3 + 8-1) respectively is safe to access depending on
2958 	 * the check.
2959 	 */
2960 
2961 	/* If our ids match, then we must have the same max_value.  And we
2962 	 * don't care about the other reg's fixed offset, since if it's too big
2963 	 * the range won't allow anything.
2964 	 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
2965 	 */
2966 	for (i = 0; i < MAX_BPF_REG; i++)
2967 		if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
2968 			/* keep the maximum range already checked */
2969 			regs[i].range = max(regs[i].range, new_range);
2970 
2971 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2972 		if (state->stack[i].slot_type[0] != STACK_SPILL)
2973 			continue;
2974 		reg = &state->stack[i].spilled_ptr;
2975 		if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
2976 			reg->range = max(reg->range, new_range);
2977 	}
2978 }
2979 
2980 /* Adjusts the register min/max values in the case that the dst_reg is the
2981  * variable register that we are working on, and src_reg is a constant or we're
2982  * simply doing a BPF_K check.
2983  * In JEQ/JNE cases we also adjust the var_off values.
2984  */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode)2985 static void reg_set_min_max(struct bpf_reg_state *true_reg,
2986 			    struct bpf_reg_state *false_reg, u64 val,
2987 			    u8 opcode)
2988 {
2989 	/* If the dst_reg is a pointer, we can't learn anything about its
2990 	 * variable offset from the compare (unless src_reg were a pointer into
2991 	 * the same object, but we don't bother with that.
2992 	 * Since false_reg and true_reg have the same type by construction, we
2993 	 * only need to check one of them for pointerness.
2994 	 */
2995 	if (__is_pointer_value(false, false_reg))
2996 		return;
2997 
2998 	switch (opcode) {
2999 	case BPF_JEQ:
3000 		/* If this is false then we know nothing Jon Snow, but if it is
3001 		 * true then we know for sure.
3002 		 */
3003 		__mark_reg_known(true_reg, val);
3004 		break;
3005 	case BPF_JNE:
3006 		/* If this is true we know nothing Jon Snow, but if it is false
3007 		 * we know the value for sure;
3008 		 */
3009 		__mark_reg_known(false_reg, val);
3010 		break;
3011 	case BPF_JGT:
3012 		false_reg->umax_value = min(false_reg->umax_value, val);
3013 		true_reg->umin_value = max(true_reg->umin_value, val + 1);
3014 		break;
3015 	case BPF_JSGT:
3016 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3017 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3018 		break;
3019 	case BPF_JLT:
3020 		false_reg->umin_value = max(false_reg->umin_value, val);
3021 		true_reg->umax_value = min(true_reg->umax_value, val - 1);
3022 		break;
3023 	case BPF_JSLT:
3024 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3025 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3026 		break;
3027 	case BPF_JGE:
3028 		false_reg->umax_value = min(false_reg->umax_value, val - 1);
3029 		true_reg->umin_value = max(true_reg->umin_value, val);
3030 		break;
3031 	case BPF_JSGE:
3032 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3033 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3034 		break;
3035 	case BPF_JLE:
3036 		false_reg->umin_value = max(false_reg->umin_value, val + 1);
3037 		true_reg->umax_value = min(true_reg->umax_value, val);
3038 		break;
3039 	case BPF_JSLE:
3040 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3041 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3042 		break;
3043 	default:
3044 		break;
3045 	}
3046 
3047 	__reg_deduce_bounds(false_reg);
3048 	__reg_deduce_bounds(true_reg);
3049 	/* We might have learned some bits from the bounds. */
3050 	__reg_bound_offset(false_reg);
3051 	__reg_bound_offset(true_reg);
3052 	/* Intersecting with the old var_off might have improved our bounds
3053 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3054 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3055 	 */
3056 	__update_reg_bounds(false_reg);
3057 	__update_reg_bounds(true_reg);
3058 }
3059 
3060 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3061  * the variable reg.
3062  */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode)3063 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3064 				struct bpf_reg_state *false_reg, u64 val,
3065 				u8 opcode)
3066 {
3067 	if (__is_pointer_value(false, false_reg))
3068 		return;
3069 
3070 	switch (opcode) {
3071 	case BPF_JEQ:
3072 		/* If this is false then we know nothing Jon Snow, but if it is
3073 		 * true then we know for sure.
3074 		 */
3075 		__mark_reg_known(true_reg, val);
3076 		break;
3077 	case BPF_JNE:
3078 		/* If this is true we know nothing Jon Snow, but if it is false
3079 		 * we know the value for sure;
3080 		 */
3081 		__mark_reg_known(false_reg, val);
3082 		break;
3083 	case BPF_JGT:
3084 		true_reg->umax_value = min(true_reg->umax_value, val - 1);
3085 		false_reg->umin_value = max(false_reg->umin_value, val);
3086 		break;
3087 	case BPF_JSGT:
3088 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3089 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3090 		break;
3091 	case BPF_JLT:
3092 		true_reg->umin_value = max(true_reg->umin_value, val + 1);
3093 		false_reg->umax_value = min(false_reg->umax_value, val);
3094 		break;
3095 	case BPF_JSLT:
3096 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3097 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3098 		break;
3099 	case BPF_JGE:
3100 		true_reg->umax_value = min(true_reg->umax_value, val);
3101 		false_reg->umin_value = max(false_reg->umin_value, val + 1);
3102 		break;
3103 	case BPF_JSGE:
3104 		true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3105 		false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3106 		break;
3107 	case BPF_JLE:
3108 		true_reg->umin_value = max(true_reg->umin_value, val);
3109 		false_reg->umax_value = min(false_reg->umax_value, val - 1);
3110 		break;
3111 	case BPF_JSLE:
3112 		true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3113 		false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3114 		break;
3115 	default:
3116 		break;
3117 	}
3118 
3119 	__reg_deduce_bounds(false_reg);
3120 	__reg_deduce_bounds(true_reg);
3121 	/* We might have learned some bits from the bounds. */
3122 	__reg_bound_offset(false_reg);
3123 	__reg_bound_offset(true_reg);
3124 	/* Intersecting with the old var_off might have improved our bounds
3125 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3126 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3127 	 */
3128 	__update_reg_bounds(false_reg);
3129 	__update_reg_bounds(true_reg);
3130 }
3131 
3132 /* Regs are known to be equal, so intersect their min/max/var_off */
__reg_combine_min_max(struct bpf_reg_state * src_reg,struct bpf_reg_state * dst_reg)3133 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3134 				  struct bpf_reg_state *dst_reg)
3135 {
3136 	src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3137 							dst_reg->umin_value);
3138 	src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3139 							dst_reg->umax_value);
3140 	src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3141 							dst_reg->smin_value);
3142 	src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3143 							dst_reg->smax_value);
3144 	src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3145 							     dst_reg->var_off);
3146 	/* We might have learned new bounds from the var_off. */
3147 	__update_reg_bounds(src_reg);
3148 	__update_reg_bounds(dst_reg);
3149 	/* We might have learned something about the sign bit. */
3150 	__reg_deduce_bounds(src_reg);
3151 	__reg_deduce_bounds(dst_reg);
3152 	/* We might have learned some bits from the bounds. */
3153 	__reg_bound_offset(src_reg);
3154 	__reg_bound_offset(dst_reg);
3155 	/* Intersecting with the old var_off might have improved our bounds
3156 	 * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3157 	 * then new var_off is (0; 0x7f...fc) which improves our umax.
3158 	 */
3159 	__update_reg_bounds(src_reg);
3160 	__update_reg_bounds(dst_reg);
3161 }
3162 
reg_combine_min_max(struct bpf_reg_state * true_src,struct bpf_reg_state * true_dst,struct bpf_reg_state * false_src,struct bpf_reg_state * false_dst,u8 opcode)3163 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3164 				struct bpf_reg_state *true_dst,
3165 				struct bpf_reg_state *false_src,
3166 				struct bpf_reg_state *false_dst,
3167 				u8 opcode)
3168 {
3169 	switch (opcode) {
3170 	case BPF_JEQ:
3171 		__reg_combine_min_max(true_src, true_dst);
3172 		break;
3173 	case BPF_JNE:
3174 		__reg_combine_min_max(false_src, false_dst);
3175 		break;
3176 	}
3177 }
3178 
mark_map_reg(struct bpf_reg_state * regs,u32 regno,u32 id,bool is_null)3179 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3180 			 bool is_null)
3181 {
3182 	struct bpf_reg_state *reg = &regs[regno];
3183 
3184 	if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3185 		/* Old offset (both fixed and variable parts) should
3186 		 * have been known-zero, because we don't allow pointer
3187 		 * arithmetic on pointers that might be NULL.
3188 		 */
3189 		if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3190 				 !tnum_equals_const(reg->var_off, 0) ||
3191 				 reg->off)) {
3192 			__mark_reg_known_zero(reg);
3193 			reg->off = 0;
3194 		}
3195 		if (is_null) {
3196 			reg->type = SCALAR_VALUE;
3197 		} else if (reg->map_ptr->inner_map_meta) {
3198 			reg->type = CONST_PTR_TO_MAP;
3199 			reg->map_ptr = reg->map_ptr->inner_map_meta;
3200 		} else {
3201 			reg->type = PTR_TO_MAP_VALUE;
3202 		}
3203 		/* We don't need id from this point onwards anymore, thus we
3204 		 * should better reset it, so that state pruning has chances
3205 		 * to take effect.
3206 		 */
3207 		reg->id = 0;
3208 	}
3209 }
3210 
3211 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3212  * be folded together at some point.
3213  */
mark_map_regs(struct bpf_verifier_state * state,u32 regno,bool is_null)3214 static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
3215 			  bool is_null)
3216 {
3217 	struct bpf_reg_state *regs = state->regs;
3218 	u32 id = regs[regno].id;
3219 	int i;
3220 
3221 	for (i = 0; i < MAX_BPF_REG; i++)
3222 		mark_map_reg(regs, i, id, is_null);
3223 
3224 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3225 		if (state->stack[i].slot_type[0] != STACK_SPILL)
3226 			continue;
3227 		mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3228 	}
3229 }
3230 
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)3231 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3232 			     struct bpf_insn *insn, int *insn_idx)
3233 {
3234 	struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
3235 	struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
3236 	u8 opcode = BPF_OP(insn->code);
3237 	int err;
3238 
3239 	if (opcode > BPF_JSLE) {
3240 		verbose("invalid BPF_JMP opcode %x\n", opcode);
3241 		return -EINVAL;
3242 	}
3243 
3244 	if (BPF_SRC(insn->code) == BPF_X) {
3245 		if (insn->imm != 0) {
3246 			verbose("BPF_JMP uses reserved fields\n");
3247 			return -EINVAL;
3248 		}
3249 
3250 		/* check src1 operand */
3251 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
3252 		if (err)
3253 			return err;
3254 
3255 		if (is_pointer_value(env, insn->src_reg)) {
3256 			verbose("R%d pointer comparison prohibited\n",
3257 				insn->src_reg);
3258 			return -EACCES;
3259 		}
3260 	} else {
3261 		if (insn->src_reg != BPF_REG_0) {
3262 			verbose("BPF_JMP uses reserved fields\n");
3263 			return -EINVAL;
3264 		}
3265 	}
3266 
3267 	/* check src2 operand */
3268 	err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3269 	if (err)
3270 		return err;
3271 
3272 	dst_reg = &regs[insn->dst_reg];
3273 
3274 	/* detect if R == 0 where R was initialized to zero earlier */
3275 	if (BPF_SRC(insn->code) == BPF_K &&
3276 	    (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3277 	    dst_reg->type == SCALAR_VALUE &&
3278 	    tnum_equals_const(dst_reg->var_off, insn->imm)) {
3279 		if (opcode == BPF_JEQ) {
3280 			/* if (imm == imm) goto pc+off;
3281 			 * only follow the goto, ignore fall-through
3282 			 */
3283 			*insn_idx += insn->off;
3284 			return 0;
3285 		} else {
3286 			/* if (imm != imm) goto pc+off;
3287 			 * only follow fall-through branch, since
3288 			 * that's where the program will go
3289 			 */
3290 			return 0;
3291 		}
3292 	}
3293 
3294 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
3295 				  false);
3296 	if (!other_branch)
3297 		return -EFAULT;
3298 
3299 	/* detect if we are comparing against a constant value so we can adjust
3300 	 * our min/max values for our dst register.
3301 	 * this is only legit if both are scalars (or pointers to the same
3302 	 * object, I suppose, but we don't support that right now), because
3303 	 * otherwise the different base pointers mean the offsets aren't
3304 	 * comparable.
3305 	 */
3306 	if (BPF_SRC(insn->code) == BPF_X) {
3307 		if (dst_reg->type == SCALAR_VALUE &&
3308 		    regs[insn->src_reg].type == SCALAR_VALUE) {
3309 			if (tnum_is_const(regs[insn->src_reg].var_off))
3310 				reg_set_min_max(&other_branch->regs[insn->dst_reg],
3311 						dst_reg, regs[insn->src_reg].var_off.value,
3312 						opcode);
3313 			else if (tnum_is_const(dst_reg->var_off))
3314 				reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
3315 						    &regs[insn->src_reg],
3316 						    dst_reg->var_off.value, opcode);
3317 			else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3318 				/* Comparing for equality, we can combine knowledge */
3319 				reg_combine_min_max(&other_branch->regs[insn->src_reg],
3320 						    &other_branch->regs[insn->dst_reg],
3321 						    &regs[insn->src_reg],
3322 						    &regs[insn->dst_reg], opcode);
3323 		}
3324 	} else if (dst_reg->type == SCALAR_VALUE) {
3325 		reg_set_min_max(&other_branch->regs[insn->dst_reg],
3326 					dst_reg, insn->imm, opcode);
3327 	}
3328 
3329 	/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3330 	if (BPF_SRC(insn->code) == BPF_K &&
3331 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3332 	    dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3333 		/* Mark all identical map registers in each branch as either
3334 		 * safe or unknown depending R == 0 or R != 0 conditional.
3335 		 */
3336 		mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3337 		mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3338 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
3339 		   dst_reg->type == PTR_TO_PACKET &&
3340 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3341 		/* pkt_data' > pkt_end */
3342 		find_good_pkt_pointers(this_branch, dst_reg, false);
3343 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
3344 		   dst_reg->type == PTR_TO_PACKET_END &&
3345 		   regs[insn->src_reg].type == PTR_TO_PACKET) {
3346 		/* pkt_end > pkt_data' */
3347 		find_good_pkt_pointers(other_branch, &regs[insn->src_reg], true);
3348 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
3349 		   dst_reg->type == PTR_TO_PACKET &&
3350 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3351 		/* pkt_data' < pkt_end */
3352 		find_good_pkt_pointers(other_branch, dst_reg, true);
3353 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
3354 		   dst_reg->type == PTR_TO_PACKET_END &&
3355 		   regs[insn->src_reg].type == PTR_TO_PACKET) {
3356 		/* pkt_end < pkt_data' */
3357 		find_good_pkt_pointers(this_branch, &regs[insn->src_reg], false);
3358 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
3359 		   dst_reg->type == PTR_TO_PACKET &&
3360 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3361 		/* pkt_data' >= pkt_end */
3362 		find_good_pkt_pointers(this_branch, dst_reg, true);
3363 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
3364 		   dst_reg->type == PTR_TO_PACKET_END &&
3365 		   regs[insn->src_reg].type == PTR_TO_PACKET) {
3366 		/* pkt_end >= pkt_data' */
3367 		find_good_pkt_pointers(other_branch, &regs[insn->src_reg], false);
3368 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
3369 		   dst_reg->type == PTR_TO_PACKET &&
3370 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3371 		/* pkt_data' <= pkt_end */
3372 		find_good_pkt_pointers(other_branch, dst_reg, false);
3373 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
3374 		   dst_reg->type == PTR_TO_PACKET_END &&
3375 		   regs[insn->src_reg].type == PTR_TO_PACKET) {
3376 		/* pkt_end <= pkt_data' */
3377 		find_good_pkt_pointers(this_branch, &regs[insn->src_reg], true);
3378 	} else if (is_pointer_value(env, insn->dst_reg)) {
3379 		verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
3380 		return -EACCES;
3381 	}
3382 	if (log_level)
3383 		print_verifier_state(this_branch);
3384 	return 0;
3385 }
3386 
3387 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
ld_imm64_to_map_ptr(struct bpf_insn * insn)3388 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3389 {
3390 	u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3391 
3392 	return (struct bpf_map *) (unsigned long) imm64;
3393 }
3394 
3395 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)3396 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3397 {
3398 	struct bpf_reg_state *regs = cur_regs(env);
3399 	int err;
3400 
3401 	if (BPF_SIZE(insn->code) != BPF_DW) {
3402 		verbose("invalid BPF_LD_IMM insn\n");
3403 		return -EINVAL;
3404 	}
3405 	if (insn->off != 0) {
3406 		verbose("BPF_LD_IMM64 uses reserved fields\n");
3407 		return -EINVAL;
3408 	}
3409 
3410 	err = check_reg_arg(env, insn->dst_reg, DST_OP);
3411 	if (err)
3412 		return err;
3413 
3414 	if (insn->src_reg == 0) {
3415 		u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3416 
3417 		regs[insn->dst_reg].type = SCALAR_VALUE;
3418 		__mark_reg_known(&regs[insn->dst_reg], imm);
3419 		return 0;
3420 	}
3421 
3422 	/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3423 	BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3424 
3425 	regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3426 	regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3427 	return 0;
3428 }
3429 
may_access_skb(enum bpf_prog_type type)3430 static bool may_access_skb(enum bpf_prog_type type)
3431 {
3432 	switch (type) {
3433 	case BPF_PROG_TYPE_SOCKET_FILTER:
3434 	case BPF_PROG_TYPE_SCHED_CLS:
3435 	case BPF_PROG_TYPE_SCHED_ACT:
3436 		return true;
3437 	default:
3438 		return false;
3439 	}
3440 }
3441 
3442 /* verify safety of LD_ABS|LD_IND instructions:
3443  * - they can only appear in the programs where ctx == skb
3444  * - since they are wrappers of function calls, they scratch R1-R5 registers,
3445  *   preserve R6-R9, and store return value into R0
3446  *
3447  * Implicit input:
3448  *   ctx == skb == R6 == CTX
3449  *
3450  * Explicit input:
3451  *   SRC == any register
3452  *   IMM == 32-bit immediate
3453  *
3454  * Output:
3455  *   R0 - 8/16/32-bit skb data converted to cpu endianness
3456  */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)3457 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3458 {
3459 	struct bpf_reg_state *regs = cur_regs(env);
3460 	static const int ctx_reg = BPF_REG_6;
3461 	u8 mode = BPF_MODE(insn->code);
3462 	int i, err;
3463 
3464 	if (!may_access_skb(env->prog->type)) {
3465 		verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3466 		return -EINVAL;
3467 	}
3468 
3469 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3470 	    BPF_SIZE(insn->code) == BPF_DW ||
3471 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3472 		verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
3473 		return -EINVAL;
3474 	}
3475 
3476 	/* check whether implicit source operand (register R6) is readable */
3477 	err = check_reg_arg(env, ctx_reg, SRC_OP);
3478 	if (err)
3479 		return err;
3480 
3481 	if (regs[ctx_reg].type != PTR_TO_CTX) {
3482 		verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3483 		return -EINVAL;
3484 	}
3485 
3486 	if (mode == BPF_IND) {
3487 		/* check explicit source operand */
3488 		err = check_reg_arg(env, insn->src_reg, SRC_OP);
3489 		if (err)
3490 			return err;
3491 	}
3492 
3493 	err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
3494 	if (err < 0)
3495 		return err;
3496 
3497 	/* reset caller saved regs to unreadable */
3498 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
3499 		mark_reg_not_init(regs, caller_saved[i]);
3500 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3501 	}
3502 
3503 	/* mark destination R0 register as readable, since it contains
3504 	 * the value fetched from the packet.
3505 	 * Already marked as written above.
3506 	 */
3507 	mark_reg_unknown(regs, BPF_REG_0);
3508 	return 0;
3509 }
3510 
3511 /* non-recursive DFS pseudo code
3512  * 1  procedure DFS-iterative(G,v):
3513  * 2      label v as discovered
3514  * 3      let S be a stack
3515  * 4      S.push(v)
3516  * 5      while S is not empty
3517  * 6            t <- S.pop()
3518  * 7            if t is what we're looking for:
3519  * 8                return t
3520  * 9            for all edges e in G.adjacentEdges(t) do
3521  * 10               if edge e is already labelled
3522  * 11                   continue with the next edge
3523  * 12               w <- G.adjacentVertex(t,e)
3524  * 13               if vertex w is not discovered and not explored
3525  * 14                   label e as tree-edge
3526  * 15                   label w as discovered
3527  * 16                   S.push(w)
3528  * 17                   continue at 5
3529  * 18               else if vertex w is discovered
3530  * 19                   label e as back-edge
3531  * 20               else
3532  * 21                   // vertex w is explored
3533  * 22                   label e as forward- or cross-edge
3534  * 23           label t as explored
3535  * 24           S.pop()
3536  *
3537  * convention:
3538  * 0x10 - discovered
3539  * 0x11 - discovered and fall-through edge labelled
3540  * 0x12 - discovered and fall-through and branch edges labelled
3541  * 0x20 - explored
3542  */
3543 
3544 enum {
3545 	DISCOVERED = 0x10,
3546 	EXPLORED = 0x20,
3547 	FALLTHROUGH = 1,
3548 	BRANCH = 2,
3549 };
3550 
3551 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3552 
3553 static int *insn_stack;	/* stack of insns to process */
3554 static int cur_stack;	/* current stack index */
3555 static int *insn_state;
3556 
3557 /* t, w, e - match pseudo-code above:
3558  * t - index of current instruction
3559  * w - next instruction
3560  * e - edge
3561  */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)3562 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3563 {
3564 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3565 		return 0;
3566 
3567 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3568 		return 0;
3569 
3570 	if (w < 0 || w >= env->prog->len) {
3571 		verbose("jump out of range from insn %d to %d\n", t, w);
3572 		return -EINVAL;
3573 	}
3574 
3575 	if (e == BRANCH)
3576 		/* mark branch target for state pruning */
3577 		env->explored_states[w] = STATE_LIST_MARK;
3578 
3579 	if (insn_state[w] == 0) {
3580 		/* tree-edge */
3581 		insn_state[t] = DISCOVERED | e;
3582 		insn_state[w] = DISCOVERED;
3583 		if (cur_stack >= env->prog->len)
3584 			return -E2BIG;
3585 		insn_stack[cur_stack++] = w;
3586 		return 1;
3587 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
3588 		verbose("back-edge from insn %d to %d\n", t, w);
3589 		return -EINVAL;
3590 	} else if (insn_state[w] == EXPLORED) {
3591 		/* forward- or cross-edge */
3592 		insn_state[t] = DISCOVERED | e;
3593 	} else {
3594 		verbose("insn state internal bug\n");
3595 		return -EFAULT;
3596 	}
3597 	return 0;
3598 }
3599 
3600 /* non-recursive depth-first-search to detect loops in BPF program
3601  * loop == back-edge in directed graph
3602  */
check_cfg(struct bpf_verifier_env * env)3603 static int check_cfg(struct bpf_verifier_env *env)
3604 {
3605 	struct bpf_insn *insns = env->prog->insnsi;
3606 	int insn_cnt = env->prog->len;
3607 	int ret = 0;
3608 	int i, t;
3609 
3610 	insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3611 	if (!insn_state)
3612 		return -ENOMEM;
3613 
3614 	insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3615 	if (!insn_stack) {
3616 		kfree(insn_state);
3617 		return -ENOMEM;
3618 	}
3619 
3620 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
3621 	insn_stack[0] = 0; /* 0 is the first instruction */
3622 	cur_stack = 1;
3623 
3624 peek_stack:
3625 	if (cur_stack == 0)
3626 		goto check_state;
3627 	t = insn_stack[cur_stack - 1];
3628 
3629 	if (BPF_CLASS(insns[t].code) == BPF_JMP) {
3630 		u8 opcode = BPF_OP(insns[t].code);
3631 
3632 		if (opcode == BPF_EXIT) {
3633 			goto mark_explored;
3634 		} else if (opcode == BPF_CALL) {
3635 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
3636 			if (ret == 1)
3637 				goto peek_stack;
3638 			else if (ret < 0)
3639 				goto err_free;
3640 			if (t + 1 < insn_cnt)
3641 				env->explored_states[t + 1] = STATE_LIST_MARK;
3642 		} else if (opcode == BPF_JA) {
3643 			if (BPF_SRC(insns[t].code) != BPF_K) {
3644 				ret = -EINVAL;
3645 				goto err_free;
3646 			}
3647 			/* unconditional jump with single edge */
3648 			ret = push_insn(t, t + insns[t].off + 1,
3649 					FALLTHROUGH, env);
3650 			if (ret == 1)
3651 				goto peek_stack;
3652 			else if (ret < 0)
3653 				goto err_free;
3654 			/* tell verifier to check for equivalent states
3655 			 * after every call and jump
3656 			 */
3657 			if (t + 1 < insn_cnt)
3658 				env->explored_states[t + 1] = STATE_LIST_MARK;
3659 		} else {
3660 			/* conditional jump with two edges */
3661 			env->explored_states[t] = STATE_LIST_MARK;
3662 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
3663 			if (ret == 1)
3664 				goto peek_stack;
3665 			else if (ret < 0)
3666 				goto err_free;
3667 
3668 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
3669 			if (ret == 1)
3670 				goto peek_stack;
3671 			else if (ret < 0)
3672 				goto err_free;
3673 		}
3674 	} else {
3675 		/* all other non-branch instructions with single
3676 		 * fall-through edge
3677 		 */
3678 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
3679 		if (ret == 1)
3680 			goto peek_stack;
3681 		else if (ret < 0)
3682 			goto err_free;
3683 	}
3684 
3685 mark_explored:
3686 	insn_state[t] = EXPLORED;
3687 	if (cur_stack-- <= 0) {
3688 		verbose("pop stack internal bug\n");
3689 		ret = -EFAULT;
3690 		goto err_free;
3691 	}
3692 	goto peek_stack;
3693 
3694 check_state:
3695 	for (i = 0; i < insn_cnt; i++) {
3696 		if (insn_state[i] != EXPLORED) {
3697 			verbose("unreachable insn %d\n", i);
3698 			ret = -EINVAL;
3699 			goto err_free;
3700 		}
3701 	}
3702 	ret = 0; /* cfg looks good */
3703 
3704 err_free:
3705 	kfree(insn_state);
3706 	kfree(insn_stack);
3707 	return ret;
3708 }
3709 
3710 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)3711 static bool range_within(struct bpf_reg_state *old,
3712 			 struct bpf_reg_state *cur)
3713 {
3714 	return old->umin_value <= cur->umin_value &&
3715 	       old->umax_value >= cur->umax_value &&
3716 	       old->smin_value <= cur->smin_value &&
3717 	       old->smax_value >= cur->smax_value;
3718 }
3719 
3720 /* Maximum number of register states that can exist at once */
3721 #define ID_MAP_SIZE	(MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
3722 struct idpair {
3723 	u32 old;
3724 	u32 cur;
3725 };
3726 
3727 /* If in the old state two registers had the same id, then they need to have
3728  * the same id in the new state as well.  But that id could be different from
3729  * the old state, so we need to track the mapping from old to new ids.
3730  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
3731  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
3732  * regs with a different old id could still have new id 9, we don't care about
3733  * that.
3734  * So we look through our idmap to see if this old id has been seen before.  If
3735  * so, we require the new id to match; otherwise, we add the id pair to the map.
3736  */
check_ids(u32 old_id,u32 cur_id,struct idpair * idmap)3737 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
3738 {
3739 	unsigned int i;
3740 
3741 	for (i = 0; i < ID_MAP_SIZE; i++) {
3742 		if (!idmap[i].old) {
3743 			/* Reached an empty slot; haven't seen this id before */
3744 			idmap[i].old = old_id;
3745 			idmap[i].cur = cur_id;
3746 			return true;
3747 		}
3748 		if (idmap[i].old == old_id)
3749 			return idmap[i].cur == cur_id;
3750 	}
3751 	/* We ran out of idmap slots, which should be impossible */
3752 	WARN_ON_ONCE(1);
3753 	return false;
3754 }
3755 
3756 /* Returns true if (rold safe implies rcur safe) */
regsafe(struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct idpair * idmap)3757 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
3758 		    struct idpair *idmap)
3759 {
3760 	if (!(rold->live & REG_LIVE_READ))
3761 		/* explored state didn't use this */
3762 		return true;
3763 
3764 	if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
3765 		return true;
3766 
3767 	if (rold->type == NOT_INIT)
3768 		/* explored state can't have used this */
3769 		return true;
3770 	if (rcur->type == NOT_INIT)
3771 		return false;
3772 	switch (rold->type) {
3773 	case SCALAR_VALUE:
3774 		if (rcur->type == SCALAR_VALUE) {
3775 			/* new val must satisfy old val knowledge */
3776 			return range_within(rold, rcur) &&
3777 			       tnum_in(rold->var_off, rcur->var_off);
3778 		} else {
3779 			/* We're trying to use a pointer in place of a scalar.
3780 			 * Even if the scalar was unbounded, this could lead to
3781 			 * pointer leaks because scalars are allowed to leak
3782 			 * while pointers are not. We could make this safe in
3783 			 * special cases if root is calling us, but it's
3784 			 * probably not worth the hassle.
3785 			 */
3786 			return false;
3787 		}
3788 	case PTR_TO_MAP_VALUE:
3789 		/* If the new min/max/var_off satisfy the old ones and
3790 		 * everything else matches, we are OK.
3791 		 * We don't care about the 'id' value, because nothing
3792 		 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
3793 		 */
3794 		return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
3795 		       range_within(rold, rcur) &&
3796 		       tnum_in(rold->var_off, rcur->var_off);
3797 	case PTR_TO_MAP_VALUE_OR_NULL:
3798 		/* a PTR_TO_MAP_VALUE could be safe to use as a
3799 		 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
3800 		 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
3801 		 * checked, doing so could have affected others with the same
3802 		 * id, and we can't check for that because we lost the id when
3803 		 * we converted to a PTR_TO_MAP_VALUE.
3804 		 */
3805 		if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
3806 			return false;
3807 		if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
3808 			return false;
3809 		/* Check our ids match any regs they're supposed to */
3810 		return check_ids(rold->id, rcur->id, idmap);
3811 	case PTR_TO_PACKET:
3812 		if (rcur->type != PTR_TO_PACKET)
3813 			return false;
3814 		/* We must have at least as much range as the old ptr
3815 		 * did, so that any accesses which were safe before are
3816 		 * still safe.  This is true even if old range < old off,
3817 		 * since someone could have accessed through (ptr - k), or
3818 		 * even done ptr -= k in a register, to get a safe access.
3819 		 */
3820 		if (rold->range > rcur->range)
3821 			return false;
3822 		/* If the offsets don't match, we can't trust our alignment;
3823 		 * nor can we be sure that we won't fall out of range.
3824 		 */
3825 		if (rold->off != rcur->off)
3826 			return false;
3827 		/* id relations must be preserved */
3828 		if (rold->id && !check_ids(rold->id, rcur->id, idmap))
3829 			return false;
3830 		/* new val must satisfy old val knowledge */
3831 		return range_within(rold, rcur) &&
3832 		       tnum_in(rold->var_off, rcur->var_off);
3833 	case PTR_TO_CTX:
3834 	case CONST_PTR_TO_MAP:
3835 	case PTR_TO_STACK:
3836 	case PTR_TO_PACKET_END:
3837 		/* Only valid matches are exact, which memcmp() above
3838 		 * would have accepted
3839 		 */
3840 	default:
3841 		/* Don't know what's going on, just say it's not safe */
3842 		return false;
3843 	}
3844 
3845 	/* Shouldn't get here; if we do, say it's not safe */
3846 	WARN_ON_ONCE(1);
3847 	return false;
3848 }
3849 
stacksafe(struct bpf_verifier_state * old,struct bpf_verifier_state * cur,struct idpair * idmap)3850 static bool stacksafe(struct bpf_verifier_state *old,
3851 		      struct bpf_verifier_state *cur,
3852 		      struct idpair *idmap)
3853 {
3854 	int i, spi;
3855 
3856 	/* if explored stack has more populated slots than current stack
3857 	 * such stacks are not equivalent
3858 	 */
3859 	if (old->allocated_stack > cur->allocated_stack)
3860 		return false;
3861 
3862 	/* walk slots of the explored stack and ignore any additional
3863 	 * slots in the current stack, since explored(safe) state
3864 	 * didn't use them
3865 	 */
3866 	for (i = 0; i < old->allocated_stack; i++) {
3867 		spi = i / BPF_REG_SIZE;
3868 
3869 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
3870 			continue;
3871 		if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
3872 		    cur->stack[spi].slot_type[i % BPF_REG_SIZE])
3873 			/* Ex: old explored (safe) state has STACK_SPILL in
3874 			 * this stack slot, but current has has STACK_MISC ->
3875 			 * this verifier states are not equivalent,
3876 			 * return false to continue verification of this path
3877 			 */
3878 			return false;
3879 		if (i % BPF_REG_SIZE)
3880 			continue;
3881 		if (old->stack[spi].slot_type[0] != STACK_SPILL)
3882 			continue;
3883 		if (!regsafe(&old->stack[spi].spilled_ptr,
3884 			     &cur->stack[spi].spilled_ptr,
3885 			     idmap))
3886 			/* when explored and current stack slot are both storing
3887 			 * spilled registers, check that stored pointers types
3888 			 * are the same as well.
3889 			 * Ex: explored safe path could have stored
3890 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
3891 			 * but current path has stored:
3892 			 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
3893 			 * such verifier states are not equivalent.
3894 			 * return false to continue verification of this path
3895 			 */
3896 			return false;
3897 	}
3898 	return true;
3899 }
3900 
3901 /* compare two verifier states
3902  *
3903  * all states stored in state_list are known to be valid, since
3904  * verifier reached 'bpf_exit' instruction through them
3905  *
3906  * this function is called when verifier exploring different branches of
3907  * execution popped from the state stack. If it sees an old state that has
3908  * more strict register state and more strict stack state then this execution
3909  * branch doesn't need to be explored further, since verifier already
3910  * concluded that more strict state leads to valid finish.
3911  *
3912  * Therefore two states are equivalent if register state is more conservative
3913  * and explored stack state is more conservative than the current one.
3914  * Example:
3915  *       explored                   current
3916  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
3917  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
3918  *
3919  * In other words if current stack state (one being explored) has more
3920  * valid slots than old one that already passed validation, it means
3921  * the verifier can stop exploring and conclude that current state is valid too
3922  *
3923  * Similarly with registers. If explored state has register type as invalid
3924  * whereas register type in current state is meaningful, it means that
3925  * the current state will reach 'bpf_exit' instruction safely
3926  */
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)3927 static bool states_equal(struct bpf_verifier_env *env,
3928 			 struct bpf_verifier_state *old,
3929 			 struct bpf_verifier_state *cur)
3930 {
3931 	struct idpair *idmap;
3932 	bool ret = false;
3933 	int i;
3934 
3935 	/* Verification state from speculative execution simulation
3936 	 * must never prune a non-speculative execution one.
3937 	 */
3938 	if (old->speculative && !cur->speculative)
3939 		return false;
3940 
3941 	idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
3942 	/* If we failed to allocate the idmap, just say it's not safe */
3943 	if (!idmap)
3944 		return false;
3945 
3946 	for (i = 0; i < MAX_BPF_REG; i++) {
3947 		if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
3948 			goto out_free;
3949 	}
3950 
3951 	if (!stacksafe(old, cur, idmap))
3952 		goto out_free;
3953 	ret = true;
3954 out_free:
3955 	kfree(idmap);
3956 	return ret;
3957 }
3958 
3959 /* A write screens off any subsequent reads; but write marks come from the
3960  * straight-line code between a state and its parent.  When we arrive at a
3961  * jump target (in the first iteration of the propagate_liveness() loop),
3962  * we didn't arrive by the straight-line code, so read marks in state must
3963  * propagate to parent regardless of state's write marks.
3964  */
do_propagate_liveness(const struct bpf_verifier_state * state,struct bpf_verifier_state * parent)3965 static bool do_propagate_liveness(const struct bpf_verifier_state *state,
3966 				  struct bpf_verifier_state *parent)
3967 {
3968 	bool writes = parent == state->parent; /* Observe write marks */
3969 	bool touched = false; /* any changes made? */
3970 	int i;
3971 
3972 	if (!parent)
3973 		return touched;
3974 	/* Propagate read liveness of registers... */
3975 	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
3976 	/* We don't need to worry about FP liveness because it's read-only */
3977 	for (i = 0; i < BPF_REG_FP; i++) {
3978 		if (parent->regs[i].live & REG_LIVE_READ)
3979 			continue;
3980 		if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
3981 			continue;
3982 		if (state->regs[i].live & REG_LIVE_READ) {
3983 			parent->regs[i].live |= REG_LIVE_READ;
3984 			touched = true;
3985 		}
3986 	}
3987 	/* ... and stack slots */
3988 	for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
3989 		    i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3990 		if (parent->stack[i].slot_type[0] != STACK_SPILL)
3991 			continue;
3992 		if (state->stack[i].slot_type[0] != STACK_SPILL)
3993 			continue;
3994 		if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
3995 			continue;
3996 		if (writes &&
3997 		    (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
3998 			continue;
3999 		if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
4000 			parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
4001 			touched = true;
4002 		}
4003 	}
4004 	return touched;
4005 }
4006 
4007 /* "parent" is "a state from which we reach the current state", but initially
4008  * it is not the state->parent (i.e. "the state whose straight-line code leads
4009  * to the current state"), instead it is the state that happened to arrive at
4010  * a (prunable) equivalent of the current state.  See comment above
4011  * do_propagate_liveness() for consequences of this.
4012  * This function is just a more efficient way of calling mark_reg_read() or
4013  * mark_stack_slot_read() on each reg in "parent" that is read in "state",
4014  * though it requires that parent != state->parent in the call arguments.
4015  */
propagate_liveness(const struct bpf_verifier_state * state,struct bpf_verifier_state * parent)4016 static void propagate_liveness(const struct bpf_verifier_state *state,
4017 			       struct bpf_verifier_state *parent)
4018 {
4019 	while (do_propagate_liveness(state, parent)) {
4020 		/* Something changed, so we need to feed those changes onward */
4021 		state = parent;
4022 		parent = state->parent;
4023 	}
4024 }
4025 
is_state_visited(struct bpf_verifier_env * env,int insn_idx)4026 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4027 {
4028 	struct bpf_verifier_state_list *new_sl;
4029 	struct bpf_verifier_state_list *sl;
4030 	struct bpf_verifier_state *cur = env->cur_state;
4031 	int i, err;
4032 
4033 	sl = env->explored_states[insn_idx];
4034 	if (!sl)
4035 		/* this 'insn_idx' instruction wasn't marked, so we will not
4036 		 * be doing state search here
4037 		 */
4038 		return 0;
4039 
4040 	while (sl != STATE_LIST_MARK) {
4041 		if (states_equal(env, &sl->state, cur)) {
4042 			/* reached equivalent register/stack state,
4043 			 * prune the search.
4044 			 * Registers read by the continuation are read by us.
4045 			 * If we have any write marks in env->cur_state, they
4046 			 * will prevent corresponding reads in the continuation
4047 			 * from reaching our parent (an explored_state).  Our
4048 			 * own state will get the read marks recorded, but
4049 			 * they'll be immediately forgotten as we're pruning
4050 			 * this state and will pop a new one.
4051 			 */
4052 			propagate_liveness(&sl->state, cur);
4053 			return 1;
4054 		}
4055 		sl = sl->next;
4056 	}
4057 
4058 	/* there were no equivalent states, remember current one.
4059 	 * technically the current state is not proven to be safe yet,
4060 	 * but it will either reach bpf_exit (which means it's safe) or
4061 	 * it will be rejected. Since there are no loops, we won't be
4062 	 * seeing this 'insn_idx' instruction again on the way to bpf_exit
4063 	 */
4064 	new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4065 	if (!new_sl)
4066 		return -ENOMEM;
4067 
4068 	/* add new state to the head of linked list */
4069 	err = copy_verifier_state(&new_sl->state, cur);
4070 	if (err) {
4071 		free_verifier_state(&new_sl->state, false);
4072 		kfree(new_sl);
4073 		return err;
4074 	}
4075 	new_sl->next = env->explored_states[insn_idx];
4076 	env->explored_states[insn_idx] = new_sl;
4077 	/* connect new state to parentage chain */
4078 	cur->parent = &new_sl->state;
4079 	/* clear write marks in current state: the writes we did are not writes
4080 	 * our child did, so they don't screen off its reads from us.
4081 	 * (There are no read marks in current state, because reads always mark
4082 	 * their parent and current state never has children yet.  Only
4083 	 * explored_states can get read marks.)
4084 	 */
4085 	for (i = 0; i < BPF_REG_FP; i++)
4086 		cur->regs[i].live = REG_LIVE_NONE;
4087 	for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
4088 		if (cur->stack[i].slot_type[0] == STACK_SPILL)
4089 			cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4090 	return 0;
4091 }
4092 
ext_analyzer_insn_hook(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx)4093 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
4094 				  int insn_idx, int prev_insn_idx)
4095 {
4096 	if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
4097 		return 0;
4098 
4099 	return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
4100 }
4101 
do_check(struct bpf_verifier_env * env)4102 static int do_check(struct bpf_verifier_env *env)
4103 {
4104 	struct bpf_verifier_state *state;
4105 	struct bpf_insn *insns = env->prog->insnsi;
4106 	struct bpf_reg_state *regs;
4107 	int insn_cnt = env->prog->len;
4108 	int insn_processed = 0;
4109 	bool do_print_state = false;
4110 
4111 	state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4112 	if (!state)
4113 		return -ENOMEM;
4114 	env->cur_state = state;
4115 	init_reg_state(state->regs);
4116 	state->parent = NULL;
4117 	for (;;) {
4118 		struct bpf_insn *insn;
4119 		u8 class;
4120 		int err;
4121 
4122 		if (env->insn_idx >= insn_cnt) {
4123 			verbose("invalid insn idx %d insn_cnt %d\n",
4124 				env->insn_idx, insn_cnt);
4125 			return -EFAULT;
4126 		}
4127 
4128 		insn = &insns[env->insn_idx];
4129 		class = BPF_CLASS(insn->code);
4130 
4131 		if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4132 			verbose("BPF program is too large. Processed %d insn\n",
4133 				insn_processed);
4134 			return -E2BIG;
4135 		}
4136 
4137 		err = is_state_visited(env, env->insn_idx);
4138 		if (err < 0)
4139 			return err;
4140 		if (err == 1) {
4141 			/* found equivalent state, can prune the search */
4142 			if (log_level) {
4143 				if (do_print_state)
4144 					verbose("\nfrom %d to %d%s: safe\n",
4145 						env->prev_insn_idx, env->insn_idx,
4146 						env->cur_state->speculative ?
4147 						" (speculative execution)" : "");
4148 				else
4149 					verbose("%d: safe\n", env->insn_idx);
4150 			}
4151 			goto process_bpf_exit;
4152 		}
4153 
4154 		if (need_resched())
4155 			cond_resched();
4156 
4157 		if (log_level > 1 || (log_level && do_print_state)) {
4158 			if (log_level > 1)
4159 				verbose("%d:", env->insn_idx);
4160 			else
4161 				verbose("\nfrom %d to %d%s:",
4162 					env->prev_insn_idx, env->insn_idx,
4163 					env->cur_state->speculative ?
4164 					" (speculative execution)" : "");
4165 			print_verifier_state(env->cur_state);
4166 			do_print_state = false;
4167 		}
4168 
4169 		if (log_level) {
4170 			verbose("%d: ", env->insn_idx);
4171 			print_bpf_insn(env, insn);
4172 		}
4173 
4174 		err = ext_analyzer_insn_hook(env, env->insn_idx, env->prev_insn_idx);
4175 		if (err)
4176 			return err;
4177 
4178 		regs = cur_regs(env);
4179 		env->insn_aux_data[env->insn_idx].seen = true;
4180 		if (class == BPF_ALU || class == BPF_ALU64) {
4181 			err = check_alu_op(env, insn);
4182 			if (err)
4183 				return err;
4184 
4185 		} else if (class == BPF_LDX) {
4186 			enum bpf_reg_type *prev_src_type, src_reg_type;
4187 
4188 			/* check for reserved fields is already done */
4189 
4190 			/* check src operand */
4191 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
4192 			if (err)
4193 				return err;
4194 
4195 			err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4196 			if (err)
4197 				return err;
4198 
4199 			src_reg_type = regs[insn->src_reg].type;
4200 
4201 			/* check that memory (src_reg + off) is readable,
4202 			 * the state of dst_reg will be updated by this func
4203 			 */
4204 			err = check_mem_access(env, env->insn_idx, insn->src_reg,
4205 					       insn->off, BPF_SIZE(insn->code),
4206 					       BPF_READ, insn->dst_reg, false);
4207 			if (err)
4208 				return err;
4209 
4210 			prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
4211 
4212 			if (*prev_src_type == NOT_INIT) {
4213 				/* saw a valid insn
4214 				 * dst_reg = *(u32 *)(src_reg + off)
4215 				 * save type to validate intersecting paths
4216 				 */
4217 				*prev_src_type = src_reg_type;
4218 
4219 			} else if (src_reg_type != *prev_src_type &&
4220 				   (src_reg_type == PTR_TO_CTX ||
4221 				    *prev_src_type == PTR_TO_CTX)) {
4222 				/* ABuser program is trying to use the same insn
4223 				 * dst_reg = *(u32*) (src_reg + off)
4224 				 * with different pointer types:
4225 				 * src_reg == ctx in one branch and
4226 				 * src_reg == stack|map in some other branch.
4227 				 * Reject it.
4228 				 */
4229 				verbose("same insn cannot be used with different pointers\n");
4230 				return -EINVAL;
4231 			}
4232 
4233 		} else if (class == BPF_STX) {
4234 			enum bpf_reg_type *prev_dst_type, dst_reg_type;
4235 
4236 			if (BPF_MODE(insn->code) == BPF_XADD) {
4237 				err = check_xadd(env, env->insn_idx, insn);
4238 				if (err)
4239 					return err;
4240 				env->insn_idx++;
4241 				continue;
4242 			}
4243 
4244 			/* check src1 operand */
4245 			err = check_reg_arg(env, insn->src_reg, SRC_OP);
4246 			if (err)
4247 				return err;
4248 			/* check src2 operand */
4249 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4250 			if (err)
4251 				return err;
4252 
4253 			dst_reg_type = regs[insn->dst_reg].type;
4254 
4255 			/* check that memory (dst_reg + off) is writeable */
4256 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
4257 					       insn->off, BPF_SIZE(insn->code),
4258 					       BPF_WRITE, insn->src_reg, false);
4259 			if (err)
4260 				return err;
4261 
4262 			prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
4263 
4264 			if (*prev_dst_type == NOT_INIT) {
4265 				*prev_dst_type = dst_reg_type;
4266 			} else if (dst_reg_type != *prev_dst_type &&
4267 				   (dst_reg_type == PTR_TO_CTX ||
4268 				    *prev_dst_type == PTR_TO_CTX)) {
4269 				verbose("same insn cannot be used with different pointers\n");
4270 				return -EINVAL;
4271 			}
4272 
4273 		} else if (class == BPF_ST) {
4274 			if (BPF_MODE(insn->code) != BPF_MEM ||
4275 			    insn->src_reg != BPF_REG_0) {
4276 				verbose("BPF_ST uses reserved fields\n");
4277 				return -EINVAL;
4278 			}
4279 			/* check src operand */
4280 			err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4281 			if (err)
4282 				return err;
4283 
4284 			if (is_ctx_reg(env, insn->dst_reg)) {
4285 				verbose("BPF_ST stores into R%d context is not allowed\n",
4286 					insn->dst_reg);
4287 				return -EACCES;
4288 			}
4289 
4290 			/* check that memory (dst_reg + off) is writeable */
4291 			err = check_mem_access(env, env->insn_idx, insn->dst_reg,
4292 					       insn->off, BPF_SIZE(insn->code),
4293 					       BPF_WRITE, -1, false);
4294 			if (err)
4295 				return err;
4296 
4297 		} else if (class == BPF_JMP) {
4298 			u8 opcode = BPF_OP(insn->code);
4299 
4300 			if (opcode == BPF_CALL) {
4301 				if (BPF_SRC(insn->code) != BPF_K ||
4302 				    insn->off != 0 ||
4303 				    insn->src_reg != BPF_REG_0 ||
4304 				    insn->dst_reg != BPF_REG_0) {
4305 					verbose("BPF_CALL uses reserved fields\n");
4306 					return -EINVAL;
4307 				}
4308 
4309 				err = check_call(env, insn->imm, env->insn_idx);
4310 				if (err)
4311 					return err;
4312 
4313 			} else if (opcode == BPF_JA) {
4314 				if (BPF_SRC(insn->code) != BPF_K ||
4315 				    insn->imm != 0 ||
4316 				    insn->src_reg != BPF_REG_0 ||
4317 				    insn->dst_reg != BPF_REG_0) {
4318 					verbose("BPF_JA uses reserved fields\n");
4319 					return -EINVAL;
4320 				}
4321 
4322 				env->insn_idx += insn->off + 1;
4323 				continue;
4324 
4325 			} else if (opcode == BPF_EXIT) {
4326 				if (BPF_SRC(insn->code) != BPF_K ||
4327 				    insn->imm != 0 ||
4328 				    insn->src_reg != BPF_REG_0 ||
4329 				    insn->dst_reg != BPF_REG_0) {
4330 					verbose("BPF_EXIT uses reserved fields\n");
4331 					return -EINVAL;
4332 				}
4333 
4334 				/* eBPF calling convetion is such that R0 is used
4335 				 * to return the value from eBPF program.
4336 				 * Make sure that it's readable at this time
4337 				 * of bpf_exit, which means that program wrote
4338 				 * something into it earlier
4339 				 */
4340 				err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4341 				if (err)
4342 					return err;
4343 
4344 				if (is_pointer_value(env, BPF_REG_0)) {
4345 					verbose("R0 leaks addr as return value\n");
4346 					return -EACCES;
4347 				}
4348 
4349 process_bpf_exit:
4350 				err = pop_stack(env, &env->prev_insn_idx, &env->insn_idx);
4351 				if (err < 0) {
4352 					if (err != -ENOENT)
4353 						return err;
4354 					break;
4355 				} else {
4356 					do_print_state = true;
4357 					continue;
4358 				}
4359 			} else {
4360 				err = check_cond_jmp_op(env, insn, &env->insn_idx);
4361 				if (err)
4362 					return err;
4363 			}
4364 		} else if (class == BPF_LD) {
4365 			u8 mode = BPF_MODE(insn->code);
4366 
4367 			if (mode == BPF_ABS || mode == BPF_IND) {
4368 				err = check_ld_abs(env, insn);
4369 				if (err)
4370 					return err;
4371 
4372 			} else if (mode == BPF_IMM) {
4373 				err = check_ld_imm(env, insn);
4374 				if (err)
4375 					return err;
4376 
4377 				env->insn_idx++;
4378 				env->insn_aux_data[env->insn_idx].seen = true;
4379 			} else {
4380 				verbose("invalid BPF_LD mode\n");
4381 				return -EINVAL;
4382 			}
4383 		} else {
4384 			verbose("unknown insn class %d\n", class);
4385 			return -EINVAL;
4386 		}
4387 
4388 		env->insn_idx++;
4389 	}
4390 
4391 	verbose("processed %d insns, stack depth %d\n",
4392 		insn_processed, env->prog->aux->stack_depth);
4393 	return 0;
4394 }
4395 
check_map_prealloc(struct bpf_map * map)4396 static int check_map_prealloc(struct bpf_map *map)
4397 {
4398 	return (map->map_type != BPF_MAP_TYPE_HASH &&
4399 		map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4400 		map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4401 		!(map->map_flags & BPF_F_NO_PREALLOC);
4402 }
4403 
check_map_prog_compatibility(struct bpf_map * map,struct bpf_prog * prog)4404 static int check_map_prog_compatibility(struct bpf_map *map,
4405 					struct bpf_prog *prog)
4406 
4407 {
4408 	/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4409 	 * preallocated hash maps, since doing memory allocation
4410 	 * in overflow_handler can crash depending on where nmi got
4411 	 * triggered.
4412 	 */
4413 	if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4414 		if (!check_map_prealloc(map)) {
4415 			verbose("perf_event programs can only use preallocated hash map\n");
4416 			return -EINVAL;
4417 		}
4418 		if (map->inner_map_meta &&
4419 		    !check_map_prealloc(map->inner_map_meta)) {
4420 			verbose("perf_event programs can only use preallocated inner hash map\n");
4421 			return -EINVAL;
4422 		}
4423 	}
4424 	return 0;
4425 }
4426 
4427 /* look for pseudo eBPF instructions that access map FDs and
4428  * replace them with actual map pointers
4429  */
replace_map_fd_with_map_ptr(struct bpf_verifier_env * env)4430 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4431 {
4432 	struct bpf_insn *insn = env->prog->insnsi;
4433 	int insn_cnt = env->prog->len;
4434 	int i, j, err;
4435 
4436 	err = bpf_prog_calc_tag(env->prog);
4437 	if (err)
4438 		return err;
4439 
4440 	for (i = 0; i < insn_cnt; i++, insn++) {
4441 		if (BPF_CLASS(insn->code) == BPF_LDX &&
4442 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4443 			verbose("BPF_LDX uses reserved fields\n");
4444 			return -EINVAL;
4445 		}
4446 
4447 		if (BPF_CLASS(insn->code) == BPF_STX &&
4448 		    ((BPF_MODE(insn->code) != BPF_MEM &&
4449 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4450 			verbose("BPF_STX uses reserved fields\n");
4451 			return -EINVAL;
4452 		}
4453 
4454 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4455 			struct bpf_map *map;
4456 			struct fd f;
4457 
4458 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
4459 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4460 			    insn[1].off != 0) {
4461 				verbose("invalid bpf_ld_imm64 insn\n");
4462 				return -EINVAL;
4463 			}
4464 
4465 			if (insn->src_reg == 0)
4466 				/* valid generic load 64-bit imm */
4467 				goto next_insn;
4468 
4469 			if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4470 				verbose("unrecognized bpf_ld_imm64 insn\n");
4471 				return -EINVAL;
4472 			}
4473 
4474 			f = fdget(insn->imm);
4475 			map = __bpf_map_get(f);
4476 			if (IS_ERR(map)) {
4477 				verbose("fd %d is not pointing to valid bpf_map\n",
4478 					insn->imm);
4479 				return PTR_ERR(map);
4480 			}
4481 
4482 			err = check_map_prog_compatibility(map, env->prog);
4483 			if (err) {
4484 				fdput(f);
4485 				return err;
4486 			}
4487 
4488 			/* store map pointer inside BPF_LD_IMM64 instruction */
4489 			insn[0].imm = (u32) (unsigned long) map;
4490 			insn[1].imm = ((u64) (unsigned long) map) >> 32;
4491 
4492 			/* check whether we recorded this map already */
4493 			for (j = 0; j < env->used_map_cnt; j++)
4494 				if (env->used_maps[j] == map) {
4495 					fdput(f);
4496 					goto next_insn;
4497 				}
4498 
4499 			if (env->used_map_cnt >= MAX_USED_MAPS) {
4500 				fdput(f);
4501 				return -E2BIG;
4502 			}
4503 
4504 			/* hold the map. If the program is rejected by verifier,
4505 			 * the map will be released by release_maps() or it
4506 			 * will be used by the valid program until it's unloaded
4507 			 * and all maps are released in free_used_maps()
4508 			 */
4509 			map = bpf_map_inc(map, false);
4510 			if (IS_ERR(map)) {
4511 				fdput(f);
4512 				return PTR_ERR(map);
4513 			}
4514 			env->used_maps[env->used_map_cnt++] = map;
4515 
4516 			fdput(f);
4517 next_insn:
4518 			insn++;
4519 			i++;
4520 		}
4521 	}
4522 
4523 	/* now all pseudo BPF_LD_IMM64 instructions load valid
4524 	 * 'struct bpf_map *' into a register instead of user map_fd.
4525 	 * These pointers will be used later by verifier to validate map access.
4526 	 */
4527 	return 0;
4528 }
4529 
4530 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)4531 static void release_maps(struct bpf_verifier_env *env)
4532 {
4533 	int i;
4534 
4535 	for (i = 0; i < env->used_map_cnt; i++)
4536 		bpf_map_put(env->used_maps[i]);
4537 }
4538 
4539 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)4540 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
4541 {
4542 	struct bpf_insn *insn = env->prog->insnsi;
4543 	int insn_cnt = env->prog->len;
4544 	int i;
4545 
4546 	for (i = 0; i < insn_cnt; i++, insn++)
4547 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
4548 			insn->src_reg = 0;
4549 }
4550 
4551 /* single env->prog->insni[off] instruction was replaced with the range
4552  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
4553  * [0, off) and [off, end) to new locations, so the patched range stays zero
4554  */
adjust_insn_aux_data(struct bpf_verifier_env * env,u32 prog_len,u32 off,u32 cnt)4555 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
4556 				u32 off, u32 cnt)
4557 {
4558 	struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
4559 	int i;
4560 
4561 	if (cnt == 1)
4562 		return 0;
4563 	new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
4564 	if (!new_data)
4565 		return -ENOMEM;
4566 	memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
4567 	memcpy(new_data + off + cnt - 1, old_data + off,
4568 	       sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
4569 	for (i = off; i < off + cnt - 1; i++)
4570 		new_data[i].seen = true;
4571 	env->insn_aux_data = new_data;
4572 	vfree(old_data);
4573 	return 0;
4574 }
4575 
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)4576 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
4577 					    const struct bpf_insn *patch, u32 len)
4578 {
4579 	struct bpf_prog *new_prog;
4580 
4581 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4582 	if (!new_prog)
4583 		return NULL;
4584 	if (adjust_insn_aux_data(env, new_prog->len, off, len))
4585 		return NULL;
4586 	return new_prog;
4587 }
4588 
4589 /* The verifier does more data flow analysis than llvm and will not explore
4590  * branches that are dead at run time. Malicious programs can have dead code
4591  * too. Therefore replace all dead at-run-time code with nops.
4592  */
sanitize_dead_code(struct bpf_verifier_env * env)4593 static void sanitize_dead_code(struct bpf_verifier_env *env)
4594 {
4595 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
4596 	struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
4597 	struct bpf_insn *insn = env->prog->insnsi;
4598 	const int insn_cnt = env->prog->len;
4599 	int i;
4600 
4601 	for (i = 0; i < insn_cnt; i++) {
4602 		if (aux_data[i].seen)
4603 			continue;
4604 		memcpy(insn + i, &nop, sizeof(nop));
4605 	}
4606 }
4607 
4608 /* convert load instructions that access fields of 'struct __sk_buff'
4609  * into sequence of instructions that access fields of 'struct sk_buff'
4610  */
convert_ctx_accesses(struct bpf_verifier_env * env)4611 static int convert_ctx_accesses(struct bpf_verifier_env *env)
4612 {
4613 	const struct bpf_verifier_ops *ops = env->prog->aux->ops;
4614 	int i, cnt, size, ctx_field_size, delta = 0;
4615 	const int insn_cnt = env->prog->len;
4616 	struct bpf_insn insn_buf[16], *insn;
4617 	struct bpf_prog *new_prog;
4618 	enum bpf_access_type type;
4619 	bool is_narrower_load;
4620 	u32 target_size;
4621 
4622 	if (ops->gen_prologue) {
4623 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
4624 					env->prog);
4625 		if (cnt >= ARRAY_SIZE(insn_buf)) {
4626 			verbose("bpf verifier is misconfigured\n");
4627 			return -EINVAL;
4628 		} else if (cnt) {
4629 			new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
4630 			if (!new_prog)
4631 				return -ENOMEM;
4632 
4633 			env->prog = new_prog;
4634 			delta += cnt - 1;
4635 		}
4636 	}
4637 
4638 	if (!ops->convert_ctx_access)
4639 		return 0;
4640 
4641 	insn = env->prog->insnsi + delta;
4642 
4643 	for (i = 0; i < insn_cnt; i++, insn++) {
4644 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
4645 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
4646 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
4647 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
4648 			type = BPF_READ;
4649 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
4650 			 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
4651 			 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
4652 			 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
4653 			type = BPF_WRITE;
4654 		else
4655 			continue;
4656 
4657 		if (type == BPF_WRITE &&
4658 		    env->insn_aux_data[i + delta].sanitize_stack_off) {
4659 			struct bpf_insn patch[] = {
4660 				/* Sanitize suspicious stack slot with zero.
4661 				 * There are no memory dependencies for this store,
4662 				 * since it's only using frame pointer and immediate
4663 				 * constant of zero
4664 				 */
4665 				BPF_ST_MEM(BPF_DW, BPF_REG_FP,
4666 					   env->insn_aux_data[i + delta].sanitize_stack_off,
4667 					   0),
4668 				/* the original STX instruction will immediately
4669 				 * overwrite the same stack slot with appropriate value
4670 				 */
4671 				*insn,
4672 			};
4673 
4674 			cnt = ARRAY_SIZE(patch);
4675 			new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
4676 			if (!new_prog)
4677 				return -ENOMEM;
4678 
4679 			delta    += cnt - 1;
4680 			env->prog = new_prog;
4681 			insn      = new_prog->insnsi + i + delta;
4682 			continue;
4683 		}
4684 
4685 		if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
4686 			continue;
4687 
4688 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
4689 		size = BPF_LDST_BYTES(insn);
4690 
4691 		/* If the read access is a narrower load of the field,
4692 		 * convert to a 4/8-byte load, to minimum program type specific
4693 		 * convert_ctx_access changes. If conversion is successful,
4694 		 * we will apply proper mask to the result.
4695 		 */
4696 		is_narrower_load = size < ctx_field_size;
4697 		if (is_narrower_load) {
4698 			u32 off = insn->off;
4699 			u8 size_code;
4700 
4701 			if (type == BPF_WRITE) {
4702 				verbose("bpf verifier narrow ctx access misconfigured\n");
4703 				return -EINVAL;
4704 			}
4705 
4706 			size_code = BPF_H;
4707 			if (ctx_field_size == 4)
4708 				size_code = BPF_W;
4709 			else if (ctx_field_size == 8)
4710 				size_code = BPF_DW;
4711 
4712 			insn->off = off & ~(ctx_field_size - 1);
4713 			insn->code = BPF_LDX | BPF_MEM | size_code;
4714 		}
4715 
4716 		target_size = 0;
4717 		cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
4718 					      &target_size);
4719 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
4720 		    (ctx_field_size && !target_size)) {
4721 			verbose("bpf verifier is misconfigured\n");
4722 			return -EINVAL;
4723 		}
4724 
4725 		if (is_narrower_load && size < target_size) {
4726 			if (ctx_field_size <= 4)
4727 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
4728 								(1 << size * 8) - 1);
4729 			else
4730 				insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
4731 								(1 << size * 8) - 1);
4732 		}
4733 
4734 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4735 		if (!new_prog)
4736 			return -ENOMEM;
4737 
4738 		delta += cnt - 1;
4739 
4740 		/* keep walking new program and skip insns we just inserted */
4741 		env->prog = new_prog;
4742 		insn      = new_prog->insnsi + i + delta;
4743 	}
4744 
4745 	return 0;
4746 }
4747 
4748 /* fixup insn->imm field of bpf_call instructions
4749  * and inline eligible helpers as explicit sequence of BPF instructions
4750  *
4751  * this function is called after eBPF program passed verification
4752  */
fixup_bpf_calls(struct bpf_verifier_env * env)4753 static int fixup_bpf_calls(struct bpf_verifier_env *env)
4754 {
4755 	struct bpf_prog *prog = env->prog;
4756 	struct bpf_insn *insn = prog->insnsi;
4757 	const struct bpf_func_proto *fn;
4758 	const int insn_cnt = prog->len;
4759 	struct bpf_insn insn_buf[16];
4760 	struct bpf_prog *new_prog;
4761 	struct bpf_map *map_ptr;
4762 	int i, cnt, delta = 0;
4763 	struct bpf_insn_aux_data *aux;
4764 
4765 	for (i = 0; i < insn_cnt; i++, insn++) {
4766 		if (insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
4767 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
4768 			/* due to JIT bugs clear upper 32-bits of src register
4769 			 * before div/mod operation
4770 			 */
4771 			insn_buf[0] = BPF_MOV32_REG(insn->src_reg, insn->src_reg);
4772 			insn_buf[1] = *insn;
4773 			cnt = 2;
4774 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4775 			if (!new_prog)
4776 				return -ENOMEM;
4777 
4778 			delta    += cnt - 1;
4779 			env->prog = prog = new_prog;
4780 			insn      = new_prog->insnsi + i + delta;
4781 			continue;
4782 		}
4783 
4784 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
4785 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
4786 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
4787 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
4788 			struct bpf_insn insn_buf[16];
4789 			struct bpf_insn *patch = &insn_buf[0];
4790 			bool issrc, isneg;
4791 			u32 off_reg;
4792 
4793 			aux = &env->insn_aux_data[i + delta];
4794 			if (!aux->alu_state ||
4795 			    aux->alu_state == BPF_ALU_NON_POINTER)
4796 				continue;
4797 
4798 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
4799 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
4800 				BPF_ALU_SANITIZE_SRC;
4801 
4802 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
4803 			if (isneg)
4804 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
4805 			*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
4806 			*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
4807 			*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
4808 			*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
4809 			*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
4810 			if (issrc) {
4811 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
4812 							 off_reg);
4813 				insn->src_reg = BPF_REG_AX;
4814 			} else {
4815 				*patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
4816 							 BPF_REG_AX);
4817 			}
4818 			if (isneg)
4819 				insn->code = insn->code == code_add ?
4820 					     code_sub : code_add;
4821 			*patch++ = *insn;
4822 			if (issrc && isneg)
4823 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
4824 			cnt = patch - insn_buf;
4825 
4826 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4827 			if (!new_prog)
4828 				return -ENOMEM;
4829 
4830 			delta    += cnt - 1;
4831 			env->prog = prog = new_prog;
4832 			insn      = new_prog->insnsi + i + delta;
4833 			continue;
4834 		}
4835 
4836 		if (insn->code != (BPF_JMP | BPF_CALL))
4837 			continue;
4838 
4839 		if (insn->imm == BPF_FUNC_get_route_realm)
4840 			prog->dst_needed = 1;
4841 		if (insn->imm == BPF_FUNC_get_prandom_u32)
4842 			bpf_user_rnd_init_once();
4843 		if (insn->imm == BPF_FUNC_tail_call) {
4844 			/* If we tail call into other programs, we
4845 			 * cannot make any assumptions since they can
4846 			 * be replaced dynamically during runtime in
4847 			 * the program array.
4848 			 */
4849 			prog->cb_access = 1;
4850 			env->prog->aux->stack_depth = MAX_BPF_STACK;
4851 
4852 			/* mark bpf_tail_call as different opcode to avoid
4853 			 * conditional branch in the interpeter for every normal
4854 			 * call and to prevent accidental JITing by JIT compiler
4855 			 * that doesn't support bpf_tail_call yet
4856 			 */
4857 			insn->imm = 0;
4858 			insn->code = BPF_JMP | BPF_TAIL_CALL;
4859 
4860 			/* instead of changing every JIT dealing with tail_call
4861 			 * emit two extra insns:
4862 			 * if (index >= max_entries) goto out;
4863 			 * index &= array->index_mask;
4864 			 * to avoid out-of-bounds cpu speculation
4865 			 */
4866 			map_ptr = env->insn_aux_data[i + delta].map_ptr;
4867 			if (map_ptr == BPF_MAP_PTR_POISON) {
4868 				verbose("tail_call obusing map_ptr\n");
4869 				return -EINVAL;
4870 			}
4871 			if (!map_ptr->unpriv_array)
4872 				continue;
4873 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
4874 						  map_ptr->max_entries, 2);
4875 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
4876 						    container_of(map_ptr,
4877 								 struct bpf_array,
4878 								 map)->index_mask);
4879 			insn_buf[2] = *insn;
4880 			cnt = 3;
4881 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4882 			if (!new_prog)
4883 				return -ENOMEM;
4884 
4885 			delta    += cnt - 1;
4886 			env->prog = prog = new_prog;
4887 			insn      = new_prog->insnsi + i + delta;
4888 			continue;
4889 		}
4890 
4891 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
4892 		 * handlers are currently limited to 64 bit only.
4893 		 */
4894 		if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
4895 		    insn->imm == BPF_FUNC_map_lookup_elem) {
4896 			map_ptr = env->insn_aux_data[i + delta].map_ptr;
4897 			if (map_ptr == BPF_MAP_PTR_POISON ||
4898 			    !map_ptr->ops->map_gen_lookup)
4899 				goto patch_call_imm;
4900 
4901 			cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
4902 			if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
4903 				verbose("bpf verifier is misconfigured\n");
4904 				return -EINVAL;
4905 			}
4906 
4907 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
4908 						       cnt);
4909 			if (!new_prog)
4910 				return -ENOMEM;
4911 
4912 			delta += cnt - 1;
4913 
4914 			/* keep walking new program and skip insns we just inserted */
4915 			env->prog = prog = new_prog;
4916 			insn      = new_prog->insnsi + i + delta;
4917 			continue;
4918 		}
4919 
4920 		if (insn->imm == BPF_FUNC_redirect_map) {
4921 			/* Note, we cannot use prog directly as imm as subsequent
4922 			 * rewrites would still change the prog pointer. The only
4923 			 * stable address we can use is aux, which also works with
4924 			 * prog clones during blinding.
4925 			 */
4926 			u64 addr = (unsigned long)prog->aux;
4927 			struct bpf_insn r4_ld[] = {
4928 				BPF_LD_IMM64(BPF_REG_4, addr),
4929 				*insn,
4930 			};
4931 			cnt = ARRAY_SIZE(r4_ld);
4932 
4933 			new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
4934 			if (!new_prog)
4935 				return -ENOMEM;
4936 
4937 			delta    += cnt - 1;
4938 			env->prog = prog = new_prog;
4939 			insn      = new_prog->insnsi + i + delta;
4940 		}
4941 patch_call_imm:
4942 		fn = prog->aux->ops->get_func_proto(insn->imm);
4943 		/* all functions that have prototype and verifier allowed
4944 		 * programs to call them, must be real in-kernel functions
4945 		 */
4946 		if (!fn->func) {
4947 			verbose("kernel subsystem misconfigured func %s#%d\n",
4948 				func_id_name(insn->imm), insn->imm);
4949 			return -EFAULT;
4950 		}
4951 		insn->imm = fn->func - __bpf_call_base;
4952 	}
4953 
4954 	return 0;
4955 }
4956 
free_states(struct bpf_verifier_env * env)4957 static void free_states(struct bpf_verifier_env *env)
4958 {
4959 	struct bpf_verifier_state_list *sl, *sln;
4960 	int i;
4961 
4962 	if (!env->explored_states)
4963 		return;
4964 
4965 	for (i = 0; i < env->prog->len; i++) {
4966 		sl = env->explored_states[i];
4967 
4968 		if (sl)
4969 			while (sl != STATE_LIST_MARK) {
4970 				sln = sl->next;
4971 				free_verifier_state(&sl->state, false);
4972 				kfree(sl);
4973 				sl = sln;
4974 			}
4975 	}
4976 
4977 	kfree(env->explored_states);
4978 }
4979 
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr)4980 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
4981 {
4982 	char __user *log_ubuf = NULL;
4983 	struct bpf_verifier_env *env;
4984 	int ret = -EINVAL;
4985 
4986 	/* 'struct bpf_verifier_env' can be global, but since it's not small,
4987 	 * allocate/free it every time bpf_check() is called
4988 	 */
4989 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
4990 	if (!env)
4991 		return -ENOMEM;
4992 
4993 	env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
4994 				     (*prog)->len);
4995 	ret = -ENOMEM;
4996 	if (!env->insn_aux_data)
4997 		goto err_free_env;
4998 	env->prog = *prog;
4999 
5000 	/* grab the mutex to protect few globals used by verifier */
5001 	mutex_lock(&bpf_verifier_lock);
5002 
5003 	if (attr->log_level || attr->log_buf || attr->log_size) {
5004 		/* user requested verbose verifier output
5005 		 * and supplied buffer to store the verification trace
5006 		 */
5007 		log_level = attr->log_level;
5008 		log_ubuf = (char __user *) (unsigned long) attr->log_buf;
5009 		log_size = attr->log_size;
5010 		log_len = 0;
5011 
5012 		ret = -EINVAL;
5013 		/* log_* values have to be sane */
5014 		if (log_size < 128 || log_size > UINT_MAX >> 8 ||
5015 		    log_level == 0 || log_ubuf == NULL)
5016 			goto err_unlock;
5017 
5018 		ret = -ENOMEM;
5019 		log_buf = vmalloc(log_size);
5020 		if (!log_buf)
5021 			goto err_unlock;
5022 	} else {
5023 		log_level = 0;
5024 	}
5025 
5026 	env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5027 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5028 		env->strict_alignment = true;
5029 
5030 	ret = replace_map_fd_with_map_ptr(env);
5031 	if (ret < 0)
5032 		goto skip_full_check;
5033 
5034 	env->explored_states = kcalloc(env->prog->len,
5035 				       sizeof(struct bpf_verifier_state_list *),
5036 				       GFP_USER);
5037 	ret = -ENOMEM;
5038 	if (!env->explored_states)
5039 		goto skip_full_check;
5040 
5041 	ret = check_cfg(env);
5042 	if (ret < 0)
5043 		goto skip_full_check;
5044 
5045 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5046 
5047 	ret = do_check(env);
5048 	if (env->cur_state) {
5049 		free_verifier_state(env->cur_state, true);
5050 		env->cur_state = NULL;
5051 	}
5052 
5053 skip_full_check:
5054 	while (!pop_stack(env, NULL, NULL));
5055 	free_states(env);
5056 
5057 	if (ret == 0)
5058 		sanitize_dead_code(env);
5059 
5060 	if (ret == 0)
5061 		/* program is valid, convert *(u32*)(ctx + off) accesses */
5062 		ret = convert_ctx_accesses(env);
5063 
5064 	if (ret == 0)
5065 		ret = fixup_bpf_calls(env);
5066 
5067 	if (log_level && log_len >= log_size - 1) {
5068 		BUG_ON(log_len >= log_size);
5069 		/* verifier log exceeded user supplied buffer */
5070 		ret = -ENOSPC;
5071 		/* fall through to return what was recorded */
5072 	}
5073 
5074 	/* copy verifier log back to user space including trailing zero */
5075 	if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
5076 		ret = -EFAULT;
5077 		goto free_log_buf;
5078 	}
5079 
5080 	if (ret == 0 && env->used_map_cnt) {
5081 		/* if program passed verifier, update used_maps in bpf_prog_info */
5082 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5083 							  sizeof(env->used_maps[0]),
5084 							  GFP_KERNEL);
5085 
5086 		if (!env->prog->aux->used_maps) {
5087 			ret = -ENOMEM;
5088 			goto free_log_buf;
5089 		}
5090 
5091 		memcpy(env->prog->aux->used_maps, env->used_maps,
5092 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
5093 		env->prog->aux->used_map_cnt = env->used_map_cnt;
5094 
5095 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
5096 		 * bpf_ld_imm64 instructions
5097 		 */
5098 		convert_pseudo_ld_imm64(env);
5099 	}
5100 
5101 free_log_buf:
5102 	if (log_level)
5103 		vfree(log_buf);
5104 	if (!env->prog->aux->used_maps)
5105 		/* if we didn't copy map pointers into bpf_prog_info, release
5106 		 * them now. Otherwise free_used_maps() will release them.
5107 		 */
5108 		release_maps(env);
5109 	*prog = env->prog;
5110 err_unlock:
5111 	mutex_unlock(&bpf_verifier_lock);
5112 	vfree(env->insn_aux_data);
5113 err_free_env:
5114 	kfree(env);
5115 	return ret;
5116 }
5117 
bpf_analyzer(struct bpf_prog * prog,const struct bpf_ext_analyzer_ops * ops,void * priv)5118 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
5119 		 void *priv)
5120 {
5121 	struct bpf_verifier_env *env;
5122 	int ret;
5123 
5124 	env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5125 	if (!env)
5126 		return -ENOMEM;
5127 
5128 	env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5129 				     prog->len);
5130 	ret = -ENOMEM;
5131 	if (!env->insn_aux_data)
5132 		goto err_free_env;
5133 	env->prog = prog;
5134 	env->analyzer_ops = ops;
5135 	env->analyzer_priv = priv;
5136 
5137 	/* grab the mutex to protect few globals used by verifier */
5138 	mutex_lock(&bpf_verifier_lock);
5139 
5140 	log_level = 0;
5141 
5142 	env->strict_alignment = false;
5143 	if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5144 		env->strict_alignment = true;
5145 
5146 	env->explored_states = kcalloc(env->prog->len,
5147 				       sizeof(struct bpf_verifier_state_list *),
5148 				       GFP_KERNEL);
5149 	ret = -ENOMEM;
5150 	if (!env->explored_states)
5151 		goto skip_full_check;
5152 
5153 	ret = check_cfg(env);
5154 	if (ret < 0)
5155 		goto skip_full_check;
5156 
5157 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5158 
5159 	ret = do_check(env);
5160 	if (env->cur_state) {
5161 		free_verifier_state(env->cur_state, true);
5162 		env->cur_state = NULL;
5163 	}
5164 
5165 skip_full_check:
5166 	while (!pop_stack(env, NULL, NULL));
5167 	free_states(env);
5168 
5169 	mutex_unlock(&bpf_verifier_lock);
5170 	vfree(env->insn_aux_data);
5171 err_free_env:
5172 	kfree(env);
5173 	return ret;
5174 }
5175 EXPORT_SYMBOL_GPL(bpf_analyzer);
5176