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