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