1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 * Copyright (c) 2016 Facebook
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.
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.
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
22 #include <linux/stringify.h>
24 /* bpf_check() is a static code analyzer that walks eBPF program
25 * instruction by instruction and updates register/stack state.
26 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
28 * The first pass is depth-first-search to check that the program is a DAG.
29 * It rejects the following programs:
30 * - larger than BPF_MAXINSNS insns
31 * - if loop is present (detected via back-edge)
32 * - unreachable insns exist (shouldn't be a forest. program = one function)
33 * - out of bounds or malformed jumps
34 * The second pass is all possible path descent from the 1st insn.
35 * Since it's analyzing all pathes through the program, the length of the
36 * analysis is limited to 64k insn, which may be hit even if total number of
37 * insn is less then 4K, but there are too many branches that change stack/regs.
38 * Number of 'branches to be analyzed' is limited to 1k
40 * On entry to each instruction, each register has a type, and the instruction
41 * changes the types of the registers depending on instruction semantics.
42 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
45 * All registers are 64-bit.
46 * R0 - return register
47 * R1-R5 argument passing registers
48 * R6-R9 callee saved registers
49 * R10 - frame pointer read-only
51 * At the start of BPF program the register R1 contains a pointer to bpf_context
52 * and has type PTR_TO_CTX.
54 * Verifier tracks arithmetic operations on pointers in case:
55 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
56 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
57 * 1st insn copies R10 (which has FRAME_PTR) type into R1
58 * and 2nd arithmetic instruction is pattern matched to recognize
59 * that it wants to construct a pointer to some element within stack.
60 * So after 2nd insn, the register R1 has type PTR_TO_STACK
61 * (and -20 constant is saved for further stack bounds checking).
62 * Meaning that this reg is a pointer to stack plus known immediate constant.
64 * Most of the time the registers have SCALAR_VALUE type, which
65 * means the register has some value, but it's not a valid pointer.
66 * (like pointer plus pointer becomes SCALAR_VALUE type)
68 * When verifier sees load or store instructions the type of base register
69 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
70 * types recognized by check_mem_access() function.
72 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
73 * and the range of [ptr, ptr + map's value_size) is accessible.
75 * registers used to pass values to function calls are checked against
76 * function argument constraints.
78 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
79 * It means that the register type passed to this function must be
80 * PTR_TO_STACK and it will be used inside the function as
81 * 'pointer to map element key'
83 * For example the argument constraints for bpf_map_lookup_elem():
84 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
85 * .arg1_type = ARG_CONST_MAP_PTR,
86 * .arg2_type = ARG_PTR_TO_MAP_KEY,
88 * ret_type says that this function returns 'pointer to map elem value or null'
89 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
90 * 2nd argument should be a pointer to stack, which will be used inside
91 * the helper function as a pointer to map element key.
93 * On the kernel side the helper function looks like:
94 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
96 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
97 * void *key = (void *) (unsigned long) r2;
100 * here kernel can access 'key' and 'map' pointers safely, knowing that
101 * [key, key + map->key_size) bytes are valid and were initialized on
102 * the stack of eBPF program.
105 * Corresponding eBPF program may look like:
106 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
107 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
108 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
109 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
110 * here verifier looks at prototype of map_lookup_elem() and sees:
111 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
112 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
114 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
115 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
116 * and were initialized prior to this call.
117 * If it's ok, then verifier allows this BPF_CALL insn and looks at
118 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
119 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
120 * returns ether pointer to map value or NULL.
122 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
123 * insn, the register holding that pointer in the true branch changes state to
124 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
125 * branch. See check_cond_jmp_op().
127 * After the call R0 is set to return type of the function and registers R1-R5
128 * are set to NOT_INIT to indicate that they are no longer readable.
131 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
132 struct bpf_verifier_stack_elem {
133 /* verifer state is 'st'
134 * before processing instruction 'insn_idx'
135 * and after processing instruction 'prev_insn_idx'
137 struct bpf_verifier_state st;
140 struct bpf_verifier_stack_elem *next;
143 #define BPF_COMPLEXITY_LIMIT_INSNS 131072
144 #define BPF_COMPLEXITY_LIMIT_STACK 1024
146 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
148 struct bpf_call_arg_meta {
149 struct bpf_map *map_ptr;
156 /* verbose verifier prints what it's seeing
157 * bpf_check() is called under lock, so no race to access these global vars
159 static u32 log_level, log_size, log_len;
160 static char *log_buf;
162 static DEFINE_MUTEX(bpf_verifier_lock);
164 /* log_level controls verbosity level of eBPF verifier.
165 * verbose() is used to dump the verification trace to the log, so the user
166 * can figure out what's wrong with the program
168 static __printf(1, 2) void verbose(const char *fmt, ...)
172 if (log_level == 0 || log_len >= log_size - 1)
176 log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
180 /* string representation of 'enum bpf_reg_type' */
181 static const char * const reg_type_str[] = {
183 [SCALAR_VALUE] = "inv",
184 [PTR_TO_CTX] = "ctx",
185 [CONST_PTR_TO_MAP] = "map_ptr",
186 [PTR_TO_MAP_VALUE] = "map_value",
187 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
188 [PTR_TO_STACK] = "fp",
189 [PTR_TO_PACKET] = "pkt",
190 [PTR_TO_PACKET_END] = "pkt_end",
193 #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
194 static const char * const func_id_str[] = {
195 __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
197 #undef __BPF_FUNC_STR_FN
199 static const char *func_id_name(int id)
201 BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
203 if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
204 return func_id_str[id];
209 static void print_verifier_state(struct bpf_verifier_state *state)
211 struct bpf_reg_state *reg;
215 for (i = 0; i < MAX_BPF_REG; i++) {
216 reg = &state->regs[i];
220 verbose(" R%d=%s", i, reg_type_str[t]);
221 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
222 tnum_is_const(reg->var_off)) {
223 /* reg->off should be 0 for SCALAR_VALUE */
224 verbose("%lld", reg->var_off.value + reg->off);
226 verbose("(id=%d", reg->id);
227 if (t != SCALAR_VALUE)
228 verbose(",off=%d", reg->off);
229 if (t == PTR_TO_PACKET)
230 verbose(",r=%d", reg->range);
231 else if (t == CONST_PTR_TO_MAP ||
232 t == PTR_TO_MAP_VALUE ||
233 t == PTR_TO_MAP_VALUE_OR_NULL)
234 verbose(",ks=%d,vs=%d",
235 reg->map_ptr->key_size,
236 reg->map_ptr->value_size);
237 if (tnum_is_const(reg->var_off)) {
238 /* Typically an immediate SCALAR_VALUE, but
239 * could be a pointer whose offset is too big
242 verbose(",imm=%llx", reg->var_off.value);
244 if (reg->smin_value != reg->umin_value &&
245 reg->smin_value != S64_MIN)
246 verbose(",smin_value=%lld",
247 (long long)reg->smin_value);
248 if (reg->smax_value != reg->umax_value &&
249 reg->smax_value != S64_MAX)
250 verbose(",smax_value=%lld",
251 (long long)reg->smax_value);
252 if (reg->umin_value != 0)
253 verbose(",umin_value=%llu",
254 (unsigned long long)reg->umin_value);
255 if (reg->umax_value != U64_MAX)
256 verbose(",umax_value=%llu",
257 (unsigned long long)reg->umax_value);
258 if (!tnum_is_unknown(reg->var_off)) {
261 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
262 verbose(",var_off=%s", tn_buf);
268 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
269 if (state->stack[i].slot_type[0] == STACK_SPILL)
271 (-i - 1) * BPF_REG_SIZE,
272 reg_type_str[state->stack[i].spilled_ptr.type]);
277 static const char *const bpf_class_string[] = {
285 [BPF_ALU64] = "alu64",
288 static const char *const bpf_alu_string[16] = {
289 [BPF_ADD >> 4] = "+=",
290 [BPF_SUB >> 4] = "-=",
291 [BPF_MUL >> 4] = "*=",
292 [BPF_DIV >> 4] = "/=",
293 [BPF_OR >> 4] = "|=",
294 [BPF_AND >> 4] = "&=",
295 [BPF_LSH >> 4] = "<<=",
296 [BPF_RSH >> 4] = ">>=",
297 [BPF_NEG >> 4] = "neg",
298 [BPF_MOD >> 4] = "%=",
299 [BPF_XOR >> 4] = "^=",
300 [BPF_MOV >> 4] = "=",
301 [BPF_ARSH >> 4] = "s>>=",
302 [BPF_END >> 4] = "endian",
305 static const char *const bpf_ldst_string[] = {
306 [BPF_W >> 3] = "u32",
307 [BPF_H >> 3] = "u16",
309 [BPF_DW >> 3] = "u64",
312 static const char *const bpf_jmp_string[16] = {
313 [BPF_JA >> 4] = "jmp",
314 [BPF_JEQ >> 4] = "==",
315 [BPF_JGT >> 4] = ">",
316 [BPF_JLT >> 4] = "<",
317 [BPF_JGE >> 4] = ">=",
318 [BPF_JLE >> 4] = "<=",
319 [BPF_JSET >> 4] = "&",
320 [BPF_JNE >> 4] = "!=",
321 [BPF_JSGT >> 4] = "s>",
322 [BPF_JSLT >> 4] = "s<",
323 [BPF_JSGE >> 4] = "s>=",
324 [BPF_JSLE >> 4] = "s<=",
325 [BPF_CALL >> 4] = "call",
326 [BPF_EXIT >> 4] = "exit",
329 static void print_bpf_insn(const struct bpf_verifier_env *env,
330 const struct bpf_insn *insn)
332 u8 class = BPF_CLASS(insn->code);
334 if (class == BPF_ALU || class == BPF_ALU64) {
335 if (BPF_SRC(insn->code) == BPF_X)
336 verbose("(%02x) %sr%d %s %sr%d\n",
337 insn->code, class == BPF_ALU ? "(u32) " : "",
339 bpf_alu_string[BPF_OP(insn->code) >> 4],
340 class == BPF_ALU ? "(u32) " : "",
343 verbose("(%02x) %sr%d %s %s%d\n",
344 insn->code, class == BPF_ALU ? "(u32) " : "",
346 bpf_alu_string[BPF_OP(insn->code) >> 4],
347 class == BPF_ALU ? "(u32) " : "",
349 } else if (class == BPF_STX) {
350 if (BPF_MODE(insn->code) == BPF_MEM)
351 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
353 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
355 insn->off, insn->src_reg);
356 else if (BPF_MODE(insn->code) == BPF_XADD)
357 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
359 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
360 insn->dst_reg, insn->off,
363 verbose("BUG_%02x\n", insn->code);
364 } else if (class == BPF_ST) {
365 if (BPF_MODE(insn->code) != BPF_MEM) {
366 verbose("BUG_st_%02x\n", insn->code);
369 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
371 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
373 insn->off, insn->imm);
374 } else if (class == BPF_LDX) {
375 if (BPF_MODE(insn->code) != BPF_MEM) {
376 verbose("BUG_ldx_%02x\n", insn->code);
379 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
380 insn->code, insn->dst_reg,
381 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
382 insn->src_reg, insn->off);
383 } else if (class == BPF_LD) {
384 if (BPF_MODE(insn->code) == BPF_ABS) {
385 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
387 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
389 } else if (BPF_MODE(insn->code) == BPF_IND) {
390 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
392 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
393 insn->src_reg, insn->imm);
394 } else if (BPF_MODE(insn->code) == BPF_IMM &&
395 BPF_SIZE(insn->code) == BPF_DW) {
396 /* At this point, we already made sure that the second
397 * part of the ldimm64 insn is accessible.
399 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
400 bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
402 if (map_ptr && !env->allow_ptr_leaks)
405 verbose("(%02x) r%d = 0x%llx\n", insn->code,
406 insn->dst_reg, (unsigned long long)imm);
408 verbose("BUG_ld_%02x\n", insn->code);
411 } else if (class == BPF_JMP) {
412 u8 opcode = BPF_OP(insn->code);
414 if (opcode == BPF_CALL) {
415 verbose("(%02x) call %s#%d\n", insn->code,
416 func_id_name(insn->imm), insn->imm);
417 } else if (insn->code == (BPF_JMP | BPF_JA)) {
418 verbose("(%02x) goto pc%+d\n",
419 insn->code, insn->off);
420 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
421 verbose("(%02x) exit\n", insn->code);
422 } else if (BPF_SRC(insn->code) == BPF_X) {
423 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
424 insn->code, insn->dst_reg,
425 bpf_jmp_string[BPF_OP(insn->code) >> 4],
426 insn->src_reg, insn->off);
428 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
429 insn->code, insn->dst_reg,
430 bpf_jmp_string[BPF_OP(insn->code) >> 4],
431 insn->imm, insn->off);
434 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
438 static int copy_stack_state(struct bpf_verifier_state *dst,
439 const struct bpf_verifier_state *src)
443 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
444 /* internal bug, make state invalid to reject the program */
445 memset(dst, 0, sizeof(*dst));
448 memcpy(dst->stack, src->stack,
449 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
453 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
454 * make it consume minimal amount of memory. check_stack_write() access from
455 * the program calls into realloc_verifier_state() to grow the stack size.
456 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
457 * which this function copies over. It points to previous bpf_verifier_state
458 * which is never reallocated
460 static int realloc_verifier_state(struct bpf_verifier_state *state, int size,
463 u32 old_size = state->allocated_stack;
464 struct bpf_stack_state *new_stack;
465 int slot = size / BPF_REG_SIZE;
467 if (size <= old_size || !size) {
470 state->allocated_stack = slot * BPF_REG_SIZE;
471 if (!size && old_size) {
477 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
483 memcpy(new_stack, state->stack,
484 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
485 memset(new_stack + old_size / BPF_REG_SIZE, 0,
486 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
488 state->allocated_stack = slot * BPF_REG_SIZE;
490 state->stack = new_stack;
494 static void free_verifier_state(struct bpf_verifier_state *state,
502 /* copy verifier state from src to dst growing dst stack space
503 * when necessary to accommodate larger src stack
505 static int copy_verifier_state(struct bpf_verifier_state *dst,
506 const struct bpf_verifier_state *src)
510 err = realloc_verifier_state(dst, src->allocated_stack, false);
513 memcpy(dst, src, offsetof(struct bpf_verifier_state, allocated_stack));
514 return copy_stack_state(dst, src);
517 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
520 struct bpf_verifier_state *cur = env->cur_state;
521 struct bpf_verifier_stack_elem *elem, *head = env->head;
524 if (env->head == NULL)
528 err = copy_verifier_state(cur, &head->st);
533 *insn_idx = head->insn_idx;
535 *prev_insn_idx = head->prev_insn_idx;
537 free_verifier_state(&head->st, false);
544 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
545 int insn_idx, int prev_insn_idx,
548 struct bpf_verifier_stack_elem *elem;
549 struct bpf_verifier_state *cur = env->cur_state;
552 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
556 elem->insn_idx = insn_idx;
557 elem->prev_insn_idx = prev_insn_idx;
558 elem->next = env->head;
559 elem->st.speculative |= speculative;
562 err = copy_verifier_state(&elem->st, cur);
565 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
566 verbose("BPF program is too complex\n");
571 /* pop all elements and return */
572 while (!pop_stack(env, NULL, NULL));
576 #define CALLER_SAVED_REGS 6
577 static const int caller_saved[CALLER_SAVED_REGS] = {
578 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
581 static void __mark_reg_not_init(struct bpf_reg_state *reg);
583 /* Mark the unknown part of a register (variable offset or scalar value) as
584 * known to have the value @imm.
586 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
589 reg->var_off = tnum_const(imm);
590 reg->smin_value = (s64)imm;
591 reg->smax_value = (s64)imm;
592 reg->umin_value = imm;
593 reg->umax_value = imm;
596 /* Mark the 'variable offset' part of a register as zero. This should be
597 * used only on registers holding a pointer type.
599 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
601 __mark_reg_known(reg, 0);
604 static void mark_reg_known_zero(struct bpf_reg_state *regs, u32 regno)
606 if (WARN_ON(regno >= MAX_BPF_REG)) {
607 verbose("mark_reg_known_zero(regs, %u)\n", regno);
608 /* Something bad happened, let's kill all regs */
609 for (regno = 0; regno < MAX_BPF_REG; regno++)
610 __mark_reg_not_init(regs + regno);
613 __mark_reg_known_zero(regs + regno);
616 /* Attempts to improve min/max values based on var_off information */
617 static void __update_reg_bounds(struct bpf_reg_state *reg)
619 /* min signed is max(sign bit) | min(other bits) */
620 reg->smin_value = max_t(s64, reg->smin_value,
621 reg->var_off.value | (reg->var_off.mask & S64_MIN));
622 /* max signed is min(sign bit) | max(other bits) */
623 reg->smax_value = min_t(s64, reg->smax_value,
624 reg->var_off.value | (reg->var_off.mask & S64_MAX));
625 reg->umin_value = max(reg->umin_value, reg->var_off.value);
626 reg->umax_value = min(reg->umax_value,
627 reg->var_off.value | reg->var_off.mask);
630 /* Uses signed min/max values to inform unsigned, and vice-versa */
631 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
633 /* Learn sign from signed bounds.
634 * If we cannot cross the sign boundary, then signed and unsigned bounds
635 * are the same, so combine. This works even in the negative case, e.g.
636 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
638 if (reg->smin_value >= 0 || reg->smax_value < 0) {
639 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
641 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
645 /* Learn sign from unsigned bounds. Signed bounds cross the sign
646 * boundary, so we must be careful.
648 if ((s64)reg->umax_value >= 0) {
649 /* Positive. We can't learn anything from the smin, but smax
650 * is positive, hence safe.
652 reg->smin_value = reg->umin_value;
653 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
655 } else if ((s64)reg->umin_value < 0) {
656 /* Negative. We can't learn anything from the smax, but smin
657 * is negative, hence safe.
659 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
661 reg->smax_value = reg->umax_value;
665 /* Attempts to improve var_off based on unsigned min/max information */
666 static void __reg_bound_offset(struct bpf_reg_state *reg)
668 reg->var_off = tnum_intersect(reg->var_off,
669 tnum_range(reg->umin_value,
673 /* Reset the min/max bounds of a register */
674 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
676 reg->smin_value = S64_MIN;
677 reg->smax_value = S64_MAX;
679 reg->umax_value = U64_MAX;
682 /* Mark a register as having a completely unknown (scalar) value. */
683 static void __mark_reg_unknown(struct bpf_reg_state *reg)
685 reg->type = SCALAR_VALUE;
688 reg->var_off = tnum_unknown;
689 __mark_reg_unbounded(reg);
692 static void mark_reg_unknown(struct bpf_reg_state *regs, u32 regno)
694 if (WARN_ON(regno >= MAX_BPF_REG)) {
695 verbose("mark_reg_unknown(regs, %u)\n", regno);
696 /* Something bad happened, let's kill all regs */
697 for (regno = 0; regno < MAX_BPF_REG; regno++)
698 __mark_reg_not_init(regs + regno);
701 __mark_reg_unknown(regs + regno);
704 static void __mark_reg_not_init(struct bpf_reg_state *reg)
706 __mark_reg_unknown(reg);
707 reg->type = NOT_INIT;
710 static void mark_reg_not_init(struct bpf_reg_state *regs, u32 regno)
712 if (WARN_ON(regno >= MAX_BPF_REG)) {
713 verbose("mark_reg_not_init(regs, %u)\n", regno);
714 /* Something bad happened, let's kill all regs */
715 for (regno = 0; regno < MAX_BPF_REG; regno++)
716 __mark_reg_not_init(regs + regno);
719 __mark_reg_not_init(regs + regno);
722 static void init_reg_state(struct bpf_reg_state *regs)
726 for (i = 0; i < MAX_BPF_REG; i++) {
727 mark_reg_not_init(regs, i);
728 regs[i].live = REG_LIVE_NONE;
732 regs[BPF_REG_FP].type = PTR_TO_STACK;
733 mark_reg_known_zero(regs, BPF_REG_FP);
735 /* 1st arg to a function */
736 regs[BPF_REG_1].type = PTR_TO_CTX;
737 mark_reg_known_zero(regs, BPF_REG_1);
741 SRC_OP, /* register is used as source operand */
742 DST_OP, /* register is used as destination operand */
743 DST_OP_NO_MARK /* same as above, check only, don't mark */
746 static void mark_reg_read(const struct bpf_verifier_state *state, u32 regno)
748 struct bpf_verifier_state *parent = state->parent;
750 if (regno == BPF_REG_FP)
751 /* We don't need to worry about FP liveness because it's read-only */
755 /* if read wasn't screened by an earlier write ... */
756 if (state->regs[regno].live & REG_LIVE_WRITTEN)
758 /* ... then we depend on parent's value */
759 parent->regs[regno].live |= REG_LIVE_READ;
761 parent = state->parent;
765 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
768 struct bpf_reg_state *regs = env->cur_state->regs;
770 if (regno >= MAX_BPF_REG) {
771 verbose("R%d is invalid\n", regno);
776 /* check whether register used as source operand can be read */
777 if (regs[regno].type == NOT_INIT) {
778 verbose("R%d !read_ok\n", regno);
781 mark_reg_read(env->cur_state, regno);
783 /* check whether register used as dest operand can be written to */
784 if (regno == BPF_REG_FP) {
785 verbose("frame pointer is read only\n");
788 regs[regno].live |= REG_LIVE_WRITTEN;
790 mark_reg_unknown(regs, regno);
795 static bool is_spillable_regtype(enum bpf_reg_type type)
798 case PTR_TO_MAP_VALUE:
799 case PTR_TO_MAP_VALUE_OR_NULL:
803 case PTR_TO_PACKET_END:
804 case CONST_PTR_TO_MAP:
811 /* check_stack_read/write functions track spill/fill of registers,
812 * stack boundary and alignment are checked in check_mem_access()
814 static int check_stack_write(struct bpf_verifier_env *env,
815 struct bpf_verifier_state *state, int off,
816 int size, int value_regno, int insn_idx)
818 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
820 err = realloc_verifier_state(state, round_up(slot + 1, BPF_REG_SIZE),
824 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
825 * so it's aligned access and [off, off + size) are within stack limits
827 if (!env->allow_ptr_leaks &&
828 state->stack[spi].slot_type[0] == STACK_SPILL &&
829 size != BPF_REG_SIZE) {
830 verbose("attempt to corrupt spilled pointer on stack\n");
834 if (value_regno >= 0 &&
835 is_spillable_regtype(state->regs[value_regno].type)) {
837 /* register containing pointer is being spilled into stack */
838 if (size != BPF_REG_SIZE) {
839 verbose("invalid size of register spill\n");
843 /* save register state */
844 state->stack[spi].spilled_ptr = state->regs[value_regno];
845 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
847 for (i = 0; i < BPF_REG_SIZE; i++) {
848 if (state->stack[spi].slot_type[i] == STACK_MISC &&
849 !env->allow_ptr_leaks) {
850 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
851 int soff = (-spi - 1) * BPF_REG_SIZE;
853 /* detected reuse of integer stack slot with a pointer
854 * which means either llvm is reusing stack slot or
855 * an attacker is trying to exploit CVE-2018-3639
856 * (speculative store bypass)
857 * Have to sanitize that slot with preemptive
860 if (*poff && *poff != soff) {
861 /* disallow programs where single insn stores
862 * into two different stack slots, since verifier
863 * cannot sanitize them
865 verbose("insn %d cannot access two stack slots fp%d and fp%d",
866 insn_idx, *poff, soff);
871 state->stack[spi].slot_type[i] = STACK_SPILL;
874 /* regular write of data into stack */
875 state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
877 for (i = 0; i < size; i++)
878 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
884 static void mark_stack_slot_read(const struct bpf_verifier_state *state, int slot)
886 struct bpf_verifier_state *parent = state->parent;
889 /* if read wasn't screened by an earlier write ... */
890 if (state->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
892 /* ... then we depend on parent's value */
893 parent->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
895 parent = state->parent;
899 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
902 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
905 if (state->allocated_stack <= slot) {
906 verbose("invalid read from stack off %d+0 size %d\n",
910 stype = state->stack[spi].slot_type;
912 if (stype[0] == STACK_SPILL) {
913 if (size != BPF_REG_SIZE) {
914 verbose("invalid size of register spill\n");
917 for (i = 1; i < BPF_REG_SIZE; i++) {
918 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
919 verbose("corrupted spill memory\n");
924 if (value_regno >= 0) {
925 /* restore register state from stack */
926 state->regs[value_regno] = state->stack[spi].spilled_ptr;
927 mark_stack_slot_read(state, spi);
931 for (i = 0; i < size; i++) {
932 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_MISC) {
933 verbose("invalid read from stack off %d+%d size %d\n",
938 if (value_regno >= 0)
939 /* have read misc data from the stack */
940 mark_reg_unknown(state->regs, value_regno);
945 static int check_stack_access(struct bpf_verifier_env *env,
946 const struct bpf_reg_state *reg,
949 /* Stack accesses must be at a fixed offset, so that we
950 * can determine what type of data were returned. See
951 * check_stack_read().
953 if (!tnum_is_const(reg->var_off)) {
956 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
957 verbose("variable stack access var_off=%s off=%d size=%d",
962 if (off >= 0 || off < -MAX_BPF_STACK) {
963 verbose("invalid stack off=%d size=%d\n", off, size);
970 /* check read/write into map element returned by bpf_map_lookup_elem() */
971 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
974 struct bpf_reg_state *regs = cur_regs(env);
975 struct bpf_map *map = regs[regno].map_ptr;
977 if (off < 0 || size <= 0 || off + size > map->value_size) {
978 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
979 map->value_size, off, size);
985 /* check read/write into a map element with possible variable offset */
986 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
989 struct bpf_verifier_state *state = env->cur_state;
990 struct bpf_reg_state *reg = &state->regs[regno];
993 /* We may have adjusted the register to this map value, so we
994 * need to try adding each of min_value and max_value to off
995 * to make sure our theoretical access will be safe.
998 print_verifier_state(state);
1000 /* The minimum value is only important with signed
1001 * comparisons where we can't assume the floor of a
1002 * value is 0. If we are using signed variables for our
1003 * index'es we need to make sure that whatever we use
1004 * will have a set floor within our range.
1006 if (reg->smin_value < 0 &&
1007 (reg->smin_value == S64_MIN ||
1008 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1009 reg->smin_value + off < 0)) {
1010 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1014 err = __check_map_access(env, regno, reg->smin_value + off, size);
1016 verbose("R%d min value is outside of the array range\n", regno);
1020 /* If we haven't set a max value then we need to bail since we can't be
1021 * sure we won't do bad things.
1022 * If reg->umax_value + off could overflow, treat that as unbounded too.
1024 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1025 verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1029 err = __check_map_access(env, regno, reg->umax_value + off, size);
1031 verbose("R%d max value is outside of the array range\n", regno);
1035 #define MAX_PACKET_OFF 0xffff
1037 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1038 const struct bpf_call_arg_meta *meta,
1039 enum bpf_access_type t)
1041 switch (env->prog->type) {
1042 case BPF_PROG_TYPE_LWT_IN:
1043 case BPF_PROG_TYPE_LWT_OUT:
1044 /* dst_input() and dst_output() can't write for now */
1048 case BPF_PROG_TYPE_SCHED_CLS:
1049 case BPF_PROG_TYPE_SCHED_ACT:
1050 case BPF_PROG_TYPE_XDP:
1051 case BPF_PROG_TYPE_LWT_XMIT:
1052 case BPF_PROG_TYPE_SK_SKB:
1054 return meta->pkt_access;
1056 env->seen_direct_write = true;
1063 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1066 struct bpf_reg_state *regs = cur_regs(env);
1067 struct bpf_reg_state *reg = ®s[regno];
1069 if (off < 0 || size <= 0 || (u64)off + size > reg->range) {
1070 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1071 off, size, regno, reg->id, reg->off, reg->range);
1077 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1080 struct bpf_reg_state *regs = cur_regs(env);
1081 struct bpf_reg_state *reg = ®s[regno];
1084 /* We may have added a variable offset to the packet pointer; but any
1085 * reg->range we have comes after that. We are only checking the fixed
1089 /* We don't allow negative numbers, because we aren't tracking enough
1090 * detail to prove they're safe.
1092 if (reg->smin_value < 0) {
1093 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1097 err = __check_packet_access(env, regno, off, size);
1099 verbose("R%d offset is outside of the packet\n", regno);
1105 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1106 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1107 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1109 struct bpf_insn_access_aux info = {
1110 .reg_type = *reg_type,
1113 /* for analyzer ctx accesses are already validated and converted */
1114 if (env->analyzer_ops)
1117 if (env->prog->aux->ops->is_valid_access &&
1118 env->prog->aux->ops->is_valid_access(off, size, t, &info)) {
1119 /* A non zero info.ctx_field_size indicates that this field is a
1120 * candidate for later verifier transformation to load the whole
1121 * field and then apply a mask when accessed with a narrower
1122 * access than actual ctx access size. A zero info.ctx_field_size
1123 * will only allow for whole field access and rejects any other
1124 * type of narrower access.
1126 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1127 *reg_type = info.reg_type;
1129 /* remember the offset of last byte accessed in ctx */
1130 if (env->prog->aux->max_ctx_offset < off + size)
1131 env->prog->aux->max_ctx_offset = off + size;
1135 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
1139 static bool __is_pointer_value(bool allow_ptr_leaks,
1140 const struct bpf_reg_state *reg)
1142 if (allow_ptr_leaks)
1145 return reg->type != SCALAR_VALUE;
1148 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1150 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1153 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1155 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1157 return reg->type == PTR_TO_CTX;
1160 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1162 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1164 return reg->type == PTR_TO_PACKET;
1167 static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
1168 int off, int size, bool strict)
1170 struct tnum reg_off;
1173 /* Byte size accesses are always allowed. */
1174 if (!strict || size == 1)
1177 /* For platforms that do not have a Kconfig enabling
1178 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1179 * NET_IP_ALIGN is universally set to '2'. And on platforms
1180 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1181 * to this code only in strict mode where we want to emulate
1182 * the NET_IP_ALIGN==2 checking. Therefore use an
1183 * unconditional IP align value of '2'.
1187 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1188 if (!tnum_is_aligned(reg_off, size)) {
1191 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1192 verbose("misaligned packet access off %d+%s+%d+%d size %d\n",
1193 ip_align, tn_buf, reg->off, off, size);
1200 static int check_generic_ptr_alignment(const struct bpf_reg_state *reg,
1201 const char *pointer_desc,
1202 int off, int size, bool strict)
1204 struct tnum reg_off;
1206 /* Byte size accesses are always allowed. */
1207 if (!strict || size == 1)
1210 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1211 if (!tnum_is_aligned(reg_off, size)) {
1214 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1215 verbose("misaligned %saccess off %s+%d+%d size %d\n",
1216 pointer_desc, tn_buf, reg->off, off, size);
1223 static int check_ptr_alignment(struct bpf_verifier_env *env,
1224 const struct bpf_reg_state *reg, int off,
1225 int size, bool strict_alignment_once)
1227 bool strict = env->strict_alignment || strict_alignment_once;
1228 const char *pointer_desc = "";
1230 switch (reg->type) {
1232 /* special case, because of NET_IP_ALIGN */
1233 return check_pkt_ptr_alignment(reg, off, size, strict);
1234 case PTR_TO_MAP_VALUE:
1235 pointer_desc = "value ";
1238 pointer_desc = "context ";
1241 pointer_desc = "stack ";
1242 /* The stack spill tracking logic in check_stack_write()
1243 * and check_stack_read() relies on stack accesses being
1251 return check_generic_ptr_alignment(reg, pointer_desc, off, size, strict);
1254 static int check_ctx_reg(struct bpf_verifier_env *env,
1255 const struct bpf_reg_state *reg, int regno)
1257 /* Access to ctx or passing it to a helper is only allowed in
1258 * its original, unmodified form.
1262 verbose("dereference of modified ctx ptr R%d off=%d disallowed\n",
1267 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1270 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1271 verbose("variable ctx access var_off=%s disallowed\n", tn_buf);
1278 /* truncate register to smaller size (in bytes)
1279 * must be called with size < BPF_REG_SIZE
1281 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1285 /* clear high bits in bit representation */
1286 reg->var_off = tnum_cast(reg->var_off, size);
1288 /* fix arithmetic bounds */
1289 mask = ((u64)1 << (size * 8)) - 1;
1290 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1291 reg->umin_value &= mask;
1292 reg->umax_value &= mask;
1294 reg->umin_value = 0;
1295 reg->umax_value = mask;
1297 reg->smin_value = reg->umin_value;
1298 reg->smax_value = reg->umax_value;
1301 /* check whether memory at (regno + off) is accessible for t = (read | write)
1302 * if t==write, value_regno is a register which value is stored into memory
1303 * if t==read, value_regno is a register which will receive the value from memory
1304 * if t==write && value_regno==-1, some unknown value is stored into memory
1305 * if t==read && value_regno==-1, don't care what we read from memory
1307 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1308 int off, int bpf_size, enum bpf_access_type t,
1309 int value_regno, bool strict_alignment_once)
1311 struct bpf_verifier_state *state = env->cur_state;
1312 struct bpf_reg_state *regs = cur_regs(env);
1313 struct bpf_reg_state *reg = regs + regno;
1316 size = bpf_size_to_bytes(bpf_size);
1320 /* alignment checks will add in reg->off themselves */
1321 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1325 /* for access checks, reg->off is just part of off */
1328 if (reg->type == PTR_TO_MAP_VALUE) {
1329 if (t == BPF_WRITE && value_regno >= 0 &&
1330 is_pointer_value(env, value_regno)) {
1331 verbose("R%d leaks addr into map\n", value_regno);
1335 err = check_map_access(env, regno, off, size);
1336 if (!err && t == BPF_READ && value_regno >= 0)
1337 mark_reg_unknown(regs, value_regno);
1339 } else if (reg->type == PTR_TO_CTX) {
1340 enum bpf_reg_type reg_type = SCALAR_VALUE;
1342 if (t == BPF_WRITE && value_regno >= 0 &&
1343 is_pointer_value(env, value_regno)) {
1344 verbose("R%d leaks addr into ctx\n", value_regno);
1347 err = check_ctx_reg(env, reg, regno);
1351 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1352 if (!err && t == BPF_READ && value_regno >= 0) {
1353 /* ctx access returns either a scalar, or a
1354 * PTR_TO_PACKET[_END]. In the latter case, we know
1355 * the offset is zero.
1357 if (reg_type == SCALAR_VALUE)
1358 mark_reg_unknown(regs, value_regno);
1360 mark_reg_known_zero(regs, value_regno);
1361 regs[value_regno].id = 0;
1362 regs[value_regno].off = 0;
1363 regs[value_regno].range = 0;
1364 regs[value_regno].type = reg_type;
1367 } else if (reg->type == PTR_TO_STACK) {
1368 off += reg->var_off.value;
1369 err = check_stack_access(env, reg, off, size);
1373 if (env->prog->aux->stack_depth < -off)
1374 env->prog->aux->stack_depth = -off;
1377 err = check_stack_write(env, state, off, size,
1378 value_regno, insn_idx);
1380 err = check_stack_read(state, off, size, value_regno);
1381 } else if (reg->type == PTR_TO_PACKET) {
1382 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1383 verbose("cannot write into packet\n");
1386 if (t == BPF_WRITE && value_regno >= 0 &&
1387 is_pointer_value(env, value_regno)) {
1388 verbose("R%d leaks addr into packet\n", value_regno);
1391 err = check_packet_access(env, regno, off, size);
1392 if (!err && t == BPF_READ && value_regno >= 0)
1393 mark_reg_unknown(regs, value_regno);
1395 verbose("R%d invalid mem access '%s'\n",
1396 regno, reg_type_str[reg->type]);
1400 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1401 regs[value_regno].type == SCALAR_VALUE) {
1402 /* b/h/w load zero-extends, mark upper bits as known 0 */
1403 coerce_reg_to_size(®s[value_regno], size);
1408 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1412 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1414 verbose("BPF_XADD uses reserved fields\n");
1418 /* check src1 operand */
1419 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1423 /* check src2 operand */
1424 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1428 if (is_pointer_value(env, insn->src_reg)) {
1429 verbose("R%d leaks addr into mem\n", insn->src_reg);
1433 if (is_ctx_reg(env, insn->dst_reg) ||
1434 is_pkt_reg(env, insn->dst_reg)) {
1435 verbose("BPF_XADD stores into R%d %s is not allowed\n",
1436 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1437 "context" : "packet");
1441 /* check whether atomic_add can read the memory */
1442 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1443 BPF_SIZE(insn->code), BPF_READ, -1, true);
1447 /* check whether atomic_add can write into the same memory */
1448 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1449 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1452 /* Does this register contain a constant zero? */
1453 static bool register_is_null(struct bpf_reg_state reg)
1455 return reg.type == SCALAR_VALUE && tnum_equals_const(reg.var_off, 0);
1458 /* when register 'regno' is passed into function that will read 'access_size'
1459 * bytes from that pointer, make sure that it's within stack boundary
1460 * and all elements of stack are initialized.
1461 * Unlike most pointer bounds-checking functions, this one doesn't take an
1462 * 'off' argument, so it has to add in reg->off itself.
1464 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1465 int access_size, bool zero_size_allowed,
1466 struct bpf_call_arg_meta *meta)
1468 struct bpf_verifier_state *state = env->cur_state;
1469 struct bpf_reg_state *regs = state->regs;
1470 int off, i, slot, spi;
1472 if (regs[regno].type != PTR_TO_STACK) {
1473 /* Allow zero-byte read from NULL, regardless of pointer type */
1474 if (zero_size_allowed && access_size == 0 &&
1475 register_is_null(regs[regno]))
1478 verbose("R%d type=%s expected=%s\n", regno,
1479 reg_type_str[regs[regno].type],
1480 reg_type_str[PTR_TO_STACK]);
1484 /* Only allow fixed-offset stack reads */
1485 if (!tnum_is_const(regs[regno].var_off)) {
1488 tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off);
1489 verbose("invalid variable stack read R%d var_off=%s\n",
1493 off = regs[regno].off + regs[regno].var_off.value;
1494 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1496 verbose("invalid stack type R%d off=%d access_size=%d\n",
1497 regno, off, access_size);
1501 if (env->prog->aux->stack_depth < -off)
1502 env->prog->aux->stack_depth = -off;
1504 if (meta && meta->raw_mode) {
1505 meta->access_size = access_size;
1506 meta->regno = regno;
1510 for (i = 0; i < access_size; i++) {
1511 slot = -(off + i) - 1;
1512 spi = slot / BPF_REG_SIZE;
1513 if (state->allocated_stack <= slot ||
1514 state->stack[spi].slot_type[slot % BPF_REG_SIZE] !=
1516 verbose("invalid indirect read from stack off %d+%d size %d\n",
1517 off, i, access_size);
1524 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1525 int access_size, bool zero_size_allowed,
1526 struct bpf_call_arg_meta *meta)
1528 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1530 switch (reg->type) {
1532 return check_packet_access(env, regno, reg->off, access_size);
1533 case PTR_TO_MAP_VALUE:
1534 return check_map_access(env, regno, reg->off, access_size);
1535 default: /* scalar_value|ptr_to_stack or invalid ptr */
1536 return check_stack_boundary(env, regno, access_size,
1537 zero_size_allowed, meta);
1541 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1542 enum bpf_arg_type arg_type,
1543 struct bpf_call_arg_meta *meta)
1545 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1546 enum bpf_reg_type expected_type, type = reg->type;
1549 if (arg_type == ARG_DONTCARE)
1552 err = check_reg_arg(env, regno, SRC_OP);
1556 if (arg_type == ARG_ANYTHING) {
1557 if (is_pointer_value(env, regno)) {
1558 verbose("R%d leaks addr into helper function\n", regno);
1564 if (type == PTR_TO_PACKET &&
1565 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1566 verbose("helper access to the packet is not allowed\n");
1570 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1571 arg_type == ARG_PTR_TO_MAP_VALUE) {
1572 expected_type = PTR_TO_STACK;
1573 if (type != PTR_TO_PACKET && type != expected_type)
1575 } else if (arg_type == ARG_CONST_SIZE ||
1576 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1577 expected_type = SCALAR_VALUE;
1578 if (type != expected_type)
1580 } else if (arg_type == ARG_CONST_MAP_PTR) {
1581 expected_type = CONST_PTR_TO_MAP;
1582 if (type != expected_type)
1584 } else if (arg_type == ARG_PTR_TO_CTX) {
1585 expected_type = PTR_TO_CTX;
1586 if (type != expected_type)
1588 err = check_ctx_reg(env, reg, regno);
1591 } else if (arg_type == ARG_PTR_TO_MEM ||
1592 arg_type == ARG_PTR_TO_UNINIT_MEM) {
1593 expected_type = PTR_TO_STACK;
1594 /* One exception here. In case function allows for NULL to be
1595 * passed in as argument, it's a SCALAR_VALUE type. Final test
1596 * happens during stack boundary checking.
1598 if (register_is_null(*reg))
1599 /* final test in check_stack_boundary() */;
1600 else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
1601 type != expected_type)
1603 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1605 verbose("unsupported arg_type %d\n", arg_type);
1609 if (arg_type == ARG_CONST_MAP_PTR) {
1610 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1611 meta->map_ptr = reg->map_ptr;
1612 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1613 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1614 * check that [key, key + map->key_size) are within
1615 * stack limits and initialized
1617 if (!meta->map_ptr) {
1618 /* in function declaration map_ptr must come before
1619 * map_key, so that it's verified and known before
1620 * we have to check map_key here. Otherwise it means
1621 * that kernel subsystem misconfigured verifier
1623 verbose("invalid map_ptr to access map->key\n");
1626 if (type == PTR_TO_PACKET)
1627 err = check_packet_access(env, regno, reg->off,
1628 meta->map_ptr->key_size);
1630 err = check_stack_boundary(env, regno,
1631 meta->map_ptr->key_size,
1633 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1634 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1635 * check [value, value + map->value_size) validity
1637 if (!meta->map_ptr) {
1638 /* kernel subsystem misconfigured verifier */
1639 verbose("invalid map_ptr to access map->value\n");
1642 if (type == PTR_TO_PACKET)
1643 err = check_packet_access(env, regno, reg->off,
1644 meta->map_ptr->value_size);
1646 err = check_stack_boundary(env, regno,
1647 meta->map_ptr->value_size,
1649 } else if (arg_type == ARG_CONST_SIZE ||
1650 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1651 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1653 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1654 * from stack pointer 'buf'. Check it
1655 * note: regno == len, regno - 1 == buf
1658 /* kernel subsystem misconfigured verifier */
1659 verbose("ARG_CONST_SIZE cannot be first argument\n");
1663 /* The register is SCALAR_VALUE; the access check
1664 * happens using its boundaries.
1667 if (!tnum_is_const(reg->var_off))
1668 /* For unprivileged variable accesses, disable raw
1669 * mode so that the program is required to
1670 * initialize all the memory that the helper could
1671 * just partially fill up.
1675 if (reg->smin_value < 0) {
1676 verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
1681 if (reg->umin_value == 0) {
1682 err = check_helper_mem_access(env, regno - 1, 0,
1689 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
1690 verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
1694 err = check_helper_mem_access(env, regno - 1,
1696 zero_size_allowed, meta);
1701 verbose("R%d type=%s expected=%s\n", regno,
1702 reg_type_str[type], reg_type_str[expected_type]);
1706 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1711 /* We need a two way check, first is from map perspective ... */
1712 switch (map->map_type) {
1713 case BPF_MAP_TYPE_PROG_ARRAY:
1714 if (func_id != BPF_FUNC_tail_call)
1717 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1718 if (func_id != BPF_FUNC_perf_event_read &&
1719 func_id != BPF_FUNC_perf_event_output)
1722 case BPF_MAP_TYPE_STACK_TRACE:
1723 if (func_id != BPF_FUNC_get_stackid)
1726 case BPF_MAP_TYPE_CGROUP_ARRAY:
1727 if (func_id != BPF_FUNC_skb_under_cgroup &&
1728 func_id != BPF_FUNC_current_task_under_cgroup)
1731 /* devmap returns a pointer to a live net_device ifindex that we cannot
1732 * allow to be modified from bpf side. So do not allow lookup elements
1735 case BPF_MAP_TYPE_DEVMAP:
1736 if (func_id != BPF_FUNC_redirect_map)
1739 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1740 case BPF_MAP_TYPE_HASH_OF_MAPS:
1741 if (func_id != BPF_FUNC_map_lookup_elem)
1744 case BPF_MAP_TYPE_SOCKMAP:
1745 if (func_id != BPF_FUNC_sk_redirect_map &&
1746 func_id != BPF_FUNC_sock_map_update &&
1747 func_id != BPF_FUNC_map_delete_elem)
1754 /* ... and second from the function itself. */
1756 case BPF_FUNC_tail_call:
1757 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1760 case BPF_FUNC_perf_event_read:
1761 case BPF_FUNC_perf_event_output:
1762 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1765 case BPF_FUNC_get_stackid:
1766 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1769 case BPF_FUNC_current_task_under_cgroup:
1770 case BPF_FUNC_skb_under_cgroup:
1771 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1774 case BPF_FUNC_redirect_map:
1775 if (map->map_type != BPF_MAP_TYPE_DEVMAP)
1778 case BPF_FUNC_sk_redirect_map:
1779 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
1782 case BPF_FUNC_sock_map_update:
1783 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
1792 verbose("cannot pass map_type %d into func %s#%d\n",
1793 map->map_type, func_id_name(func_id), func_id);
1797 static int check_raw_mode(const struct bpf_func_proto *fn)
1801 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
1803 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
1805 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
1807 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
1809 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
1812 return count > 1 ? -EINVAL : 0;
1815 /* Packet data might have moved, any old PTR_TO_PACKET[_END] are now invalid,
1816 * so turn them into unknown SCALAR_VALUE.
1818 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1820 struct bpf_verifier_state *state = env->cur_state;
1821 struct bpf_reg_state *regs = state->regs, *reg;
1824 for (i = 0; i < MAX_BPF_REG; i++)
1825 if (regs[i].type == PTR_TO_PACKET ||
1826 regs[i].type == PTR_TO_PACKET_END)
1827 mark_reg_unknown(regs, i);
1829 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1830 if (state->stack[i].slot_type[0] != STACK_SPILL)
1832 reg = &state->stack[i].spilled_ptr;
1833 if (reg->type != PTR_TO_PACKET &&
1834 reg->type != PTR_TO_PACKET_END)
1836 __mark_reg_unknown(reg);
1840 static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
1842 const struct bpf_func_proto *fn = NULL;
1843 struct bpf_reg_state *regs;
1844 struct bpf_call_arg_meta meta;
1848 /* find function prototype */
1849 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1850 verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
1854 if (env->prog->aux->ops->get_func_proto)
1855 fn = env->prog->aux->ops->get_func_proto(func_id);
1858 verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
1862 /* eBPF programs must be GPL compatible to use GPL-ed functions */
1863 if (!env->prog->gpl_compatible && fn->gpl_only) {
1864 verbose("cannot call GPL only function from proprietary program\n");
1868 changes_data = bpf_helper_changes_pkt_data(fn->func);
1870 memset(&meta, 0, sizeof(meta));
1871 meta.pkt_access = fn->pkt_access;
1873 /* We only support one arg being in raw mode at the moment, which
1874 * is sufficient for the helper functions we have right now.
1876 err = check_raw_mode(fn);
1878 verbose("kernel subsystem misconfigured func %s#%d\n",
1879 func_id_name(func_id), func_id);
1884 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1887 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1890 if (func_id == BPF_FUNC_tail_call) {
1891 if (meta.map_ptr == NULL) {
1892 verbose("verifier bug\n");
1895 env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
1897 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1900 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1903 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1907 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1908 * is inferred from register state.
1910 for (i = 0; i < meta.access_size; i++) {
1911 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
1912 BPF_WRITE, -1, false);
1917 regs = cur_regs(env);
1918 /* reset caller saved regs */
1919 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1920 mark_reg_not_init(regs, caller_saved[i]);
1921 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
1924 /* update return register (already marked as written above) */
1925 if (fn->ret_type == RET_INTEGER) {
1926 /* sets type to SCALAR_VALUE */
1927 mark_reg_unknown(regs, BPF_REG_0);
1928 } else if (fn->ret_type == RET_VOID) {
1929 regs[BPF_REG_0].type = NOT_INIT;
1930 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1931 struct bpf_insn_aux_data *insn_aux;
1933 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1934 /* There is no offset yet applied, variable or fixed */
1935 mark_reg_known_zero(regs, BPF_REG_0);
1936 regs[BPF_REG_0].off = 0;
1937 /* remember map_ptr, so that check_map_access()
1938 * can check 'value_size' boundary of memory access
1939 * to map element returned from bpf_map_lookup_elem()
1941 if (meta.map_ptr == NULL) {
1942 verbose("kernel subsystem misconfigured verifier\n");
1945 regs[BPF_REG_0].map_ptr = meta.map_ptr;
1946 regs[BPF_REG_0].id = ++env->id_gen;
1947 insn_aux = &env->insn_aux_data[insn_idx];
1948 if (!insn_aux->map_ptr)
1949 insn_aux->map_ptr = meta.map_ptr;
1950 else if (insn_aux->map_ptr != meta.map_ptr)
1951 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
1953 verbose("unknown return type %d of func %s#%d\n",
1954 fn->ret_type, func_id_name(func_id), func_id);
1958 err = check_map_func_compatibility(meta.map_ptr, func_id);
1963 clear_all_pkt_pointers(env);
1967 static bool signed_add_overflows(s64 a, s64 b)
1969 /* Do the add in u64, where overflow is well-defined */
1970 s64 res = (s64)((u64)a + (u64)b);
1977 static bool signed_sub_overflows(s64 a, s64 b)
1979 /* Do the sub in u64, where overflow is well-defined */
1980 s64 res = (s64)((u64)a - (u64)b);
1987 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
1988 const struct bpf_reg_state *reg,
1989 enum bpf_reg_type type)
1991 bool known = tnum_is_const(reg->var_off);
1992 s64 val = reg->var_off.value;
1993 s64 smin = reg->smin_value;
1995 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
1996 verbose("math between %s pointer and %lld is not allowed\n",
1997 reg_type_str[type], val);
2001 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2002 verbose("%s pointer offset %d is not allowed\n",
2003 reg_type_str[type], reg->off);
2007 if (smin == S64_MIN) {
2008 verbose("math between %s pointer and register with unbounded min value is not allowed\n",
2009 reg_type_str[type]);
2013 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2014 verbose("value %lld makes %s pointer be out of bounds\n",
2015 smin, reg_type_str[type]);
2022 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
2024 return &env->insn_aux_data[env->insn_idx];
2035 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
2036 u32 *alu_limit, bool mask_to_left)
2038 u32 max = 0, ptr_limit = 0;
2040 switch (ptr_reg->type) {
2042 /* Offset 0 is out-of-bounds, but acceptable start for the
2043 * left direction, see BPF_REG_FP. Also, unknown scalar
2044 * offset where we would need to deal with min/max bounds is
2045 * currently prohibited for unprivileged.
2047 max = MAX_BPF_STACK + mask_to_left;
2048 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
2050 case PTR_TO_MAP_VALUE:
2051 max = ptr_reg->map_ptr->value_size;
2052 ptr_limit = (mask_to_left ?
2053 ptr_reg->smin_value :
2054 ptr_reg->umax_value) + ptr_reg->off;
2060 if (ptr_limit >= max)
2061 return REASON_LIMIT;
2062 *alu_limit = ptr_limit;
2066 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
2067 const struct bpf_insn *insn)
2069 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
2072 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
2073 u32 alu_state, u32 alu_limit)
2075 /* If we arrived here from different branches with different
2076 * state or limits to sanitize, then this won't work.
2078 if (aux->alu_state &&
2079 (aux->alu_state != alu_state ||
2080 aux->alu_limit != alu_limit))
2081 return REASON_PATHS;
2083 /* Corresponding fixup done in fixup_bpf_calls(). */
2084 aux->alu_state = alu_state;
2085 aux->alu_limit = alu_limit;
2089 static int sanitize_val_alu(struct bpf_verifier_env *env,
2090 struct bpf_insn *insn)
2092 struct bpf_insn_aux_data *aux = cur_aux(env);
2094 if (can_skip_alu_sanitation(env, insn))
2097 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
2100 static bool sanitize_needed(u8 opcode)
2102 return opcode == BPF_ADD || opcode == BPF_SUB;
2105 struct bpf_sanitize_info {
2106 struct bpf_insn_aux_data aux;
2110 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
2111 struct bpf_insn *insn,
2112 const struct bpf_reg_state *ptr_reg,
2113 const struct bpf_reg_state *off_reg,
2114 struct bpf_reg_state *dst_reg,
2115 struct bpf_sanitize_info *info,
2116 const bool commit_window)
2118 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
2119 struct bpf_verifier_state *vstate = env->cur_state;
2120 bool off_is_imm = tnum_is_const(off_reg->var_off);
2121 bool off_is_neg = off_reg->smin_value < 0;
2122 bool ptr_is_dst_reg = ptr_reg == dst_reg;
2123 u8 opcode = BPF_OP(insn->code);
2124 u32 alu_state, alu_limit;
2125 struct bpf_reg_state tmp;
2129 if (can_skip_alu_sanitation(env, insn))
2132 /* We already marked aux for masking from non-speculative
2133 * paths, thus we got here in the first place. We only care
2134 * to explore bad access from here.
2136 if (vstate->speculative)
2139 if (!commit_window) {
2140 if (!tnum_is_const(off_reg->var_off) &&
2141 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
2142 return REASON_BOUNDS;
2144 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
2145 (opcode == BPF_SUB && !off_is_neg);
2148 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
2152 if (commit_window) {
2153 /* In commit phase we narrow the masking window based on
2154 * the observed pointer move after the simulated operation.
2156 alu_state = info->aux.alu_state;
2157 alu_limit = abs(info->aux.alu_limit - alu_limit);
2159 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
2160 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
2161 alu_state |= ptr_is_dst_reg ?
2162 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
2165 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
2169 /* If we're in commit phase, we're done here given we already
2170 * pushed the truncated dst_reg into the speculative verification
2173 * Also, when register is a known constant, we rewrite register-based
2174 * operation to immediate-based, and thus do not need masking (and as
2175 * a consequence, do not need to simulate the zero-truncation either).
2177 if (commit_window || off_is_imm)
2180 /* Simulate and find potential out-of-bounds access under
2181 * speculative execution from truncation as a result of
2182 * masking when off was not within expected range. If off
2183 * sits in dst, then we temporarily need to move ptr there
2184 * to simulate dst (== 0) +/-= ptr. Needed, for example,
2185 * for cases where we use K-based arithmetic in one direction
2186 * and truncated reg-based in the other in order to explore
2189 if (!ptr_is_dst_reg) {
2191 *dst_reg = *ptr_reg;
2193 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
2194 if (!ptr_is_dst_reg && ret)
2196 return !ret ? REASON_STACK : 0;
2199 static int sanitize_err(struct bpf_verifier_env *env,
2200 const struct bpf_insn *insn, int reason,
2201 const struct bpf_reg_state *off_reg,
2202 const struct bpf_reg_state *dst_reg)
2204 static const char *err = "pointer arithmetic with it prohibited for !root";
2205 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
2206 u32 dst = insn->dst_reg, src = insn->src_reg;
2210 verbose("R%d has unknown scalar with mixed signed bounds, %s\n",
2211 off_reg == dst_reg ? dst : src, err);
2214 verbose("R%d has pointer with unsupported alu operation, %s\n",
2215 off_reg == dst_reg ? src : dst, err);
2218 verbose("R%d tried to %s from different maps, paths or scalars, %s\n",
2222 verbose("R%d tried to %s beyond pointer bounds, %s\n",
2226 verbose("R%d could not be pushed for speculative verification, %s\n",
2230 verbose("verifier internal error: unknown reason (%d)\n",
2238 static int sanitize_check_bounds(struct bpf_verifier_env *env,
2239 const struct bpf_insn *insn,
2240 const struct bpf_reg_state *dst_reg)
2242 u32 dst = insn->dst_reg;
2244 /* For unprivileged we require that resulting offset must be in bounds
2245 * in order to be able to sanitize access later on.
2247 if (env->allow_ptr_leaks)
2250 switch (dst_reg->type) {
2252 if (check_stack_access(env, dst_reg, dst_reg->off +
2253 dst_reg->var_off.value, 1)) {
2254 verbose("R%d stack pointer arithmetic goes out of range, "
2255 "prohibited for !root\n", dst);
2259 case PTR_TO_MAP_VALUE:
2260 if (check_map_access(env, dst, dst_reg->off, 1)) {
2261 verbose("R%d pointer arithmetic of map value goes out of range, "
2262 "prohibited for !root\n", dst);
2273 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2274 * Caller should also handle BPF_MOV case separately.
2275 * If we return -EACCES, caller may want to try again treating pointer as a
2276 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
2278 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2279 struct bpf_insn *insn,
2280 const struct bpf_reg_state *ptr_reg,
2281 const struct bpf_reg_state *off_reg)
2283 struct bpf_reg_state *regs = cur_regs(env), *dst_reg;
2284 bool known = tnum_is_const(off_reg->var_off);
2285 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2286 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2287 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2288 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2289 struct bpf_sanitize_info info = {};
2290 u8 opcode = BPF_OP(insn->code);
2291 u32 dst = insn->dst_reg;
2294 dst_reg = ®s[dst];
2296 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2297 smin_val > smax_val || umin_val > umax_val) {
2298 /* Taint dst register if offset had invalid bounds derived from
2299 * e.g. dead branches.
2301 __mark_reg_unknown(dst_reg);
2305 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2306 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2307 verbose("R%d 32-bit pointer arithmetic prohibited\n",
2312 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2313 verbose("R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2317 if (ptr_reg->type == CONST_PTR_TO_MAP) {
2318 verbose("R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2322 if (ptr_reg->type == PTR_TO_PACKET_END) {
2323 verbose("R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2328 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2329 * The id may be overwritten later if we create a new variable offset.
2331 dst_reg->type = ptr_reg->type;
2332 dst_reg->id = ptr_reg->id;
2334 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2335 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2338 if (sanitize_needed(opcode)) {
2339 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
2342 return sanitize_err(env, insn, ret, off_reg, dst_reg);
2347 /* We can take a fixed offset as long as it doesn't overflow
2348 * the s32 'off' field
2350 if (known && (ptr_reg->off + smin_val ==
2351 (s64)(s32)(ptr_reg->off + smin_val))) {
2352 /* pointer += K. Accumulate it into fixed offset */
2353 dst_reg->smin_value = smin_ptr;
2354 dst_reg->smax_value = smax_ptr;
2355 dst_reg->umin_value = umin_ptr;
2356 dst_reg->umax_value = umax_ptr;
2357 dst_reg->var_off = ptr_reg->var_off;
2358 dst_reg->off = ptr_reg->off + smin_val;
2359 dst_reg->raw = ptr_reg->raw;
2362 /* A new variable offset is created. Note that off_reg->off
2363 * == 0, since it's a scalar.
2364 * dst_reg gets the pointer type and since some positive
2365 * integer value was added to the pointer, give it a new 'id'
2366 * if it's a PTR_TO_PACKET.
2367 * this creates a new 'base' pointer, off_reg (variable) gets
2368 * added into the variable offset, and we copy the fixed offset
2371 if (signed_add_overflows(smin_ptr, smin_val) ||
2372 signed_add_overflows(smax_ptr, smax_val)) {
2373 dst_reg->smin_value = S64_MIN;
2374 dst_reg->smax_value = S64_MAX;
2376 dst_reg->smin_value = smin_ptr + smin_val;
2377 dst_reg->smax_value = smax_ptr + smax_val;
2379 if (umin_ptr + umin_val < umin_ptr ||
2380 umax_ptr + umax_val < umax_ptr) {
2381 dst_reg->umin_value = 0;
2382 dst_reg->umax_value = U64_MAX;
2384 dst_reg->umin_value = umin_ptr + umin_val;
2385 dst_reg->umax_value = umax_ptr + umax_val;
2387 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2388 dst_reg->off = ptr_reg->off;
2389 dst_reg->raw = ptr_reg->raw;
2390 if (ptr_reg->type == PTR_TO_PACKET) {
2391 dst_reg->id = ++env->id_gen;
2392 /* something was added to pkt_ptr, set range to zero */
2397 if (dst_reg == off_reg) {
2398 /* scalar -= pointer. Creates an unknown scalar */
2399 verbose("R%d tried to subtract pointer from scalar\n",
2403 /* We don't allow subtraction from FP, because (according to
2404 * test_verifier.c test "invalid fp arithmetic", JITs might not
2405 * be able to deal with it.
2407 if (ptr_reg->type == PTR_TO_STACK) {
2408 verbose("R%d subtraction from stack pointer prohibited\n",
2412 if (known && (ptr_reg->off - smin_val ==
2413 (s64)(s32)(ptr_reg->off - smin_val))) {
2414 /* pointer -= K. Subtract it from fixed offset */
2415 dst_reg->smin_value = smin_ptr;
2416 dst_reg->smax_value = smax_ptr;
2417 dst_reg->umin_value = umin_ptr;
2418 dst_reg->umax_value = umax_ptr;
2419 dst_reg->var_off = ptr_reg->var_off;
2420 dst_reg->id = ptr_reg->id;
2421 dst_reg->off = ptr_reg->off - smin_val;
2422 dst_reg->raw = ptr_reg->raw;
2425 /* A new variable offset is created. If the subtrahend is known
2426 * nonnegative, then any reg->range we had before is still good.
2428 if (signed_sub_overflows(smin_ptr, smax_val) ||
2429 signed_sub_overflows(smax_ptr, smin_val)) {
2430 /* Overflow possible, we know nothing */
2431 dst_reg->smin_value = S64_MIN;
2432 dst_reg->smax_value = S64_MAX;
2434 dst_reg->smin_value = smin_ptr - smax_val;
2435 dst_reg->smax_value = smax_ptr - smin_val;
2437 if (umin_ptr < umax_val) {
2438 /* Overflow possible, we know nothing */
2439 dst_reg->umin_value = 0;
2440 dst_reg->umax_value = U64_MAX;
2442 /* Cannot overflow (as long as bounds are consistent) */
2443 dst_reg->umin_value = umin_ptr - umax_val;
2444 dst_reg->umax_value = umax_ptr - umin_val;
2446 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2447 dst_reg->off = ptr_reg->off;
2448 dst_reg->raw = ptr_reg->raw;
2449 if (ptr_reg->type == PTR_TO_PACKET) {
2450 dst_reg->id = ++env->id_gen;
2451 /* something was added to pkt_ptr, set range to zero */
2459 /* bitwise ops on pointers are troublesome. */
2460 verbose("R%d bitwise operator %s on pointer prohibited\n",
2461 dst, bpf_alu_string[opcode >> 4]);
2464 /* other operators (e.g. MUL,LSH) produce non-pointer results */
2465 verbose("R%d pointer arithmetic with %s operator prohibited\n",
2466 dst, bpf_alu_string[opcode >> 4]);
2470 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2473 __update_reg_bounds(dst_reg);
2474 __reg_deduce_bounds(dst_reg);
2475 __reg_bound_offset(dst_reg);
2477 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
2479 if (sanitize_needed(opcode)) {
2480 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
2483 return sanitize_err(env, insn, ret, off_reg, dst_reg);
2489 /* WARNING: This function does calculations on 64-bit values, but the actual
2490 * execution may occur on 32-bit values. Therefore, things like bitshifts
2491 * need extra checks in the 32-bit case.
2493 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2494 struct bpf_insn *insn,
2495 struct bpf_reg_state *dst_reg,
2496 struct bpf_reg_state src_reg)
2498 struct bpf_reg_state *regs = cur_regs(env);
2499 u8 opcode = BPF_OP(insn->code);
2500 bool src_known, dst_known;
2501 s64 smin_val, smax_val;
2502 u64 umin_val, umax_val;
2503 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2506 if (insn_bitness == 32) {
2507 /* Relevant for 32-bit RSH: Information can propagate towards
2508 * LSB, so it isn't sufficient to only truncate the output to
2511 coerce_reg_to_size(dst_reg, 4);
2512 coerce_reg_to_size(&src_reg, 4);
2515 smin_val = src_reg.smin_value;
2516 smax_val = src_reg.smax_value;
2517 umin_val = src_reg.umin_value;
2518 umax_val = src_reg.umax_value;
2519 src_known = tnum_is_const(src_reg.var_off);
2520 dst_known = tnum_is_const(dst_reg->var_off);
2522 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2523 smin_val > smax_val || umin_val > umax_val) {
2524 /* Taint dst register if offset had invalid bounds derived from
2525 * e.g. dead branches.
2527 __mark_reg_unknown(dst_reg);
2532 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2533 __mark_reg_unknown(dst_reg);
2537 if (sanitize_needed(opcode)) {
2538 ret = sanitize_val_alu(env, insn);
2540 return sanitize_err(env, insn, ret, NULL, NULL);
2545 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2546 signed_add_overflows(dst_reg->smax_value, smax_val)) {
2547 dst_reg->smin_value = S64_MIN;
2548 dst_reg->smax_value = S64_MAX;
2550 dst_reg->smin_value += smin_val;
2551 dst_reg->smax_value += smax_val;
2553 if (dst_reg->umin_value + umin_val < umin_val ||
2554 dst_reg->umax_value + umax_val < umax_val) {
2555 dst_reg->umin_value = 0;
2556 dst_reg->umax_value = U64_MAX;
2558 dst_reg->umin_value += umin_val;
2559 dst_reg->umax_value += umax_val;
2561 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2564 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2565 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2566 /* Overflow possible, we know nothing */
2567 dst_reg->smin_value = S64_MIN;
2568 dst_reg->smax_value = S64_MAX;
2570 dst_reg->smin_value -= smax_val;
2571 dst_reg->smax_value -= smin_val;
2573 if (dst_reg->umin_value < umax_val) {
2574 /* Overflow possible, we know nothing */
2575 dst_reg->umin_value = 0;
2576 dst_reg->umax_value = U64_MAX;
2578 /* Cannot overflow (as long as bounds are consistent) */
2579 dst_reg->umin_value -= umax_val;
2580 dst_reg->umax_value -= umin_val;
2582 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2585 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2586 if (smin_val < 0 || dst_reg->smin_value < 0) {
2587 /* Ain't nobody got time to multiply that sign */
2588 __mark_reg_unbounded(dst_reg);
2589 __update_reg_bounds(dst_reg);
2592 /* Both values are positive, so we can work with unsigned and
2593 * copy the result to signed (unless it exceeds S64_MAX).
2595 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2596 /* Potential overflow, we know nothing */
2597 __mark_reg_unbounded(dst_reg);
2598 /* (except what we can learn from the var_off) */
2599 __update_reg_bounds(dst_reg);
2602 dst_reg->umin_value *= umin_val;
2603 dst_reg->umax_value *= umax_val;
2604 if (dst_reg->umax_value > S64_MAX) {
2605 /* Overflow possible, we know nothing */
2606 dst_reg->smin_value = S64_MIN;
2607 dst_reg->smax_value = S64_MAX;
2609 dst_reg->smin_value = dst_reg->umin_value;
2610 dst_reg->smax_value = dst_reg->umax_value;
2614 if (src_known && dst_known) {
2615 __mark_reg_known(dst_reg, dst_reg->var_off.value &
2616 src_reg.var_off.value);
2619 /* We get our minimum from the var_off, since that's inherently
2620 * bitwise. Our maximum is the minimum of the operands' maxima.
2622 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2623 dst_reg->umin_value = dst_reg->var_off.value;
2624 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2625 if (dst_reg->smin_value < 0 || smin_val < 0) {
2626 /* Lose signed bounds when ANDing negative numbers,
2627 * ain't nobody got time for that.
2629 dst_reg->smin_value = S64_MIN;
2630 dst_reg->smax_value = S64_MAX;
2632 /* ANDing two positives gives a positive, so safe to
2633 * cast result into s64.
2635 dst_reg->smin_value = dst_reg->umin_value;
2636 dst_reg->smax_value = dst_reg->umax_value;
2638 /* We may learn something more from the var_off */
2639 __update_reg_bounds(dst_reg);
2642 if (src_known && dst_known) {
2643 __mark_reg_known(dst_reg, dst_reg->var_off.value |
2644 src_reg.var_off.value);
2647 /* We get our maximum from the var_off, and our minimum is the
2648 * maximum of the operands' minima
2650 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2651 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2652 dst_reg->umax_value = dst_reg->var_off.value |
2653 dst_reg->var_off.mask;
2654 if (dst_reg->smin_value < 0 || smin_val < 0) {
2655 /* Lose signed bounds when ORing negative numbers,
2656 * ain't nobody got time for that.
2658 dst_reg->smin_value = S64_MIN;
2659 dst_reg->smax_value = S64_MAX;
2661 /* ORing two positives gives a positive, so safe to
2662 * cast result into s64.
2664 dst_reg->smin_value = dst_reg->umin_value;
2665 dst_reg->smax_value = dst_reg->umax_value;
2667 /* We may learn something more from the var_off */
2668 __update_reg_bounds(dst_reg);
2671 if (umax_val >= insn_bitness) {
2672 /* Shifts greater than 31 or 63 are undefined.
2673 * This includes shifts by a negative number.
2675 mark_reg_unknown(regs, insn->dst_reg);
2678 /* We lose all sign bit information (except what we can pick
2681 dst_reg->smin_value = S64_MIN;
2682 dst_reg->smax_value = S64_MAX;
2683 /* If we might shift our top bit out, then we know nothing */
2684 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2685 dst_reg->umin_value = 0;
2686 dst_reg->umax_value = U64_MAX;
2688 dst_reg->umin_value <<= umin_val;
2689 dst_reg->umax_value <<= umax_val;
2692 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2694 dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2695 /* We may learn something more from the var_off */
2696 __update_reg_bounds(dst_reg);
2699 if (umax_val >= insn_bitness) {
2700 /* Shifts greater than 31 or 63 are undefined.
2701 * This includes shifts by a negative number.
2703 mark_reg_unknown(regs, insn->dst_reg);
2706 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
2707 * be negative, then either:
2708 * 1) src_reg might be zero, so the sign bit of the result is
2709 * unknown, so we lose our signed bounds
2710 * 2) it's known negative, thus the unsigned bounds capture the
2712 * 3) the signed bounds cross zero, so they tell us nothing
2714 * If the value in dst_reg is known nonnegative, then again the
2715 * unsigned bounts capture the signed bounds.
2716 * Thus, in all cases it suffices to blow away our signed bounds
2717 * and rely on inferring new ones from the unsigned bounds and
2718 * var_off of the result.
2720 dst_reg->smin_value = S64_MIN;
2721 dst_reg->smax_value = S64_MAX;
2723 dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2726 dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2727 dst_reg->umin_value >>= umax_val;
2728 dst_reg->umax_value >>= umin_val;
2729 /* We may learn something more from the var_off */
2730 __update_reg_bounds(dst_reg);
2733 mark_reg_unknown(regs, insn->dst_reg);
2737 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2738 /* 32-bit ALU ops are (32,32)->32 */
2739 coerce_reg_to_size(dst_reg, 4);
2742 __update_reg_bounds(dst_reg);
2743 __reg_deduce_bounds(dst_reg);
2744 __reg_bound_offset(dst_reg);
2748 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2751 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2752 struct bpf_insn *insn)
2754 struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
2755 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2756 u8 opcode = BPF_OP(insn->code);
2758 dst_reg = ®s[insn->dst_reg];
2760 if (dst_reg->type != SCALAR_VALUE)
2762 if (BPF_SRC(insn->code) == BPF_X) {
2763 src_reg = ®s[insn->src_reg];
2764 if (src_reg->type != SCALAR_VALUE) {
2765 if (dst_reg->type != SCALAR_VALUE) {
2766 /* Combining two pointers by any ALU op yields
2767 * an arbitrary scalar. Disallow all math except
2768 * pointer subtraction
2770 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
2771 mark_reg_unknown(regs, insn->dst_reg);
2774 verbose("R%d pointer %s pointer prohibited\n",
2776 bpf_alu_string[opcode >> 4]);
2779 /* scalar += pointer
2780 * This is legal, but we have to reverse our
2781 * src/dest handling in computing the range
2783 return adjust_ptr_min_max_vals(env, insn,
2786 } else if (ptr_reg) {
2787 /* pointer += scalar */
2788 return adjust_ptr_min_max_vals(env, insn,
2792 /* Pretend the src is a reg with a known value, since we only
2793 * need to be able to read from this state.
2795 off_reg.type = SCALAR_VALUE;
2796 __mark_reg_known(&off_reg, insn->imm);
2798 if (ptr_reg) /* pointer += K */
2799 return adjust_ptr_min_max_vals(env, insn,
2803 /* Got here implies adding two SCALAR_VALUEs */
2804 if (WARN_ON_ONCE(ptr_reg)) {
2805 print_verifier_state(env->cur_state);
2806 verbose("verifier internal error: unexpected ptr_reg\n");
2809 if (WARN_ON(!src_reg)) {
2810 print_verifier_state(env->cur_state);
2811 verbose("verifier internal error: no src_reg\n");
2814 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
2817 /* check validity of 32-bit and 64-bit arithmetic operations */
2818 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
2820 struct bpf_reg_state *regs = cur_regs(env);
2821 u8 opcode = BPF_OP(insn->code);
2824 if (opcode == BPF_END || opcode == BPF_NEG) {
2825 if (opcode == BPF_NEG) {
2826 if (BPF_SRC(insn->code) != 0 ||
2827 insn->src_reg != BPF_REG_0 ||
2828 insn->off != 0 || insn->imm != 0) {
2829 verbose("BPF_NEG uses reserved fields\n");
2833 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
2834 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
2835 BPF_CLASS(insn->code) == BPF_ALU64) {
2836 verbose("BPF_END uses reserved fields\n");
2841 /* check src operand */
2842 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2846 if (is_pointer_value(env, insn->dst_reg)) {
2847 verbose("R%d pointer arithmetic prohibited\n",
2852 /* check dest operand */
2853 err = check_reg_arg(env, insn->dst_reg, DST_OP);
2857 } else if (opcode == BPF_MOV) {
2859 if (BPF_SRC(insn->code) == BPF_X) {
2860 if (insn->imm != 0 || insn->off != 0) {
2861 verbose("BPF_MOV uses reserved fields\n");
2865 /* check src operand */
2866 err = check_reg_arg(env, insn->src_reg, SRC_OP);
2870 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2871 verbose("BPF_MOV uses reserved fields\n");
2876 /* check dest operand */
2877 err = check_reg_arg(env, insn->dst_reg, DST_OP);
2881 if (BPF_SRC(insn->code) == BPF_X) {
2882 if (BPF_CLASS(insn->code) == BPF_ALU64) {
2884 * copy register state to dest reg
2886 regs[insn->dst_reg] = regs[insn->src_reg];
2887 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
2890 if (is_pointer_value(env, insn->src_reg)) {
2891 verbose("R%d partial copy of pointer\n",
2895 mark_reg_unknown(regs, insn->dst_reg);
2896 coerce_reg_to_size(®s[insn->dst_reg], 4);
2900 * remember the value we stored into this reg
2902 regs[insn->dst_reg].type = SCALAR_VALUE;
2903 if (BPF_CLASS(insn->code) == BPF_ALU64) {
2904 __mark_reg_known(regs + insn->dst_reg,
2907 __mark_reg_known(regs + insn->dst_reg,
2912 } else if (opcode > BPF_END) {
2913 verbose("invalid BPF_ALU opcode %x\n", opcode);
2916 } else { /* all other ALU ops: and, sub, xor, add, ... */
2918 if (BPF_SRC(insn->code) == BPF_X) {
2919 if (insn->imm != 0 || insn->off != 0) {
2920 verbose("BPF_ALU uses reserved fields\n");
2923 /* check src1 operand */
2924 err = check_reg_arg(env, insn->src_reg, SRC_OP);
2928 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2929 verbose("BPF_ALU uses reserved fields\n");
2934 /* check src2 operand */
2935 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2939 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
2940 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
2941 verbose("div by zero\n");
2945 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
2946 verbose("BPF_ARSH not supported for 32 bit ALU\n");
2950 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
2951 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
2952 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
2954 if (insn->imm < 0 || insn->imm >= size) {
2955 verbose("invalid shift %d\n", insn->imm);
2960 /* check dest operand */
2961 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
2965 return adjust_reg_min_max_vals(env, insn);
2971 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
2972 struct bpf_reg_state *dst_reg,
2973 bool range_right_open)
2975 struct bpf_reg_state *regs = state->regs, *reg;
2979 if (dst_reg->off < 0 ||
2980 (dst_reg->off == 0 && range_right_open))
2981 /* This doesn't give us any range */
2984 if (dst_reg->umax_value > MAX_PACKET_OFF ||
2985 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
2986 /* Risk of overflow. For instance, ptr + (1<<63) may be less
2987 * than pkt_end, but that's because it's also less than pkt.
2991 new_range = dst_reg->off;
2992 if (range_right_open)
2995 /* Examples for register markings:
2997 * pkt_data in dst register:
3001 * if (r2 > pkt_end) goto <handle exception>
3006 * if (r2 < pkt_end) goto <access okay>
3007 * <handle exception>
3010 * r2 == dst_reg, pkt_end == src_reg
3011 * r2=pkt(id=n,off=8,r=0)
3012 * r3=pkt(id=n,off=0,r=0)
3014 * pkt_data in src register:
3018 * if (pkt_end >= r2) goto <access okay>
3019 * <handle exception>
3023 * if (pkt_end <= r2) goto <handle exception>
3027 * pkt_end == dst_reg, r2 == src_reg
3028 * r2=pkt(id=n,off=8,r=0)
3029 * r3=pkt(id=n,off=0,r=0)
3031 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3032 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3033 * and [r3, r3 + 8-1) respectively is safe to access depending on
3037 /* If our ids match, then we must have the same max_value. And we
3038 * don't care about the other reg's fixed offset, since if it's too big
3039 * the range won't allow anything.
3040 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3042 for (i = 0; i < MAX_BPF_REG; i++)
3043 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
3044 /* keep the maximum range already checked */
3045 regs[i].range = max(regs[i].range, new_range);
3047 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3048 if (state->stack[i].slot_type[0] != STACK_SPILL)
3050 reg = &state->stack[i].spilled_ptr;
3051 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
3052 reg->range = max(reg->range, new_range);
3056 /* Adjusts the register min/max values in the case that the dst_reg is the
3057 * variable register that we are working on, and src_reg is a constant or we're
3058 * simply doing a BPF_K check.
3059 * In JEQ/JNE cases we also adjust the var_off values.
3061 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3062 struct bpf_reg_state *false_reg, u64 val,
3065 /* If the dst_reg is a pointer, we can't learn anything about its
3066 * variable offset from the compare (unless src_reg were a pointer into
3067 * the same object, but we don't bother with that.
3068 * Since false_reg and true_reg have the same type by construction, we
3069 * only need to check one of them for pointerness.
3071 if (__is_pointer_value(false, false_reg))
3076 /* If this is false then we know nothing Jon Snow, but if it is
3077 * true then we know for sure.
3079 __mark_reg_known(true_reg, val);
3082 /* If this is true we know nothing Jon Snow, but if it is false
3083 * we know the value for sure;
3085 __mark_reg_known(false_reg, val);
3088 false_reg->umax_value = min(false_reg->umax_value, val);
3089 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3092 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3093 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3096 false_reg->umin_value = max(false_reg->umin_value, val);
3097 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3100 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3101 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3104 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3105 true_reg->umin_value = max(true_reg->umin_value, val);
3108 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3109 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3112 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3113 true_reg->umax_value = min(true_reg->umax_value, val);
3116 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3117 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3123 __reg_deduce_bounds(false_reg);
3124 __reg_deduce_bounds(true_reg);
3125 /* We might have learned some bits from the bounds. */
3126 __reg_bound_offset(false_reg);
3127 __reg_bound_offset(true_reg);
3128 /* Intersecting with the old var_off might have improved our bounds
3129 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3130 * then new var_off is (0; 0x7f...fc) which improves our umax.
3132 __update_reg_bounds(false_reg);
3133 __update_reg_bounds(true_reg);
3136 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3139 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3140 struct bpf_reg_state *false_reg, u64 val,
3143 if (__is_pointer_value(false, false_reg))
3148 /* If this is false then we know nothing Jon Snow, but if it is
3149 * true then we know for sure.
3151 __mark_reg_known(true_reg, val);
3154 /* If this is true we know nothing Jon Snow, but if it is false
3155 * we know the value for sure;
3157 __mark_reg_known(false_reg, val);
3160 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3161 false_reg->umin_value = max(false_reg->umin_value, val);
3164 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3165 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3168 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3169 false_reg->umax_value = min(false_reg->umax_value, val);
3172 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3173 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3176 true_reg->umax_value = min(true_reg->umax_value, val);
3177 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3180 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3181 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3184 true_reg->umin_value = max(true_reg->umin_value, val);
3185 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3188 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3189 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3195 __reg_deduce_bounds(false_reg);
3196 __reg_deduce_bounds(true_reg);
3197 /* We might have learned some bits from the bounds. */
3198 __reg_bound_offset(false_reg);
3199 __reg_bound_offset(true_reg);
3200 /* Intersecting with the old var_off might have improved our bounds
3201 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3202 * then new var_off is (0; 0x7f...fc) which improves our umax.
3204 __update_reg_bounds(false_reg);
3205 __update_reg_bounds(true_reg);
3208 /* Regs are known to be equal, so intersect their min/max/var_off */
3209 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3210 struct bpf_reg_state *dst_reg)
3212 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3213 dst_reg->umin_value);
3214 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3215 dst_reg->umax_value);
3216 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3217 dst_reg->smin_value);
3218 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3219 dst_reg->smax_value);
3220 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3222 /* We might have learned new bounds from the var_off. */
3223 __update_reg_bounds(src_reg);
3224 __update_reg_bounds(dst_reg);
3225 /* We might have learned something about the sign bit. */
3226 __reg_deduce_bounds(src_reg);
3227 __reg_deduce_bounds(dst_reg);
3228 /* We might have learned some bits from the bounds. */
3229 __reg_bound_offset(src_reg);
3230 __reg_bound_offset(dst_reg);
3231 /* Intersecting with the old var_off might have improved our bounds
3232 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3233 * then new var_off is (0; 0x7f...fc) which improves our umax.
3235 __update_reg_bounds(src_reg);
3236 __update_reg_bounds(dst_reg);
3239 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3240 struct bpf_reg_state *true_dst,
3241 struct bpf_reg_state *false_src,
3242 struct bpf_reg_state *false_dst,
3247 __reg_combine_min_max(true_src, true_dst);
3250 __reg_combine_min_max(false_src, false_dst);
3255 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3258 struct bpf_reg_state *reg = ®s[regno];
3260 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3261 /* Old offset (both fixed and variable parts) should
3262 * have been known-zero, because we don't allow pointer
3263 * arithmetic on pointers that might be NULL.
3265 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3266 !tnum_equals_const(reg->var_off, 0) ||
3268 __mark_reg_known_zero(reg);
3272 reg->type = SCALAR_VALUE;
3273 } else if (reg->map_ptr->inner_map_meta) {
3274 reg->type = CONST_PTR_TO_MAP;
3275 reg->map_ptr = reg->map_ptr->inner_map_meta;
3277 reg->type = PTR_TO_MAP_VALUE;
3279 /* We don't need id from this point onwards anymore, thus we
3280 * should better reset it, so that state pruning has chances
3287 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3288 * be folded together at some point.
3290 static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
3293 struct bpf_reg_state *regs = state->regs;
3294 u32 id = regs[regno].id;
3297 for (i = 0; i < MAX_BPF_REG; i++)
3298 mark_map_reg(regs, i, id, is_null);
3300 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3301 if (state->stack[i].slot_type[0] != STACK_SPILL)
3303 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3307 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3308 struct bpf_insn *insn, int *insn_idx)
3310 struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
3311 struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
3312 u8 opcode = BPF_OP(insn->code);
3315 if (opcode > BPF_JSLE) {
3316 verbose("invalid BPF_JMP opcode %x\n", opcode);
3320 if (BPF_SRC(insn->code) == BPF_X) {
3321 if (insn->imm != 0) {
3322 verbose("BPF_JMP uses reserved fields\n");
3326 /* check src1 operand */
3327 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3331 if (is_pointer_value(env, insn->src_reg)) {
3332 verbose("R%d pointer comparison prohibited\n",
3337 if (insn->src_reg != BPF_REG_0) {
3338 verbose("BPF_JMP uses reserved fields\n");
3343 /* check src2 operand */
3344 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3348 dst_reg = ®s[insn->dst_reg];
3350 /* detect if R == 0 where R was initialized to zero earlier */
3351 if (BPF_SRC(insn->code) == BPF_K &&
3352 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3353 dst_reg->type == SCALAR_VALUE &&
3354 tnum_equals_const(dst_reg->var_off, insn->imm)) {
3355 if (opcode == BPF_JEQ) {
3356 /* if (imm == imm) goto pc+off;
3357 * only follow the goto, ignore fall-through
3359 *insn_idx += insn->off;
3362 /* if (imm != imm) goto pc+off;
3363 * only follow fall-through branch, since
3364 * that's where the program will go
3370 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
3375 /* detect if we are comparing against a constant value so we can adjust
3376 * our min/max values for our dst register.
3377 * this is only legit if both are scalars (or pointers to the same
3378 * object, I suppose, but we don't support that right now), because
3379 * otherwise the different base pointers mean the offsets aren't
3382 if (BPF_SRC(insn->code) == BPF_X) {
3383 if (dst_reg->type == SCALAR_VALUE &&
3384 regs[insn->src_reg].type == SCALAR_VALUE) {
3385 if (tnum_is_const(regs[insn->src_reg].var_off))
3386 reg_set_min_max(&other_branch->regs[insn->dst_reg],
3387 dst_reg, regs[insn->src_reg].var_off.value,
3389 else if (tnum_is_const(dst_reg->var_off))
3390 reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
3391 ®s[insn->src_reg],
3392 dst_reg->var_off.value, opcode);
3393 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3394 /* Comparing for equality, we can combine knowledge */
3395 reg_combine_min_max(&other_branch->regs[insn->src_reg],
3396 &other_branch->regs[insn->dst_reg],
3397 ®s[insn->src_reg],
3398 ®s[insn->dst_reg], opcode);
3400 } else if (dst_reg->type == SCALAR_VALUE) {
3401 reg_set_min_max(&other_branch->regs[insn->dst_reg],
3402 dst_reg, insn->imm, opcode);
3405 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3406 if (BPF_SRC(insn->code) == BPF_K &&
3407 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3408 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3409 /* Mark all identical map registers in each branch as either
3410 * safe or unknown depending R == 0 or R != 0 conditional.
3412 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3413 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3414 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
3415 dst_reg->type == PTR_TO_PACKET &&
3416 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3417 /* pkt_data' > pkt_end */
3418 find_good_pkt_pointers(this_branch, dst_reg, false);
3419 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
3420 dst_reg->type == PTR_TO_PACKET_END &&
3421 regs[insn->src_reg].type == PTR_TO_PACKET) {
3422 /* pkt_end > pkt_data' */
3423 find_good_pkt_pointers(other_branch, ®s[insn->src_reg], true);
3424 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
3425 dst_reg->type == PTR_TO_PACKET &&
3426 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3427 /* pkt_data' < pkt_end */
3428 find_good_pkt_pointers(other_branch, dst_reg, true);
3429 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
3430 dst_reg->type == PTR_TO_PACKET_END &&
3431 regs[insn->src_reg].type == PTR_TO_PACKET) {
3432 /* pkt_end < pkt_data' */
3433 find_good_pkt_pointers(this_branch, ®s[insn->src_reg], false);
3434 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
3435 dst_reg->type == PTR_TO_PACKET &&
3436 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3437 /* pkt_data' >= pkt_end */
3438 find_good_pkt_pointers(this_branch, dst_reg, true);
3439 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
3440 dst_reg->type == PTR_TO_PACKET_END &&
3441 regs[insn->src_reg].type == PTR_TO_PACKET) {
3442 /* pkt_end >= pkt_data' */
3443 find_good_pkt_pointers(other_branch, ®s[insn->src_reg], false);
3444 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
3445 dst_reg->type == PTR_TO_PACKET &&
3446 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3447 /* pkt_data' <= pkt_end */
3448 find_good_pkt_pointers(other_branch, dst_reg, false);
3449 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
3450 dst_reg->type == PTR_TO_PACKET_END &&
3451 regs[insn->src_reg].type == PTR_TO_PACKET) {
3452 /* pkt_end <= pkt_data' */
3453 find_good_pkt_pointers(this_branch, ®s[insn->src_reg], true);
3454 } else if (is_pointer_value(env, insn->dst_reg)) {
3455 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
3459 print_verifier_state(this_branch);
3463 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3464 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3466 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3468 return (struct bpf_map *) (unsigned long) imm64;
3471 /* verify BPF_LD_IMM64 instruction */
3472 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3474 struct bpf_reg_state *regs = cur_regs(env);
3477 if (BPF_SIZE(insn->code) != BPF_DW) {
3478 verbose("invalid BPF_LD_IMM insn\n");
3481 if (insn->off != 0) {
3482 verbose("BPF_LD_IMM64 uses reserved fields\n");
3486 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3490 if (insn->src_reg == 0) {
3491 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3493 regs[insn->dst_reg].type = SCALAR_VALUE;
3494 __mark_reg_known(®s[insn->dst_reg], imm);
3498 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3499 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3501 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3502 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3506 static bool may_access_skb(enum bpf_prog_type type)
3509 case BPF_PROG_TYPE_SOCKET_FILTER:
3510 case BPF_PROG_TYPE_SCHED_CLS:
3511 case BPF_PROG_TYPE_SCHED_ACT:
3518 /* verify safety of LD_ABS|LD_IND instructions:
3519 * - they can only appear in the programs where ctx == skb
3520 * - since they are wrappers of function calls, they scratch R1-R5 registers,
3521 * preserve R6-R9, and store return value into R0
3524 * ctx == skb == R6 == CTX
3527 * SRC == any register
3528 * IMM == 32-bit immediate
3531 * R0 - 8/16/32-bit skb data converted to cpu endianness
3533 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3535 struct bpf_reg_state *regs = cur_regs(env);
3536 static const int ctx_reg = BPF_REG_6;
3537 u8 mode = BPF_MODE(insn->code);
3540 if (!may_access_skb(env->prog->type)) {
3541 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3545 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3546 BPF_SIZE(insn->code) == BPF_DW ||
3547 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3548 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
3552 /* check whether implicit source operand (register R6) is readable */
3553 err = check_reg_arg(env, ctx_reg, SRC_OP);
3557 if (regs[ctx_reg].type != PTR_TO_CTX) {
3558 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3562 if (mode == BPF_IND) {
3563 /* check explicit source operand */
3564 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3569 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
3573 /* reset caller saved regs to unreadable */
3574 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3575 mark_reg_not_init(regs, caller_saved[i]);
3576 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3579 /* mark destination R0 register as readable, since it contains
3580 * the value fetched from the packet.
3581 * Already marked as written above.
3583 mark_reg_unknown(regs, BPF_REG_0);
3587 /* non-recursive DFS pseudo code
3588 * 1 procedure DFS-iterative(G,v):
3589 * 2 label v as discovered
3590 * 3 let S be a stack
3592 * 5 while S is not empty
3594 * 7 if t is what we're looking for:
3596 * 9 for all edges e in G.adjacentEdges(t) do
3597 * 10 if edge e is already labelled
3598 * 11 continue with the next edge
3599 * 12 w <- G.adjacentVertex(t,e)
3600 * 13 if vertex w is not discovered and not explored
3601 * 14 label e as tree-edge
3602 * 15 label w as discovered
3605 * 18 else if vertex w is discovered
3606 * 19 label e as back-edge
3608 * 21 // vertex w is explored
3609 * 22 label e as forward- or cross-edge
3610 * 23 label t as explored
3615 * 0x11 - discovered and fall-through edge labelled
3616 * 0x12 - discovered and fall-through and branch edges labelled
3627 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3629 static int *insn_stack; /* stack of insns to process */
3630 static int cur_stack; /* current stack index */
3631 static int *insn_state;
3633 /* t, w, e - match pseudo-code above:
3634 * t - index of current instruction
3635 * w - next instruction
3638 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3640 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3643 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3646 if (w < 0 || w >= env->prog->len) {
3647 verbose("jump out of range from insn %d to %d\n", t, w);
3652 /* mark branch target for state pruning */
3653 env->explored_states[w] = STATE_LIST_MARK;
3655 if (insn_state[w] == 0) {
3657 insn_state[t] = DISCOVERED | e;
3658 insn_state[w] = DISCOVERED;
3659 if (cur_stack >= env->prog->len)
3661 insn_stack[cur_stack++] = w;
3663 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
3664 verbose("back-edge from insn %d to %d\n", t, w);
3666 } else if (insn_state[w] == EXPLORED) {
3667 /* forward- or cross-edge */
3668 insn_state[t] = DISCOVERED | e;
3670 verbose("insn state internal bug\n");
3676 /* non-recursive depth-first-search to detect loops in BPF program
3677 * loop == back-edge in directed graph
3679 static int check_cfg(struct bpf_verifier_env *env)
3681 struct bpf_insn *insns = env->prog->insnsi;
3682 int insn_cnt = env->prog->len;
3686 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3690 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3696 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
3697 insn_stack[0] = 0; /* 0 is the first instruction */
3703 t = insn_stack[cur_stack - 1];
3705 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
3706 u8 opcode = BPF_OP(insns[t].code);
3708 if (opcode == BPF_EXIT) {
3710 } else if (opcode == BPF_CALL) {
3711 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3716 if (t + 1 < insn_cnt)
3717 env->explored_states[t + 1] = STATE_LIST_MARK;
3718 } else if (opcode == BPF_JA) {
3719 if (BPF_SRC(insns[t].code) != BPF_K) {
3723 /* unconditional jump with single edge */
3724 ret = push_insn(t, t + insns[t].off + 1,
3730 /* tell verifier to check for equivalent states
3731 * after every call and jump
3733 if (t + 1 < insn_cnt)
3734 env->explored_states[t + 1] = STATE_LIST_MARK;
3736 /* conditional jump with two edges */
3737 env->explored_states[t] = STATE_LIST_MARK;
3738 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3744 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
3751 /* all other non-branch instructions with single
3754 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3762 insn_state[t] = EXPLORED;
3763 if (cur_stack-- <= 0) {
3764 verbose("pop stack internal bug\n");
3771 for (i = 0; i < insn_cnt; i++) {
3772 if (insn_state[i] != EXPLORED) {
3773 verbose("unreachable insn %d\n", i);
3778 ret = 0; /* cfg looks good */
3786 /* check %cur's range satisfies %old's */
3787 static bool range_within(struct bpf_reg_state *old,
3788 struct bpf_reg_state *cur)
3790 return old->umin_value <= cur->umin_value &&
3791 old->umax_value >= cur->umax_value &&
3792 old->smin_value <= cur->smin_value &&
3793 old->smax_value >= cur->smax_value;
3796 /* Maximum number of register states that can exist at once */
3797 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
3803 /* If in the old state two registers had the same id, then they need to have
3804 * the same id in the new state as well. But that id could be different from
3805 * the old state, so we need to track the mapping from old to new ids.
3806 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
3807 * regs with old id 5 must also have new id 9 for the new state to be safe. But
3808 * regs with a different old id could still have new id 9, we don't care about
3810 * So we look through our idmap to see if this old id has been seen before. If
3811 * so, we require the new id to match; otherwise, we add the id pair to the map.
3813 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
3817 for (i = 0; i < ID_MAP_SIZE; i++) {
3818 if (!idmap[i].old) {
3819 /* Reached an empty slot; haven't seen this id before */
3820 idmap[i].old = old_id;
3821 idmap[i].cur = cur_id;
3824 if (idmap[i].old == old_id)
3825 return idmap[i].cur == cur_id;
3827 /* We ran out of idmap slots, which should be impossible */
3832 /* Returns true if (rold safe implies rcur safe) */
3833 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
3834 struct idpair *idmap)
3836 if (!(rold->live & REG_LIVE_READ))
3837 /* explored state didn't use this */
3840 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
3843 if (rold->type == NOT_INIT)
3844 /* explored state can't have used this */
3846 if (rcur->type == NOT_INIT)
3848 switch (rold->type) {
3850 if (rcur->type == SCALAR_VALUE) {
3851 /* new val must satisfy old val knowledge */
3852 return range_within(rold, rcur) &&
3853 tnum_in(rold->var_off, rcur->var_off);
3855 /* We're trying to use a pointer in place of a scalar.
3856 * Even if the scalar was unbounded, this could lead to
3857 * pointer leaks because scalars are allowed to leak
3858 * while pointers are not. We could make this safe in
3859 * special cases if root is calling us, but it's
3860 * probably not worth the hassle.
3864 case PTR_TO_MAP_VALUE:
3865 /* If the new min/max/var_off satisfy the old ones and
3866 * everything else matches, we are OK.
3867 * We don't care about the 'id' value, because nothing
3868 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
3870 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
3871 range_within(rold, rcur) &&
3872 tnum_in(rold->var_off, rcur->var_off);
3873 case PTR_TO_MAP_VALUE_OR_NULL:
3874 /* a PTR_TO_MAP_VALUE could be safe to use as a
3875 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
3876 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
3877 * checked, doing so could have affected others with the same
3878 * id, and we can't check for that because we lost the id when
3879 * we converted to a PTR_TO_MAP_VALUE.
3881 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
3883 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
3885 /* Check our ids match any regs they're supposed to */
3886 return check_ids(rold->id, rcur->id, idmap);
3888 if (rcur->type != PTR_TO_PACKET)
3890 /* We must have at least as much range as the old ptr
3891 * did, so that any accesses which were safe before are
3892 * still safe. This is true even if old range < old off,
3893 * since someone could have accessed through (ptr - k), or
3894 * even done ptr -= k in a register, to get a safe access.
3896 if (rold->range > rcur->range)
3898 /* If the offsets don't match, we can't trust our alignment;
3899 * nor can we be sure that we won't fall out of range.
3901 if (rold->off != rcur->off)
3903 /* id relations must be preserved */
3904 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
3906 /* new val must satisfy old val knowledge */
3907 return range_within(rold, rcur) &&
3908 tnum_in(rold->var_off, rcur->var_off);
3910 case CONST_PTR_TO_MAP:
3912 case PTR_TO_PACKET_END:
3913 /* Only valid matches are exact, which memcmp() above
3914 * would have accepted
3917 /* Don't know what's going on, just say it's not safe */
3921 /* Shouldn't get here; if we do, say it's not safe */
3926 static bool stacksafe(struct bpf_verifier_state *old,
3927 struct bpf_verifier_state *cur,
3928 struct idpair *idmap)
3932 /* if explored stack has more populated slots than current stack
3933 * such stacks are not equivalent
3935 if (old->allocated_stack > cur->allocated_stack)
3938 /* walk slots of the explored stack and ignore any additional
3939 * slots in the current stack, since explored(safe) state
3942 for (i = 0; i < old->allocated_stack; i++) {
3943 spi = i / BPF_REG_SIZE;
3945 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
3947 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
3948 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
3949 /* Ex: old explored (safe) state has STACK_SPILL in
3950 * this stack slot, but current has has STACK_MISC ->
3951 * this verifier states are not equivalent,
3952 * return false to continue verification of this path
3955 if (i % BPF_REG_SIZE)
3957 if (old->stack[spi].slot_type[0] != STACK_SPILL)
3959 if (!regsafe(&old->stack[spi].spilled_ptr,
3960 &cur->stack[spi].spilled_ptr,
3962 /* when explored and current stack slot are both storing
3963 * spilled registers, check that stored pointers types
3964 * are the same as well.
3965 * Ex: explored safe path could have stored
3966 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
3967 * but current path has stored:
3968 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
3969 * such verifier states are not equivalent.
3970 * return false to continue verification of this path
3977 /* compare two verifier states
3979 * all states stored in state_list are known to be valid, since
3980 * verifier reached 'bpf_exit' instruction through them
3982 * this function is called when verifier exploring different branches of
3983 * execution popped from the state stack. If it sees an old state that has
3984 * more strict register state and more strict stack state then this execution
3985 * branch doesn't need to be explored further, since verifier already
3986 * concluded that more strict state leads to valid finish.
3988 * Therefore two states are equivalent if register state is more conservative
3989 * and explored stack state is more conservative than the current one.
3992 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
3993 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
3995 * In other words if current stack state (one being explored) has more
3996 * valid slots than old one that already passed validation, it means
3997 * the verifier can stop exploring and conclude that current state is valid too
3999 * Similarly with registers. If explored state has register type as invalid
4000 * whereas register type in current state is meaningful, it means that
4001 * the current state will reach 'bpf_exit' instruction safely
4003 static bool states_equal(struct bpf_verifier_env *env,
4004 struct bpf_verifier_state *old,
4005 struct bpf_verifier_state *cur)
4007 struct idpair *idmap;
4011 /* Verification state from speculative execution simulation
4012 * must never prune a non-speculative execution one.
4014 if (old->speculative && !cur->speculative)
4017 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4018 /* If we failed to allocate the idmap, just say it's not safe */
4022 for (i = 0; i < MAX_BPF_REG; i++) {
4023 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4027 if (!stacksafe(old, cur, idmap))
4035 /* A write screens off any subsequent reads; but write marks come from the
4036 * straight-line code between a state and its parent. When we arrive at a
4037 * jump target (in the first iteration of the propagate_liveness() loop),
4038 * we didn't arrive by the straight-line code, so read marks in state must
4039 * propagate to parent regardless of state's write marks.
4041 static bool do_propagate_liveness(const struct bpf_verifier_state *state,
4042 struct bpf_verifier_state *parent)
4044 bool writes = parent == state->parent; /* Observe write marks */
4045 bool touched = false; /* any changes made? */
4050 /* Propagate read liveness of registers... */
4051 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4052 /* We don't need to worry about FP liveness because it's read-only */
4053 for (i = 0; i < BPF_REG_FP; i++) {
4054 if (parent->regs[i].live & REG_LIVE_READ)
4056 if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
4058 if (state->regs[i].live & REG_LIVE_READ) {
4059 parent->regs[i].live |= REG_LIVE_READ;
4063 /* ... and stack slots */
4064 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4065 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4066 if (parent->stack[i].slot_type[0] != STACK_SPILL)
4068 if (state->stack[i].slot_type[0] != STACK_SPILL)
4070 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4073 (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
4075 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
4076 parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
4083 /* "parent" is "a state from which we reach the current state", but initially
4084 * it is not the state->parent (i.e. "the state whose straight-line code leads
4085 * to the current state"), instead it is the state that happened to arrive at
4086 * a (prunable) equivalent of the current state. See comment above
4087 * do_propagate_liveness() for consequences of this.
4088 * This function is just a more efficient way of calling mark_reg_read() or
4089 * mark_stack_slot_read() on each reg in "parent" that is read in "state",
4090 * though it requires that parent != state->parent in the call arguments.
4092 static void propagate_liveness(const struct bpf_verifier_state *state,
4093 struct bpf_verifier_state *parent)
4095 while (do_propagate_liveness(state, parent)) {
4096 /* Something changed, so we need to feed those changes onward */
4098 parent = state->parent;
4102 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4104 struct bpf_verifier_state_list *new_sl;
4105 struct bpf_verifier_state_list *sl;
4106 struct bpf_verifier_state *cur = env->cur_state;
4109 sl = env->explored_states[insn_idx];
4111 /* this 'insn_idx' instruction wasn't marked, so we will not
4112 * be doing state search here
4116 while (sl != STATE_LIST_MARK) {
4117 if (states_equal(env, &sl->state, cur)) {
4118 /* reached equivalent register/stack state,
4120 * Registers read by the continuation are read by us.
4121 * If we have any write marks in env->cur_state, they
4122 * will prevent corresponding reads in the continuation
4123 * from reaching our parent (an explored_state). Our
4124 * own state will get the read marks recorded, but
4125 * they'll be immediately forgotten as we're pruning
4126 * this state and will pop a new one.
4128 propagate_liveness(&sl->state, cur);
4134 /* there were no equivalent states, remember current one.
4135 * technically the current state is not proven to be safe yet,
4136 * but it will either reach bpf_exit (which means it's safe) or
4137 * it will be rejected. Since there are no loops, we won't be
4138 * seeing this 'insn_idx' instruction again on the way to bpf_exit
4140 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4144 /* add new state to the head of linked list */
4145 err = copy_verifier_state(&new_sl->state, cur);
4147 free_verifier_state(&new_sl->state, false);
4151 new_sl->next = env->explored_states[insn_idx];
4152 env->explored_states[insn_idx] = new_sl;
4153 /* connect new state to parentage chain */
4154 cur->parent = &new_sl->state;
4155 /* clear write marks in current state: the writes we did are not writes
4156 * our child did, so they don't screen off its reads from us.
4157 * (There are no read marks in current state, because reads always mark
4158 * their parent and current state never has children yet. Only
4159 * explored_states can get read marks.)
4161 for (i = 0; i < BPF_REG_FP; i++)
4162 cur->regs[i].live = REG_LIVE_NONE;
4163 for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
4164 if (cur->stack[i].slot_type[0] == STACK_SPILL)
4165 cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4169 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
4170 int insn_idx, int prev_insn_idx)
4172 if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
4175 return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
4178 static int do_check(struct bpf_verifier_env *env)
4180 struct bpf_verifier_state *state;
4181 struct bpf_insn *insns = env->prog->insnsi;
4182 struct bpf_reg_state *regs;
4183 int insn_cnt = env->prog->len;
4184 int insn_processed = 0;
4185 bool do_print_state = false;
4187 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4190 env->cur_state = state;
4191 init_reg_state(state->regs);
4192 state->parent = NULL;
4194 struct bpf_insn *insn;
4198 if (env->insn_idx >= insn_cnt) {
4199 verbose("invalid insn idx %d insn_cnt %d\n",
4200 env->insn_idx, insn_cnt);
4204 insn = &insns[env->insn_idx];
4205 class = BPF_CLASS(insn->code);
4207 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4208 verbose("BPF program is too large. Processed %d insn\n",
4213 err = is_state_visited(env, env->insn_idx);
4217 /* found equivalent state, can prune the search */
4220 verbose("\nfrom %d to %d%s: safe\n",
4221 env->prev_insn_idx, env->insn_idx,
4222 env->cur_state->speculative ?
4223 " (speculative execution)" : "");
4225 verbose("%d: safe\n", env->insn_idx);
4227 goto process_bpf_exit;
4233 if (log_level > 1 || (log_level && do_print_state)) {
4235 verbose("%d:", env->insn_idx);
4237 verbose("\nfrom %d to %d%s:",
4238 env->prev_insn_idx, env->insn_idx,
4239 env->cur_state->speculative ?
4240 " (speculative execution)" : "");
4241 print_verifier_state(env->cur_state);
4242 do_print_state = false;
4246 verbose("%d: ", env->insn_idx);
4247 print_bpf_insn(env, insn);
4250 err = ext_analyzer_insn_hook(env, env->insn_idx, env->prev_insn_idx);
4254 regs = cur_regs(env);
4255 env->insn_aux_data[env->insn_idx].seen = true;
4256 if (class == BPF_ALU || class == BPF_ALU64) {
4257 err = check_alu_op(env, insn);
4261 } else if (class == BPF_LDX) {
4262 enum bpf_reg_type *prev_src_type, src_reg_type;
4264 /* check for reserved fields is already done */
4266 /* check src operand */
4267 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4271 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4275 src_reg_type = regs[insn->src_reg].type;
4277 /* check that memory (src_reg + off) is readable,
4278 * the state of dst_reg will be updated by this func
4280 err = check_mem_access(env, env->insn_idx, insn->src_reg,
4281 insn->off, BPF_SIZE(insn->code),
4282 BPF_READ, insn->dst_reg, false);
4286 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
4288 if (*prev_src_type == NOT_INIT) {
4290 * dst_reg = *(u32 *)(src_reg + off)
4291 * save type to validate intersecting paths
4293 *prev_src_type = src_reg_type;
4295 } else if (src_reg_type != *prev_src_type &&
4296 (src_reg_type == PTR_TO_CTX ||
4297 *prev_src_type == PTR_TO_CTX)) {
4298 /* ABuser program is trying to use the same insn
4299 * dst_reg = *(u32*) (src_reg + off)
4300 * with different pointer types:
4301 * src_reg == ctx in one branch and
4302 * src_reg == stack|map in some other branch.
4305 verbose("same insn cannot be used with different pointers\n");
4309 } else if (class == BPF_STX) {
4310 enum bpf_reg_type *prev_dst_type, dst_reg_type;
4312 if (BPF_MODE(insn->code) == BPF_XADD) {
4313 err = check_xadd(env, env->insn_idx, insn);
4320 /* check src1 operand */
4321 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4324 /* check src2 operand */
4325 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4329 dst_reg_type = regs[insn->dst_reg].type;
4331 /* check that memory (dst_reg + off) is writeable */
4332 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
4333 insn->off, BPF_SIZE(insn->code),
4334 BPF_WRITE, insn->src_reg, false);
4338 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
4340 if (*prev_dst_type == NOT_INIT) {
4341 *prev_dst_type = dst_reg_type;
4342 } else if (dst_reg_type != *prev_dst_type &&
4343 (dst_reg_type == PTR_TO_CTX ||
4344 *prev_dst_type == PTR_TO_CTX)) {
4345 verbose("same insn cannot be used with different pointers\n");
4349 } else if (class == BPF_ST) {
4350 if (BPF_MODE(insn->code) != BPF_MEM ||
4351 insn->src_reg != BPF_REG_0) {
4352 verbose("BPF_ST uses reserved fields\n");
4355 /* check src operand */
4356 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4360 if (is_ctx_reg(env, insn->dst_reg)) {
4361 verbose("BPF_ST stores into R%d context is not allowed\n",
4366 /* check that memory (dst_reg + off) is writeable */
4367 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
4368 insn->off, BPF_SIZE(insn->code),
4369 BPF_WRITE, -1, false);
4373 } else if (class == BPF_JMP) {
4374 u8 opcode = BPF_OP(insn->code);
4376 if (opcode == BPF_CALL) {
4377 if (BPF_SRC(insn->code) != BPF_K ||
4379 insn->src_reg != BPF_REG_0 ||
4380 insn->dst_reg != BPF_REG_0) {
4381 verbose("BPF_CALL uses reserved fields\n");
4385 err = check_call(env, insn->imm, env->insn_idx);
4389 } else if (opcode == BPF_JA) {
4390 if (BPF_SRC(insn->code) != BPF_K ||
4392 insn->src_reg != BPF_REG_0 ||
4393 insn->dst_reg != BPF_REG_0) {
4394 verbose("BPF_JA uses reserved fields\n");
4398 env->insn_idx += insn->off + 1;
4401 } else if (opcode == BPF_EXIT) {
4402 if (BPF_SRC(insn->code) != BPF_K ||
4404 insn->src_reg != BPF_REG_0 ||
4405 insn->dst_reg != BPF_REG_0) {
4406 verbose("BPF_EXIT uses reserved fields\n");
4410 /* eBPF calling convetion is such that R0 is used
4411 * to return the value from eBPF program.
4412 * Make sure that it's readable at this time
4413 * of bpf_exit, which means that program wrote
4414 * something into it earlier
4416 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4420 if (is_pointer_value(env, BPF_REG_0)) {
4421 verbose("R0 leaks addr as return value\n");
4426 err = pop_stack(env, &env->prev_insn_idx, &env->insn_idx);
4432 do_print_state = true;
4436 err = check_cond_jmp_op(env, insn, &env->insn_idx);
4440 } else if (class == BPF_LD) {
4441 u8 mode = BPF_MODE(insn->code);
4443 if (mode == BPF_ABS || mode == BPF_IND) {
4444 err = check_ld_abs(env, insn);
4448 } else if (mode == BPF_IMM) {
4449 err = check_ld_imm(env, insn);
4454 env->insn_aux_data[env->insn_idx].seen = true;
4456 verbose("invalid BPF_LD mode\n");
4460 verbose("unknown insn class %d\n", class);
4467 verbose("processed %d insns, stack depth %d\n",
4468 insn_processed, env->prog->aux->stack_depth);
4472 static int check_map_prealloc(struct bpf_map *map)
4474 return (map->map_type != BPF_MAP_TYPE_HASH &&
4475 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4476 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4477 !(map->map_flags & BPF_F_NO_PREALLOC);
4480 static int check_map_prog_compatibility(struct bpf_map *map,
4481 struct bpf_prog *prog)
4484 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4485 * preallocated hash maps, since doing memory allocation
4486 * in overflow_handler can crash depending on where nmi got
4489 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4490 if (!check_map_prealloc(map)) {
4491 verbose("perf_event programs can only use preallocated hash map\n");
4494 if (map->inner_map_meta &&
4495 !check_map_prealloc(map->inner_map_meta)) {
4496 verbose("perf_event programs can only use preallocated inner hash map\n");
4503 /* look for pseudo eBPF instructions that access map FDs and
4504 * replace them with actual map pointers
4506 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4508 struct bpf_insn *insn = env->prog->insnsi;
4509 int insn_cnt = env->prog->len;
4512 err = bpf_prog_calc_tag(env->prog);
4516 for (i = 0; i < insn_cnt; i++, insn++) {
4517 if (BPF_CLASS(insn->code) == BPF_LDX &&
4518 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4519 verbose("BPF_LDX uses reserved fields\n");
4523 if (BPF_CLASS(insn->code) == BPF_STX &&
4524 ((BPF_MODE(insn->code) != BPF_MEM &&
4525 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4526 verbose("BPF_STX uses reserved fields\n");
4530 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4531 struct bpf_map *map;
4534 if (i == insn_cnt - 1 || insn[1].code != 0 ||
4535 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4537 verbose("invalid bpf_ld_imm64 insn\n");
4541 if (insn->src_reg == 0)
4542 /* valid generic load 64-bit imm */
4545 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4546 verbose("unrecognized bpf_ld_imm64 insn\n");
4550 f = fdget(insn->imm);
4551 map = __bpf_map_get(f);
4553 verbose("fd %d is not pointing to valid bpf_map\n",
4555 return PTR_ERR(map);
4558 err = check_map_prog_compatibility(map, env->prog);
4564 /* store map pointer inside BPF_LD_IMM64 instruction */
4565 insn[0].imm = (u32) (unsigned long) map;
4566 insn[1].imm = ((u64) (unsigned long) map) >> 32;
4568 /* check whether we recorded this map already */
4569 for (j = 0; j < env->used_map_cnt; j++)
4570 if (env->used_maps[j] == map) {
4575 if (env->used_map_cnt >= MAX_USED_MAPS) {
4580 /* hold the map. If the program is rejected by verifier,
4581 * the map will be released by release_maps() or it
4582 * will be used by the valid program until it's unloaded
4583 * and all maps are released in free_used_maps()
4585 map = bpf_map_inc(map, false);
4588 return PTR_ERR(map);
4590 env->used_maps[env->used_map_cnt++] = map;
4599 /* now all pseudo BPF_LD_IMM64 instructions load valid
4600 * 'struct bpf_map *' into a register instead of user map_fd.
4601 * These pointers will be used later by verifier to validate map access.
4606 /* drop refcnt of maps used by the rejected program */
4607 static void release_maps(struct bpf_verifier_env *env)
4611 for (i = 0; i < env->used_map_cnt; i++)
4612 bpf_map_put(env->used_maps[i]);
4615 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
4616 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
4618 struct bpf_insn *insn = env->prog->insnsi;
4619 int insn_cnt = env->prog->len;
4622 for (i = 0; i < insn_cnt; i++, insn++)
4623 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
4627 /* single env->prog->insni[off] instruction was replaced with the range
4628 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
4629 * [0, off) and [off, end) to new locations, so the patched range stays zero
4631 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
4634 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
4639 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
4642 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
4643 memcpy(new_data + off + cnt - 1, old_data + off,
4644 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
4645 for (i = off; i < off + cnt - 1; i++)
4646 new_data[i].seen = true;
4647 env->insn_aux_data = new_data;
4652 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
4653 const struct bpf_insn *patch, u32 len)
4655 struct bpf_prog *new_prog;
4657 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4660 if (adjust_insn_aux_data(env, new_prog->len, off, len))
4665 /* The verifier does more data flow analysis than llvm and will not explore
4666 * branches that are dead at run time. Malicious programs can have dead code
4667 * too. Therefore replace all dead at-run-time code with nops.
4669 static void sanitize_dead_code(struct bpf_verifier_env *env)
4671 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
4672 struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
4673 struct bpf_insn *insn = env->prog->insnsi;
4674 const int insn_cnt = env->prog->len;
4677 for (i = 0; i < insn_cnt; i++) {
4678 if (aux_data[i].seen)
4680 memcpy(insn + i, &nop, sizeof(nop));
4684 /* convert load instructions that access fields of 'struct __sk_buff'
4685 * into sequence of instructions that access fields of 'struct sk_buff'
4687 static int convert_ctx_accesses(struct bpf_verifier_env *env)
4689 const struct bpf_verifier_ops *ops = env->prog->aux->ops;
4690 int i, cnt, size, ctx_field_size, delta = 0;
4691 const int insn_cnt = env->prog->len;
4692 struct bpf_insn insn_buf[16], *insn;
4693 struct bpf_prog *new_prog;
4694 enum bpf_access_type type;
4695 bool is_narrower_load;
4698 if (ops->gen_prologue) {
4699 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
4701 if (cnt >= ARRAY_SIZE(insn_buf)) {
4702 verbose("bpf verifier is misconfigured\n");
4705 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
4709 env->prog = new_prog;
4714 if (!ops->convert_ctx_access)
4717 insn = env->prog->insnsi + delta;
4719 for (i = 0; i < insn_cnt; i++, insn++) {
4720 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
4721 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
4722 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
4723 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
4725 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
4726 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
4727 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
4728 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
4733 if (type == BPF_WRITE &&
4734 env->insn_aux_data[i + delta].sanitize_stack_off) {
4735 struct bpf_insn patch[] = {
4736 /* Sanitize suspicious stack slot with zero.
4737 * There are no memory dependencies for this store,
4738 * since it's only using frame pointer and immediate
4741 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
4742 env->insn_aux_data[i + delta].sanitize_stack_off,
4744 /* the original STX instruction will immediately
4745 * overwrite the same stack slot with appropriate value
4750 cnt = ARRAY_SIZE(patch);
4751 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
4756 env->prog = new_prog;
4757 insn = new_prog->insnsi + i + delta;
4761 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
4764 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
4765 size = BPF_LDST_BYTES(insn);
4767 /* If the read access is a narrower load of the field,
4768 * convert to a 4/8-byte load, to minimum program type specific
4769 * convert_ctx_access changes. If conversion is successful,
4770 * we will apply proper mask to the result.
4772 is_narrower_load = size < ctx_field_size;
4773 if (is_narrower_load) {
4774 u32 off = insn->off;
4777 if (type == BPF_WRITE) {
4778 verbose("bpf verifier narrow ctx access misconfigured\n");
4783 if (ctx_field_size == 4)
4785 else if (ctx_field_size == 8)
4788 insn->off = off & ~(ctx_field_size - 1);
4789 insn->code = BPF_LDX | BPF_MEM | size_code;
4793 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
4795 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
4796 (ctx_field_size && !target_size)) {
4797 verbose("bpf verifier is misconfigured\n");
4801 if (is_narrower_load && size < target_size) {
4802 if (ctx_field_size <= 4)
4803 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
4804 (1 << size * 8) - 1);
4806 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
4807 (1 << size * 8) - 1);
4810 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4816 /* keep walking new program and skip insns we just inserted */
4817 env->prog = new_prog;
4818 insn = new_prog->insnsi + i + delta;
4824 /* fixup insn->imm field of bpf_call instructions
4825 * and inline eligible helpers as explicit sequence of BPF instructions
4827 * this function is called after eBPF program passed verification
4829 static int fixup_bpf_calls(struct bpf_verifier_env *env)
4831 struct bpf_prog *prog = env->prog;
4832 struct bpf_insn *insn = prog->insnsi;
4833 const struct bpf_func_proto *fn;
4834 const int insn_cnt = prog->len;
4835 struct bpf_insn insn_buf[16];
4836 struct bpf_prog *new_prog;
4837 struct bpf_map *map_ptr;
4838 int i, cnt, delta = 0;
4839 struct bpf_insn_aux_data *aux;
4841 for (i = 0; i < insn_cnt; i++, insn++) {
4842 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
4843 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
4844 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
4845 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
4846 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
4847 struct bpf_insn mask_and_div[] = {
4848 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
4849 /* [R,W]x div 0 -> 0 */
4850 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 2),
4851 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
4852 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
4853 BPF_ALU_REG(BPF_CLASS(insn->code), BPF_XOR, insn->dst_reg, insn->dst_reg),
4855 struct bpf_insn mask_and_mod[] = {
4856 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
4857 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 1 + (is64 ? 0 : 1)),
4858 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
4859 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
4860 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
4862 struct bpf_insn *patchlet;
4864 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
4865 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
4866 patchlet = mask_and_div;
4867 cnt = ARRAY_SIZE(mask_and_div);
4869 patchlet = mask_and_mod;
4870 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 2 : 0);
4873 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
4878 env->prog = prog = new_prog;
4879 insn = new_prog->insnsi + i + delta;
4883 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
4884 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
4885 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
4886 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
4887 struct bpf_insn insn_buf[16];
4888 struct bpf_insn *patch = &insn_buf[0];
4889 bool issrc, isneg, isimm;
4892 aux = &env->insn_aux_data[i + delta];
4893 if (!aux->alu_state ||
4894 aux->alu_state == BPF_ALU_NON_POINTER)
4897 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
4898 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
4899 BPF_ALU_SANITIZE_SRC;
4900 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
4902 off_reg = issrc ? insn->src_reg : insn->dst_reg;
4904 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
4907 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
4908 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
4909 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
4910 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
4911 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
4912 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
4913 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
4916 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
4917 insn->src_reg = BPF_REG_AX;
4919 insn->code = insn->code == code_add ?
4920 code_sub : code_add;
4922 if (issrc && isneg && !isimm)
4923 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
4924 cnt = patch - insn_buf;
4926 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4931 env->prog = prog = new_prog;
4932 insn = new_prog->insnsi + i + delta;
4936 if (insn->code != (BPF_JMP | BPF_CALL))
4939 if (insn->imm == BPF_FUNC_get_route_realm)
4940 prog->dst_needed = 1;
4941 if (insn->imm == BPF_FUNC_get_prandom_u32)
4942 bpf_user_rnd_init_once();
4943 if (insn->imm == BPF_FUNC_tail_call) {
4944 /* If we tail call into other programs, we
4945 * cannot make any assumptions since they can
4946 * be replaced dynamically during runtime in
4947 * the program array.
4949 prog->cb_access = 1;
4950 env->prog->aux->stack_depth = MAX_BPF_STACK;
4952 /* mark bpf_tail_call as different opcode to avoid
4953 * conditional branch in the interpeter for every normal
4954 * call and to prevent accidental JITing by JIT compiler
4955 * that doesn't support bpf_tail_call yet
4958 insn->code = BPF_JMP | BPF_TAIL_CALL;
4960 /* instead of changing every JIT dealing with tail_call
4961 * emit two extra insns:
4962 * if (index >= max_entries) goto out;
4963 * index &= array->index_mask;
4964 * to avoid out-of-bounds cpu speculation
4966 map_ptr = env->insn_aux_data[i + delta].map_ptr;
4967 if (map_ptr == BPF_MAP_PTR_POISON) {
4968 verbose("tail_call obusing map_ptr\n");
4971 if (!map_ptr->unpriv_array)
4973 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
4974 map_ptr->max_entries, 2);
4975 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
4976 container_of(map_ptr,
4979 insn_buf[2] = *insn;
4981 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4986 env->prog = prog = new_prog;
4987 insn = new_prog->insnsi + i + delta;
4991 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
4992 * handlers are currently limited to 64 bit only.
4994 if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
4995 insn->imm == BPF_FUNC_map_lookup_elem) {
4996 map_ptr = env->insn_aux_data[i + delta].map_ptr;
4997 if (map_ptr == BPF_MAP_PTR_POISON ||
4998 !map_ptr->ops->map_gen_lookup)
4999 goto patch_call_imm;
5001 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
5002 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5003 verbose("bpf verifier is misconfigured\n");
5007 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
5014 /* keep walking new program and skip insns we just inserted */
5015 env->prog = prog = new_prog;
5016 insn = new_prog->insnsi + i + delta;
5020 if (insn->imm == BPF_FUNC_redirect_map) {
5021 /* Note, we cannot use prog directly as imm as subsequent
5022 * rewrites would still change the prog pointer. The only
5023 * stable address we can use is aux, which also works with
5024 * prog clones during blinding.
5026 u64 addr = (unsigned long)prog->aux;
5027 struct bpf_insn r4_ld[] = {
5028 BPF_LD_IMM64(BPF_REG_4, addr),
5031 cnt = ARRAY_SIZE(r4_ld);
5033 new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
5038 env->prog = prog = new_prog;
5039 insn = new_prog->insnsi + i + delta;
5042 fn = prog->aux->ops->get_func_proto(insn->imm);
5043 /* all functions that have prototype and verifier allowed
5044 * programs to call them, must be real in-kernel functions
5047 verbose("kernel subsystem misconfigured func %s#%d\n",
5048 func_id_name(insn->imm), insn->imm);
5051 insn->imm = fn->func - __bpf_call_base;
5057 static void free_states(struct bpf_verifier_env *env)
5059 struct bpf_verifier_state_list *sl, *sln;
5062 if (!env->explored_states)
5065 for (i = 0; i < env->prog->len; i++) {
5066 sl = env->explored_states[i];
5069 while (sl != STATE_LIST_MARK) {
5071 free_verifier_state(&sl->state, false);
5077 kfree(env->explored_states);
5080 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5082 char __user *log_ubuf = NULL;
5083 struct bpf_verifier_env *env;
5086 /* 'struct bpf_verifier_env' can be global, but since it's not small,
5087 * allocate/free it every time bpf_check() is called
5089 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5093 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5096 if (!env->insn_aux_data)
5100 /* grab the mutex to protect few globals used by verifier */
5101 mutex_lock(&bpf_verifier_lock);
5103 if (attr->log_level || attr->log_buf || attr->log_size) {
5104 /* user requested verbose verifier output
5105 * and supplied buffer to store the verification trace
5107 log_level = attr->log_level;
5108 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
5109 log_size = attr->log_size;
5113 /* log_* values have to be sane */
5114 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
5115 log_level == 0 || log_ubuf == NULL)
5119 log_buf = vmalloc(log_size);
5126 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5127 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5128 env->strict_alignment = true;
5130 ret = replace_map_fd_with_map_ptr(env);
5132 goto skip_full_check;
5134 env->explored_states = kcalloc(env->prog->len,
5135 sizeof(struct bpf_verifier_state_list *),
5138 if (!env->explored_states)
5139 goto skip_full_check;
5141 ret = check_cfg(env);
5143 goto skip_full_check;
5145 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5147 ret = do_check(env);
5148 if (env->cur_state) {
5149 free_verifier_state(env->cur_state, true);
5150 env->cur_state = NULL;
5154 while (!pop_stack(env, NULL, NULL));
5158 sanitize_dead_code(env);
5161 /* program is valid, convert *(u32*)(ctx + off) accesses */
5162 ret = convert_ctx_accesses(env);
5165 ret = fixup_bpf_calls(env);
5167 if (log_level && log_len >= log_size - 1) {
5168 BUG_ON(log_len >= log_size);
5169 /* verifier log exceeded user supplied buffer */
5171 /* fall through to return what was recorded */
5174 /* copy verifier log back to user space including trailing zero */
5175 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
5180 if (ret == 0 && env->used_map_cnt) {
5181 /* if program passed verifier, update used_maps in bpf_prog_info */
5182 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5183 sizeof(env->used_maps[0]),
5186 if (!env->prog->aux->used_maps) {
5191 memcpy(env->prog->aux->used_maps, env->used_maps,
5192 sizeof(env->used_maps[0]) * env->used_map_cnt);
5193 env->prog->aux->used_map_cnt = env->used_map_cnt;
5195 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
5196 * bpf_ld_imm64 instructions
5198 convert_pseudo_ld_imm64(env);
5204 if (!env->prog->aux->used_maps)
5205 /* if we didn't copy map pointers into bpf_prog_info, release
5206 * them now. Otherwise free_used_maps() will release them.
5211 mutex_unlock(&bpf_verifier_lock);
5212 vfree(env->insn_aux_data);
5218 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
5221 struct bpf_verifier_env *env;
5224 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5228 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5231 if (!env->insn_aux_data)
5234 env->analyzer_ops = ops;
5235 env->analyzer_priv = priv;
5237 /* grab the mutex to protect few globals used by verifier */
5238 mutex_lock(&bpf_verifier_lock);
5242 env->strict_alignment = false;
5243 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5244 env->strict_alignment = true;
5246 env->explored_states = kcalloc(env->prog->len,
5247 sizeof(struct bpf_verifier_state_list *),
5250 if (!env->explored_states)
5251 goto skip_full_check;
5253 ret = check_cfg(env);
5255 goto skip_full_check;
5257 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5259 ret = do_check(env);
5260 if (env->cur_state) {
5261 free_verifier_state(env->cur_state, true);
5262 env->cur_state = NULL;
5266 while (!pop_stack(env, NULL, NULL));
5269 mutex_unlock(&bpf_verifier_lock);
5270 vfree(env->insn_aux_data);
5275 EXPORT_SYMBOL_GPL(bpf_analyzer);