xref: /linux/kernel/bpf/verifier.c (revision 0883c2c06fb5bcf5b9e008270827e63c09a88c1e)
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/filter.h>
18 #include <net/netlink.h>
19 #include <linux/file.h>
20 #include <linux/vmalloc.h>
21 
22 /* bpf_check() is a static code analyzer that walks eBPF program
23  * instruction by instruction and updates register/stack state.
24  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
25  *
26  * The first pass is depth-first-search to check that the program is a DAG.
27  * It rejects the following programs:
28  * - larger than BPF_MAXINSNS insns
29  * - if loop is present (detected via back-edge)
30  * - unreachable insns exist (shouldn't be a forest. program = one function)
31  * - out of bounds or malformed jumps
32  * The second pass is all possible path descent from the 1st insn.
33  * Since it's analyzing all pathes through the program, the length of the
34  * analysis is limited to 32k insn, which may be hit even if total number of
35  * insn is less then 4K, but there are too many branches that change stack/regs.
36  * Number of 'branches to be analyzed' is limited to 1k
37  *
38  * On entry to each instruction, each register has a type, and the instruction
39  * changes the types of the registers depending on instruction semantics.
40  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
41  * copied to R1.
42  *
43  * All registers are 64-bit.
44  * R0 - return register
45  * R1-R5 argument passing registers
46  * R6-R9 callee saved registers
47  * R10 - frame pointer read-only
48  *
49  * At the start of BPF program the register R1 contains a pointer to bpf_context
50  * and has type PTR_TO_CTX.
51  *
52  * Verifier tracks arithmetic operations on pointers in case:
53  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
54  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
55  * 1st insn copies R10 (which has FRAME_PTR) type into R1
56  * and 2nd arithmetic instruction is pattern matched to recognize
57  * that it wants to construct a pointer to some element within stack.
58  * So after 2nd insn, the register R1 has type PTR_TO_STACK
59  * (and -20 constant is saved for further stack bounds checking).
60  * Meaning that this reg is a pointer to stack plus known immediate constant.
61  *
62  * Most of the time the registers have UNKNOWN_VALUE type, which
63  * means the register has some value, but it's not a valid pointer.
64  * (like pointer plus pointer becomes UNKNOWN_VALUE type)
65  *
66  * When verifier sees load or store instructions the type of base register
67  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
68  * types recognized by check_mem_access() function.
69  *
70  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
71  * and the range of [ptr, ptr + map's value_size) is accessible.
72  *
73  * registers used to pass values to function calls are checked against
74  * function argument constraints.
75  *
76  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
77  * It means that the register type passed to this function must be
78  * PTR_TO_STACK and it will be used inside the function as
79  * 'pointer to map element key'
80  *
81  * For example the argument constraints for bpf_map_lookup_elem():
82  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
83  *   .arg1_type = ARG_CONST_MAP_PTR,
84  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
85  *
86  * ret_type says that this function returns 'pointer to map elem value or null'
87  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
88  * 2nd argument should be a pointer to stack, which will be used inside
89  * the helper function as a pointer to map element key.
90  *
91  * On the kernel side the helper function looks like:
92  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
93  * {
94  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
95  *    void *key = (void *) (unsigned long) r2;
96  *    void *value;
97  *
98  *    here kernel can access 'key' and 'map' pointers safely, knowing that
99  *    [key, key + map->key_size) bytes are valid and were initialized on
100  *    the stack of eBPF program.
101  * }
102  *
103  * Corresponding eBPF program may look like:
104  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
105  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
106  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
107  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
108  * here verifier looks at prototype of map_lookup_elem() and sees:
109  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
110  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
111  *
112  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
113  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
114  * and were initialized prior to this call.
115  * If it's ok, then verifier allows this BPF_CALL insn and looks at
116  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
117  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
118  * returns ether pointer to map value or NULL.
119  *
120  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
121  * insn, the register holding that pointer in the true branch changes state to
122  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
123  * branch. See check_cond_jmp_op().
124  *
125  * After the call R0 is set to return type of the function and registers R1-R5
126  * are set to NOT_INIT to indicate that they are no longer readable.
127  */
128 
129 /* types of values stored in eBPF registers */
130 enum bpf_reg_type {
131 	NOT_INIT = 0,		 /* nothing was written into register */
132 	UNKNOWN_VALUE,		 /* reg doesn't contain a valid pointer */
133 	PTR_TO_CTX,		 /* reg points to bpf_context */
134 	CONST_PTR_TO_MAP,	 /* reg points to struct bpf_map */
135 	PTR_TO_MAP_VALUE,	 /* reg points to map element value */
136 	PTR_TO_MAP_VALUE_OR_NULL,/* points to map elem value or NULL */
137 	FRAME_PTR,		 /* reg == frame_pointer */
138 	PTR_TO_STACK,		 /* reg == frame_pointer + imm */
139 	CONST_IMM,		 /* constant integer value */
140 
141 	/* PTR_TO_PACKET represents:
142 	 * skb->data
143 	 * skb->data + imm
144 	 * skb->data + (u16) var
145 	 * skb->data + (u16) var + imm
146 	 * if (range > 0) then [ptr, ptr + range - off) is safe to access
147 	 * if (id > 0) means that some 'var' was added
148 	 * if (off > 0) menas that 'imm' was added
149 	 */
150 	PTR_TO_PACKET,
151 	PTR_TO_PACKET_END,	 /* skb->data + headlen */
152 };
153 
154 struct reg_state {
155 	enum bpf_reg_type type;
156 	union {
157 		/* valid when type == CONST_IMM | PTR_TO_STACK | UNKNOWN_VALUE */
158 		s64 imm;
159 
160 		/* valid when type == PTR_TO_PACKET* */
161 		struct {
162 			u32 id;
163 			u16 off;
164 			u16 range;
165 		};
166 
167 		/* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
168 		 *   PTR_TO_MAP_VALUE_OR_NULL
169 		 */
170 		struct bpf_map *map_ptr;
171 	};
172 };
173 
174 enum bpf_stack_slot_type {
175 	STACK_INVALID,    /* nothing was stored in this stack slot */
176 	STACK_SPILL,      /* register spilled into stack */
177 	STACK_MISC	  /* BPF program wrote some data into this slot */
178 };
179 
180 #define BPF_REG_SIZE 8	/* size of eBPF register in bytes */
181 
182 /* state of the program:
183  * type of all registers and stack info
184  */
185 struct verifier_state {
186 	struct reg_state regs[MAX_BPF_REG];
187 	u8 stack_slot_type[MAX_BPF_STACK];
188 	struct reg_state spilled_regs[MAX_BPF_STACK / BPF_REG_SIZE];
189 };
190 
191 /* linked list of verifier states used to prune search */
192 struct verifier_state_list {
193 	struct verifier_state state;
194 	struct verifier_state_list *next;
195 };
196 
197 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
198 struct verifier_stack_elem {
199 	/* verifer state is 'st'
200 	 * before processing instruction 'insn_idx'
201 	 * and after processing instruction 'prev_insn_idx'
202 	 */
203 	struct verifier_state st;
204 	int insn_idx;
205 	int prev_insn_idx;
206 	struct verifier_stack_elem *next;
207 };
208 
209 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
210 
211 /* single container for all structs
212  * one verifier_env per bpf_check() call
213  */
214 struct verifier_env {
215 	struct bpf_prog *prog;		/* eBPF program being verified */
216 	struct verifier_stack_elem *head; /* stack of verifier states to be processed */
217 	int stack_size;			/* number of states to be processed */
218 	struct verifier_state cur_state; /* current verifier state */
219 	struct verifier_state_list **explored_states; /* search pruning optimization */
220 	struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
221 	u32 used_map_cnt;		/* number of used maps */
222 	bool allow_ptr_leaks;
223 };
224 
225 #define BPF_COMPLEXITY_LIMIT_INSNS	65536
226 #define BPF_COMPLEXITY_LIMIT_STACK	1024
227 
228 struct bpf_call_arg_meta {
229 	struct bpf_map *map_ptr;
230 	bool raw_mode;
231 	int regno;
232 	int access_size;
233 };
234 
235 /* verbose verifier prints what it's seeing
236  * bpf_check() is called under lock, so no race to access these global vars
237  */
238 static u32 log_level, log_size, log_len;
239 static char *log_buf;
240 
241 static DEFINE_MUTEX(bpf_verifier_lock);
242 
243 /* log_level controls verbosity level of eBPF verifier.
244  * verbose() is used to dump the verification trace to the log, so the user
245  * can figure out what's wrong with the program
246  */
247 static __printf(1, 2) void verbose(const char *fmt, ...)
248 {
249 	va_list args;
250 
251 	if (log_level == 0 || log_len >= log_size - 1)
252 		return;
253 
254 	va_start(args, fmt);
255 	log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
256 	va_end(args);
257 }
258 
259 /* string representation of 'enum bpf_reg_type' */
260 static const char * const reg_type_str[] = {
261 	[NOT_INIT]		= "?",
262 	[UNKNOWN_VALUE]		= "inv",
263 	[PTR_TO_CTX]		= "ctx",
264 	[CONST_PTR_TO_MAP]	= "map_ptr",
265 	[PTR_TO_MAP_VALUE]	= "map_value",
266 	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
267 	[FRAME_PTR]		= "fp",
268 	[PTR_TO_STACK]		= "fp",
269 	[CONST_IMM]		= "imm",
270 	[PTR_TO_PACKET]		= "pkt",
271 	[PTR_TO_PACKET_END]	= "pkt_end",
272 };
273 
274 static void print_verifier_state(struct verifier_state *state)
275 {
276 	struct reg_state *reg;
277 	enum bpf_reg_type t;
278 	int i;
279 
280 	for (i = 0; i < MAX_BPF_REG; i++) {
281 		reg = &state->regs[i];
282 		t = reg->type;
283 		if (t == NOT_INIT)
284 			continue;
285 		verbose(" R%d=%s", i, reg_type_str[t]);
286 		if (t == CONST_IMM || t == PTR_TO_STACK)
287 			verbose("%lld", reg->imm);
288 		else if (t == PTR_TO_PACKET)
289 			verbose("(id=%d,off=%d,r=%d)",
290 				reg->id, reg->off, reg->range);
291 		else if (t == UNKNOWN_VALUE && reg->imm)
292 			verbose("%lld", reg->imm);
293 		else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
294 			 t == PTR_TO_MAP_VALUE_OR_NULL)
295 			verbose("(ks=%d,vs=%d)",
296 				reg->map_ptr->key_size,
297 				reg->map_ptr->value_size);
298 	}
299 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
300 		if (state->stack_slot_type[i] == STACK_SPILL)
301 			verbose(" fp%d=%s", -MAX_BPF_STACK + i,
302 				reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
303 	}
304 	verbose("\n");
305 }
306 
307 static const char *const bpf_class_string[] = {
308 	[BPF_LD]    = "ld",
309 	[BPF_LDX]   = "ldx",
310 	[BPF_ST]    = "st",
311 	[BPF_STX]   = "stx",
312 	[BPF_ALU]   = "alu",
313 	[BPF_JMP]   = "jmp",
314 	[BPF_RET]   = "BUG",
315 	[BPF_ALU64] = "alu64",
316 };
317 
318 static const char *const bpf_alu_string[16] = {
319 	[BPF_ADD >> 4]  = "+=",
320 	[BPF_SUB >> 4]  = "-=",
321 	[BPF_MUL >> 4]  = "*=",
322 	[BPF_DIV >> 4]  = "/=",
323 	[BPF_OR  >> 4]  = "|=",
324 	[BPF_AND >> 4]  = "&=",
325 	[BPF_LSH >> 4]  = "<<=",
326 	[BPF_RSH >> 4]  = ">>=",
327 	[BPF_NEG >> 4]  = "neg",
328 	[BPF_MOD >> 4]  = "%=",
329 	[BPF_XOR >> 4]  = "^=",
330 	[BPF_MOV >> 4]  = "=",
331 	[BPF_ARSH >> 4] = "s>>=",
332 	[BPF_END >> 4]  = "endian",
333 };
334 
335 static const char *const bpf_ldst_string[] = {
336 	[BPF_W >> 3]  = "u32",
337 	[BPF_H >> 3]  = "u16",
338 	[BPF_B >> 3]  = "u8",
339 	[BPF_DW >> 3] = "u64",
340 };
341 
342 static const char *const bpf_jmp_string[16] = {
343 	[BPF_JA >> 4]   = "jmp",
344 	[BPF_JEQ >> 4]  = "==",
345 	[BPF_JGT >> 4]  = ">",
346 	[BPF_JGE >> 4]  = ">=",
347 	[BPF_JSET >> 4] = "&",
348 	[BPF_JNE >> 4]  = "!=",
349 	[BPF_JSGT >> 4] = "s>",
350 	[BPF_JSGE >> 4] = "s>=",
351 	[BPF_CALL >> 4] = "call",
352 	[BPF_EXIT >> 4] = "exit",
353 };
354 
355 static void print_bpf_insn(struct bpf_insn *insn)
356 {
357 	u8 class = BPF_CLASS(insn->code);
358 
359 	if (class == BPF_ALU || class == BPF_ALU64) {
360 		if (BPF_SRC(insn->code) == BPF_X)
361 			verbose("(%02x) %sr%d %s %sr%d\n",
362 				insn->code, class == BPF_ALU ? "(u32) " : "",
363 				insn->dst_reg,
364 				bpf_alu_string[BPF_OP(insn->code) >> 4],
365 				class == BPF_ALU ? "(u32) " : "",
366 				insn->src_reg);
367 		else
368 			verbose("(%02x) %sr%d %s %s%d\n",
369 				insn->code, class == BPF_ALU ? "(u32) " : "",
370 				insn->dst_reg,
371 				bpf_alu_string[BPF_OP(insn->code) >> 4],
372 				class == BPF_ALU ? "(u32) " : "",
373 				insn->imm);
374 	} else if (class == BPF_STX) {
375 		if (BPF_MODE(insn->code) == BPF_MEM)
376 			verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
377 				insn->code,
378 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
379 				insn->dst_reg,
380 				insn->off, insn->src_reg);
381 		else if (BPF_MODE(insn->code) == BPF_XADD)
382 			verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
383 				insn->code,
384 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
385 				insn->dst_reg, insn->off,
386 				insn->src_reg);
387 		else
388 			verbose("BUG_%02x\n", insn->code);
389 	} else if (class == BPF_ST) {
390 		if (BPF_MODE(insn->code) != BPF_MEM) {
391 			verbose("BUG_st_%02x\n", insn->code);
392 			return;
393 		}
394 		verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
395 			insn->code,
396 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
397 			insn->dst_reg,
398 			insn->off, insn->imm);
399 	} else if (class == BPF_LDX) {
400 		if (BPF_MODE(insn->code) != BPF_MEM) {
401 			verbose("BUG_ldx_%02x\n", insn->code);
402 			return;
403 		}
404 		verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
405 			insn->code, insn->dst_reg,
406 			bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
407 			insn->src_reg, insn->off);
408 	} else if (class == BPF_LD) {
409 		if (BPF_MODE(insn->code) == BPF_ABS) {
410 			verbose("(%02x) r0 = *(%s *)skb[%d]\n",
411 				insn->code,
412 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
413 				insn->imm);
414 		} else if (BPF_MODE(insn->code) == BPF_IND) {
415 			verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
416 				insn->code,
417 				bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
418 				insn->src_reg, insn->imm);
419 		} else if (BPF_MODE(insn->code) == BPF_IMM) {
420 			verbose("(%02x) r%d = 0x%x\n",
421 				insn->code, insn->dst_reg, insn->imm);
422 		} else {
423 			verbose("BUG_ld_%02x\n", insn->code);
424 			return;
425 		}
426 	} else if (class == BPF_JMP) {
427 		u8 opcode = BPF_OP(insn->code);
428 
429 		if (opcode == BPF_CALL) {
430 			verbose("(%02x) call %d\n", insn->code, insn->imm);
431 		} else if (insn->code == (BPF_JMP | BPF_JA)) {
432 			verbose("(%02x) goto pc%+d\n",
433 				insn->code, insn->off);
434 		} else if (insn->code == (BPF_JMP | BPF_EXIT)) {
435 			verbose("(%02x) exit\n", insn->code);
436 		} else if (BPF_SRC(insn->code) == BPF_X) {
437 			verbose("(%02x) if r%d %s r%d goto pc%+d\n",
438 				insn->code, insn->dst_reg,
439 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
440 				insn->src_reg, insn->off);
441 		} else {
442 			verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
443 				insn->code, insn->dst_reg,
444 				bpf_jmp_string[BPF_OP(insn->code) >> 4],
445 				insn->imm, insn->off);
446 		}
447 	} else {
448 		verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
449 	}
450 }
451 
452 static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
453 {
454 	struct verifier_stack_elem *elem;
455 	int insn_idx;
456 
457 	if (env->head == NULL)
458 		return -1;
459 
460 	memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
461 	insn_idx = env->head->insn_idx;
462 	if (prev_insn_idx)
463 		*prev_insn_idx = env->head->prev_insn_idx;
464 	elem = env->head->next;
465 	kfree(env->head);
466 	env->head = elem;
467 	env->stack_size--;
468 	return insn_idx;
469 }
470 
471 static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
472 					 int prev_insn_idx)
473 {
474 	struct verifier_stack_elem *elem;
475 
476 	elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
477 	if (!elem)
478 		goto err;
479 
480 	memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
481 	elem->insn_idx = insn_idx;
482 	elem->prev_insn_idx = prev_insn_idx;
483 	elem->next = env->head;
484 	env->head = elem;
485 	env->stack_size++;
486 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
487 		verbose("BPF program is too complex\n");
488 		goto err;
489 	}
490 	return &elem->st;
491 err:
492 	/* pop all elements and return */
493 	while (pop_stack(env, NULL) >= 0);
494 	return NULL;
495 }
496 
497 #define CALLER_SAVED_REGS 6
498 static const int caller_saved[CALLER_SAVED_REGS] = {
499 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
500 };
501 
502 static void init_reg_state(struct reg_state *regs)
503 {
504 	int i;
505 
506 	for (i = 0; i < MAX_BPF_REG; i++) {
507 		regs[i].type = NOT_INIT;
508 		regs[i].imm = 0;
509 	}
510 
511 	/* frame pointer */
512 	regs[BPF_REG_FP].type = FRAME_PTR;
513 
514 	/* 1st arg to a function */
515 	regs[BPF_REG_1].type = PTR_TO_CTX;
516 }
517 
518 static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
519 {
520 	BUG_ON(regno >= MAX_BPF_REG);
521 	regs[regno].type = UNKNOWN_VALUE;
522 	regs[regno].imm = 0;
523 }
524 
525 enum reg_arg_type {
526 	SRC_OP,		/* register is used as source operand */
527 	DST_OP,		/* register is used as destination operand */
528 	DST_OP_NO_MARK	/* same as above, check only, don't mark */
529 };
530 
531 static int check_reg_arg(struct reg_state *regs, u32 regno,
532 			 enum reg_arg_type t)
533 {
534 	if (regno >= MAX_BPF_REG) {
535 		verbose("R%d is invalid\n", regno);
536 		return -EINVAL;
537 	}
538 
539 	if (t == SRC_OP) {
540 		/* check whether register used as source operand can be read */
541 		if (regs[regno].type == NOT_INIT) {
542 			verbose("R%d !read_ok\n", regno);
543 			return -EACCES;
544 		}
545 	} else {
546 		/* check whether register used as dest operand can be written to */
547 		if (regno == BPF_REG_FP) {
548 			verbose("frame pointer is read only\n");
549 			return -EACCES;
550 		}
551 		if (t == DST_OP)
552 			mark_reg_unknown_value(regs, regno);
553 	}
554 	return 0;
555 }
556 
557 static int bpf_size_to_bytes(int bpf_size)
558 {
559 	if (bpf_size == BPF_W)
560 		return 4;
561 	else if (bpf_size == BPF_H)
562 		return 2;
563 	else if (bpf_size == BPF_B)
564 		return 1;
565 	else if (bpf_size == BPF_DW)
566 		return 8;
567 	else
568 		return -EINVAL;
569 }
570 
571 static bool is_spillable_regtype(enum bpf_reg_type type)
572 {
573 	switch (type) {
574 	case PTR_TO_MAP_VALUE:
575 	case PTR_TO_MAP_VALUE_OR_NULL:
576 	case PTR_TO_STACK:
577 	case PTR_TO_CTX:
578 	case PTR_TO_PACKET:
579 	case PTR_TO_PACKET_END:
580 	case FRAME_PTR:
581 	case CONST_PTR_TO_MAP:
582 		return true;
583 	default:
584 		return false;
585 	}
586 }
587 
588 /* check_stack_read/write functions track spill/fill of registers,
589  * stack boundary and alignment are checked in check_mem_access()
590  */
591 static int check_stack_write(struct verifier_state *state, int off, int size,
592 			     int value_regno)
593 {
594 	int i;
595 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
596 	 * so it's aligned access and [off, off + size) are within stack limits
597 	 */
598 
599 	if (value_regno >= 0 &&
600 	    is_spillable_regtype(state->regs[value_regno].type)) {
601 
602 		/* register containing pointer is being spilled into stack */
603 		if (size != BPF_REG_SIZE) {
604 			verbose("invalid size of register spill\n");
605 			return -EACCES;
606 		}
607 
608 		/* save register state */
609 		state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
610 			state->regs[value_regno];
611 
612 		for (i = 0; i < BPF_REG_SIZE; i++)
613 			state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
614 	} else {
615 		/* regular write of data into stack */
616 		state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
617 			(struct reg_state) {};
618 
619 		for (i = 0; i < size; i++)
620 			state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
621 	}
622 	return 0;
623 }
624 
625 static int check_stack_read(struct verifier_state *state, int off, int size,
626 			    int value_regno)
627 {
628 	u8 *slot_type;
629 	int i;
630 
631 	slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
632 
633 	if (slot_type[0] == STACK_SPILL) {
634 		if (size != BPF_REG_SIZE) {
635 			verbose("invalid size of register spill\n");
636 			return -EACCES;
637 		}
638 		for (i = 1; i < BPF_REG_SIZE; i++) {
639 			if (slot_type[i] != STACK_SPILL) {
640 				verbose("corrupted spill memory\n");
641 				return -EACCES;
642 			}
643 		}
644 
645 		if (value_regno >= 0)
646 			/* restore register state from stack */
647 			state->regs[value_regno] =
648 				state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
649 		return 0;
650 	} else {
651 		for (i = 0; i < size; i++) {
652 			if (slot_type[i] != STACK_MISC) {
653 				verbose("invalid read from stack off %d+%d size %d\n",
654 					off, i, size);
655 				return -EACCES;
656 			}
657 		}
658 		if (value_regno >= 0)
659 			/* have read misc data from the stack */
660 			mark_reg_unknown_value(state->regs, value_regno);
661 		return 0;
662 	}
663 }
664 
665 /* check read/write into map element returned by bpf_map_lookup_elem() */
666 static int check_map_access(struct verifier_env *env, u32 regno, int off,
667 			    int size)
668 {
669 	struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
670 
671 	if (off < 0 || off + size > map->value_size) {
672 		verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
673 			map->value_size, off, size);
674 		return -EACCES;
675 	}
676 	return 0;
677 }
678 
679 #define MAX_PACKET_OFF 0xffff
680 
681 static int check_packet_access(struct verifier_env *env, u32 regno, int off,
682 			       int size)
683 {
684 	struct reg_state *regs = env->cur_state.regs;
685 	struct reg_state *reg = &regs[regno];
686 
687 	off += reg->off;
688 	if (off < 0 || off + size > reg->range) {
689 		verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
690 			off, size, regno, reg->id, reg->off, reg->range);
691 		return -EACCES;
692 	}
693 	return 0;
694 }
695 
696 /* check access to 'struct bpf_context' fields */
697 static int check_ctx_access(struct verifier_env *env, int off, int size,
698 			    enum bpf_access_type t)
699 {
700 	if (env->prog->aux->ops->is_valid_access &&
701 	    env->prog->aux->ops->is_valid_access(off, size, t)) {
702 		/* remember the offset of last byte accessed in ctx */
703 		if (env->prog->aux->max_ctx_offset < off + size)
704 			env->prog->aux->max_ctx_offset = off + size;
705 		return 0;
706 	}
707 
708 	verbose("invalid bpf_context access off=%d size=%d\n", off, size);
709 	return -EACCES;
710 }
711 
712 static bool is_pointer_value(struct verifier_env *env, int regno)
713 {
714 	if (env->allow_ptr_leaks)
715 		return false;
716 
717 	switch (env->cur_state.regs[regno].type) {
718 	case UNKNOWN_VALUE:
719 	case CONST_IMM:
720 		return false;
721 	default:
722 		return true;
723 	}
724 }
725 
726 static int check_ptr_alignment(struct verifier_env *env, struct reg_state *reg,
727 			       int off, int size)
728 {
729 	if (reg->type != PTR_TO_PACKET) {
730 		if (off % size != 0) {
731 			verbose("misaligned access off %d size %d\n", off, size);
732 			return -EACCES;
733 		} else {
734 			return 0;
735 		}
736 	}
737 
738 	switch (env->prog->type) {
739 	case BPF_PROG_TYPE_SCHED_CLS:
740 	case BPF_PROG_TYPE_SCHED_ACT:
741 		break;
742 	default:
743 		verbose("verifier is misconfigured\n");
744 		return -EACCES;
745 	}
746 
747 	if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
748 		/* misaligned access to packet is ok on x86,arm,arm64 */
749 		return 0;
750 
751 	if (reg->id && size != 1) {
752 		verbose("Unknown packet alignment. Only byte-sized access allowed\n");
753 		return -EACCES;
754 	}
755 
756 	/* skb->data is NET_IP_ALIGN-ed */
757 	if ((NET_IP_ALIGN + reg->off + off) % size != 0) {
758 		verbose("misaligned packet access off %d+%d+%d size %d\n",
759 			NET_IP_ALIGN, reg->off, off, size);
760 		return -EACCES;
761 	}
762 	return 0;
763 }
764 
765 /* check whether memory at (regno + off) is accessible for t = (read | write)
766  * if t==write, value_regno is a register which value is stored into memory
767  * if t==read, value_regno is a register which will receive the value from memory
768  * if t==write && value_regno==-1, some unknown value is stored into memory
769  * if t==read && value_regno==-1, don't care what we read from memory
770  */
771 static int check_mem_access(struct verifier_env *env, u32 regno, int off,
772 			    int bpf_size, enum bpf_access_type t,
773 			    int value_regno)
774 {
775 	struct verifier_state *state = &env->cur_state;
776 	struct reg_state *reg = &state->regs[regno];
777 	int size, err = 0;
778 
779 	if (reg->type == PTR_TO_STACK)
780 		off += reg->imm;
781 
782 	size = bpf_size_to_bytes(bpf_size);
783 	if (size < 0)
784 		return size;
785 
786 	err = check_ptr_alignment(env, reg, off, size);
787 	if (err)
788 		return err;
789 
790 	if (reg->type == PTR_TO_MAP_VALUE) {
791 		if (t == BPF_WRITE && value_regno >= 0 &&
792 		    is_pointer_value(env, value_regno)) {
793 			verbose("R%d leaks addr into map\n", value_regno);
794 			return -EACCES;
795 		}
796 		err = check_map_access(env, regno, off, size);
797 		if (!err && t == BPF_READ && value_regno >= 0)
798 			mark_reg_unknown_value(state->regs, value_regno);
799 
800 	} else if (reg->type == PTR_TO_CTX) {
801 		if (t == BPF_WRITE && value_regno >= 0 &&
802 		    is_pointer_value(env, value_regno)) {
803 			verbose("R%d leaks addr into ctx\n", value_regno);
804 			return -EACCES;
805 		}
806 		err = check_ctx_access(env, off, size, t);
807 		if (!err && t == BPF_READ && value_regno >= 0) {
808 			mark_reg_unknown_value(state->regs, value_regno);
809 			if (off == offsetof(struct __sk_buff, data) &&
810 			    env->allow_ptr_leaks)
811 				/* note that reg.[id|off|range] == 0 */
812 				state->regs[value_regno].type = PTR_TO_PACKET;
813 			else if (off == offsetof(struct __sk_buff, data_end) &&
814 				 env->allow_ptr_leaks)
815 				state->regs[value_regno].type = PTR_TO_PACKET_END;
816 		}
817 
818 	} else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
819 		if (off >= 0 || off < -MAX_BPF_STACK) {
820 			verbose("invalid stack off=%d size=%d\n", off, size);
821 			return -EACCES;
822 		}
823 		if (t == BPF_WRITE) {
824 			if (!env->allow_ptr_leaks &&
825 			    state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
826 			    size != BPF_REG_SIZE) {
827 				verbose("attempt to corrupt spilled pointer on stack\n");
828 				return -EACCES;
829 			}
830 			err = check_stack_write(state, off, size, value_regno);
831 		} else {
832 			err = check_stack_read(state, off, size, value_regno);
833 		}
834 	} else if (state->regs[regno].type == PTR_TO_PACKET) {
835 		if (t == BPF_WRITE) {
836 			verbose("cannot write into packet\n");
837 			return -EACCES;
838 		}
839 		err = check_packet_access(env, regno, off, size);
840 		if (!err && t == BPF_READ && value_regno >= 0)
841 			mark_reg_unknown_value(state->regs, value_regno);
842 	} else {
843 		verbose("R%d invalid mem access '%s'\n",
844 			regno, reg_type_str[reg->type]);
845 		return -EACCES;
846 	}
847 
848 	if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
849 	    state->regs[value_regno].type == UNKNOWN_VALUE) {
850 		/* 1 or 2 byte load zero-extends, determine the number of
851 		 * zero upper bits. Not doing it fo 4 byte load, since
852 		 * such values cannot be added to ptr_to_packet anyway.
853 		 */
854 		state->regs[value_regno].imm = 64 - size * 8;
855 	}
856 	return err;
857 }
858 
859 static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
860 {
861 	struct reg_state *regs = env->cur_state.regs;
862 	int err;
863 
864 	if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
865 	    insn->imm != 0) {
866 		verbose("BPF_XADD uses reserved fields\n");
867 		return -EINVAL;
868 	}
869 
870 	/* check src1 operand */
871 	err = check_reg_arg(regs, insn->src_reg, SRC_OP);
872 	if (err)
873 		return err;
874 
875 	/* check src2 operand */
876 	err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
877 	if (err)
878 		return err;
879 
880 	/* check whether atomic_add can read the memory */
881 	err = check_mem_access(env, insn->dst_reg, insn->off,
882 			       BPF_SIZE(insn->code), BPF_READ, -1);
883 	if (err)
884 		return err;
885 
886 	/* check whether atomic_add can write into the same memory */
887 	return check_mem_access(env, insn->dst_reg, insn->off,
888 				BPF_SIZE(insn->code), BPF_WRITE, -1);
889 }
890 
891 /* when register 'regno' is passed into function that will read 'access_size'
892  * bytes from that pointer, make sure that it's within stack boundary
893  * and all elements of stack are initialized
894  */
895 static int check_stack_boundary(struct verifier_env *env, int regno,
896 				int access_size, bool zero_size_allowed,
897 				struct bpf_call_arg_meta *meta)
898 {
899 	struct verifier_state *state = &env->cur_state;
900 	struct reg_state *regs = state->regs;
901 	int off, i;
902 
903 	if (regs[regno].type != PTR_TO_STACK) {
904 		if (zero_size_allowed && access_size == 0 &&
905 		    regs[regno].type == CONST_IMM &&
906 		    regs[regno].imm  == 0)
907 			return 0;
908 
909 		verbose("R%d type=%s expected=%s\n", regno,
910 			reg_type_str[regs[regno].type],
911 			reg_type_str[PTR_TO_STACK]);
912 		return -EACCES;
913 	}
914 
915 	off = regs[regno].imm;
916 	if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
917 	    access_size <= 0) {
918 		verbose("invalid stack type R%d off=%d access_size=%d\n",
919 			regno, off, access_size);
920 		return -EACCES;
921 	}
922 
923 	if (meta && meta->raw_mode) {
924 		meta->access_size = access_size;
925 		meta->regno = regno;
926 		return 0;
927 	}
928 
929 	for (i = 0; i < access_size; i++) {
930 		if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
931 			verbose("invalid indirect read from stack off %d+%d size %d\n",
932 				off, i, access_size);
933 			return -EACCES;
934 		}
935 	}
936 	return 0;
937 }
938 
939 static int check_func_arg(struct verifier_env *env, u32 regno,
940 			  enum bpf_arg_type arg_type,
941 			  struct bpf_call_arg_meta *meta)
942 {
943 	struct reg_state *reg = env->cur_state.regs + regno;
944 	enum bpf_reg_type expected_type;
945 	int err = 0;
946 
947 	if (arg_type == ARG_DONTCARE)
948 		return 0;
949 
950 	if (reg->type == NOT_INIT) {
951 		verbose("R%d !read_ok\n", regno);
952 		return -EACCES;
953 	}
954 
955 	if (arg_type == ARG_ANYTHING) {
956 		if (is_pointer_value(env, regno)) {
957 			verbose("R%d leaks addr into helper function\n", regno);
958 			return -EACCES;
959 		}
960 		return 0;
961 	}
962 
963 	if (arg_type == ARG_PTR_TO_MAP_KEY ||
964 	    arg_type == ARG_PTR_TO_MAP_VALUE) {
965 		expected_type = PTR_TO_STACK;
966 	} else if (arg_type == ARG_CONST_STACK_SIZE ||
967 		   arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
968 		expected_type = CONST_IMM;
969 	} else if (arg_type == ARG_CONST_MAP_PTR) {
970 		expected_type = CONST_PTR_TO_MAP;
971 	} else if (arg_type == ARG_PTR_TO_CTX) {
972 		expected_type = PTR_TO_CTX;
973 	} else if (arg_type == ARG_PTR_TO_STACK ||
974 		   arg_type == ARG_PTR_TO_RAW_STACK) {
975 		expected_type = PTR_TO_STACK;
976 		/* One exception here. In case function allows for NULL to be
977 		 * passed in as argument, it's a CONST_IMM type. Final test
978 		 * happens during stack boundary checking.
979 		 */
980 		if (reg->type == CONST_IMM && reg->imm == 0)
981 			expected_type = CONST_IMM;
982 		meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
983 	} else {
984 		verbose("unsupported arg_type %d\n", arg_type);
985 		return -EFAULT;
986 	}
987 
988 	if (reg->type != expected_type) {
989 		verbose("R%d type=%s expected=%s\n", regno,
990 			reg_type_str[reg->type], reg_type_str[expected_type]);
991 		return -EACCES;
992 	}
993 
994 	if (arg_type == ARG_CONST_MAP_PTR) {
995 		/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
996 		meta->map_ptr = reg->map_ptr;
997 	} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
998 		/* bpf_map_xxx(..., map_ptr, ..., key) call:
999 		 * check that [key, key + map->key_size) are within
1000 		 * stack limits and initialized
1001 		 */
1002 		if (!meta->map_ptr) {
1003 			/* in function declaration map_ptr must come before
1004 			 * map_key, so that it's verified and known before
1005 			 * we have to check map_key here. Otherwise it means
1006 			 * that kernel subsystem misconfigured verifier
1007 			 */
1008 			verbose("invalid map_ptr to access map->key\n");
1009 			return -EACCES;
1010 		}
1011 		err = check_stack_boundary(env, regno, meta->map_ptr->key_size,
1012 					   false, NULL);
1013 	} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1014 		/* bpf_map_xxx(..., map_ptr, ..., value) call:
1015 		 * check [value, value + map->value_size) validity
1016 		 */
1017 		if (!meta->map_ptr) {
1018 			/* kernel subsystem misconfigured verifier */
1019 			verbose("invalid map_ptr to access map->value\n");
1020 			return -EACCES;
1021 		}
1022 		err = check_stack_boundary(env, regno,
1023 					   meta->map_ptr->value_size,
1024 					   false, NULL);
1025 	} else if (arg_type == ARG_CONST_STACK_SIZE ||
1026 		   arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
1027 		bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
1028 
1029 		/* bpf_xxx(..., buf, len) call will access 'len' bytes
1030 		 * from stack pointer 'buf'. Check it
1031 		 * note: regno == len, regno - 1 == buf
1032 		 */
1033 		if (regno == 0) {
1034 			/* kernel subsystem misconfigured verifier */
1035 			verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
1036 			return -EACCES;
1037 		}
1038 		err = check_stack_boundary(env, regno - 1, reg->imm,
1039 					   zero_size_allowed, meta);
1040 	}
1041 
1042 	return err;
1043 }
1044 
1045 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1046 {
1047 	if (!map)
1048 		return 0;
1049 
1050 	/* We need a two way check, first is from map perspective ... */
1051 	switch (map->map_type) {
1052 	case BPF_MAP_TYPE_PROG_ARRAY:
1053 		if (func_id != BPF_FUNC_tail_call)
1054 			goto error;
1055 		break;
1056 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1057 		if (func_id != BPF_FUNC_perf_event_read &&
1058 		    func_id != BPF_FUNC_perf_event_output)
1059 			goto error;
1060 		break;
1061 	case BPF_MAP_TYPE_STACK_TRACE:
1062 		if (func_id != BPF_FUNC_get_stackid)
1063 			goto error;
1064 		break;
1065 	default:
1066 		break;
1067 	}
1068 
1069 	/* ... and second from the function itself. */
1070 	switch (func_id) {
1071 	case BPF_FUNC_tail_call:
1072 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1073 			goto error;
1074 		break;
1075 	case BPF_FUNC_perf_event_read:
1076 	case BPF_FUNC_perf_event_output:
1077 		if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1078 			goto error;
1079 		break;
1080 	case BPF_FUNC_get_stackid:
1081 		if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1082 			goto error;
1083 		break;
1084 	default:
1085 		break;
1086 	}
1087 
1088 	return 0;
1089 error:
1090 	verbose("cannot pass map_type %d into func %d\n",
1091 		map->map_type, func_id);
1092 	return -EINVAL;
1093 }
1094 
1095 static int check_raw_mode(const struct bpf_func_proto *fn)
1096 {
1097 	int count = 0;
1098 
1099 	if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1100 		count++;
1101 	if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1102 		count++;
1103 	if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1104 		count++;
1105 	if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1106 		count++;
1107 	if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1108 		count++;
1109 
1110 	return count > 1 ? -EINVAL : 0;
1111 }
1112 
1113 static void clear_all_pkt_pointers(struct verifier_env *env)
1114 {
1115 	struct verifier_state *state = &env->cur_state;
1116 	struct reg_state *regs = state->regs, *reg;
1117 	int i;
1118 
1119 	for (i = 0; i < MAX_BPF_REG; i++)
1120 		if (regs[i].type == PTR_TO_PACKET ||
1121 		    regs[i].type == PTR_TO_PACKET_END)
1122 			mark_reg_unknown_value(regs, i);
1123 
1124 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1125 		if (state->stack_slot_type[i] != STACK_SPILL)
1126 			continue;
1127 		reg = &state->spilled_regs[i / BPF_REG_SIZE];
1128 		if (reg->type != PTR_TO_PACKET &&
1129 		    reg->type != PTR_TO_PACKET_END)
1130 			continue;
1131 		reg->type = UNKNOWN_VALUE;
1132 		reg->imm = 0;
1133 	}
1134 }
1135 
1136 static int check_call(struct verifier_env *env, int func_id)
1137 {
1138 	struct verifier_state *state = &env->cur_state;
1139 	const struct bpf_func_proto *fn = NULL;
1140 	struct reg_state *regs = state->regs;
1141 	struct reg_state *reg;
1142 	struct bpf_call_arg_meta meta;
1143 	bool changes_data;
1144 	int i, err;
1145 
1146 	/* find function prototype */
1147 	if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1148 		verbose("invalid func %d\n", func_id);
1149 		return -EINVAL;
1150 	}
1151 
1152 	if (env->prog->aux->ops->get_func_proto)
1153 		fn = env->prog->aux->ops->get_func_proto(func_id);
1154 
1155 	if (!fn) {
1156 		verbose("unknown func %d\n", func_id);
1157 		return -EINVAL;
1158 	}
1159 
1160 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
1161 	if (!env->prog->gpl_compatible && fn->gpl_only) {
1162 		verbose("cannot call GPL only function from proprietary program\n");
1163 		return -EINVAL;
1164 	}
1165 
1166 	changes_data = bpf_helper_changes_skb_data(fn->func);
1167 
1168 	memset(&meta, 0, sizeof(meta));
1169 
1170 	/* We only support one arg being in raw mode at the moment, which
1171 	 * is sufficient for the helper functions we have right now.
1172 	 */
1173 	err = check_raw_mode(fn);
1174 	if (err) {
1175 		verbose("kernel subsystem misconfigured func %d\n", func_id);
1176 		return err;
1177 	}
1178 
1179 	/* check args */
1180 	err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1181 	if (err)
1182 		return err;
1183 	err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1184 	if (err)
1185 		return err;
1186 	err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1187 	if (err)
1188 		return err;
1189 	err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1190 	if (err)
1191 		return err;
1192 	err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1193 	if (err)
1194 		return err;
1195 
1196 	/* Mark slots with STACK_MISC in case of raw mode, stack offset
1197 	 * is inferred from register state.
1198 	 */
1199 	for (i = 0; i < meta.access_size; i++) {
1200 		err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1201 		if (err)
1202 			return err;
1203 	}
1204 
1205 	/* reset caller saved regs */
1206 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
1207 		reg = regs + caller_saved[i];
1208 		reg->type = NOT_INIT;
1209 		reg->imm = 0;
1210 	}
1211 
1212 	/* update return register */
1213 	if (fn->ret_type == RET_INTEGER) {
1214 		regs[BPF_REG_0].type = UNKNOWN_VALUE;
1215 	} else if (fn->ret_type == RET_VOID) {
1216 		regs[BPF_REG_0].type = NOT_INIT;
1217 	} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1218 		regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1219 		/* remember map_ptr, so that check_map_access()
1220 		 * can check 'value_size' boundary of memory access
1221 		 * to map element returned from bpf_map_lookup_elem()
1222 		 */
1223 		if (meta.map_ptr == NULL) {
1224 			verbose("kernel subsystem misconfigured verifier\n");
1225 			return -EINVAL;
1226 		}
1227 		regs[BPF_REG_0].map_ptr = meta.map_ptr;
1228 	} else {
1229 		verbose("unknown return type %d of func %d\n",
1230 			fn->ret_type, func_id);
1231 		return -EINVAL;
1232 	}
1233 
1234 	err = check_map_func_compatibility(meta.map_ptr, func_id);
1235 	if (err)
1236 		return err;
1237 
1238 	if (changes_data)
1239 		clear_all_pkt_pointers(env);
1240 	return 0;
1241 }
1242 
1243 static int check_packet_ptr_add(struct verifier_env *env, struct bpf_insn *insn)
1244 {
1245 	struct reg_state *regs = env->cur_state.regs;
1246 	struct reg_state *dst_reg = &regs[insn->dst_reg];
1247 	struct reg_state *src_reg = &regs[insn->src_reg];
1248 	struct reg_state tmp_reg;
1249 	s32 imm;
1250 
1251 	if (BPF_SRC(insn->code) == BPF_K) {
1252 		/* pkt_ptr += imm */
1253 		imm = insn->imm;
1254 
1255 add_imm:
1256 		if (imm <= 0) {
1257 			verbose("addition of negative constant to packet pointer is not allowed\n");
1258 			return -EACCES;
1259 		}
1260 		if (imm >= MAX_PACKET_OFF ||
1261 		    imm + dst_reg->off >= MAX_PACKET_OFF) {
1262 			verbose("constant %d is too large to add to packet pointer\n",
1263 				imm);
1264 			return -EACCES;
1265 		}
1266 		/* a constant was added to pkt_ptr.
1267 		 * Remember it while keeping the same 'id'
1268 		 */
1269 		dst_reg->off += imm;
1270 	} else {
1271 		if (src_reg->type == PTR_TO_PACKET) {
1272 			/* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1273 			tmp_reg = *dst_reg;  /* save r7 state */
1274 			*dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1275 			src_reg = &tmp_reg;  /* pretend it's src_reg state */
1276 			/* if the checks below reject it, the copy won't matter,
1277 			 * since we're rejecting the whole program. If all ok,
1278 			 * then imm22 state will be added to r7
1279 			 * and r7 will be pkt(id=0,off=22,r=62) while
1280 			 * r6 will stay as pkt(id=0,off=0,r=62)
1281 			 */
1282 		}
1283 
1284 		if (src_reg->type == CONST_IMM) {
1285 			/* pkt_ptr += reg where reg is known constant */
1286 			imm = src_reg->imm;
1287 			goto add_imm;
1288 		}
1289 		/* disallow pkt_ptr += reg
1290 		 * if reg is not uknown_value with guaranteed zero upper bits
1291 		 * otherwise pkt_ptr may overflow and addition will become
1292 		 * subtraction which is not allowed
1293 		 */
1294 		if (src_reg->type != UNKNOWN_VALUE) {
1295 			verbose("cannot add '%s' to ptr_to_packet\n",
1296 				reg_type_str[src_reg->type]);
1297 			return -EACCES;
1298 		}
1299 		if (src_reg->imm < 48) {
1300 			verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1301 				src_reg->imm);
1302 			return -EACCES;
1303 		}
1304 		/* dst_reg stays as pkt_ptr type and since some positive
1305 		 * integer value was added to the pointer, increment its 'id'
1306 		 */
1307 		dst_reg->id++;
1308 
1309 		/* something was added to pkt_ptr, set range and off to zero */
1310 		dst_reg->off = 0;
1311 		dst_reg->range = 0;
1312 	}
1313 	return 0;
1314 }
1315 
1316 static int evaluate_reg_alu(struct verifier_env *env, struct bpf_insn *insn)
1317 {
1318 	struct reg_state *regs = env->cur_state.regs;
1319 	struct reg_state *dst_reg = &regs[insn->dst_reg];
1320 	u8 opcode = BPF_OP(insn->code);
1321 	s64 imm_log2;
1322 
1323 	/* for type == UNKNOWN_VALUE:
1324 	 * imm > 0 -> number of zero upper bits
1325 	 * imm == 0 -> don't track which is the same as all bits can be non-zero
1326 	 */
1327 
1328 	if (BPF_SRC(insn->code) == BPF_X) {
1329 		struct reg_state *src_reg = &regs[insn->src_reg];
1330 
1331 		if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1332 		    dst_reg->imm && opcode == BPF_ADD) {
1333 			/* dreg += sreg
1334 			 * where both have zero upper bits. Adding them
1335 			 * can only result making one more bit non-zero
1336 			 * in the larger value.
1337 			 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1338 			 *     0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1339 			 */
1340 			dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1341 			dst_reg->imm--;
1342 			return 0;
1343 		}
1344 		if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1345 		    dst_reg->imm && opcode == BPF_ADD) {
1346 			/* dreg += sreg
1347 			 * where dreg has zero upper bits and sreg is const.
1348 			 * Adding them can only result making one more bit
1349 			 * non-zero in the larger value.
1350 			 */
1351 			imm_log2 = __ilog2_u64((long long)src_reg->imm);
1352 			dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1353 			dst_reg->imm--;
1354 			return 0;
1355 		}
1356 		/* all other cases non supported yet, just mark dst_reg */
1357 		dst_reg->imm = 0;
1358 		return 0;
1359 	}
1360 
1361 	/* sign extend 32-bit imm into 64-bit to make sure that
1362 	 * negative values occupy bit 63. Note ilog2() would have
1363 	 * been incorrect, since sizeof(insn->imm) == 4
1364 	 */
1365 	imm_log2 = __ilog2_u64((long long)insn->imm);
1366 
1367 	if (dst_reg->imm && opcode == BPF_LSH) {
1368 		/* reg <<= imm
1369 		 * if reg was a result of 2 byte load, then its imm == 48
1370 		 * which means that upper 48 bits are zero and shifting this reg
1371 		 * left by 4 would mean that upper 44 bits are still zero
1372 		 */
1373 		dst_reg->imm -= insn->imm;
1374 	} else if (dst_reg->imm && opcode == BPF_MUL) {
1375 		/* reg *= imm
1376 		 * if multiplying by 14 subtract 4
1377 		 * This is conservative calculation of upper zero bits.
1378 		 * It's not trying to special case insn->imm == 1 or 0 cases
1379 		 */
1380 		dst_reg->imm -= imm_log2 + 1;
1381 	} else if (opcode == BPF_AND) {
1382 		/* reg &= imm */
1383 		dst_reg->imm = 63 - imm_log2;
1384 	} else if (dst_reg->imm && opcode == BPF_ADD) {
1385 		/* reg += imm */
1386 		dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1387 		dst_reg->imm--;
1388 	} else if (opcode == BPF_RSH) {
1389 		/* reg >>= imm
1390 		 * which means that after right shift, upper bits will be zero
1391 		 * note that verifier already checked that
1392 		 * 0 <= imm < 64 for shift insn
1393 		 */
1394 		dst_reg->imm += insn->imm;
1395 		if (unlikely(dst_reg->imm > 64))
1396 			/* some dumb code did:
1397 			 * r2 = *(u32 *)mem;
1398 			 * r2 >>= 32;
1399 			 * and all bits are zero now */
1400 			dst_reg->imm = 64;
1401 	} else {
1402 		/* all other alu ops, means that we don't know what will
1403 		 * happen to the value, mark it with unknown number of zero bits
1404 		 */
1405 		dst_reg->imm = 0;
1406 	}
1407 
1408 	if (dst_reg->imm < 0) {
1409 		/* all 64 bits of the register can contain non-zero bits
1410 		 * and such value cannot be added to ptr_to_packet, since it
1411 		 * may overflow, mark it as unknown to avoid further eval
1412 		 */
1413 		dst_reg->imm = 0;
1414 	}
1415 	return 0;
1416 }
1417 
1418 static int evaluate_reg_imm_alu(struct verifier_env *env, struct bpf_insn *insn)
1419 {
1420 	struct reg_state *regs = env->cur_state.regs;
1421 	struct reg_state *dst_reg = &regs[insn->dst_reg];
1422 	struct reg_state *src_reg = &regs[insn->src_reg];
1423 	u8 opcode = BPF_OP(insn->code);
1424 
1425 	/* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1426 	 * Don't care about overflow or negative values, just add them
1427 	 */
1428 	if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1429 		dst_reg->imm += insn->imm;
1430 	else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1431 		 src_reg->type == CONST_IMM)
1432 		dst_reg->imm += src_reg->imm;
1433 	else
1434 		mark_reg_unknown_value(regs, insn->dst_reg);
1435 	return 0;
1436 }
1437 
1438 /* check validity of 32-bit and 64-bit arithmetic operations */
1439 static int check_alu_op(struct verifier_env *env, struct bpf_insn *insn)
1440 {
1441 	struct reg_state *regs = env->cur_state.regs, *dst_reg;
1442 	u8 opcode = BPF_OP(insn->code);
1443 	int err;
1444 
1445 	if (opcode == BPF_END || opcode == BPF_NEG) {
1446 		if (opcode == BPF_NEG) {
1447 			if (BPF_SRC(insn->code) != 0 ||
1448 			    insn->src_reg != BPF_REG_0 ||
1449 			    insn->off != 0 || insn->imm != 0) {
1450 				verbose("BPF_NEG uses reserved fields\n");
1451 				return -EINVAL;
1452 			}
1453 		} else {
1454 			if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1455 			    (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1456 				verbose("BPF_END uses reserved fields\n");
1457 				return -EINVAL;
1458 			}
1459 		}
1460 
1461 		/* check src operand */
1462 		err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1463 		if (err)
1464 			return err;
1465 
1466 		if (is_pointer_value(env, insn->dst_reg)) {
1467 			verbose("R%d pointer arithmetic prohibited\n",
1468 				insn->dst_reg);
1469 			return -EACCES;
1470 		}
1471 
1472 		/* check dest operand */
1473 		err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1474 		if (err)
1475 			return err;
1476 
1477 	} else if (opcode == BPF_MOV) {
1478 
1479 		if (BPF_SRC(insn->code) == BPF_X) {
1480 			if (insn->imm != 0 || insn->off != 0) {
1481 				verbose("BPF_MOV uses reserved fields\n");
1482 				return -EINVAL;
1483 			}
1484 
1485 			/* check src operand */
1486 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1487 			if (err)
1488 				return err;
1489 		} else {
1490 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1491 				verbose("BPF_MOV uses reserved fields\n");
1492 				return -EINVAL;
1493 			}
1494 		}
1495 
1496 		/* check dest operand */
1497 		err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1498 		if (err)
1499 			return err;
1500 
1501 		if (BPF_SRC(insn->code) == BPF_X) {
1502 			if (BPF_CLASS(insn->code) == BPF_ALU64) {
1503 				/* case: R1 = R2
1504 				 * copy register state to dest reg
1505 				 */
1506 				regs[insn->dst_reg] = regs[insn->src_reg];
1507 			} else {
1508 				if (is_pointer_value(env, insn->src_reg)) {
1509 					verbose("R%d partial copy of pointer\n",
1510 						insn->src_reg);
1511 					return -EACCES;
1512 				}
1513 				regs[insn->dst_reg].type = UNKNOWN_VALUE;
1514 				regs[insn->dst_reg].map_ptr = NULL;
1515 			}
1516 		} else {
1517 			/* case: R = imm
1518 			 * remember the value we stored into this reg
1519 			 */
1520 			regs[insn->dst_reg].type = CONST_IMM;
1521 			regs[insn->dst_reg].imm = insn->imm;
1522 		}
1523 
1524 	} else if (opcode > BPF_END) {
1525 		verbose("invalid BPF_ALU opcode %x\n", opcode);
1526 		return -EINVAL;
1527 
1528 	} else {	/* all other ALU ops: and, sub, xor, add, ... */
1529 
1530 		if (BPF_SRC(insn->code) == BPF_X) {
1531 			if (insn->imm != 0 || insn->off != 0) {
1532 				verbose("BPF_ALU uses reserved fields\n");
1533 				return -EINVAL;
1534 			}
1535 			/* check src1 operand */
1536 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1537 			if (err)
1538 				return err;
1539 		} else {
1540 			if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1541 				verbose("BPF_ALU uses reserved fields\n");
1542 				return -EINVAL;
1543 			}
1544 		}
1545 
1546 		/* check src2 operand */
1547 		err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1548 		if (err)
1549 			return err;
1550 
1551 		if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1552 		    BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1553 			verbose("div by zero\n");
1554 			return -EINVAL;
1555 		}
1556 
1557 		if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1558 		     opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1559 			int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1560 
1561 			if (insn->imm < 0 || insn->imm >= size) {
1562 				verbose("invalid shift %d\n", insn->imm);
1563 				return -EINVAL;
1564 			}
1565 		}
1566 
1567 		/* check dest operand */
1568 		err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1569 		if (err)
1570 			return err;
1571 
1572 		dst_reg = &regs[insn->dst_reg];
1573 
1574 		/* pattern match 'bpf_add Rx, imm' instruction */
1575 		if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1576 		    dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1577 			dst_reg->type = PTR_TO_STACK;
1578 			dst_reg->imm = insn->imm;
1579 			return 0;
1580 		} else if (opcode == BPF_ADD &&
1581 			   BPF_CLASS(insn->code) == BPF_ALU64 &&
1582 			   (dst_reg->type == PTR_TO_PACKET ||
1583 			    (BPF_SRC(insn->code) == BPF_X &&
1584 			     regs[insn->src_reg].type == PTR_TO_PACKET))) {
1585 			/* ptr_to_packet += K|X */
1586 			return check_packet_ptr_add(env, insn);
1587 		} else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1588 			   dst_reg->type == UNKNOWN_VALUE &&
1589 			   env->allow_ptr_leaks) {
1590 			/* unknown += K|X */
1591 			return evaluate_reg_alu(env, insn);
1592 		} else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1593 			   dst_reg->type == CONST_IMM &&
1594 			   env->allow_ptr_leaks) {
1595 			/* reg_imm += K|X */
1596 			return evaluate_reg_imm_alu(env, insn);
1597 		} else if (is_pointer_value(env, insn->dst_reg)) {
1598 			verbose("R%d pointer arithmetic prohibited\n",
1599 				insn->dst_reg);
1600 			return -EACCES;
1601 		} else if (BPF_SRC(insn->code) == BPF_X &&
1602 			   is_pointer_value(env, insn->src_reg)) {
1603 			verbose("R%d pointer arithmetic prohibited\n",
1604 				insn->src_reg);
1605 			return -EACCES;
1606 		}
1607 
1608 		/* mark dest operand */
1609 		mark_reg_unknown_value(regs, insn->dst_reg);
1610 	}
1611 
1612 	return 0;
1613 }
1614 
1615 static void find_good_pkt_pointers(struct verifier_env *env,
1616 				   struct reg_state *dst_reg)
1617 {
1618 	struct verifier_state *state = &env->cur_state;
1619 	struct reg_state *regs = state->regs, *reg;
1620 	int i;
1621 	/* r2 = r3;
1622 	 * r2 += 8
1623 	 * if (r2 > pkt_end) goto somewhere
1624 	 * r2 == dst_reg, pkt_end == src_reg,
1625 	 * r2=pkt(id=n,off=8,r=0)
1626 	 * r3=pkt(id=n,off=0,r=0)
1627 	 * find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1628 	 * so that range of bytes [r3, r3 + 8) is safe to access
1629 	 */
1630 	for (i = 0; i < MAX_BPF_REG; i++)
1631 		if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
1632 			regs[i].range = dst_reg->off;
1633 
1634 	for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1635 		if (state->stack_slot_type[i] != STACK_SPILL)
1636 			continue;
1637 		reg = &state->spilled_regs[i / BPF_REG_SIZE];
1638 		if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
1639 			reg->range = dst_reg->off;
1640 	}
1641 }
1642 
1643 static int check_cond_jmp_op(struct verifier_env *env,
1644 			     struct bpf_insn *insn, int *insn_idx)
1645 {
1646 	struct reg_state *regs = env->cur_state.regs, *dst_reg;
1647 	struct verifier_state *other_branch;
1648 	u8 opcode = BPF_OP(insn->code);
1649 	int err;
1650 
1651 	if (opcode > BPF_EXIT) {
1652 		verbose("invalid BPF_JMP opcode %x\n", opcode);
1653 		return -EINVAL;
1654 	}
1655 
1656 	if (BPF_SRC(insn->code) == BPF_X) {
1657 		if (insn->imm != 0) {
1658 			verbose("BPF_JMP uses reserved fields\n");
1659 			return -EINVAL;
1660 		}
1661 
1662 		/* check src1 operand */
1663 		err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1664 		if (err)
1665 			return err;
1666 
1667 		if (is_pointer_value(env, insn->src_reg)) {
1668 			verbose("R%d pointer comparison prohibited\n",
1669 				insn->src_reg);
1670 			return -EACCES;
1671 		}
1672 	} else {
1673 		if (insn->src_reg != BPF_REG_0) {
1674 			verbose("BPF_JMP uses reserved fields\n");
1675 			return -EINVAL;
1676 		}
1677 	}
1678 
1679 	/* check src2 operand */
1680 	err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1681 	if (err)
1682 		return err;
1683 
1684 	dst_reg = &regs[insn->dst_reg];
1685 
1686 	/* detect if R == 0 where R was initialized to zero earlier */
1687 	if (BPF_SRC(insn->code) == BPF_K &&
1688 	    (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1689 	    dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
1690 		if (opcode == BPF_JEQ) {
1691 			/* if (imm == imm) goto pc+off;
1692 			 * only follow the goto, ignore fall-through
1693 			 */
1694 			*insn_idx += insn->off;
1695 			return 0;
1696 		} else {
1697 			/* if (imm != imm) goto pc+off;
1698 			 * only follow fall-through branch, since
1699 			 * that's where the program will go
1700 			 */
1701 			return 0;
1702 		}
1703 	}
1704 
1705 	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
1706 	if (!other_branch)
1707 		return -EFAULT;
1708 
1709 	/* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
1710 	if (BPF_SRC(insn->code) == BPF_K &&
1711 	    insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1712 	    dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1713 		if (opcode == BPF_JEQ) {
1714 			/* next fallthrough insn can access memory via
1715 			 * this register
1716 			 */
1717 			regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1718 			/* branch targer cannot access it, since reg == 0 */
1719 			mark_reg_unknown_value(other_branch->regs,
1720 					       insn->dst_reg);
1721 		} else {
1722 			other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1723 			mark_reg_unknown_value(regs, insn->dst_reg);
1724 		}
1725 	} else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
1726 		   dst_reg->type == PTR_TO_PACKET &&
1727 		   regs[insn->src_reg].type == PTR_TO_PACKET_END) {
1728 		find_good_pkt_pointers(env, dst_reg);
1729 	} else if (is_pointer_value(env, insn->dst_reg)) {
1730 		verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
1731 		return -EACCES;
1732 	}
1733 	if (log_level)
1734 		print_verifier_state(&env->cur_state);
1735 	return 0;
1736 }
1737 
1738 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
1739 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
1740 {
1741 	u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
1742 
1743 	return (struct bpf_map *) (unsigned long) imm64;
1744 }
1745 
1746 /* verify BPF_LD_IMM64 instruction */
1747 static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
1748 {
1749 	struct reg_state *regs = env->cur_state.regs;
1750 	int err;
1751 
1752 	if (BPF_SIZE(insn->code) != BPF_DW) {
1753 		verbose("invalid BPF_LD_IMM insn\n");
1754 		return -EINVAL;
1755 	}
1756 	if (insn->off != 0) {
1757 		verbose("BPF_LD_IMM64 uses reserved fields\n");
1758 		return -EINVAL;
1759 	}
1760 
1761 	err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1762 	if (err)
1763 		return err;
1764 
1765 	if (insn->src_reg == 0)
1766 		/* generic move 64-bit immediate into a register */
1767 		return 0;
1768 
1769 	/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
1770 	BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
1771 
1772 	regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
1773 	regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
1774 	return 0;
1775 }
1776 
1777 static bool may_access_skb(enum bpf_prog_type type)
1778 {
1779 	switch (type) {
1780 	case BPF_PROG_TYPE_SOCKET_FILTER:
1781 	case BPF_PROG_TYPE_SCHED_CLS:
1782 	case BPF_PROG_TYPE_SCHED_ACT:
1783 		return true;
1784 	default:
1785 		return false;
1786 	}
1787 }
1788 
1789 /* verify safety of LD_ABS|LD_IND instructions:
1790  * - they can only appear in the programs where ctx == skb
1791  * - since they are wrappers of function calls, they scratch R1-R5 registers,
1792  *   preserve R6-R9, and store return value into R0
1793  *
1794  * Implicit input:
1795  *   ctx == skb == R6 == CTX
1796  *
1797  * Explicit input:
1798  *   SRC == any register
1799  *   IMM == 32-bit immediate
1800  *
1801  * Output:
1802  *   R0 - 8/16/32-bit skb data converted to cpu endianness
1803  */
1804 static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
1805 {
1806 	struct reg_state *regs = env->cur_state.regs;
1807 	u8 mode = BPF_MODE(insn->code);
1808 	struct reg_state *reg;
1809 	int i, err;
1810 
1811 	if (!may_access_skb(env->prog->type)) {
1812 		verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
1813 		return -EINVAL;
1814 	}
1815 
1816 	if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
1817 	    BPF_SIZE(insn->code) == BPF_DW ||
1818 	    (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1819 		verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
1820 		return -EINVAL;
1821 	}
1822 
1823 	/* check whether implicit source operand (register R6) is readable */
1824 	err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
1825 	if (err)
1826 		return err;
1827 
1828 	if (regs[BPF_REG_6].type != PTR_TO_CTX) {
1829 		verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
1830 		return -EINVAL;
1831 	}
1832 
1833 	if (mode == BPF_IND) {
1834 		/* check explicit source operand */
1835 		err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1836 		if (err)
1837 			return err;
1838 	}
1839 
1840 	/* reset caller saved regs to unreadable */
1841 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
1842 		reg = regs + caller_saved[i];
1843 		reg->type = NOT_INIT;
1844 		reg->imm = 0;
1845 	}
1846 
1847 	/* mark destination R0 register as readable, since it contains
1848 	 * the value fetched from the packet
1849 	 */
1850 	regs[BPF_REG_0].type = UNKNOWN_VALUE;
1851 	return 0;
1852 }
1853 
1854 /* non-recursive DFS pseudo code
1855  * 1  procedure DFS-iterative(G,v):
1856  * 2      label v as discovered
1857  * 3      let S be a stack
1858  * 4      S.push(v)
1859  * 5      while S is not empty
1860  * 6            t <- S.pop()
1861  * 7            if t is what we're looking for:
1862  * 8                return t
1863  * 9            for all edges e in G.adjacentEdges(t) do
1864  * 10               if edge e is already labelled
1865  * 11                   continue with the next edge
1866  * 12               w <- G.adjacentVertex(t,e)
1867  * 13               if vertex w is not discovered and not explored
1868  * 14                   label e as tree-edge
1869  * 15                   label w as discovered
1870  * 16                   S.push(w)
1871  * 17                   continue at 5
1872  * 18               else if vertex w is discovered
1873  * 19                   label e as back-edge
1874  * 20               else
1875  * 21                   // vertex w is explored
1876  * 22                   label e as forward- or cross-edge
1877  * 23           label t as explored
1878  * 24           S.pop()
1879  *
1880  * convention:
1881  * 0x10 - discovered
1882  * 0x11 - discovered and fall-through edge labelled
1883  * 0x12 - discovered and fall-through and branch edges labelled
1884  * 0x20 - explored
1885  */
1886 
1887 enum {
1888 	DISCOVERED = 0x10,
1889 	EXPLORED = 0x20,
1890 	FALLTHROUGH = 1,
1891 	BRANCH = 2,
1892 };
1893 
1894 #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
1895 
1896 static int *insn_stack;	/* stack of insns to process */
1897 static int cur_stack;	/* current stack index */
1898 static int *insn_state;
1899 
1900 /* t, w, e - match pseudo-code above:
1901  * t - index of current instruction
1902  * w - next instruction
1903  * e - edge
1904  */
1905 static int push_insn(int t, int w, int e, struct verifier_env *env)
1906 {
1907 	if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
1908 		return 0;
1909 
1910 	if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
1911 		return 0;
1912 
1913 	if (w < 0 || w >= env->prog->len) {
1914 		verbose("jump out of range from insn %d to %d\n", t, w);
1915 		return -EINVAL;
1916 	}
1917 
1918 	if (e == BRANCH)
1919 		/* mark branch target for state pruning */
1920 		env->explored_states[w] = STATE_LIST_MARK;
1921 
1922 	if (insn_state[w] == 0) {
1923 		/* tree-edge */
1924 		insn_state[t] = DISCOVERED | e;
1925 		insn_state[w] = DISCOVERED;
1926 		if (cur_stack >= env->prog->len)
1927 			return -E2BIG;
1928 		insn_stack[cur_stack++] = w;
1929 		return 1;
1930 	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
1931 		verbose("back-edge from insn %d to %d\n", t, w);
1932 		return -EINVAL;
1933 	} else if (insn_state[w] == EXPLORED) {
1934 		/* forward- or cross-edge */
1935 		insn_state[t] = DISCOVERED | e;
1936 	} else {
1937 		verbose("insn state internal bug\n");
1938 		return -EFAULT;
1939 	}
1940 	return 0;
1941 }
1942 
1943 /* non-recursive depth-first-search to detect loops in BPF program
1944  * loop == back-edge in directed graph
1945  */
1946 static int check_cfg(struct verifier_env *env)
1947 {
1948 	struct bpf_insn *insns = env->prog->insnsi;
1949 	int insn_cnt = env->prog->len;
1950 	int ret = 0;
1951 	int i, t;
1952 
1953 	insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1954 	if (!insn_state)
1955 		return -ENOMEM;
1956 
1957 	insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1958 	if (!insn_stack) {
1959 		kfree(insn_state);
1960 		return -ENOMEM;
1961 	}
1962 
1963 	insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
1964 	insn_stack[0] = 0; /* 0 is the first instruction */
1965 	cur_stack = 1;
1966 
1967 peek_stack:
1968 	if (cur_stack == 0)
1969 		goto check_state;
1970 	t = insn_stack[cur_stack - 1];
1971 
1972 	if (BPF_CLASS(insns[t].code) == BPF_JMP) {
1973 		u8 opcode = BPF_OP(insns[t].code);
1974 
1975 		if (opcode == BPF_EXIT) {
1976 			goto mark_explored;
1977 		} else if (opcode == BPF_CALL) {
1978 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
1979 			if (ret == 1)
1980 				goto peek_stack;
1981 			else if (ret < 0)
1982 				goto err_free;
1983 			if (t + 1 < insn_cnt)
1984 				env->explored_states[t + 1] = STATE_LIST_MARK;
1985 		} else if (opcode == BPF_JA) {
1986 			if (BPF_SRC(insns[t].code) != BPF_K) {
1987 				ret = -EINVAL;
1988 				goto err_free;
1989 			}
1990 			/* unconditional jump with single edge */
1991 			ret = push_insn(t, t + insns[t].off + 1,
1992 					FALLTHROUGH, env);
1993 			if (ret == 1)
1994 				goto peek_stack;
1995 			else if (ret < 0)
1996 				goto err_free;
1997 			/* tell verifier to check for equivalent states
1998 			 * after every call and jump
1999 			 */
2000 			if (t + 1 < insn_cnt)
2001 				env->explored_states[t + 1] = STATE_LIST_MARK;
2002 		} else {
2003 			/* conditional jump with two edges */
2004 			ret = push_insn(t, t + 1, FALLTHROUGH, env);
2005 			if (ret == 1)
2006 				goto peek_stack;
2007 			else if (ret < 0)
2008 				goto err_free;
2009 
2010 			ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2011 			if (ret == 1)
2012 				goto peek_stack;
2013 			else if (ret < 0)
2014 				goto err_free;
2015 		}
2016 	} else {
2017 		/* all other non-branch instructions with single
2018 		 * fall-through edge
2019 		 */
2020 		ret = push_insn(t, t + 1, FALLTHROUGH, env);
2021 		if (ret == 1)
2022 			goto peek_stack;
2023 		else if (ret < 0)
2024 			goto err_free;
2025 	}
2026 
2027 mark_explored:
2028 	insn_state[t] = EXPLORED;
2029 	if (cur_stack-- <= 0) {
2030 		verbose("pop stack internal bug\n");
2031 		ret = -EFAULT;
2032 		goto err_free;
2033 	}
2034 	goto peek_stack;
2035 
2036 check_state:
2037 	for (i = 0; i < insn_cnt; i++) {
2038 		if (insn_state[i] != EXPLORED) {
2039 			verbose("unreachable insn %d\n", i);
2040 			ret = -EINVAL;
2041 			goto err_free;
2042 		}
2043 	}
2044 	ret = 0; /* cfg looks good */
2045 
2046 err_free:
2047 	kfree(insn_state);
2048 	kfree(insn_stack);
2049 	return ret;
2050 }
2051 
2052 /* the following conditions reduce the number of explored insns
2053  * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2054  */
2055 static bool compare_ptrs_to_packet(struct reg_state *old, struct reg_state *cur)
2056 {
2057 	if (old->id != cur->id)
2058 		return false;
2059 
2060 	/* old ptr_to_packet is more conservative, since it allows smaller
2061 	 * range. Ex:
2062 	 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2063 	 * old(off=0,r=10) means that with range=10 the verifier proceeded
2064 	 * further and found no issues with the program. Now we're in the same
2065 	 * spot with cur(off=0,r=20), so we're safe too, since anything further
2066 	 * will only be looking at most 10 bytes after this pointer.
2067 	 */
2068 	if (old->off == cur->off && old->range < cur->range)
2069 		return true;
2070 
2071 	/* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2072 	 * since both cannot be used for packet access and safe(old)
2073 	 * pointer has smaller off that could be used for further
2074 	 * 'if (ptr > data_end)' check
2075 	 * Ex:
2076 	 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2077 	 * that we cannot access the packet.
2078 	 * The safe range is:
2079 	 * [ptr, ptr + range - off)
2080 	 * so whenever off >=range, it means no safe bytes from this pointer.
2081 	 * When comparing old->off <= cur->off, it means that older code
2082 	 * went with smaller offset and that offset was later
2083 	 * used to figure out the safe range after 'if (ptr > data_end)' check
2084 	 * Say, 'old' state was explored like:
2085 	 * ... R3(off=0, r=0)
2086 	 * R4 = R3 + 20
2087 	 * ... now R4(off=20,r=0)  <-- here
2088 	 * if (R4 > data_end)
2089 	 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2090 	 * ... the code further went all the way to bpf_exit.
2091 	 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2092 	 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2093 	 * goes further, such cur_R4 will give larger safe packet range after
2094 	 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2095 	 * so they will be good with r=30 and we can prune the search.
2096 	 */
2097 	if (old->off <= cur->off &&
2098 	    old->off >= old->range && cur->off >= cur->range)
2099 		return true;
2100 
2101 	return false;
2102 }
2103 
2104 /* compare two verifier states
2105  *
2106  * all states stored in state_list are known to be valid, since
2107  * verifier reached 'bpf_exit' instruction through them
2108  *
2109  * this function is called when verifier exploring different branches of
2110  * execution popped from the state stack. If it sees an old state that has
2111  * more strict register state and more strict stack state then this execution
2112  * branch doesn't need to be explored further, since verifier already
2113  * concluded that more strict state leads to valid finish.
2114  *
2115  * Therefore two states are equivalent if register state is more conservative
2116  * and explored stack state is more conservative than the current one.
2117  * Example:
2118  *       explored                   current
2119  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2120  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2121  *
2122  * In other words if current stack state (one being explored) has more
2123  * valid slots than old one that already passed validation, it means
2124  * the verifier can stop exploring and conclude that current state is valid too
2125  *
2126  * Similarly with registers. If explored state has register type as invalid
2127  * whereas register type in current state is meaningful, it means that
2128  * the current state will reach 'bpf_exit' instruction safely
2129  */
2130 static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
2131 {
2132 	struct reg_state *rold, *rcur;
2133 	int i;
2134 
2135 	for (i = 0; i < MAX_BPF_REG; i++) {
2136 		rold = &old->regs[i];
2137 		rcur = &cur->regs[i];
2138 
2139 		if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2140 			continue;
2141 
2142 		if (rold->type == NOT_INIT ||
2143 		    (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
2144 			continue;
2145 
2146 		if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2147 		    compare_ptrs_to_packet(rold, rcur))
2148 			continue;
2149 
2150 		return false;
2151 	}
2152 
2153 	for (i = 0; i < MAX_BPF_STACK; i++) {
2154 		if (old->stack_slot_type[i] == STACK_INVALID)
2155 			continue;
2156 		if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2157 			/* Ex: old explored (safe) state has STACK_SPILL in
2158 			 * this stack slot, but current has has STACK_MISC ->
2159 			 * this verifier states are not equivalent,
2160 			 * return false to continue verification of this path
2161 			 */
2162 			return false;
2163 		if (i % BPF_REG_SIZE)
2164 			continue;
2165 		if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2166 			   &cur->spilled_regs[i / BPF_REG_SIZE],
2167 			   sizeof(old->spilled_regs[0])))
2168 			/* when explored and current stack slot types are
2169 			 * the same, check that stored pointers types
2170 			 * are the same as well.
2171 			 * Ex: explored safe path could have stored
2172 			 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
2173 			 * but current path has stored:
2174 			 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
2175 			 * such verifier states are not equivalent.
2176 			 * return false to continue verification of this path
2177 			 */
2178 			return false;
2179 		else
2180 			continue;
2181 	}
2182 	return true;
2183 }
2184 
2185 static int is_state_visited(struct verifier_env *env, int insn_idx)
2186 {
2187 	struct verifier_state_list *new_sl;
2188 	struct verifier_state_list *sl;
2189 
2190 	sl = env->explored_states[insn_idx];
2191 	if (!sl)
2192 		/* this 'insn_idx' instruction wasn't marked, so we will not
2193 		 * be doing state search here
2194 		 */
2195 		return 0;
2196 
2197 	while (sl != STATE_LIST_MARK) {
2198 		if (states_equal(&sl->state, &env->cur_state))
2199 			/* reached equivalent register/stack state,
2200 			 * prune the search
2201 			 */
2202 			return 1;
2203 		sl = sl->next;
2204 	}
2205 
2206 	/* there were no equivalent states, remember current one.
2207 	 * technically the current state is not proven to be safe yet,
2208 	 * but it will either reach bpf_exit (which means it's safe) or
2209 	 * it will be rejected. Since there are no loops, we won't be
2210 	 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2211 	 */
2212 	new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
2213 	if (!new_sl)
2214 		return -ENOMEM;
2215 
2216 	/* add new state to the head of linked list */
2217 	memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2218 	new_sl->next = env->explored_states[insn_idx];
2219 	env->explored_states[insn_idx] = new_sl;
2220 	return 0;
2221 }
2222 
2223 static int do_check(struct verifier_env *env)
2224 {
2225 	struct verifier_state *state = &env->cur_state;
2226 	struct bpf_insn *insns = env->prog->insnsi;
2227 	struct reg_state *regs = state->regs;
2228 	int insn_cnt = env->prog->len;
2229 	int insn_idx, prev_insn_idx = 0;
2230 	int insn_processed = 0;
2231 	bool do_print_state = false;
2232 
2233 	init_reg_state(regs);
2234 	insn_idx = 0;
2235 	for (;;) {
2236 		struct bpf_insn *insn;
2237 		u8 class;
2238 		int err;
2239 
2240 		if (insn_idx >= insn_cnt) {
2241 			verbose("invalid insn idx %d insn_cnt %d\n",
2242 				insn_idx, insn_cnt);
2243 			return -EFAULT;
2244 		}
2245 
2246 		insn = &insns[insn_idx];
2247 		class = BPF_CLASS(insn->code);
2248 
2249 		if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2250 			verbose("BPF program is too large. Proccessed %d insn\n",
2251 				insn_processed);
2252 			return -E2BIG;
2253 		}
2254 
2255 		err = is_state_visited(env, insn_idx);
2256 		if (err < 0)
2257 			return err;
2258 		if (err == 1) {
2259 			/* found equivalent state, can prune the search */
2260 			if (log_level) {
2261 				if (do_print_state)
2262 					verbose("\nfrom %d to %d: safe\n",
2263 						prev_insn_idx, insn_idx);
2264 				else
2265 					verbose("%d: safe\n", insn_idx);
2266 			}
2267 			goto process_bpf_exit;
2268 		}
2269 
2270 		if (log_level && do_print_state) {
2271 			verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
2272 			print_verifier_state(&env->cur_state);
2273 			do_print_state = false;
2274 		}
2275 
2276 		if (log_level) {
2277 			verbose("%d: ", insn_idx);
2278 			print_bpf_insn(insn);
2279 		}
2280 
2281 		if (class == BPF_ALU || class == BPF_ALU64) {
2282 			err = check_alu_op(env, insn);
2283 			if (err)
2284 				return err;
2285 
2286 		} else if (class == BPF_LDX) {
2287 			enum bpf_reg_type src_reg_type;
2288 
2289 			/* check for reserved fields is already done */
2290 
2291 			/* check src operand */
2292 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2293 			if (err)
2294 				return err;
2295 
2296 			err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2297 			if (err)
2298 				return err;
2299 
2300 			src_reg_type = regs[insn->src_reg].type;
2301 
2302 			/* check that memory (src_reg + off) is readable,
2303 			 * the state of dst_reg will be updated by this func
2304 			 */
2305 			err = check_mem_access(env, insn->src_reg, insn->off,
2306 					       BPF_SIZE(insn->code), BPF_READ,
2307 					       insn->dst_reg);
2308 			if (err)
2309 				return err;
2310 
2311 			if (BPF_SIZE(insn->code) != BPF_W) {
2312 				insn_idx++;
2313 				continue;
2314 			}
2315 
2316 			if (insn->imm == 0) {
2317 				/* saw a valid insn
2318 				 * dst_reg = *(u32 *)(src_reg + off)
2319 				 * use reserved 'imm' field to mark this insn
2320 				 */
2321 				insn->imm = src_reg_type;
2322 
2323 			} else if (src_reg_type != insn->imm &&
2324 				   (src_reg_type == PTR_TO_CTX ||
2325 				    insn->imm == PTR_TO_CTX)) {
2326 				/* ABuser program is trying to use the same insn
2327 				 * dst_reg = *(u32*) (src_reg + off)
2328 				 * with different pointer types:
2329 				 * src_reg == ctx in one branch and
2330 				 * src_reg == stack|map in some other branch.
2331 				 * Reject it.
2332 				 */
2333 				verbose("same insn cannot be used with different pointers\n");
2334 				return -EINVAL;
2335 			}
2336 
2337 		} else if (class == BPF_STX) {
2338 			enum bpf_reg_type dst_reg_type;
2339 
2340 			if (BPF_MODE(insn->code) == BPF_XADD) {
2341 				err = check_xadd(env, insn);
2342 				if (err)
2343 					return err;
2344 				insn_idx++;
2345 				continue;
2346 			}
2347 
2348 			/* check src1 operand */
2349 			err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2350 			if (err)
2351 				return err;
2352 			/* check src2 operand */
2353 			err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2354 			if (err)
2355 				return err;
2356 
2357 			dst_reg_type = regs[insn->dst_reg].type;
2358 
2359 			/* check that memory (dst_reg + off) is writeable */
2360 			err = check_mem_access(env, insn->dst_reg, insn->off,
2361 					       BPF_SIZE(insn->code), BPF_WRITE,
2362 					       insn->src_reg);
2363 			if (err)
2364 				return err;
2365 
2366 			if (insn->imm == 0) {
2367 				insn->imm = dst_reg_type;
2368 			} else if (dst_reg_type != insn->imm &&
2369 				   (dst_reg_type == PTR_TO_CTX ||
2370 				    insn->imm == PTR_TO_CTX)) {
2371 				verbose("same insn cannot be used with different pointers\n");
2372 				return -EINVAL;
2373 			}
2374 
2375 		} else if (class == BPF_ST) {
2376 			if (BPF_MODE(insn->code) != BPF_MEM ||
2377 			    insn->src_reg != BPF_REG_0) {
2378 				verbose("BPF_ST uses reserved fields\n");
2379 				return -EINVAL;
2380 			}
2381 			/* check src operand */
2382 			err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2383 			if (err)
2384 				return err;
2385 
2386 			/* check that memory (dst_reg + off) is writeable */
2387 			err = check_mem_access(env, insn->dst_reg, insn->off,
2388 					       BPF_SIZE(insn->code), BPF_WRITE,
2389 					       -1);
2390 			if (err)
2391 				return err;
2392 
2393 		} else if (class == BPF_JMP) {
2394 			u8 opcode = BPF_OP(insn->code);
2395 
2396 			if (opcode == BPF_CALL) {
2397 				if (BPF_SRC(insn->code) != BPF_K ||
2398 				    insn->off != 0 ||
2399 				    insn->src_reg != BPF_REG_0 ||
2400 				    insn->dst_reg != BPF_REG_0) {
2401 					verbose("BPF_CALL uses reserved fields\n");
2402 					return -EINVAL;
2403 				}
2404 
2405 				err = check_call(env, insn->imm);
2406 				if (err)
2407 					return err;
2408 
2409 			} else if (opcode == BPF_JA) {
2410 				if (BPF_SRC(insn->code) != BPF_K ||
2411 				    insn->imm != 0 ||
2412 				    insn->src_reg != BPF_REG_0 ||
2413 				    insn->dst_reg != BPF_REG_0) {
2414 					verbose("BPF_JA uses reserved fields\n");
2415 					return -EINVAL;
2416 				}
2417 
2418 				insn_idx += insn->off + 1;
2419 				continue;
2420 
2421 			} else if (opcode == BPF_EXIT) {
2422 				if (BPF_SRC(insn->code) != BPF_K ||
2423 				    insn->imm != 0 ||
2424 				    insn->src_reg != BPF_REG_0 ||
2425 				    insn->dst_reg != BPF_REG_0) {
2426 					verbose("BPF_EXIT uses reserved fields\n");
2427 					return -EINVAL;
2428 				}
2429 
2430 				/* eBPF calling convetion is such that R0 is used
2431 				 * to return the value from eBPF program.
2432 				 * Make sure that it's readable at this time
2433 				 * of bpf_exit, which means that program wrote
2434 				 * something into it earlier
2435 				 */
2436 				err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2437 				if (err)
2438 					return err;
2439 
2440 				if (is_pointer_value(env, BPF_REG_0)) {
2441 					verbose("R0 leaks addr as return value\n");
2442 					return -EACCES;
2443 				}
2444 
2445 process_bpf_exit:
2446 				insn_idx = pop_stack(env, &prev_insn_idx);
2447 				if (insn_idx < 0) {
2448 					break;
2449 				} else {
2450 					do_print_state = true;
2451 					continue;
2452 				}
2453 			} else {
2454 				err = check_cond_jmp_op(env, insn, &insn_idx);
2455 				if (err)
2456 					return err;
2457 			}
2458 		} else if (class == BPF_LD) {
2459 			u8 mode = BPF_MODE(insn->code);
2460 
2461 			if (mode == BPF_ABS || mode == BPF_IND) {
2462 				err = check_ld_abs(env, insn);
2463 				if (err)
2464 					return err;
2465 
2466 			} else if (mode == BPF_IMM) {
2467 				err = check_ld_imm(env, insn);
2468 				if (err)
2469 					return err;
2470 
2471 				insn_idx++;
2472 			} else {
2473 				verbose("invalid BPF_LD mode\n");
2474 				return -EINVAL;
2475 			}
2476 		} else {
2477 			verbose("unknown insn class %d\n", class);
2478 			return -EINVAL;
2479 		}
2480 
2481 		insn_idx++;
2482 	}
2483 
2484 	verbose("processed %d insns\n", insn_processed);
2485 	return 0;
2486 }
2487 
2488 /* look for pseudo eBPF instructions that access map FDs and
2489  * replace them with actual map pointers
2490  */
2491 static int replace_map_fd_with_map_ptr(struct verifier_env *env)
2492 {
2493 	struct bpf_insn *insn = env->prog->insnsi;
2494 	int insn_cnt = env->prog->len;
2495 	int i, j;
2496 
2497 	for (i = 0; i < insn_cnt; i++, insn++) {
2498 		if (BPF_CLASS(insn->code) == BPF_LDX &&
2499 		    (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
2500 			verbose("BPF_LDX uses reserved fields\n");
2501 			return -EINVAL;
2502 		}
2503 
2504 		if (BPF_CLASS(insn->code) == BPF_STX &&
2505 		    ((BPF_MODE(insn->code) != BPF_MEM &&
2506 		      BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2507 			verbose("BPF_STX uses reserved fields\n");
2508 			return -EINVAL;
2509 		}
2510 
2511 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2512 			struct bpf_map *map;
2513 			struct fd f;
2514 
2515 			if (i == insn_cnt - 1 || insn[1].code != 0 ||
2516 			    insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2517 			    insn[1].off != 0) {
2518 				verbose("invalid bpf_ld_imm64 insn\n");
2519 				return -EINVAL;
2520 			}
2521 
2522 			if (insn->src_reg == 0)
2523 				/* valid generic load 64-bit imm */
2524 				goto next_insn;
2525 
2526 			if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2527 				verbose("unrecognized bpf_ld_imm64 insn\n");
2528 				return -EINVAL;
2529 			}
2530 
2531 			f = fdget(insn->imm);
2532 			map = __bpf_map_get(f);
2533 			if (IS_ERR(map)) {
2534 				verbose("fd %d is not pointing to valid bpf_map\n",
2535 					insn->imm);
2536 				return PTR_ERR(map);
2537 			}
2538 
2539 			/* store map pointer inside BPF_LD_IMM64 instruction */
2540 			insn[0].imm = (u32) (unsigned long) map;
2541 			insn[1].imm = ((u64) (unsigned long) map) >> 32;
2542 
2543 			/* check whether we recorded this map already */
2544 			for (j = 0; j < env->used_map_cnt; j++)
2545 				if (env->used_maps[j] == map) {
2546 					fdput(f);
2547 					goto next_insn;
2548 				}
2549 
2550 			if (env->used_map_cnt >= MAX_USED_MAPS) {
2551 				fdput(f);
2552 				return -E2BIG;
2553 			}
2554 
2555 			/* hold the map. If the program is rejected by verifier,
2556 			 * the map will be released by release_maps() or it
2557 			 * will be used by the valid program until it's unloaded
2558 			 * and all maps are released in free_bpf_prog_info()
2559 			 */
2560 			map = bpf_map_inc(map, false);
2561 			if (IS_ERR(map)) {
2562 				fdput(f);
2563 				return PTR_ERR(map);
2564 			}
2565 			env->used_maps[env->used_map_cnt++] = map;
2566 
2567 			fdput(f);
2568 next_insn:
2569 			insn++;
2570 			i++;
2571 		}
2572 	}
2573 
2574 	/* now all pseudo BPF_LD_IMM64 instructions load valid
2575 	 * 'struct bpf_map *' into a register instead of user map_fd.
2576 	 * These pointers will be used later by verifier to validate map access.
2577 	 */
2578 	return 0;
2579 }
2580 
2581 /* drop refcnt of maps used by the rejected program */
2582 static void release_maps(struct verifier_env *env)
2583 {
2584 	int i;
2585 
2586 	for (i = 0; i < env->used_map_cnt; i++)
2587 		bpf_map_put(env->used_maps[i]);
2588 }
2589 
2590 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
2591 static void convert_pseudo_ld_imm64(struct verifier_env *env)
2592 {
2593 	struct bpf_insn *insn = env->prog->insnsi;
2594 	int insn_cnt = env->prog->len;
2595 	int i;
2596 
2597 	for (i = 0; i < insn_cnt; i++, insn++)
2598 		if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2599 			insn->src_reg = 0;
2600 }
2601 
2602 /* convert load instructions that access fields of 'struct __sk_buff'
2603  * into sequence of instructions that access fields of 'struct sk_buff'
2604  */
2605 static int convert_ctx_accesses(struct verifier_env *env)
2606 {
2607 	struct bpf_insn *insn = env->prog->insnsi;
2608 	int insn_cnt = env->prog->len;
2609 	struct bpf_insn insn_buf[16];
2610 	struct bpf_prog *new_prog;
2611 	enum bpf_access_type type;
2612 	int i;
2613 
2614 	if (!env->prog->aux->ops->convert_ctx_access)
2615 		return 0;
2616 
2617 	for (i = 0; i < insn_cnt; i++, insn++) {
2618 		u32 insn_delta, cnt;
2619 
2620 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_W))
2621 			type = BPF_READ;
2622 		else if (insn->code == (BPF_STX | BPF_MEM | BPF_W))
2623 			type = BPF_WRITE;
2624 		else
2625 			continue;
2626 
2627 		if (insn->imm != PTR_TO_CTX) {
2628 			/* clear internal mark */
2629 			insn->imm = 0;
2630 			continue;
2631 		}
2632 
2633 		cnt = env->prog->aux->ops->
2634 			convert_ctx_access(type, insn->dst_reg, insn->src_reg,
2635 					   insn->off, insn_buf, env->prog);
2636 		if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
2637 			verbose("bpf verifier is misconfigured\n");
2638 			return -EINVAL;
2639 		}
2640 
2641 		new_prog = bpf_patch_insn_single(env->prog, i, insn_buf, cnt);
2642 		if (!new_prog)
2643 			return -ENOMEM;
2644 
2645 		insn_delta = cnt - 1;
2646 
2647 		/* keep walking new program and skip insns we just inserted */
2648 		env->prog = new_prog;
2649 		insn      = new_prog->insnsi + i + insn_delta;
2650 
2651 		insn_cnt += insn_delta;
2652 		i        += insn_delta;
2653 	}
2654 
2655 	return 0;
2656 }
2657 
2658 static void free_states(struct verifier_env *env)
2659 {
2660 	struct verifier_state_list *sl, *sln;
2661 	int i;
2662 
2663 	if (!env->explored_states)
2664 		return;
2665 
2666 	for (i = 0; i < env->prog->len; i++) {
2667 		sl = env->explored_states[i];
2668 
2669 		if (sl)
2670 			while (sl != STATE_LIST_MARK) {
2671 				sln = sl->next;
2672 				kfree(sl);
2673 				sl = sln;
2674 			}
2675 	}
2676 
2677 	kfree(env->explored_states);
2678 }
2679 
2680 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
2681 {
2682 	char __user *log_ubuf = NULL;
2683 	struct verifier_env *env;
2684 	int ret = -EINVAL;
2685 
2686 	if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
2687 		return -E2BIG;
2688 
2689 	/* 'struct verifier_env' can be global, but since it's not small,
2690 	 * allocate/free it every time bpf_check() is called
2691 	 */
2692 	env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
2693 	if (!env)
2694 		return -ENOMEM;
2695 
2696 	env->prog = *prog;
2697 
2698 	/* grab the mutex to protect few globals used by verifier */
2699 	mutex_lock(&bpf_verifier_lock);
2700 
2701 	if (attr->log_level || attr->log_buf || attr->log_size) {
2702 		/* user requested verbose verifier output
2703 		 * and supplied buffer to store the verification trace
2704 		 */
2705 		log_level = attr->log_level;
2706 		log_ubuf = (char __user *) (unsigned long) attr->log_buf;
2707 		log_size = attr->log_size;
2708 		log_len = 0;
2709 
2710 		ret = -EINVAL;
2711 		/* log_* values have to be sane */
2712 		if (log_size < 128 || log_size > UINT_MAX >> 8 ||
2713 		    log_level == 0 || log_ubuf == NULL)
2714 			goto free_env;
2715 
2716 		ret = -ENOMEM;
2717 		log_buf = vmalloc(log_size);
2718 		if (!log_buf)
2719 			goto free_env;
2720 	} else {
2721 		log_level = 0;
2722 	}
2723 
2724 	ret = replace_map_fd_with_map_ptr(env);
2725 	if (ret < 0)
2726 		goto skip_full_check;
2727 
2728 	env->explored_states = kcalloc(env->prog->len,
2729 				       sizeof(struct verifier_state_list *),
2730 				       GFP_USER);
2731 	ret = -ENOMEM;
2732 	if (!env->explored_states)
2733 		goto skip_full_check;
2734 
2735 	ret = check_cfg(env);
2736 	if (ret < 0)
2737 		goto skip_full_check;
2738 
2739 	env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2740 
2741 	ret = do_check(env);
2742 
2743 skip_full_check:
2744 	while (pop_stack(env, NULL) >= 0);
2745 	free_states(env);
2746 
2747 	if (ret == 0)
2748 		/* program is valid, convert *(u32*)(ctx + off) accesses */
2749 		ret = convert_ctx_accesses(env);
2750 
2751 	if (log_level && log_len >= log_size - 1) {
2752 		BUG_ON(log_len >= log_size);
2753 		/* verifier log exceeded user supplied buffer */
2754 		ret = -ENOSPC;
2755 		/* fall through to return what was recorded */
2756 	}
2757 
2758 	/* copy verifier log back to user space including trailing zero */
2759 	if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
2760 		ret = -EFAULT;
2761 		goto free_log_buf;
2762 	}
2763 
2764 	if (ret == 0 && env->used_map_cnt) {
2765 		/* if program passed verifier, update used_maps in bpf_prog_info */
2766 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
2767 							  sizeof(env->used_maps[0]),
2768 							  GFP_KERNEL);
2769 
2770 		if (!env->prog->aux->used_maps) {
2771 			ret = -ENOMEM;
2772 			goto free_log_buf;
2773 		}
2774 
2775 		memcpy(env->prog->aux->used_maps, env->used_maps,
2776 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
2777 		env->prog->aux->used_map_cnt = env->used_map_cnt;
2778 
2779 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
2780 		 * bpf_ld_imm64 instructions
2781 		 */
2782 		convert_pseudo_ld_imm64(env);
2783 	}
2784 
2785 free_log_buf:
2786 	if (log_level)
2787 		vfree(log_buf);
2788 free_env:
2789 	if (!env->prog->aux->used_maps)
2790 		/* if we didn't copy map pointers into bpf_prog_info, release
2791 		 * them now. Otherwise free_bpf_prog_info() will release them.
2792 		 */
2793 		release_maps(env);
2794 	*prog = env->prog;
2795 	kfree(env);
2796 	mutex_unlock(&bpf_verifier_lock);
2797 	return ret;
2798 }
2799