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>
23 #include <linux/bsearch.h>
24 #include <linux/sort.h>
25 #include <linux/perf_event.h>
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name) \
31 [_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #include <linux/bpf_types.h>
38 /* bpf_check() is a static code analyzer that walks eBPF program
39 * instruction by instruction and updates register/stack state.
40 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 * The first pass is depth-first-search to check that the program is a DAG.
43 * It rejects the following programs:
44 * - larger than BPF_MAXINSNS insns
45 * - if loop is present (detected via back-edge)
46 * - unreachable insns exist (shouldn't be a forest. program = one function)
47 * - out of bounds or malformed jumps
48 * The second pass is all possible path descent from the 1st insn.
49 * Since it's analyzing all pathes through the program, the length of the
50 * analysis is limited to 64k insn, which may be hit even if total number of
51 * insn is less then 4K, but there are too many branches that change stack/regs.
52 * Number of 'branches to be analyzed' is limited to 1k
54 * On entry to each instruction, each register has a type, and the instruction
55 * changes the types of the registers depending on instruction semantics.
56 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59 * All registers are 64-bit.
60 * R0 - return register
61 * R1-R5 argument passing registers
62 * R6-R9 callee saved registers
63 * R10 - frame pointer read-only
65 * At the start of BPF program the register R1 contains a pointer to bpf_context
66 * and has type PTR_TO_CTX.
68 * Verifier tracks arithmetic operations on pointers in case:
69 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
70 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
71 * 1st insn copies R10 (which has FRAME_PTR) type into R1
72 * and 2nd arithmetic instruction is pattern matched to recognize
73 * that it wants to construct a pointer to some element within stack.
74 * So after 2nd insn, the register R1 has type PTR_TO_STACK
75 * (and -20 constant is saved for further stack bounds checking).
76 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 * Most of the time the registers have SCALAR_VALUE type, which
79 * means the register has some value, but it's not a valid pointer.
80 * (like pointer plus pointer becomes SCALAR_VALUE type)
82 * When verifier sees load or store instructions the type of base register
83 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
84 * types recognized by check_mem_access() function.
86 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
87 * and the range of [ptr, ptr + map's value_size) is accessible.
89 * registers used to pass values to function calls are checked against
90 * function argument constraints.
92 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
93 * It means that the register type passed to this function must be
94 * PTR_TO_STACK and it will be used inside the function as
95 * 'pointer to map element key'
97 * For example the argument constraints for bpf_map_lookup_elem():
98 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
99 * .arg1_type = ARG_CONST_MAP_PTR,
100 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 * ret_type says that this function returns 'pointer to map elem value or null'
103 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
104 * 2nd argument should be a pointer to stack, which will be used inside
105 * the helper function as a pointer to map element key.
107 * On the kernel side the helper function looks like:
108 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
111 * void *key = (void *) (unsigned long) r2;
114 * here kernel can access 'key' and 'map' pointers safely, knowing that
115 * [key, key + map->key_size) bytes are valid and were initialized on
116 * the stack of eBPF program.
119 * Corresponding eBPF program may look like:
120 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
121 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
122 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
123 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
124 * here verifier looks at prototype of map_lookup_elem() and sees:
125 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
126 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
129 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
130 * and were initialized prior to this call.
131 * If it's ok, then verifier allows this BPF_CALL insn and looks at
132 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
133 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
134 * returns ether pointer to map value or NULL.
136 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
137 * insn, the register holding that pointer in the true branch changes state to
138 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
139 * branch. See check_cond_jmp_op().
141 * After the call R0 is set to return type of the function and registers R1-R5
142 * are set to NOT_INIT to indicate that they are no longer readable.
145 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
146 struct bpf_verifier_stack_elem {
147 /* verifer state is 'st'
148 * before processing instruction 'insn_idx'
149 * and after processing instruction 'prev_insn_idx'
151 struct bpf_verifier_state st;
154 struct bpf_verifier_stack_elem *next;
157 #define BPF_COMPLEXITY_LIMIT_INSNS 131072
158 #define BPF_COMPLEXITY_LIMIT_STACK 1024
159 #define BPF_COMPLEXITY_LIMIT_STATES 64
161 #define BPF_MAP_PTR_UNPRIV 1UL
162 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
163 POISON_POINTER_DELTA))
164 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
166 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
168 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
171 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
173 return aux->map_state & BPF_MAP_PTR_UNPRIV;
176 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
177 const struct bpf_map *map, bool unpriv)
179 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
180 unpriv |= bpf_map_ptr_unpriv(aux);
181 aux->map_state = (unsigned long)map |
182 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
185 struct bpf_call_arg_meta {
186 struct bpf_map *map_ptr;
191 s64 msize_smax_value;
192 u64 msize_umax_value;
195 static DEFINE_MUTEX(bpf_verifier_lock);
197 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
202 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
204 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
205 "verifier log line truncated - local buffer too short\n");
207 n = min(log->len_total - log->len_used - 1, n);
210 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
216 /* log_level controls verbosity level of eBPF verifier.
217 * bpf_verifier_log_write() is used to dump the verification trace to the log,
218 * so the user can figure out what's wrong with the program
220 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
221 const char *fmt, ...)
225 if (!bpf_verifier_log_needed(&env->log))
229 bpf_verifier_vlog(&env->log, fmt, args);
232 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
234 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
236 struct bpf_verifier_env *env = private_data;
239 if (!bpf_verifier_log_needed(&env->log))
243 bpf_verifier_vlog(&env->log, fmt, args);
247 static bool type_is_pkt_pointer(enum bpf_reg_type type)
249 return type == PTR_TO_PACKET ||
250 type == PTR_TO_PACKET_META;
253 /* string representation of 'enum bpf_reg_type' */
254 static const char * const reg_type_str[] = {
256 [SCALAR_VALUE] = "inv",
257 [PTR_TO_CTX] = "ctx",
258 [CONST_PTR_TO_MAP] = "map_ptr",
259 [PTR_TO_MAP_VALUE] = "map_value",
260 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
261 [PTR_TO_STACK] = "fp",
262 [PTR_TO_PACKET] = "pkt",
263 [PTR_TO_PACKET_META] = "pkt_meta",
264 [PTR_TO_PACKET_END] = "pkt_end",
267 static void print_liveness(struct bpf_verifier_env *env,
268 enum bpf_reg_liveness live)
270 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
272 if (live & REG_LIVE_READ)
274 if (live & REG_LIVE_WRITTEN)
278 static struct bpf_func_state *func(struct bpf_verifier_env *env,
279 const struct bpf_reg_state *reg)
281 struct bpf_verifier_state *cur = env->cur_state;
283 return cur->frame[reg->frameno];
286 static void print_verifier_state(struct bpf_verifier_env *env,
287 const struct bpf_func_state *state)
289 const struct bpf_reg_state *reg;
294 verbose(env, " frame%d:", state->frameno);
295 for (i = 0; i < MAX_BPF_REG; i++) {
296 reg = &state->regs[i];
300 verbose(env, " R%d", i);
301 print_liveness(env, reg->live);
302 verbose(env, "=%s", reg_type_str[t]);
303 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
304 tnum_is_const(reg->var_off)) {
305 /* reg->off should be 0 for SCALAR_VALUE */
306 verbose(env, "%lld", reg->var_off.value + reg->off);
307 if (t == PTR_TO_STACK)
308 verbose(env, ",call_%d", func(env, reg)->callsite);
310 verbose(env, "(id=%d", reg->id);
311 if (t != SCALAR_VALUE)
312 verbose(env, ",off=%d", reg->off);
313 if (type_is_pkt_pointer(t))
314 verbose(env, ",r=%d", reg->range);
315 else if (t == CONST_PTR_TO_MAP ||
316 t == PTR_TO_MAP_VALUE ||
317 t == PTR_TO_MAP_VALUE_OR_NULL)
318 verbose(env, ",ks=%d,vs=%d",
319 reg->map_ptr->key_size,
320 reg->map_ptr->value_size);
321 if (tnum_is_const(reg->var_off)) {
322 /* Typically an immediate SCALAR_VALUE, but
323 * could be a pointer whose offset is too big
326 verbose(env, ",imm=%llx", reg->var_off.value);
328 if (reg->smin_value != reg->umin_value &&
329 reg->smin_value != S64_MIN)
330 verbose(env, ",smin_value=%lld",
331 (long long)reg->smin_value);
332 if (reg->smax_value != reg->umax_value &&
333 reg->smax_value != S64_MAX)
334 verbose(env, ",smax_value=%lld",
335 (long long)reg->smax_value);
336 if (reg->umin_value != 0)
337 verbose(env, ",umin_value=%llu",
338 (unsigned long long)reg->umin_value);
339 if (reg->umax_value != U64_MAX)
340 verbose(env, ",umax_value=%llu",
341 (unsigned long long)reg->umax_value);
342 if (!tnum_is_unknown(reg->var_off)) {
345 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
346 verbose(env, ",var_off=%s", tn_buf);
352 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
353 if (state->stack[i].slot_type[0] == STACK_SPILL) {
354 verbose(env, " fp%d",
355 (-i - 1) * BPF_REG_SIZE);
356 print_liveness(env, state->stack[i].spilled_ptr.live);
358 reg_type_str[state->stack[i].spilled_ptr.type]);
360 if (state->stack[i].slot_type[0] == STACK_ZERO)
361 verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
366 static int copy_stack_state(struct bpf_func_state *dst,
367 const struct bpf_func_state *src)
371 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
372 /* internal bug, make state invalid to reject the program */
373 memset(dst, 0, sizeof(*dst));
376 memcpy(dst->stack, src->stack,
377 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
381 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
382 * make it consume minimal amount of memory. check_stack_write() access from
383 * the program calls into realloc_func_state() to grow the stack size.
384 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
385 * which this function copies over. It points to previous bpf_verifier_state
386 * which is never reallocated
388 static int realloc_func_state(struct bpf_func_state *state, int size,
391 u32 old_size = state->allocated_stack;
392 struct bpf_stack_state *new_stack;
393 int slot = size / BPF_REG_SIZE;
395 if (size <= old_size || !size) {
398 state->allocated_stack = slot * BPF_REG_SIZE;
399 if (!size && old_size) {
405 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
411 memcpy(new_stack, state->stack,
412 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
413 memset(new_stack + old_size / BPF_REG_SIZE, 0,
414 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
416 state->allocated_stack = slot * BPF_REG_SIZE;
418 state->stack = new_stack;
422 static void free_func_state(struct bpf_func_state *state)
430 static void free_verifier_state(struct bpf_verifier_state *state,
435 for (i = 0; i <= state->curframe; i++) {
436 free_func_state(state->frame[i]);
437 state->frame[i] = NULL;
443 /* copy verifier state from src to dst growing dst stack space
444 * when necessary to accommodate larger src stack
446 static int copy_func_state(struct bpf_func_state *dst,
447 const struct bpf_func_state *src)
451 err = realloc_func_state(dst, src->allocated_stack, false);
454 memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
455 return copy_stack_state(dst, src);
458 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
459 const struct bpf_verifier_state *src)
461 struct bpf_func_state *dst;
464 /* if dst has more stack frames then src frame, free them */
465 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
466 free_func_state(dst_state->frame[i]);
467 dst_state->frame[i] = NULL;
469 dst_state->speculative = src->speculative;
470 dst_state->curframe = src->curframe;
471 dst_state->parent = src->parent;
472 for (i = 0; i <= src->curframe; i++) {
473 dst = dst_state->frame[i];
475 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
478 dst_state->frame[i] = dst;
480 err = copy_func_state(dst, src->frame[i]);
487 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
490 struct bpf_verifier_state *cur = env->cur_state;
491 struct bpf_verifier_stack_elem *elem, *head = env->head;
494 if (env->head == NULL)
498 err = copy_verifier_state(cur, &head->st);
503 *insn_idx = head->insn_idx;
505 *prev_insn_idx = head->prev_insn_idx;
507 free_verifier_state(&head->st, false);
514 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
515 int insn_idx, int prev_insn_idx,
518 struct bpf_verifier_state *cur = env->cur_state;
519 struct bpf_verifier_stack_elem *elem;
522 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
526 elem->insn_idx = insn_idx;
527 elem->prev_insn_idx = prev_insn_idx;
528 elem->next = env->head;
531 err = copy_verifier_state(&elem->st, cur);
534 elem->st.speculative |= speculative;
535 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
536 verbose(env, "BPF program is too complex\n");
541 free_verifier_state(env->cur_state, true);
542 env->cur_state = NULL;
543 /* pop all elements and return */
544 while (!pop_stack(env, NULL, NULL));
548 #define CALLER_SAVED_REGS 6
549 static const int caller_saved[CALLER_SAVED_REGS] = {
550 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
553 static void __mark_reg_not_init(struct bpf_reg_state *reg);
555 /* Mark the unknown part of a register (variable offset or scalar value) as
556 * known to have the value @imm.
558 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
560 /* Clear id, off, and union(map_ptr, range) */
561 memset(((u8 *)reg) + sizeof(reg->type), 0,
562 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
563 reg->var_off = tnum_const(imm);
564 reg->smin_value = (s64)imm;
565 reg->smax_value = (s64)imm;
566 reg->umin_value = imm;
567 reg->umax_value = imm;
570 /* Mark the 'variable offset' part of a register as zero. This should be
571 * used only on registers holding a pointer type.
573 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
575 __mark_reg_known(reg, 0);
578 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
580 __mark_reg_known(reg, 0);
581 reg->type = SCALAR_VALUE;
584 static void mark_reg_known_zero(struct bpf_verifier_env *env,
585 struct bpf_reg_state *regs, u32 regno)
587 if (WARN_ON(regno >= MAX_BPF_REG)) {
588 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
589 /* Something bad happened, let's kill all regs */
590 for (regno = 0; regno < MAX_BPF_REG; regno++)
591 __mark_reg_not_init(regs + regno);
594 __mark_reg_known_zero(regs + regno);
597 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
599 return type_is_pkt_pointer(reg->type);
602 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
604 return reg_is_pkt_pointer(reg) ||
605 reg->type == PTR_TO_PACKET_END;
608 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
609 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
610 enum bpf_reg_type which)
612 /* The register can already have a range from prior markings.
613 * This is fine as long as it hasn't been advanced from its
616 return reg->type == which &&
619 tnum_equals_const(reg->var_off, 0);
622 /* Attempts to improve min/max values based on var_off information */
623 static void __update_reg_bounds(struct bpf_reg_state *reg)
625 /* min signed is max(sign bit) | min(other bits) */
626 reg->smin_value = max_t(s64, reg->smin_value,
627 reg->var_off.value | (reg->var_off.mask & S64_MIN));
628 /* max signed is min(sign bit) | max(other bits) */
629 reg->smax_value = min_t(s64, reg->smax_value,
630 reg->var_off.value | (reg->var_off.mask & S64_MAX));
631 reg->umin_value = max(reg->umin_value, reg->var_off.value);
632 reg->umax_value = min(reg->umax_value,
633 reg->var_off.value | reg->var_off.mask);
636 /* Uses signed min/max values to inform unsigned, and vice-versa */
637 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
639 /* Learn sign from signed bounds.
640 * If we cannot cross the sign boundary, then signed and unsigned bounds
641 * are the same, so combine. This works even in the negative case, e.g.
642 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
644 if (reg->smin_value >= 0 || reg->smax_value < 0) {
645 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
647 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
651 /* Learn sign from unsigned bounds. Signed bounds cross the sign
652 * boundary, so we must be careful.
654 if ((s64)reg->umax_value >= 0) {
655 /* Positive. We can't learn anything from the smin, but smax
656 * is positive, hence safe.
658 reg->smin_value = reg->umin_value;
659 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
661 } else if ((s64)reg->umin_value < 0) {
662 /* Negative. We can't learn anything from the smax, but smin
663 * is negative, hence safe.
665 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
667 reg->smax_value = reg->umax_value;
671 /* Attempts to improve var_off based on unsigned min/max information */
672 static void __reg_bound_offset(struct bpf_reg_state *reg)
674 reg->var_off = tnum_intersect(reg->var_off,
675 tnum_range(reg->umin_value,
679 /* Reset the min/max bounds of a register */
680 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
682 reg->smin_value = S64_MIN;
683 reg->smax_value = S64_MAX;
685 reg->umax_value = U64_MAX;
688 /* Mark a register as having a completely unknown (scalar) value. */
689 static void __mark_reg_unknown(struct bpf_reg_state *reg)
692 * Clear type, id, off, and union(map_ptr, range) and
693 * padding between 'type' and union
695 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
696 reg->type = SCALAR_VALUE;
697 reg->var_off = tnum_unknown;
699 __mark_reg_unbounded(reg);
702 static void mark_reg_unknown(struct bpf_verifier_env *env,
703 struct bpf_reg_state *regs, u32 regno)
705 if (WARN_ON(regno >= MAX_BPF_REG)) {
706 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
707 /* Something bad happened, let's kill all regs except FP */
708 for (regno = 0; regno < BPF_REG_FP; regno++)
709 __mark_reg_not_init(regs + regno);
712 __mark_reg_unknown(regs + regno);
715 static void __mark_reg_not_init(struct bpf_reg_state *reg)
717 __mark_reg_unknown(reg);
718 reg->type = NOT_INIT;
721 static void mark_reg_not_init(struct bpf_verifier_env *env,
722 struct bpf_reg_state *regs, u32 regno)
724 if (WARN_ON(regno >= MAX_BPF_REG)) {
725 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
726 /* Something bad happened, let's kill all regs except FP */
727 for (regno = 0; regno < BPF_REG_FP; regno++)
728 __mark_reg_not_init(regs + regno);
731 __mark_reg_not_init(regs + regno);
734 static void init_reg_state(struct bpf_verifier_env *env,
735 struct bpf_func_state *state)
737 struct bpf_reg_state *regs = state->regs;
740 for (i = 0; i < MAX_BPF_REG; i++) {
741 mark_reg_not_init(env, regs, i);
742 regs[i].live = REG_LIVE_NONE;
746 regs[BPF_REG_FP].type = PTR_TO_STACK;
747 mark_reg_known_zero(env, regs, BPF_REG_FP);
748 regs[BPF_REG_FP].frameno = state->frameno;
750 /* 1st arg to a function */
751 regs[BPF_REG_1].type = PTR_TO_CTX;
752 mark_reg_known_zero(env, regs, BPF_REG_1);
755 #define BPF_MAIN_FUNC (-1)
756 static void init_func_state(struct bpf_verifier_env *env,
757 struct bpf_func_state *state,
758 int callsite, int frameno, int subprogno)
760 state->callsite = callsite;
761 state->frameno = frameno;
762 state->subprogno = subprogno;
763 init_reg_state(env, state);
767 SRC_OP, /* register is used as source operand */
768 DST_OP, /* register is used as destination operand */
769 DST_OP_NO_MARK /* same as above, check only, don't mark */
772 static int cmp_subprogs(const void *a, const void *b)
774 return ((struct bpf_subprog_info *)a)->start -
775 ((struct bpf_subprog_info *)b)->start;
778 static int find_subprog(struct bpf_verifier_env *env, int off)
780 struct bpf_subprog_info *p;
782 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
783 sizeof(env->subprog_info[0]), cmp_subprogs);
786 return p - env->subprog_info;
790 static int add_subprog(struct bpf_verifier_env *env, int off)
792 int insn_cnt = env->prog->len;
795 if (off >= insn_cnt || off < 0) {
796 verbose(env, "call to invalid destination\n");
799 ret = find_subprog(env, off);
802 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
803 verbose(env, "too many subprograms\n");
806 env->subprog_info[env->subprog_cnt++].start = off;
807 sort(env->subprog_info, env->subprog_cnt,
808 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
812 static int check_subprogs(struct bpf_verifier_env *env)
814 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
815 struct bpf_subprog_info *subprog = env->subprog_info;
816 struct bpf_insn *insn = env->prog->insnsi;
817 int insn_cnt = env->prog->len;
819 /* Add entry function. */
820 ret = add_subprog(env, 0);
824 /* determine subprog starts. The end is one before the next starts */
825 for (i = 0; i < insn_cnt; i++) {
826 if (insn[i].code != (BPF_JMP | BPF_CALL))
828 if (insn[i].src_reg != BPF_PSEUDO_CALL)
830 if (!env->allow_ptr_leaks) {
831 verbose(env, "function calls to other bpf functions are allowed for root only\n");
834 if (bpf_prog_is_dev_bound(env->prog->aux)) {
835 verbose(env, "function calls in offloaded programs are not supported yet\n");
838 ret = add_subprog(env, i + insn[i].imm + 1);
843 /* Add a fake 'exit' subprog which could simplify subprog iteration
844 * logic. 'subprog_cnt' should not be increased.
846 subprog[env->subprog_cnt].start = insn_cnt;
848 if (env->log.level > 1)
849 for (i = 0; i < env->subprog_cnt; i++)
850 verbose(env, "func#%d @%d\n", i, subprog[i].start);
852 /* now check that all jumps are within the same subprog */
853 subprog_start = subprog[cur_subprog].start;
854 subprog_end = subprog[cur_subprog + 1].start;
855 for (i = 0; i < insn_cnt; i++) {
856 u8 code = insn[i].code;
858 if (BPF_CLASS(code) != BPF_JMP)
860 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
862 off = i + insn[i].off + 1;
863 if (off < subprog_start || off >= subprog_end) {
864 verbose(env, "jump out of range from insn %d to %d\n", i, off);
868 if (i == subprog_end - 1) {
869 /* to avoid fall-through from one subprog into another
870 * the last insn of the subprog should be either exit
871 * or unconditional jump back
873 if (code != (BPF_JMP | BPF_EXIT) &&
874 code != (BPF_JMP | BPF_JA)) {
875 verbose(env, "last insn is not an exit or jmp\n");
878 subprog_start = subprog_end;
880 if (cur_subprog < env->subprog_cnt)
881 subprog_end = subprog[cur_subprog + 1].start;
888 struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
889 const struct bpf_verifier_state *state,
890 struct bpf_verifier_state *parent,
893 struct bpf_verifier_state *tmp = NULL;
895 /* 'parent' could be a state of caller and
896 * 'state' could be a state of callee. In such case
897 * parent->curframe < state->curframe
898 * and it's ok for r1 - r5 registers
900 * 'parent' could be a callee's state after it bpf_exit-ed.
901 * In such case parent->curframe > state->curframe
902 * and it's ok for r0 only
904 if (parent->curframe == state->curframe ||
905 (parent->curframe < state->curframe &&
906 regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
907 (parent->curframe > state->curframe &&
911 if (parent->curframe > state->curframe &&
912 regno >= BPF_REG_6) {
913 /* for callee saved regs we have to skip the whole chain
914 * of states that belong to callee and mark as LIVE_READ
915 * the registers before the call
918 while (tmp && tmp->curframe != state->curframe) {
929 verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
930 verbose(env, "regno %d parent frame %d current frame %d\n",
931 regno, parent->curframe, state->curframe);
935 static int mark_reg_read(struct bpf_verifier_env *env,
936 const struct bpf_verifier_state *state,
937 struct bpf_verifier_state *parent,
940 bool writes = parent == state->parent; /* Observe write marks */
942 if (regno == BPF_REG_FP)
943 /* We don't need to worry about FP liveness because it's read-only */
947 /* if read wasn't screened by an earlier write ... */
948 if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
950 parent = skip_callee(env, state, parent, regno);
953 /* ... then we depend on parent's value */
954 parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
956 parent = state->parent;
962 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
965 struct bpf_verifier_state *vstate = env->cur_state;
966 struct bpf_func_state *state = vstate->frame[vstate->curframe];
967 struct bpf_reg_state *regs = state->regs;
969 if (regno >= MAX_BPF_REG) {
970 verbose(env, "R%d is invalid\n", regno);
975 /* check whether register used as source operand can be read */
976 if (regs[regno].type == NOT_INIT) {
977 verbose(env, "R%d !read_ok\n", regno);
980 return mark_reg_read(env, vstate, vstate->parent, regno);
982 /* check whether register used as dest operand can be written to */
983 if (regno == BPF_REG_FP) {
984 verbose(env, "frame pointer is read only\n");
987 regs[regno].live |= REG_LIVE_WRITTEN;
989 mark_reg_unknown(env, regs, regno);
994 static bool is_spillable_regtype(enum bpf_reg_type type)
997 case PTR_TO_MAP_VALUE:
998 case PTR_TO_MAP_VALUE_OR_NULL:
1002 case PTR_TO_PACKET_META:
1003 case PTR_TO_PACKET_END:
1004 case CONST_PTR_TO_MAP:
1011 /* Does this register contain a constant zero? */
1012 static bool register_is_null(struct bpf_reg_state *reg)
1014 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1017 /* check_stack_read/write functions track spill/fill of registers,
1018 * stack boundary and alignment are checked in check_mem_access()
1020 static int check_stack_write(struct bpf_verifier_env *env,
1021 struct bpf_func_state *state, /* func where register points to */
1022 int off, int size, int value_regno, int insn_idx)
1024 struct bpf_func_state *cur; /* state of the current function */
1025 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
1026 enum bpf_reg_type type;
1028 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
1032 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1033 * so it's aligned access and [off, off + size) are within stack limits
1035 if (!env->allow_ptr_leaks &&
1036 state->stack[spi].slot_type[0] == STACK_SPILL &&
1037 size != BPF_REG_SIZE) {
1038 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1042 cur = env->cur_state->frame[env->cur_state->curframe];
1043 if (value_regno >= 0 &&
1044 is_spillable_regtype((type = cur->regs[value_regno].type))) {
1046 /* register containing pointer is being spilled into stack */
1047 if (size != BPF_REG_SIZE) {
1048 verbose(env, "invalid size of register spill\n");
1052 if (state != cur && type == PTR_TO_STACK) {
1053 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1057 /* save register state */
1058 state->stack[spi].spilled_ptr = cur->regs[value_regno];
1059 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1061 for (i = 0; i < BPF_REG_SIZE; i++) {
1062 if (state->stack[spi].slot_type[i] == STACK_MISC &&
1063 !env->allow_ptr_leaks) {
1064 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1065 int soff = (-spi - 1) * BPF_REG_SIZE;
1067 /* detected reuse of integer stack slot with a pointer
1068 * which means either llvm is reusing stack slot or
1069 * an attacker is trying to exploit CVE-2018-3639
1070 * (speculative store bypass)
1071 * Have to sanitize that slot with preemptive
1074 if (*poff && *poff != soff) {
1075 /* disallow programs where single insn stores
1076 * into two different stack slots, since verifier
1077 * cannot sanitize them
1080 "insn %d cannot access two stack slots fp%d and fp%d",
1081 insn_idx, *poff, soff);
1086 state->stack[spi].slot_type[i] = STACK_SPILL;
1089 u8 type = STACK_MISC;
1091 /* regular write of data into stack */
1092 state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
1094 /* only mark the slot as written if all 8 bytes were written
1095 * otherwise read propagation may incorrectly stop too soon
1096 * when stack slots are partially written.
1097 * This heuristic means that read propagation will be
1098 * conservative, since it will add reg_live_read marks
1099 * to stack slots all the way to first state when programs
1100 * writes+reads less than 8 bytes
1102 if (size == BPF_REG_SIZE)
1103 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1105 /* when we zero initialize stack slots mark them as such */
1106 if (value_regno >= 0 &&
1107 register_is_null(&cur->regs[value_regno]))
1110 for (i = 0; i < size; i++)
1111 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1117 /* registers of every function are unique and mark_reg_read() propagates
1118 * the liveness in the following cases:
1119 * - from callee into caller for R1 - R5 that were used as arguments
1120 * - from caller into callee for R0 that used as result of the call
1121 * - from caller to the same caller skipping states of the callee for R6 - R9,
1122 * since R6 - R9 are callee saved by implicit function prologue and
1123 * caller's R6 != callee's R6, so when we propagate liveness up to
1124 * parent states we need to skip callee states for R6 - R9.
1126 * stack slot marking is different, since stacks of caller and callee are
1127 * accessible in both (since caller can pass a pointer to caller's stack to
1128 * callee which can pass it to another function), hence mark_stack_slot_read()
1129 * has to propagate the stack liveness to all parent states at given frame number.
1139 * First *ptr is reading from f1's stack and mark_stack_slot_read() has
1140 * to mark liveness at the f1's frame and not f2's frame.
1141 * Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
1142 * to propagate liveness to f2 states at f1's frame level and further into
1143 * f1 states at f1's frame level until write into that stack slot
1145 static void mark_stack_slot_read(struct bpf_verifier_env *env,
1146 const struct bpf_verifier_state *state,
1147 struct bpf_verifier_state *parent,
1148 int slot, int frameno)
1150 bool writes = parent == state->parent; /* Observe write marks */
1153 if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
1154 /* since LIVE_WRITTEN mark is only done for full 8-byte
1155 * write the read marks are conservative and parent
1156 * state may not even have the stack allocated. In such case
1157 * end the propagation, since the loop reached beginning
1161 /* if read wasn't screened by an earlier write ... */
1162 if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
1164 /* ... then we depend on parent's value */
1165 parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
1167 parent = state->parent;
1172 static int check_stack_read(struct bpf_verifier_env *env,
1173 struct bpf_func_state *reg_state /* func where register points to */,
1174 int off, int size, int value_regno)
1176 struct bpf_verifier_state *vstate = env->cur_state;
1177 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1178 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1181 if (reg_state->allocated_stack <= slot) {
1182 verbose(env, "invalid read from stack off %d+0 size %d\n",
1186 stype = reg_state->stack[spi].slot_type;
1188 if (stype[0] == STACK_SPILL) {
1189 if (size != BPF_REG_SIZE) {
1190 verbose(env, "invalid size of register spill\n");
1193 for (i = 1; i < BPF_REG_SIZE; i++) {
1194 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1195 verbose(env, "corrupted spill memory\n");
1200 if (value_regno >= 0) {
1201 /* restore register state from stack */
1202 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1203 /* mark reg as written since spilled pointer state likely
1204 * has its liveness marks cleared by is_state_visited()
1205 * which resets stack/reg liveness for state transitions
1207 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1209 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1210 reg_state->frameno);
1215 for (i = 0; i < size; i++) {
1216 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1218 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1222 verbose(env, "invalid read from stack off %d+%d size %d\n",
1226 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1227 reg_state->frameno);
1228 if (value_regno >= 0) {
1229 if (zeros == size) {
1230 /* any size read into register is zero extended,
1231 * so the whole register == const_zero
1233 __mark_reg_const_zero(&state->regs[value_regno]);
1235 /* have read misc data from the stack */
1236 mark_reg_unknown(env, state->regs, value_regno);
1238 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1244 static int check_stack_access(struct bpf_verifier_env *env,
1245 const struct bpf_reg_state *reg,
1248 /* Stack accesses must be at a fixed offset, so that we
1249 * can determine what type of data were returned. See
1250 * check_stack_read().
1252 if (!tnum_is_const(reg->var_off)) {
1255 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1256 verbose(env, "variable stack access var_off=%s off=%d size=%d",
1261 if (off >= 0 || off < -MAX_BPF_STACK) {
1262 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1269 /* check read/write into map element returned by bpf_map_lookup_elem() */
1270 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1271 int size, bool zero_size_allowed)
1273 struct bpf_reg_state *regs = cur_regs(env);
1274 struct bpf_map *map = regs[regno].map_ptr;
1276 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1277 off + size > map->value_size) {
1278 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1279 map->value_size, off, size);
1285 /* check read/write into a map element with possible variable offset */
1286 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1287 int off, int size, bool zero_size_allowed)
1289 struct bpf_verifier_state *vstate = env->cur_state;
1290 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1291 struct bpf_reg_state *reg = &state->regs[regno];
1294 /* We may have adjusted the register to this map value, so we
1295 * need to try adding each of min_value and max_value to off
1296 * to make sure our theoretical access will be safe.
1299 print_verifier_state(env, state);
1301 /* The minimum value is only important with signed
1302 * comparisons where we can't assume the floor of a
1303 * value is 0. If we are using signed variables for our
1304 * index'es we need to make sure that whatever we use
1305 * will have a set floor within our range.
1307 if (reg->smin_value < 0 &&
1308 (reg->smin_value == S64_MIN ||
1309 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1310 reg->smin_value + off < 0)) {
1311 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1315 err = __check_map_access(env, regno, reg->smin_value + off, size,
1318 verbose(env, "R%d min value is outside of the array range\n",
1323 /* If we haven't set a max value then we need to bail since we can't be
1324 * sure we won't do bad things.
1325 * If reg->umax_value + off could overflow, treat that as unbounded too.
1327 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1328 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1332 err = __check_map_access(env, regno, reg->umax_value + off, size,
1335 verbose(env, "R%d max value is outside of the array range\n",
1340 #define MAX_PACKET_OFF 0xffff
1342 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1343 const struct bpf_call_arg_meta *meta,
1344 enum bpf_access_type t)
1346 switch (env->prog->type) {
1347 case BPF_PROG_TYPE_LWT_IN:
1348 case BPF_PROG_TYPE_LWT_OUT:
1349 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1350 case BPF_PROG_TYPE_SK_REUSEPORT:
1351 /* dst_input() and dst_output() can't write for now */
1355 case BPF_PROG_TYPE_SCHED_CLS:
1356 case BPF_PROG_TYPE_SCHED_ACT:
1357 case BPF_PROG_TYPE_XDP:
1358 case BPF_PROG_TYPE_LWT_XMIT:
1359 case BPF_PROG_TYPE_SK_SKB:
1360 case BPF_PROG_TYPE_SK_MSG:
1362 return meta->pkt_access;
1364 env->seen_direct_write = true;
1371 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1372 int off, int size, bool zero_size_allowed)
1374 struct bpf_reg_state *regs = cur_regs(env);
1375 struct bpf_reg_state *reg = ®s[regno];
1377 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1378 (u64)off + size > reg->range) {
1379 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1380 off, size, regno, reg->id, reg->off, reg->range);
1386 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1387 int size, bool zero_size_allowed)
1389 struct bpf_reg_state *regs = cur_regs(env);
1390 struct bpf_reg_state *reg = ®s[regno];
1393 /* We may have added a variable offset to the packet pointer; but any
1394 * reg->range we have comes after that. We are only checking the fixed
1398 /* We don't allow negative numbers, because we aren't tracking enough
1399 * detail to prove they're safe.
1401 if (reg->smin_value < 0) {
1402 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1406 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1408 verbose(env, "R%d offset is outside of the packet\n", regno);
1414 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1415 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1416 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1418 struct bpf_insn_access_aux info = {
1419 .reg_type = *reg_type,
1422 if (env->ops->is_valid_access &&
1423 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1424 /* A non zero info.ctx_field_size indicates that this field is a
1425 * candidate for later verifier transformation to load the whole
1426 * field and then apply a mask when accessed with a narrower
1427 * access than actual ctx access size. A zero info.ctx_field_size
1428 * will only allow for whole field access and rejects any other
1429 * type of narrower access.
1431 *reg_type = info.reg_type;
1433 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1434 /* remember the offset of last byte accessed in ctx */
1435 if (env->prog->aux->max_ctx_offset < off + size)
1436 env->prog->aux->max_ctx_offset = off + size;
1440 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1444 static bool __is_pointer_value(bool allow_ptr_leaks,
1445 const struct bpf_reg_state *reg)
1447 if (allow_ptr_leaks)
1450 return reg->type != SCALAR_VALUE;
1453 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1455 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1458 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1460 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1462 return reg->type == PTR_TO_CTX;
1465 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1467 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1469 return type_is_pkt_pointer(reg->type);
1472 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1473 const struct bpf_reg_state *reg,
1474 int off, int size, bool strict)
1476 struct tnum reg_off;
1479 /* Byte size accesses are always allowed. */
1480 if (!strict || size == 1)
1483 /* For platforms that do not have a Kconfig enabling
1484 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1485 * NET_IP_ALIGN is universally set to '2'. And on platforms
1486 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1487 * to this code only in strict mode where we want to emulate
1488 * the NET_IP_ALIGN==2 checking. Therefore use an
1489 * unconditional IP align value of '2'.
1493 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1494 if (!tnum_is_aligned(reg_off, size)) {
1497 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1499 "misaligned packet access off %d+%s+%d+%d size %d\n",
1500 ip_align, tn_buf, reg->off, off, size);
1507 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1508 const struct bpf_reg_state *reg,
1509 const char *pointer_desc,
1510 int off, int size, bool strict)
1512 struct tnum reg_off;
1514 /* Byte size accesses are always allowed. */
1515 if (!strict || size == 1)
1518 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1519 if (!tnum_is_aligned(reg_off, size)) {
1522 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1523 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1524 pointer_desc, tn_buf, reg->off, off, size);
1531 static int check_ptr_alignment(struct bpf_verifier_env *env,
1532 const struct bpf_reg_state *reg, int off,
1533 int size, bool strict_alignment_once)
1535 bool strict = env->strict_alignment || strict_alignment_once;
1536 const char *pointer_desc = "";
1538 switch (reg->type) {
1540 case PTR_TO_PACKET_META:
1541 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1542 * right in front, treat it the very same way.
1544 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1545 case PTR_TO_MAP_VALUE:
1546 pointer_desc = "value ";
1549 pointer_desc = "context ";
1552 pointer_desc = "stack ";
1553 /* The stack spill tracking logic in check_stack_write()
1554 * and check_stack_read() relies on stack accesses being
1562 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1566 static int update_stack_depth(struct bpf_verifier_env *env,
1567 const struct bpf_func_state *func,
1570 u16 stack = env->subprog_info[func->subprogno].stack_depth;
1575 /* update known max for given subprogram */
1576 env->subprog_info[func->subprogno].stack_depth = -off;
1580 /* starting from main bpf function walk all instructions of the function
1581 * and recursively walk all callees that given function can call.
1582 * Ignore jump and exit insns.
1583 * Since recursion is prevented by check_cfg() this algorithm
1584 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1586 static int check_max_stack_depth(struct bpf_verifier_env *env)
1588 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1589 struct bpf_subprog_info *subprog = env->subprog_info;
1590 struct bpf_insn *insn = env->prog->insnsi;
1591 int ret_insn[MAX_CALL_FRAMES];
1592 int ret_prog[MAX_CALL_FRAMES];
1595 /* round up to 32-bytes, since this is granularity
1596 * of interpreter stack size
1598 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1599 if (depth > MAX_BPF_STACK) {
1600 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1605 subprog_end = subprog[idx + 1].start;
1606 for (; i < subprog_end; i++) {
1607 if (insn[i].code != (BPF_JMP | BPF_CALL))
1609 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1611 /* remember insn and function to return to */
1612 ret_insn[frame] = i + 1;
1613 ret_prog[frame] = idx;
1615 /* find the callee */
1616 i = i + insn[i].imm + 1;
1617 idx = find_subprog(env, i);
1619 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1624 if (frame >= MAX_CALL_FRAMES) {
1625 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1630 /* end of for() loop means the last insn of the 'subprog'
1631 * was reached. Doesn't matter whether it was JA or EXIT
1635 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1637 i = ret_insn[frame];
1638 idx = ret_prog[frame];
1642 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1643 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1644 const struct bpf_insn *insn, int idx)
1646 int start = idx + insn->imm + 1, subprog;
1648 subprog = find_subprog(env, start);
1650 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1654 return env->subprog_info[subprog].stack_depth;
1658 static int check_ctx_reg(struct bpf_verifier_env *env,
1659 const struct bpf_reg_state *reg, int regno)
1661 /* Access to ctx or passing it to a helper is only allowed in
1662 * its original, unmodified form.
1666 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1671 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1674 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1675 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1682 /* truncate register to smaller size (in bytes)
1683 * must be called with size < BPF_REG_SIZE
1685 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1689 /* clear high bits in bit representation */
1690 reg->var_off = tnum_cast(reg->var_off, size);
1692 /* fix arithmetic bounds */
1693 mask = ((u64)1 << (size * 8)) - 1;
1694 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1695 reg->umin_value &= mask;
1696 reg->umax_value &= mask;
1698 reg->umin_value = 0;
1699 reg->umax_value = mask;
1701 reg->smin_value = reg->umin_value;
1702 reg->smax_value = reg->umax_value;
1705 /* check whether memory at (regno + off) is accessible for t = (read | write)
1706 * if t==write, value_regno is a register which value is stored into memory
1707 * if t==read, value_regno is a register which will receive the value from memory
1708 * if t==write && value_regno==-1, some unknown value is stored into memory
1709 * if t==read && value_regno==-1, don't care what we read from memory
1711 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1712 int off, int bpf_size, enum bpf_access_type t,
1713 int value_regno, bool strict_alignment_once)
1715 struct bpf_reg_state *regs = cur_regs(env);
1716 struct bpf_reg_state *reg = regs + regno;
1717 struct bpf_func_state *state;
1720 size = bpf_size_to_bytes(bpf_size);
1724 /* alignment checks will add in reg->off themselves */
1725 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1729 /* for access checks, reg->off is just part of off */
1732 if (reg->type == PTR_TO_MAP_VALUE) {
1733 if (t == BPF_WRITE && value_regno >= 0 &&
1734 is_pointer_value(env, value_regno)) {
1735 verbose(env, "R%d leaks addr into map\n", value_regno);
1739 err = check_map_access(env, regno, off, size, false);
1740 if (!err && t == BPF_READ && value_regno >= 0)
1741 mark_reg_unknown(env, regs, value_regno);
1743 } else if (reg->type == PTR_TO_CTX) {
1744 enum bpf_reg_type reg_type = SCALAR_VALUE;
1746 if (t == BPF_WRITE && value_regno >= 0 &&
1747 is_pointer_value(env, value_regno)) {
1748 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1752 err = check_ctx_reg(env, reg, regno);
1756 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1757 if (!err && t == BPF_READ && value_regno >= 0) {
1758 /* ctx access returns either a scalar, or a
1759 * PTR_TO_PACKET[_META,_END]. In the latter
1760 * case, we know the offset is zero.
1762 if (reg_type == SCALAR_VALUE)
1763 mark_reg_unknown(env, regs, value_regno);
1765 mark_reg_known_zero(env, regs,
1767 regs[value_regno].type = reg_type;
1770 } else if (reg->type == PTR_TO_STACK) {
1771 off += reg->var_off.value;
1772 err = check_stack_access(env, reg, off, size);
1776 state = func(env, reg);
1777 err = update_stack_depth(env, state, off);
1782 err = check_stack_write(env, state, off, size,
1783 value_regno, insn_idx);
1785 err = check_stack_read(env, state, off, size,
1787 } else if (reg_is_pkt_pointer(reg)) {
1788 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1789 verbose(env, "cannot write into packet\n");
1792 if (t == BPF_WRITE && value_regno >= 0 &&
1793 is_pointer_value(env, value_regno)) {
1794 verbose(env, "R%d leaks addr into packet\n",
1798 err = check_packet_access(env, regno, off, size, false);
1799 if (!err && t == BPF_READ && value_regno >= 0)
1800 mark_reg_unknown(env, regs, value_regno);
1802 verbose(env, "R%d invalid mem access '%s'\n", regno,
1803 reg_type_str[reg->type]);
1807 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1808 regs[value_regno].type == SCALAR_VALUE) {
1809 /* b/h/w load zero-extends, mark upper bits as known 0 */
1810 coerce_reg_to_size(®s[value_regno], size);
1815 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1819 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1821 verbose(env, "BPF_XADD uses reserved fields\n");
1825 /* check src1 operand */
1826 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1830 /* check src2 operand */
1831 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1835 if (is_pointer_value(env, insn->src_reg)) {
1836 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1840 if (is_ctx_reg(env, insn->dst_reg) ||
1841 is_pkt_reg(env, insn->dst_reg)) {
1842 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1843 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1844 "context" : "packet");
1848 /* check whether atomic_add can read the memory */
1849 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1850 BPF_SIZE(insn->code), BPF_READ, -1, true);
1854 /* check whether atomic_add can write into the same memory */
1855 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1856 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1859 /* when register 'regno' is passed into function that will read 'access_size'
1860 * bytes from that pointer, make sure that it's within stack boundary
1861 * and all elements of stack are initialized.
1862 * Unlike most pointer bounds-checking functions, this one doesn't take an
1863 * 'off' argument, so it has to add in reg->off itself.
1865 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1866 int access_size, bool zero_size_allowed,
1867 struct bpf_call_arg_meta *meta)
1869 struct bpf_reg_state *reg = cur_regs(env) + regno;
1870 struct bpf_func_state *state = func(env, reg);
1871 int off, i, slot, spi;
1873 if (reg->type != PTR_TO_STACK) {
1874 /* Allow zero-byte read from NULL, regardless of pointer type */
1875 if (zero_size_allowed && access_size == 0 &&
1876 register_is_null(reg))
1879 verbose(env, "R%d type=%s expected=%s\n", regno,
1880 reg_type_str[reg->type],
1881 reg_type_str[PTR_TO_STACK]);
1885 /* Only allow fixed-offset stack reads */
1886 if (!tnum_is_const(reg->var_off)) {
1889 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1890 verbose(env, "invalid variable stack read R%d var_off=%s\n",
1894 off = reg->off + reg->var_off.value;
1895 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1896 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1897 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1898 regno, off, access_size);
1902 if (meta && meta->raw_mode) {
1903 meta->access_size = access_size;
1904 meta->regno = regno;
1908 for (i = 0; i < access_size; i++) {
1911 slot = -(off + i) - 1;
1912 spi = slot / BPF_REG_SIZE;
1913 if (state->allocated_stack <= slot)
1915 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1916 if (*stype == STACK_MISC)
1918 if (*stype == STACK_ZERO) {
1919 /* helper can write anything into the stack */
1920 *stype = STACK_MISC;
1924 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1925 off, i, access_size);
1928 /* reading any byte out of 8-byte 'spill_slot' will cause
1929 * the whole slot to be marked as 'read'
1931 mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
1932 spi, state->frameno);
1934 return update_stack_depth(env, state, off);
1937 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1938 int access_size, bool zero_size_allowed,
1939 struct bpf_call_arg_meta *meta)
1941 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1943 switch (reg->type) {
1945 case PTR_TO_PACKET_META:
1946 return check_packet_access(env, regno, reg->off, access_size,
1948 case PTR_TO_MAP_VALUE:
1949 return check_map_access(env, regno, reg->off, access_size,
1951 default: /* scalar_value|ptr_to_stack or invalid ptr */
1952 return check_stack_boundary(env, regno, access_size,
1953 zero_size_allowed, meta);
1957 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1959 return type == ARG_PTR_TO_MEM ||
1960 type == ARG_PTR_TO_MEM_OR_NULL ||
1961 type == ARG_PTR_TO_UNINIT_MEM;
1964 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1966 return type == ARG_CONST_SIZE ||
1967 type == ARG_CONST_SIZE_OR_ZERO;
1970 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1971 enum bpf_arg_type arg_type,
1972 struct bpf_call_arg_meta *meta)
1974 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1975 enum bpf_reg_type expected_type, type = reg->type;
1978 if (arg_type == ARG_DONTCARE)
1981 err = check_reg_arg(env, regno, SRC_OP);
1985 if (arg_type == ARG_ANYTHING) {
1986 if (is_pointer_value(env, regno)) {
1987 verbose(env, "R%d leaks addr into helper function\n",
1994 if (type_is_pkt_pointer(type) &&
1995 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1996 verbose(env, "helper access to the packet is not allowed\n");
2000 if (arg_type == ARG_PTR_TO_MAP_KEY ||
2001 arg_type == ARG_PTR_TO_MAP_VALUE) {
2002 expected_type = PTR_TO_STACK;
2003 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
2004 type != expected_type)
2006 } else if (arg_type == ARG_CONST_SIZE ||
2007 arg_type == ARG_CONST_SIZE_OR_ZERO) {
2008 expected_type = SCALAR_VALUE;
2009 if (type != expected_type)
2011 } else if (arg_type == ARG_CONST_MAP_PTR) {
2012 expected_type = CONST_PTR_TO_MAP;
2013 if (type != expected_type)
2015 } else if (arg_type == ARG_PTR_TO_CTX) {
2016 expected_type = PTR_TO_CTX;
2017 if (type != expected_type)
2019 err = check_ctx_reg(env, reg, regno);
2022 } else if (arg_type_is_mem_ptr(arg_type)) {
2023 expected_type = PTR_TO_STACK;
2024 /* One exception here. In case function allows for NULL to be
2025 * passed in as argument, it's a SCALAR_VALUE type. Final test
2026 * happens during stack boundary checking.
2028 if (register_is_null(reg) &&
2029 arg_type == ARG_PTR_TO_MEM_OR_NULL)
2030 /* final test in check_stack_boundary() */;
2031 else if (!type_is_pkt_pointer(type) &&
2032 type != PTR_TO_MAP_VALUE &&
2033 type != expected_type)
2035 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
2037 verbose(env, "unsupported arg_type %d\n", arg_type);
2041 if (arg_type == ARG_CONST_MAP_PTR) {
2042 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2043 meta->map_ptr = reg->map_ptr;
2044 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2045 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2046 * check that [key, key + map->key_size) are within
2047 * stack limits and initialized
2049 if (!meta->map_ptr) {
2050 /* in function declaration map_ptr must come before
2051 * map_key, so that it's verified and known before
2052 * we have to check map_key here. Otherwise it means
2053 * that kernel subsystem misconfigured verifier
2055 verbose(env, "invalid map_ptr to access map->key\n");
2058 err = check_helper_mem_access(env, regno,
2059 meta->map_ptr->key_size, false,
2061 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
2062 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2063 * check [value, value + map->value_size) validity
2065 if (!meta->map_ptr) {
2066 /* kernel subsystem misconfigured verifier */
2067 verbose(env, "invalid map_ptr to access map->value\n");
2070 err = check_helper_mem_access(env, regno,
2071 meta->map_ptr->value_size, false,
2073 } else if (arg_type_is_mem_size(arg_type)) {
2074 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2076 /* remember the mem_size which may be used later
2077 * to refine return values.
2079 meta->msize_smax_value = reg->smax_value;
2080 meta->msize_umax_value = reg->umax_value;
2082 /* The register is SCALAR_VALUE; the access check
2083 * happens using its boundaries.
2085 if (!tnum_is_const(reg->var_off))
2086 /* For unprivileged variable accesses, disable raw
2087 * mode so that the program is required to
2088 * initialize all the memory that the helper could
2089 * just partially fill up.
2093 if (reg->smin_value < 0) {
2094 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2099 if (reg->umin_value == 0) {
2100 err = check_helper_mem_access(env, regno - 1, 0,
2107 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2108 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2112 err = check_helper_mem_access(env, regno - 1,
2114 zero_size_allowed, meta);
2119 verbose(env, "R%d type=%s expected=%s\n", regno,
2120 reg_type_str[type], reg_type_str[expected_type]);
2124 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2125 struct bpf_map *map, int func_id)
2130 /* We need a two way check, first is from map perspective ... */
2131 switch (map->map_type) {
2132 case BPF_MAP_TYPE_PROG_ARRAY:
2133 if (func_id != BPF_FUNC_tail_call)
2136 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2137 if (func_id != BPF_FUNC_perf_event_read &&
2138 func_id != BPF_FUNC_perf_event_output &&
2139 func_id != BPF_FUNC_perf_event_read_value)
2142 case BPF_MAP_TYPE_STACK_TRACE:
2143 if (func_id != BPF_FUNC_get_stackid)
2146 case BPF_MAP_TYPE_CGROUP_ARRAY:
2147 if (func_id != BPF_FUNC_skb_under_cgroup &&
2148 func_id != BPF_FUNC_current_task_under_cgroup)
2151 case BPF_MAP_TYPE_CGROUP_STORAGE:
2152 if (func_id != BPF_FUNC_get_local_storage)
2155 /* devmap returns a pointer to a live net_device ifindex that we cannot
2156 * allow to be modified from bpf side. So do not allow lookup elements
2159 case BPF_MAP_TYPE_DEVMAP:
2160 if (func_id != BPF_FUNC_redirect_map)
2163 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2166 case BPF_MAP_TYPE_CPUMAP:
2167 case BPF_MAP_TYPE_XSKMAP:
2168 if (func_id != BPF_FUNC_redirect_map)
2171 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2172 case BPF_MAP_TYPE_HASH_OF_MAPS:
2173 if (func_id != BPF_FUNC_map_lookup_elem)
2176 case BPF_MAP_TYPE_SOCKMAP:
2177 if (func_id != BPF_FUNC_sk_redirect_map &&
2178 func_id != BPF_FUNC_sock_map_update &&
2179 func_id != BPF_FUNC_map_delete_elem &&
2180 func_id != BPF_FUNC_msg_redirect_map)
2183 case BPF_MAP_TYPE_SOCKHASH:
2184 if (func_id != BPF_FUNC_sk_redirect_hash &&
2185 func_id != BPF_FUNC_sock_hash_update &&
2186 func_id != BPF_FUNC_map_delete_elem &&
2187 func_id != BPF_FUNC_msg_redirect_hash)
2190 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2191 if (func_id != BPF_FUNC_sk_select_reuseport)
2198 /* ... and second from the function itself. */
2200 case BPF_FUNC_tail_call:
2201 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2203 if (env->subprog_cnt > 1) {
2204 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2208 case BPF_FUNC_perf_event_read:
2209 case BPF_FUNC_perf_event_output:
2210 case BPF_FUNC_perf_event_read_value:
2211 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2214 case BPF_FUNC_get_stackid:
2215 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2218 case BPF_FUNC_current_task_under_cgroup:
2219 case BPF_FUNC_skb_under_cgroup:
2220 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2223 case BPF_FUNC_redirect_map:
2224 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2225 map->map_type != BPF_MAP_TYPE_CPUMAP &&
2226 map->map_type != BPF_MAP_TYPE_XSKMAP)
2229 case BPF_FUNC_sk_redirect_map:
2230 case BPF_FUNC_msg_redirect_map:
2231 case BPF_FUNC_sock_map_update:
2232 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2235 case BPF_FUNC_sk_redirect_hash:
2236 case BPF_FUNC_msg_redirect_hash:
2237 case BPF_FUNC_sock_hash_update:
2238 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2241 case BPF_FUNC_get_local_storage:
2242 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
2245 case BPF_FUNC_sk_select_reuseport:
2246 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2255 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2256 map->map_type, func_id_name(func_id), func_id);
2260 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2264 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2266 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2268 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2270 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2272 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2275 /* We only support one arg being in raw mode at the moment,
2276 * which is sufficient for the helper functions we have
2282 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2283 enum bpf_arg_type arg_next)
2285 return (arg_type_is_mem_ptr(arg_curr) &&
2286 !arg_type_is_mem_size(arg_next)) ||
2287 (!arg_type_is_mem_ptr(arg_curr) &&
2288 arg_type_is_mem_size(arg_next));
2291 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2293 /* bpf_xxx(..., buf, len) call will access 'len'
2294 * bytes from memory 'buf'. Both arg types need
2295 * to be paired, so make sure there's no buggy
2296 * helper function specification.
2298 if (arg_type_is_mem_size(fn->arg1_type) ||
2299 arg_type_is_mem_ptr(fn->arg5_type) ||
2300 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2301 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2302 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2303 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2309 static int check_func_proto(const struct bpf_func_proto *fn)
2311 return check_raw_mode_ok(fn) &&
2312 check_arg_pair_ok(fn) ? 0 : -EINVAL;
2315 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2316 * are now invalid, so turn them into unknown SCALAR_VALUE.
2318 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2319 struct bpf_func_state *state)
2321 struct bpf_reg_state *regs = state->regs, *reg;
2324 for (i = 0; i < MAX_BPF_REG; i++)
2325 if (reg_is_pkt_pointer_any(®s[i]))
2326 mark_reg_unknown(env, regs, i);
2328 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2329 if (state->stack[i].slot_type[0] != STACK_SPILL)
2331 reg = &state->stack[i].spilled_ptr;
2332 if (reg_is_pkt_pointer_any(reg))
2333 __mark_reg_unknown(reg);
2337 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2339 struct bpf_verifier_state *vstate = env->cur_state;
2342 for (i = 0; i <= vstate->curframe; i++)
2343 __clear_all_pkt_pointers(env, vstate->frame[i]);
2346 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2349 struct bpf_verifier_state *state = env->cur_state;
2350 struct bpf_func_state *caller, *callee;
2351 int i, subprog, target_insn;
2353 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2354 verbose(env, "the call stack of %d frames is too deep\n",
2355 state->curframe + 2);
2359 target_insn = *insn_idx + insn->imm;
2360 subprog = find_subprog(env, target_insn + 1);
2362 verbose(env, "verifier bug. No program starts at insn %d\n",
2367 caller = state->frame[state->curframe];
2368 if (state->frame[state->curframe + 1]) {
2369 verbose(env, "verifier bug. Frame %d already allocated\n",
2370 state->curframe + 1);
2374 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2377 state->frame[state->curframe + 1] = callee;
2379 /* callee cannot access r0, r6 - r9 for reading and has to write
2380 * into its own stack before reading from it.
2381 * callee can read/write into caller's stack
2383 init_func_state(env, callee,
2384 /* remember the callsite, it will be used by bpf_exit */
2385 *insn_idx /* callsite */,
2386 state->curframe + 1 /* frameno within this callchain */,
2387 subprog /* subprog number within this prog */);
2389 /* copy r1 - r5 args that callee can access */
2390 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2391 callee->regs[i] = caller->regs[i];
2393 /* after the call regsiters r0 - r5 were scratched */
2394 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2395 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2396 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2399 /* only increment it after check_reg_arg() finished */
2402 /* and go analyze first insn of the callee */
2403 *insn_idx = target_insn;
2405 if (env->log.level) {
2406 verbose(env, "caller:\n");
2407 print_verifier_state(env, caller);
2408 verbose(env, "callee:\n");
2409 print_verifier_state(env, callee);
2414 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2416 struct bpf_verifier_state *state = env->cur_state;
2417 struct bpf_func_state *caller, *callee;
2418 struct bpf_reg_state *r0;
2420 callee = state->frame[state->curframe];
2421 r0 = &callee->regs[BPF_REG_0];
2422 if (r0->type == PTR_TO_STACK) {
2423 /* technically it's ok to return caller's stack pointer
2424 * (or caller's caller's pointer) back to the caller,
2425 * since these pointers are valid. Only current stack
2426 * pointer will be invalid as soon as function exits,
2427 * but let's be conservative
2429 verbose(env, "cannot return stack pointer to the caller\n");
2434 caller = state->frame[state->curframe];
2435 /* return to the caller whatever r0 had in the callee */
2436 caller->regs[BPF_REG_0] = *r0;
2438 *insn_idx = callee->callsite + 1;
2439 if (env->log.level) {
2440 verbose(env, "returning from callee:\n");
2441 print_verifier_state(env, callee);
2442 verbose(env, "to caller at %d:\n", *insn_idx);
2443 print_verifier_state(env, caller);
2445 /* clear everything in the callee */
2446 free_func_state(callee);
2447 state->frame[state->curframe + 1] = NULL;
2451 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
2453 struct bpf_call_arg_meta *meta)
2455 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
2457 if (ret_type != RET_INTEGER ||
2458 (func_id != BPF_FUNC_get_stack &&
2459 func_id != BPF_FUNC_probe_read_str))
2462 ret_reg->smax_value = meta->msize_smax_value;
2463 ret_reg->umax_value = meta->msize_umax_value;
2464 __reg_deduce_bounds(ret_reg);
2465 __reg_bound_offset(ret_reg);
2469 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2470 int func_id, int insn_idx)
2472 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2474 if (func_id != BPF_FUNC_tail_call &&
2475 func_id != BPF_FUNC_map_lookup_elem &&
2476 func_id != BPF_FUNC_map_update_elem &&
2477 func_id != BPF_FUNC_map_delete_elem)
2480 if (meta->map_ptr == NULL) {
2481 verbose(env, "kernel subsystem misconfigured verifier\n");
2485 if (!BPF_MAP_PTR(aux->map_state))
2486 bpf_map_ptr_store(aux, meta->map_ptr,
2487 meta->map_ptr->unpriv_array);
2488 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2489 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2490 meta->map_ptr->unpriv_array);
2494 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2496 const struct bpf_func_proto *fn = NULL;
2497 struct bpf_reg_state *regs;
2498 struct bpf_call_arg_meta meta;
2502 /* find function prototype */
2503 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2504 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2509 if (env->ops->get_func_proto)
2510 fn = env->ops->get_func_proto(func_id, env->prog);
2512 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2517 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2518 if (!env->prog->gpl_compatible && fn->gpl_only) {
2519 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2523 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2524 changes_data = bpf_helper_changes_pkt_data(fn->func);
2525 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2526 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2527 func_id_name(func_id), func_id);
2531 memset(&meta, 0, sizeof(meta));
2532 meta.pkt_access = fn->pkt_access;
2534 err = check_func_proto(fn);
2536 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2537 func_id_name(func_id), func_id);
2542 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2545 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2548 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2551 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2554 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2558 err = record_func_map(env, &meta, func_id, insn_idx);
2562 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2563 * is inferred from register state.
2565 for (i = 0; i < meta.access_size; i++) {
2566 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2567 BPF_WRITE, -1, false);
2572 regs = cur_regs(env);
2574 /* check that flags argument in get_local_storage(map, flags) is 0,
2575 * this is required because get_local_storage() can't return an error.
2577 if (func_id == BPF_FUNC_get_local_storage &&
2578 !register_is_null(®s[BPF_REG_2])) {
2579 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
2583 /* reset caller saved regs */
2584 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2585 mark_reg_not_init(env, regs, caller_saved[i]);
2586 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2589 /* update return register (already marked as written above) */
2590 if (fn->ret_type == RET_INTEGER) {
2591 /* sets type to SCALAR_VALUE */
2592 mark_reg_unknown(env, regs, BPF_REG_0);
2593 } else if (fn->ret_type == RET_VOID) {
2594 regs[BPF_REG_0].type = NOT_INIT;
2595 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
2596 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2597 if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
2598 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
2600 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2601 /* There is no offset yet applied, variable or fixed */
2602 mark_reg_known_zero(env, regs, BPF_REG_0);
2603 /* remember map_ptr, so that check_map_access()
2604 * can check 'value_size' boundary of memory access
2605 * to map element returned from bpf_map_lookup_elem()
2607 if (meta.map_ptr == NULL) {
2609 "kernel subsystem misconfigured verifier\n");
2612 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2613 regs[BPF_REG_0].id = ++env->id_gen;
2615 verbose(env, "unknown return type %d of func %s#%d\n",
2616 fn->ret_type, func_id_name(func_id), func_id);
2620 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
2622 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2626 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
2627 const char *err_str;
2629 #ifdef CONFIG_PERF_EVENTS
2630 err = get_callchain_buffers(sysctl_perf_event_max_stack);
2631 err_str = "cannot get callchain buffer for func %s#%d\n";
2634 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
2637 verbose(env, err_str, func_id_name(func_id), func_id);
2641 env->prog->has_callchain_buf = true;
2645 clear_all_pkt_pointers(env);
2649 static bool signed_add_overflows(s64 a, s64 b)
2651 /* Do the add in u64, where overflow is well-defined */
2652 s64 res = (s64)((u64)a + (u64)b);
2659 static bool signed_sub_overflows(s64 a, s64 b)
2661 /* Do the sub in u64, where overflow is well-defined */
2662 s64 res = (s64)((u64)a - (u64)b);
2669 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2670 const struct bpf_reg_state *reg,
2671 enum bpf_reg_type type)
2673 bool known = tnum_is_const(reg->var_off);
2674 s64 val = reg->var_off.value;
2675 s64 smin = reg->smin_value;
2677 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2678 verbose(env, "math between %s pointer and %lld is not allowed\n",
2679 reg_type_str[type], val);
2683 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2684 verbose(env, "%s pointer offset %d is not allowed\n",
2685 reg_type_str[type], reg->off);
2689 if (smin == S64_MIN) {
2690 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2691 reg_type_str[type]);
2695 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2696 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2697 smin, reg_type_str[type]);
2704 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
2706 return &env->insn_aux_data[env->insn_idx];
2709 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
2710 u32 *ptr_limit, u8 opcode, bool off_is_neg)
2712 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
2713 (opcode == BPF_SUB && !off_is_neg);
2716 switch (ptr_reg->type) {
2718 off = ptr_reg->off + ptr_reg->var_off.value;
2720 *ptr_limit = MAX_BPF_STACK + off;
2724 case PTR_TO_MAP_VALUE:
2726 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
2728 off = ptr_reg->smin_value + ptr_reg->off;
2729 *ptr_limit = ptr_reg->map_ptr->value_size - off;
2737 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
2738 const struct bpf_insn *insn)
2740 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
2743 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
2744 u32 alu_state, u32 alu_limit)
2746 /* If we arrived here from different branches with different
2747 * state or limits to sanitize, then this won't work.
2749 if (aux->alu_state &&
2750 (aux->alu_state != alu_state ||
2751 aux->alu_limit != alu_limit))
2754 /* Corresponding fixup done in fixup_bpf_calls(). */
2755 aux->alu_state = alu_state;
2756 aux->alu_limit = alu_limit;
2760 static int sanitize_val_alu(struct bpf_verifier_env *env,
2761 struct bpf_insn *insn)
2763 struct bpf_insn_aux_data *aux = cur_aux(env);
2765 if (can_skip_alu_sanitation(env, insn))
2768 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
2771 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
2772 struct bpf_insn *insn,
2773 const struct bpf_reg_state *ptr_reg,
2774 struct bpf_reg_state *dst_reg,
2777 struct bpf_verifier_state *vstate = env->cur_state;
2778 struct bpf_insn_aux_data *aux = cur_aux(env);
2779 bool ptr_is_dst_reg = ptr_reg == dst_reg;
2780 u8 opcode = BPF_OP(insn->code);
2781 u32 alu_state, alu_limit;
2782 struct bpf_reg_state tmp;
2785 if (can_skip_alu_sanitation(env, insn))
2788 /* We already marked aux for masking from non-speculative
2789 * paths, thus we got here in the first place. We only care
2790 * to explore bad access from here.
2792 if (vstate->speculative)
2795 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
2796 alu_state |= ptr_is_dst_reg ?
2797 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
2799 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
2801 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
2804 /* Simulate and find potential out-of-bounds access under
2805 * speculative execution from truncation as a result of
2806 * masking when off was not within expected range. If off
2807 * sits in dst, then we temporarily need to move ptr there
2808 * to simulate dst (== 0) +/-= ptr. Needed, for example,
2809 * for cases where we use K-based arithmetic in one direction
2810 * and truncated reg-based in the other in order to explore
2813 if (!ptr_is_dst_reg) {
2815 *dst_reg = *ptr_reg;
2817 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
2818 if (!ptr_is_dst_reg && ret)
2820 return !ret ? -EFAULT : 0;
2823 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2824 * Caller should also handle BPF_MOV case separately.
2825 * If we return -EACCES, caller may want to try again treating pointer as a
2826 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
2828 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2829 struct bpf_insn *insn,
2830 const struct bpf_reg_state *ptr_reg,
2831 const struct bpf_reg_state *off_reg)
2833 struct bpf_verifier_state *vstate = env->cur_state;
2834 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2835 struct bpf_reg_state *regs = state->regs, *dst_reg;
2836 bool known = tnum_is_const(off_reg->var_off);
2837 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2838 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2839 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2840 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2841 u32 dst = insn->dst_reg, src = insn->src_reg;
2842 u8 opcode = BPF_OP(insn->code);
2845 dst_reg = ®s[dst];
2847 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2848 smin_val > smax_val || umin_val > umax_val) {
2849 /* Taint dst register if offset had invalid bounds derived from
2850 * e.g. dead branches.
2852 __mark_reg_unknown(dst_reg);
2856 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2857 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2859 "R%d 32-bit pointer arithmetic prohibited\n",
2864 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2865 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2869 if (ptr_reg->type == CONST_PTR_TO_MAP) {
2870 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2874 if (ptr_reg->type == PTR_TO_PACKET_END) {
2875 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2879 if (ptr_reg->type == PTR_TO_MAP_VALUE &&
2880 !env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
2881 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
2882 off_reg == dst_reg ? dst : src);
2886 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2887 * The id may be overwritten later if we create a new variable offset.
2889 dst_reg->type = ptr_reg->type;
2890 dst_reg->id = ptr_reg->id;
2892 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2893 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2898 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
2900 verbose(env, "R%d tried to add from different maps or paths\n", dst);
2903 /* We can take a fixed offset as long as it doesn't overflow
2904 * the s32 'off' field
2906 if (known && (ptr_reg->off + smin_val ==
2907 (s64)(s32)(ptr_reg->off + smin_val))) {
2908 /* pointer += K. Accumulate it into fixed offset */
2909 dst_reg->smin_value = smin_ptr;
2910 dst_reg->smax_value = smax_ptr;
2911 dst_reg->umin_value = umin_ptr;
2912 dst_reg->umax_value = umax_ptr;
2913 dst_reg->var_off = ptr_reg->var_off;
2914 dst_reg->off = ptr_reg->off + smin_val;
2915 dst_reg->raw = ptr_reg->raw;
2918 /* A new variable offset is created. Note that off_reg->off
2919 * == 0, since it's a scalar.
2920 * dst_reg gets the pointer type and since some positive
2921 * integer value was added to the pointer, give it a new 'id'
2922 * if it's a PTR_TO_PACKET.
2923 * this creates a new 'base' pointer, off_reg (variable) gets
2924 * added into the variable offset, and we copy the fixed offset
2927 if (signed_add_overflows(smin_ptr, smin_val) ||
2928 signed_add_overflows(smax_ptr, smax_val)) {
2929 dst_reg->smin_value = S64_MIN;
2930 dst_reg->smax_value = S64_MAX;
2932 dst_reg->smin_value = smin_ptr + smin_val;
2933 dst_reg->smax_value = smax_ptr + smax_val;
2935 if (umin_ptr + umin_val < umin_ptr ||
2936 umax_ptr + umax_val < umax_ptr) {
2937 dst_reg->umin_value = 0;
2938 dst_reg->umax_value = U64_MAX;
2940 dst_reg->umin_value = umin_ptr + umin_val;
2941 dst_reg->umax_value = umax_ptr + umax_val;
2943 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2944 dst_reg->off = ptr_reg->off;
2945 dst_reg->raw = ptr_reg->raw;
2946 if (reg_is_pkt_pointer(ptr_reg)) {
2947 dst_reg->id = ++env->id_gen;
2948 /* something was added to pkt_ptr, set range to zero */
2953 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
2955 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
2958 if (dst_reg == off_reg) {
2959 /* scalar -= pointer. Creates an unknown scalar */
2960 verbose(env, "R%d tried to subtract pointer from scalar\n",
2964 /* We don't allow subtraction from FP, because (according to
2965 * test_verifier.c test "invalid fp arithmetic", JITs might not
2966 * be able to deal with it.
2968 if (ptr_reg->type == PTR_TO_STACK) {
2969 verbose(env, "R%d subtraction from stack pointer prohibited\n",
2973 if (known && (ptr_reg->off - smin_val ==
2974 (s64)(s32)(ptr_reg->off - smin_val))) {
2975 /* pointer -= K. Subtract it from fixed offset */
2976 dst_reg->smin_value = smin_ptr;
2977 dst_reg->smax_value = smax_ptr;
2978 dst_reg->umin_value = umin_ptr;
2979 dst_reg->umax_value = umax_ptr;
2980 dst_reg->var_off = ptr_reg->var_off;
2981 dst_reg->id = ptr_reg->id;
2982 dst_reg->off = ptr_reg->off - smin_val;
2983 dst_reg->raw = ptr_reg->raw;
2986 /* A new variable offset is created. If the subtrahend is known
2987 * nonnegative, then any reg->range we had before is still good.
2989 if (signed_sub_overflows(smin_ptr, smax_val) ||
2990 signed_sub_overflows(smax_ptr, smin_val)) {
2991 /* Overflow possible, we know nothing */
2992 dst_reg->smin_value = S64_MIN;
2993 dst_reg->smax_value = S64_MAX;
2995 dst_reg->smin_value = smin_ptr - smax_val;
2996 dst_reg->smax_value = smax_ptr - smin_val;
2998 if (umin_ptr < umax_val) {
2999 /* Overflow possible, we know nothing */
3000 dst_reg->umin_value = 0;
3001 dst_reg->umax_value = U64_MAX;
3003 /* Cannot overflow (as long as bounds are consistent) */
3004 dst_reg->umin_value = umin_ptr - umax_val;
3005 dst_reg->umax_value = umax_ptr - umin_val;
3007 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3008 dst_reg->off = ptr_reg->off;
3009 dst_reg->raw = ptr_reg->raw;
3010 if (reg_is_pkt_pointer(ptr_reg)) {
3011 dst_reg->id = ++env->id_gen;
3012 /* something was added to pkt_ptr, set range to zero */
3020 /* bitwise ops on pointers are troublesome, prohibit. */
3021 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3022 dst, bpf_alu_string[opcode >> 4]);
3025 /* other operators (e.g. MUL,LSH) produce non-pointer results */
3026 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3027 dst, bpf_alu_string[opcode >> 4]);
3031 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3034 __update_reg_bounds(dst_reg);
3035 __reg_deduce_bounds(dst_reg);
3036 __reg_bound_offset(dst_reg);
3038 /* For unprivileged we require that resulting offset must be in bounds
3039 * in order to be able to sanitize access later on.
3041 if (!env->allow_ptr_leaks) {
3042 if (dst_reg->type == PTR_TO_MAP_VALUE &&
3043 check_map_access(env, dst, dst_reg->off, 1, false)) {
3044 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
3045 "prohibited for !root\n", dst);
3047 } else if (dst_reg->type == PTR_TO_STACK &&
3048 check_stack_access(env, dst_reg, dst_reg->off +
3049 dst_reg->var_off.value, 1)) {
3050 verbose(env, "R%d stack pointer arithmetic goes out of range, "
3051 "prohibited for !root\n", dst);
3059 /* WARNING: This function does calculations on 64-bit values, but the actual
3060 * execution may occur on 32-bit values. Therefore, things like bitshifts
3061 * need extra checks in the 32-bit case.
3063 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3064 struct bpf_insn *insn,
3065 struct bpf_reg_state *dst_reg,
3066 struct bpf_reg_state src_reg)
3068 struct bpf_reg_state *regs = cur_regs(env);
3069 u8 opcode = BPF_OP(insn->code);
3070 bool src_known, dst_known;
3071 s64 smin_val, smax_val;
3072 u64 umin_val, umax_val;
3073 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3074 u32 dst = insn->dst_reg;
3077 if (insn_bitness == 32) {
3078 /* Relevant for 32-bit RSH: Information can propagate towards
3079 * LSB, so it isn't sufficient to only truncate the output to
3082 coerce_reg_to_size(dst_reg, 4);
3083 coerce_reg_to_size(&src_reg, 4);
3086 smin_val = src_reg.smin_value;
3087 smax_val = src_reg.smax_value;
3088 umin_val = src_reg.umin_value;
3089 umax_val = src_reg.umax_value;
3090 src_known = tnum_is_const(src_reg.var_off);
3091 dst_known = tnum_is_const(dst_reg->var_off);
3093 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3094 smin_val > smax_val || umin_val > umax_val) {
3095 /* Taint dst register if offset had invalid bounds derived from
3096 * e.g. dead branches.
3098 __mark_reg_unknown(dst_reg);
3103 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3104 __mark_reg_unknown(dst_reg);
3110 ret = sanitize_val_alu(env, insn);
3112 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
3115 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3116 signed_add_overflows(dst_reg->smax_value, smax_val)) {
3117 dst_reg->smin_value = S64_MIN;
3118 dst_reg->smax_value = S64_MAX;
3120 dst_reg->smin_value += smin_val;
3121 dst_reg->smax_value += smax_val;
3123 if (dst_reg->umin_value + umin_val < umin_val ||
3124 dst_reg->umax_value + umax_val < umax_val) {
3125 dst_reg->umin_value = 0;
3126 dst_reg->umax_value = U64_MAX;
3128 dst_reg->umin_value += umin_val;
3129 dst_reg->umax_value += umax_val;
3131 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
3134 ret = sanitize_val_alu(env, insn);
3136 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
3139 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3140 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3141 /* Overflow possible, we know nothing */
3142 dst_reg->smin_value = S64_MIN;
3143 dst_reg->smax_value = S64_MAX;
3145 dst_reg->smin_value -= smax_val;
3146 dst_reg->smax_value -= smin_val;
3148 if (dst_reg->umin_value < umax_val) {
3149 /* Overflow possible, we know nothing */
3150 dst_reg->umin_value = 0;
3151 dst_reg->umax_value = U64_MAX;
3153 /* Cannot overflow (as long as bounds are consistent) */
3154 dst_reg->umin_value -= umax_val;
3155 dst_reg->umax_value -= umin_val;
3157 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
3160 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3161 if (smin_val < 0 || dst_reg->smin_value < 0) {
3162 /* Ain't nobody got time to multiply that sign */
3163 __mark_reg_unbounded(dst_reg);
3164 __update_reg_bounds(dst_reg);
3167 /* Both values are positive, so we can work with unsigned and
3168 * copy the result to signed (unless it exceeds S64_MAX).
3170 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3171 /* Potential overflow, we know nothing */
3172 __mark_reg_unbounded(dst_reg);
3173 /* (except what we can learn from the var_off) */
3174 __update_reg_bounds(dst_reg);
3177 dst_reg->umin_value *= umin_val;
3178 dst_reg->umax_value *= umax_val;
3179 if (dst_reg->umax_value > S64_MAX) {
3180 /* Overflow possible, we know nothing */
3181 dst_reg->smin_value = S64_MIN;
3182 dst_reg->smax_value = S64_MAX;
3184 dst_reg->smin_value = dst_reg->umin_value;
3185 dst_reg->smax_value = dst_reg->umax_value;
3189 if (src_known && dst_known) {
3190 __mark_reg_known(dst_reg, dst_reg->var_off.value &
3191 src_reg.var_off.value);
3194 /* We get our minimum from the var_off, since that's inherently
3195 * bitwise. Our maximum is the minimum of the operands' maxima.
3197 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
3198 dst_reg->umin_value = dst_reg->var_off.value;
3199 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3200 if (dst_reg->smin_value < 0 || smin_val < 0) {
3201 /* Lose signed bounds when ANDing negative numbers,
3202 * ain't nobody got time for that.
3204 dst_reg->smin_value = S64_MIN;
3205 dst_reg->smax_value = S64_MAX;
3207 /* ANDing two positives gives a positive, so safe to
3208 * cast result into s64.
3210 dst_reg->smin_value = dst_reg->umin_value;
3211 dst_reg->smax_value = dst_reg->umax_value;
3213 /* We may learn something more from the var_off */
3214 __update_reg_bounds(dst_reg);
3217 if (src_known && dst_known) {
3218 __mark_reg_known(dst_reg, dst_reg->var_off.value |
3219 src_reg.var_off.value);
3222 /* We get our maximum from the var_off, and our minimum is the
3223 * maximum of the operands' minima
3225 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
3226 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
3227 dst_reg->umax_value = dst_reg->var_off.value |
3228 dst_reg->var_off.mask;
3229 if (dst_reg->smin_value < 0 || smin_val < 0) {
3230 /* Lose signed bounds when ORing negative numbers,
3231 * ain't nobody got time for that.
3233 dst_reg->smin_value = S64_MIN;
3234 dst_reg->smax_value = S64_MAX;
3236 /* ORing two positives gives a positive, so safe to
3237 * cast result into s64.
3239 dst_reg->smin_value = dst_reg->umin_value;
3240 dst_reg->smax_value = dst_reg->umax_value;
3242 /* We may learn something more from the var_off */
3243 __update_reg_bounds(dst_reg);
3246 if (umax_val >= insn_bitness) {
3247 /* Shifts greater than 31 or 63 are undefined.
3248 * This includes shifts by a negative number.
3250 mark_reg_unknown(env, regs, insn->dst_reg);
3253 /* We lose all sign bit information (except what we can pick
3256 dst_reg->smin_value = S64_MIN;
3257 dst_reg->smax_value = S64_MAX;
3258 /* If we might shift our top bit out, then we know nothing */
3259 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
3260 dst_reg->umin_value = 0;
3261 dst_reg->umax_value = U64_MAX;
3263 dst_reg->umin_value <<= umin_val;
3264 dst_reg->umax_value <<= umax_val;
3266 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
3267 /* We may learn something more from the var_off */
3268 __update_reg_bounds(dst_reg);
3271 if (umax_val >= insn_bitness) {
3272 /* Shifts greater than 31 or 63 are undefined.
3273 * This includes shifts by a negative number.
3275 mark_reg_unknown(env, regs, insn->dst_reg);
3278 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
3279 * be negative, then either:
3280 * 1) src_reg might be zero, so the sign bit of the result is
3281 * unknown, so we lose our signed bounds
3282 * 2) it's known negative, thus the unsigned bounds capture the
3284 * 3) the signed bounds cross zero, so they tell us nothing
3286 * If the value in dst_reg is known nonnegative, then again the
3287 * unsigned bounts capture the signed bounds.
3288 * Thus, in all cases it suffices to blow away our signed bounds
3289 * and rely on inferring new ones from the unsigned bounds and
3290 * var_off of the result.
3292 dst_reg->smin_value = S64_MIN;
3293 dst_reg->smax_value = S64_MAX;
3294 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3295 dst_reg->umin_value >>= umax_val;
3296 dst_reg->umax_value >>= umin_val;
3297 /* We may learn something more from the var_off */
3298 __update_reg_bounds(dst_reg);
3301 if (umax_val >= insn_bitness) {
3302 /* Shifts greater than 31 or 63 are undefined.
3303 * This includes shifts by a negative number.
3305 mark_reg_unknown(env, regs, insn->dst_reg);
3309 /* Upon reaching here, src_known is true and
3310 * umax_val is equal to umin_val.
3312 dst_reg->smin_value >>= umin_val;
3313 dst_reg->smax_value >>= umin_val;
3314 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
3316 /* blow away the dst_reg umin_value/umax_value and rely on
3317 * dst_reg var_off to refine the result.
3319 dst_reg->umin_value = 0;
3320 dst_reg->umax_value = U64_MAX;
3321 __update_reg_bounds(dst_reg);
3324 mark_reg_unknown(env, regs, insn->dst_reg);
3328 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3329 /* 32-bit ALU ops are (32,32)->32 */
3330 coerce_reg_to_size(dst_reg, 4);
3333 __reg_deduce_bounds(dst_reg);
3334 __reg_bound_offset(dst_reg);
3338 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3341 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3342 struct bpf_insn *insn)
3344 struct bpf_verifier_state *vstate = env->cur_state;
3345 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3346 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3347 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3348 u8 opcode = BPF_OP(insn->code);
3350 dst_reg = ®s[insn->dst_reg];
3352 if (dst_reg->type != SCALAR_VALUE)
3354 if (BPF_SRC(insn->code) == BPF_X) {
3355 src_reg = ®s[insn->src_reg];
3356 if (src_reg->type != SCALAR_VALUE) {
3357 if (dst_reg->type != SCALAR_VALUE) {
3358 /* Combining two pointers by any ALU op yields
3359 * an arbitrary scalar. Disallow all math except
3360 * pointer subtraction
3362 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
3363 mark_reg_unknown(env, regs, insn->dst_reg);
3366 verbose(env, "R%d pointer %s pointer prohibited\n",
3368 bpf_alu_string[opcode >> 4]);
3371 /* scalar += pointer
3372 * This is legal, but we have to reverse our
3373 * src/dest handling in computing the range
3375 return adjust_ptr_min_max_vals(env, insn,
3378 } else if (ptr_reg) {
3379 /* pointer += scalar */
3380 return adjust_ptr_min_max_vals(env, insn,
3384 /* Pretend the src is a reg with a known value, since we only
3385 * need to be able to read from this state.
3387 off_reg.type = SCALAR_VALUE;
3388 __mark_reg_known(&off_reg, insn->imm);
3390 if (ptr_reg) /* pointer += K */
3391 return adjust_ptr_min_max_vals(env, insn,
3395 /* Got here implies adding two SCALAR_VALUEs */
3396 if (WARN_ON_ONCE(ptr_reg)) {
3397 print_verifier_state(env, state);
3398 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3401 if (WARN_ON(!src_reg)) {
3402 print_verifier_state(env, state);
3403 verbose(env, "verifier internal error: no src_reg\n");
3406 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3409 /* check validity of 32-bit and 64-bit arithmetic operations */
3410 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3412 struct bpf_reg_state *regs = cur_regs(env);
3413 u8 opcode = BPF_OP(insn->code);
3416 if (opcode == BPF_END || opcode == BPF_NEG) {
3417 if (opcode == BPF_NEG) {
3418 if (BPF_SRC(insn->code) != 0 ||
3419 insn->src_reg != BPF_REG_0 ||
3420 insn->off != 0 || insn->imm != 0) {
3421 verbose(env, "BPF_NEG uses reserved fields\n");
3425 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3426 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3427 BPF_CLASS(insn->code) == BPF_ALU64) {
3428 verbose(env, "BPF_END uses reserved fields\n");
3433 /* check src operand */
3434 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3438 if (is_pointer_value(env, insn->dst_reg)) {
3439 verbose(env, "R%d pointer arithmetic prohibited\n",
3444 /* check dest operand */
3445 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3449 } else if (opcode == BPF_MOV) {
3451 if (BPF_SRC(insn->code) == BPF_X) {
3452 if (insn->imm != 0 || insn->off != 0) {
3453 verbose(env, "BPF_MOV uses reserved fields\n");
3457 /* check src operand */
3458 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3462 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3463 verbose(env, "BPF_MOV uses reserved fields\n");
3468 /* check dest operand, mark as required later */
3469 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3473 if (BPF_SRC(insn->code) == BPF_X) {
3474 struct bpf_reg_state *src_reg = regs + insn->src_reg;
3475 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
3477 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3479 * copy register state to dest reg
3481 *dst_reg = *src_reg;
3482 dst_reg->live |= REG_LIVE_WRITTEN;
3485 if (is_pointer_value(env, insn->src_reg)) {
3487 "R%d partial copy of pointer\n",
3490 } else if (src_reg->type == SCALAR_VALUE) {
3491 *dst_reg = *src_reg;
3492 dst_reg->live |= REG_LIVE_WRITTEN;
3494 mark_reg_unknown(env, regs,
3497 coerce_reg_to_size(dst_reg, 4);
3501 * remember the value we stored into this reg
3503 /* clear any state __mark_reg_known doesn't set */
3504 mark_reg_unknown(env, regs, insn->dst_reg);
3505 regs[insn->dst_reg].type = SCALAR_VALUE;
3506 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3507 __mark_reg_known(regs + insn->dst_reg,
3510 __mark_reg_known(regs + insn->dst_reg,
3515 } else if (opcode > BPF_END) {
3516 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3519 } else { /* all other ALU ops: and, sub, xor, add, ... */
3521 if (BPF_SRC(insn->code) == BPF_X) {
3522 if (insn->imm != 0 || insn->off != 0) {
3523 verbose(env, "BPF_ALU uses reserved fields\n");
3526 /* check src1 operand */
3527 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3531 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3532 verbose(env, "BPF_ALU uses reserved fields\n");
3537 /* check src2 operand */
3538 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3542 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3543 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3544 verbose(env, "div by zero\n");
3548 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3549 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3553 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3554 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3555 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3557 if (insn->imm < 0 || insn->imm >= size) {
3558 verbose(env, "invalid shift %d\n", insn->imm);
3563 /* check dest operand */
3564 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3568 return adjust_reg_min_max_vals(env, insn);
3574 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3575 struct bpf_reg_state *dst_reg,
3576 enum bpf_reg_type type,
3577 bool range_right_open)
3579 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3580 struct bpf_reg_state *regs = state->regs, *reg;
3584 if (dst_reg->off < 0 ||
3585 (dst_reg->off == 0 && range_right_open))
3586 /* This doesn't give us any range */
3589 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3590 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3591 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3592 * than pkt_end, but that's because it's also less than pkt.
3596 new_range = dst_reg->off;
3597 if (range_right_open)
3600 /* Examples for register markings:
3602 * pkt_data in dst register:
3606 * if (r2 > pkt_end) goto <handle exception>
3611 * if (r2 < pkt_end) goto <access okay>
3612 * <handle exception>
3615 * r2 == dst_reg, pkt_end == src_reg
3616 * r2=pkt(id=n,off=8,r=0)
3617 * r3=pkt(id=n,off=0,r=0)
3619 * pkt_data in src register:
3623 * if (pkt_end >= r2) goto <access okay>
3624 * <handle exception>
3628 * if (pkt_end <= r2) goto <handle exception>
3632 * pkt_end == dst_reg, r2 == src_reg
3633 * r2=pkt(id=n,off=8,r=0)
3634 * r3=pkt(id=n,off=0,r=0)
3636 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3637 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3638 * and [r3, r3 + 8-1) respectively is safe to access depending on
3642 /* If our ids match, then we must have the same max_value. And we
3643 * don't care about the other reg's fixed offset, since if it's too big
3644 * the range won't allow anything.
3645 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3647 for (i = 0; i < MAX_BPF_REG; i++)
3648 if (regs[i].type == type && regs[i].id == dst_reg->id)
3649 /* keep the maximum range already checked */
3650 regs[i].range = max(regs[i].range, new_range);
3652 for (j = 0; j <= vstate->curframe; j++) {
3653 state = vstate->frame[j];
3654 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3655 if (state->stack[i].slot_type[0] != STACK_SPILL)
3657 reg = &state->stack[i].spilled_ptr;
3658 if (reg->type == type && reg->id == dst_reg->id)
3659 reg->range = max(reg->range, new_range);
3664 /* compute branch direction of the expression "if (reg opcode val) goto target;"
3666 * 1 - branch will be taken and "goto target" will be executed
3667 * 0 - branch will not be taken and fall-through to next insn
3668 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
3670 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
3672 if (__is_pointer_value(false, reg))
3677 if (tnum_is_const(reg->var_off))
3678 return !!tnum_equals_const(reg->var_off, val);
3681 if (tnum_is_const(reg->var_off))
3682 return !tnum_equals_const(reg->var_off, val);
3685 if (reg->umin_value > val)
3687 else if (reg->umax_value <= val)
3691 if (reg->smin_value > (s64)val)
3693 else if (reg->smax_value < (s64)val)
3697 if (reg->umax_value < val)
3699 else if (reg->umin_value >= val)
3703 if (reg->smax_value < (s64)val)
3705 else if (reg->smin_value >= (s64)val)
3709 if (reg->umin_value >= val)
3711 else if (reg->umax_value < val)
3715 if (reg->smin_value >= (s64)val)
3717 else if (reg->smax_value < (s64)val)
3721 if (reg->umax_value <= val)
3723 else if (reg->umin_value > val)
3727 if (reg->smax_value <= (s64)val)
3729 else if (reg->smin_value > (s64)val)
3737 /* Adjusts the register min/max values in the case that the dst_reg is the
3738 * variable register that we are working on, and src_reg is a constant or we're
3739 * simply doing a BPF_K check.
3740 * In JEQ/JNE cases we also adjust the var_off values.
3742 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3743 struct bpf_reg_state *false_reg, u64 val,
3746 /* If the dst_reg is a pointer, we can't learn anything about its
3747 * variable offset from the compare (unless src_reg were a pointer into
3748 * the same object, but we don't bother with that.
3749 * Since false_reg and true_reg have the same type by construction, we
3750 * only need to check one of them for pointerness.
3752 if (__is_pointer_value(false, false_reg))
3757 /* If this is false then we know nothing Jon Snow, but if it is
3758 * true then we know for sure.
3760 __mark_reg_known(true_reg, val);
3763 /* If this is true we know nothing Jon Snow, but if it is false
3764 * we know the value for sure;
3766 __mark_reg_known(false_reg, val);
3769 false_reg->umax_value = min(false_reg->umax_value, val);
3770 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3773 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3774 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3777 false_reg->umin_value = max(false_reg->umin_value, val);
3778 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3781 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3782 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3785 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3786 true_reg->umin_value = max(true_reg->umin_value, val);
3789 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3790 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3793 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3794 true_reg->umax_value = min(true_reg->umax_value, val);
3797 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3798 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3804 __reg_deduce_bounds(false_reg);
3805 __reg_deduce_bounds(true_reg);
3806 /* We might have learned some bits from the bounds. */
3807 __reg_bound_offset(false_reg);
3808 __reg_bound_offset(true_reg);
3809 /* Intersecting with the old var_off might have improved our bounds
3810 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3811 * then new var_off is (0; 0x7f...fc) which improves our umax.
3813 __update_reg_bounds(false_reg);
3814 __update_reg_bounds(true_reg);
3817 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3820 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3821 struct bpf_reg_state *false_reg, u64 val,
3824 if (__is_pointer_value(false, false_reg))
3829 /* If this is false then we know nothing Jon Snow, but if it is
3830 * true then we know for sure.
3832 __mark_reg_known(true_reg, val);
3835 /* If this is true we know nothing Jon Snow, but if it is false
3836 * we know the value for sure;
3838 __mark_reg_known(false_reg, val);
3841 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3842 false_reg->umin_value = max(false_reg->umin_value, val);
3845 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3846 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3849 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3850 false_reg->umax_value = min(false_reg->umax_value, val);
3853 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3854 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3857 true_reg->umax_value = min(true_reg->umax_value, val);
3858 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3861 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3862 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3865 true_reg->umin_value = max(true_reg->umin_value, val);
3866 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3869 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3870 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3876 __reg_deduce_bounds(false_reg);
3877 __reg_deduce_bounds(true_reg);
3878 /* We might have learned some bits from the bounds. */
3879 __reg_bound_offset(false_reg);
3880 __reg_bound_offset(true_reg);
3881 /* Intersecting with the old var_off might have improved our bounds
3882 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3883 * then new var_off is (0; 0x7f...fc) which improves our umax.
3885 __update_reg_bounds(false_reg);
3886 __update_reg_bounds(true_reg);
3889 /* Regs are known to be equal, so intersect their min/max/var_off */
3890 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3891 struct bpf_reg_state *dst_reg)
3893 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3894 dst_reg->umin_value);
3895 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3896 dst_reg->umax_value);
3897 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3898 dst_reg->smin_value);
3899 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3900 dst_reg->smax_value);
3901 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3903 /* We might have learned new bounds from the var_off. */
3904 __update_reg_bounds(src_reg);
3905 __update_reg_bounds(dst_reg);
3906 /* We might have learned something about the sign bit. */
3907 __reg_deduce_bounds(src_reg);
3908 __reg_deduce_bounds(dst_reg);
3909 /* We might have learned some bits from the bounds. */
3910 __reg_bound_offset(src_reg);
3911 __reg_bound_offset(dst_reg);
3912 /* Intersecting with the old var_off might have improved our bounds
3913 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3914 * then new var_off is (0; 0x7f...fc) which improves our umax.
3916 __update_reg_bounds(src_reg);
3917 __update_reg_bounds(dst_reg);
3920 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3921 struct bpf_reg_state *true_dst,
3922 struct bpf_reg_state *false_src,
3923 struct bpf_reg_state *false_dst,
3928 __reg_combine_min_max(true_src, true_dst);
3931 __reg_combine_min_max(false_src, false_dst);
3936 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3939 struct bpf_reg_state *reg = ®s[regno];
3941 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3942 /* Old offset (both fixed and variable parts) should
3943 * have been known-zero, because we don't allow pointer
3944 * arithmetic on pointers that might be NULL.
3946 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3947 !tnum_equals_const(reg->var_off, 0) ||
3949 __mark_reg_known_zero(reg);
3953 reg->type = SCALAR_VALUE;
3954 } else if (reg->map_ptr->inner_map_meta) {
3955 reg->type = CONST_PTR_TO_MAP;
3956 reg->map_ptr = reg->map_ptr->inner_map_meta;
3958 reg->type = PTR_TO_MAP_VALUE;
3960 /* We don't need id from this point onwards anymore, thus we
3961 * should better reset it, so that state pruning has chances
3968 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3969 * be folded together at some point.
3971 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
3974 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3975 struct bpf_reg_state *regs = state->regs;
3976 u32 id = regs[regno].id;
3979 for (i = 0; i < MAX_BPF_REG; i++)
3980 mark_map_reg(regs, i, id, is_null);
3982 for (j = 0; j <= vstate->curframe; j++) {
3983 state = vstate->frame[j];
3984 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3985 if (state->stack[i].slot_type[0] != STACK_SPILL)
3987 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3992 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
3993 struct bpf_reg_state *dst_reg,
3994 struct bpf_reg_state *src_reg,
3995 struct bpf_verifier_state *this_branch,
3996 struct bpf_verifier_state *other_branch)
3998 if (BPF_SRC(insn->code) != BPF_X)
4001 switch (BPF_OP(insn->code)) {
4003 if ((dst_reg->type == PTR_TO_PACKET &&
4004 src_reg->type == PTR_TO_PACKET_END) ||
4005 (dst_reg->type == PTR_TO_PACKET_META &&
4006 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4007 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4008 find_good_pkt_pointers(this_branch, dst_reg,
4009 dst_reg->type, false);
4010 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4011 src_reg->type == PTR_TO_PACKET) ||
4012 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4013 src_reg->type == PTR_TO_PACKET_META)) {
4014 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4015 find_good_pkt_pointers(other_branch, src_reg,
4016 src_reg->type, true);
4022 if ((dst_reg->type == PTR_TO_PACKET &&
4023 src_reg->type == PTR_TO_PACKET_END) ||
4024 (dst_reg->type == PTR_TO_PACKET_META &&
4025 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4026 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4027 find_good_pkt_pointers(other_branch, dst_reg,
4028 dst_reg->type, true);
4029 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4030 src_reg->type == PTR_TO_PACKET) ||
4031 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4032 src_reg->type == PTR_TO_PACKET_META)) {
4033 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
4034 find_good_pkt_pointers(this_branch, src_reg,
4035 src_reg->type, false);
4041 if ((dst_reg->type == PTR_TO_PACKET &&
4042 src_reg->type == PTR_TO_PACKET_END) ||
4043 (dst_reg->type == PTR_TO_PACKET_META &&
4044 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4045 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
4046 find_good_pkt_pointers(this_branch, dst_reg,
4047 dst_reg->type, true);
4048 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4049 src_reg->type == PTR_TO_PACKET) ||
4050 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4051 src_reg->type == PTR_TO_PACKET_META)) {
4052 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
4053 find_good_pkt_pointers(other_branch, src_reg,
4054 src_reg->type, false);
4060 if ((dst_reg->type == PTR_TO_PACKET &&
4061 src_reg->type == PTR_TO_PACKET_END) ||
4062 (dst_reg->type == PTR_TO_PACKET_META &&
4063 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4064 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
4065 find_good_pkt_pointers(other_branch, dst_reg,
4066 dst_reg->type, false);
4067 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4068 src_reg->type == PTR_TO_PACKET) ||
4069 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4070 src_reg->type == PTR_TO_PACKET_META)) {
4071 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
4072 find_good_pkt_pointers(this_branch, src_reg,
4073 src_reg->type, true);
4085 static int check_cond_jmp_op(struct bpf_verifier_env *env,
4086 struct bpf_insn *insn, int *insn_idx)
4088 struct bpf_verifier_state *this_branch = env->cur_state;
4089 struct bpf_verifier_state *other_branch;
4090 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
4091 struct bpf_reg_state *dst_reg, *other_branch_regs;
4092 u8 opcode = BPF_OP(insn->code);
4095 if (opcode > BPF_JSLE) {
4096 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
4100 if (BPF_SRC(insn->code) == BPF_X) {
4101 if (insn->imm != 0) {
4102 verbose(env, "BPF_JMP uses reserved fields\n");
4106 /* check src1 operand */
4107 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4111 if (is_pointer_value(env, insn->src_reg)) {
4112 verbose(env, "R%d pointer comparison prohibited\n",
4117 if (insn->src_reg != BPF_REG_0) {
4118 verbose(env, "BPF_JMP uses reserved fields\n");
4123 /* check src2 operand */
4124 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4128 dst_reg = ®s[insn->dst_reg];
4130 if (BPF_SRC(insn->code) == BPF_K) {
4131 int pred = is_branch_taken(dst_reg, insn->imm, opcode);
4134 /* only follow the goto, ignore fall-through */
4135 *insn_idx += insn->off;
4137 } else if (pred == 0) {
4138 /* only follow fall-through branch, since
4139 * that's where the program will go
4145 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
4149 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
4151 /* detect if we are comparing against a constant value so we can adjust
4152 * our min/max values for our dst register.
4153 * this is only legit if both are scalars (or pointers to the same
4154 * object, I suppose, but we don't support that right now), because
4155 * otherwise the different base pointers mean the offsets aren't
4158 if (BPF_SRC(insn->code) == BPF_X) {
4159 if (dst_reg->type == SCALAR_VALUE &&
4160 regs[insn->src_reg].type == SCALAR_VALUE) {
4161 if (tnum_is_const(regs[insn->src_reg].var_off))
4162 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4163 dst_reg, regs[insn->src_reg].var_off.value,
4165 else if (tnum_is_const(dst_reg->var_off))
4166 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
4167 ®s[insn->src_reg],
4168 dst_reg->var_off.value, opcode);
4169 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
4170 /* Comparing for equality, we can combine knowledge */
4171 reg_combine_min_max(&other_branch_regs[insn->src_reg],
4172 &other_branch_regs[insn->dst_reg],
4173 ®s[insn->src_reg],
4174 ®s[insn->dst_reg], opcode);
4176 } else if (dst_reg->type == SCALAR_VALUE) {
4177 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4178 dst_reg, insn->imm, opcode);
4181 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
4182 if (BPF_SRC(insn->code) == BPF_K &&
4183 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4184 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
4185 /* Mark all identical map registers in each branch as either
4186 * safe or unknown depending R == 0 or R != 0 conditional.
4188 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
4189 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
4190 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
4191 this_branch, other_branch) &&
4192 is_pointer_value(env, insn->dst_reg)) {
4193 verbose(env, "R%d pointer comparison prohibited\n",
4198 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
4202 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
4203 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
4205 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
4207 return (struct bpf_map *) (unsigned long) imm64;
4210 /* verify BPF_LD_IMM64 instruction */
4211 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
4213 struct bpf_reg_state *regs = cur_regs(env);
4216 if (BPF_SIZE(insn->code) != BPF_DW) {
4217 verbose(env, "invalid BPF_LD_IMM insn\n");
4220 if (insn->off != 0) {
4221 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
4225 err = check_reg_arg(env, insn->dst_reg, DST_OP);
4229 if (insn->src_reg == 0) {
4230 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
4232 regs[insn->dst_reg].type = SCALAR_VALUE;
4233 __mark_reg_known(®s[insn->dst_reg], imm);
4237 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
4238 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
4240 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
4241 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
4245 static bool may_access_skb(enum bpf_prog_type type)
4248 case BPF_PROG_TYPE_SOCKET_FILTER:
4249 case BPF_PROG_TYPE_SCHED_CLS:
4250 case BPF_PROG_TYPE_SCHED_ACT:
4257 /* verify safety of LD_ABS|LD_IND instructions:
4258 * - they can only appear in the programs where ctx == skb
4259 * - since they are wrappers of function calls, they scratch R1-R5 registers,
4260 * preserve R6-R9, and store return value into R0
4263 * ctx == skb == R6 == CTX
4266 * SRC == any register
4267 * IMM == 32-bit immediate
4270 * R0 - 8/16/32-bit skb data converted to cpu endianness
4272 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
4274 struct bpf_reg_state *regs = cur_regs(env);
4275 u8 mode = BPF_MODE(insn->code);
4278 if (!may_access_skb(env->prog->type)) {
4279 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
4283 if (!env->ops->gen_ld_abs) {
4284 verbose(env, "bpf verifier is misconfigured\n");
4288 if (env->subprog_cnt > 1) {
4289 /* when program has LD_ABS insn JITs and interpreter assume
4290 * that r1 == ctx == skb which is not the case for callees
4291 * that can have arbitrary arguments. It's problematic
4292 * for main prog as well since JITs would need to analyze
4293 * all functions in order to make proper register save/restore
4294 * decisions in the main prog. Hence disallow LD_ABS with calls
4296 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
4300 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
4301 BPF_SIZE(insn->code) == BPF_DW ||
4302 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
4303 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
4307 /* check whether implicit source operand (register R6) is readable */
4308 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
4312 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
4314 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
4318 if (mode == BPF_IND) {
4319 /* check explicit source operand */
4320 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4325 /* reset caller saved regs to unreadable */
4326 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4327 mark_reg_not_init(env, regs, caller_saved[i]);
4328 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4331 /* mark destination R0 register as readable, since it contains
4332 * the value fetched from the packet.
4333 * Already marked as written above.
4335 mark_reg_unknown(env, regs, BPF_REG_0);
4339 static int check_return_code(struct bpf_verifier_env *env)
4341 struct bpf_reg_state *reg;
4342 struct tnum range = tnum_range(0, 1);
4344 switch (env->prog->type) {
4345 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4346 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
4347 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
4348 range = tnum_range(1, 1);
4349 case BPF_PROG_TYPE_CGROUP_SKB:
4350 case BPF_PROG_TYPE_CGROUP_SOCK:
4351 case BPF_PROG_TYPE_SOCK_OPS:
4352 case BPF_PROG_TYPE_CGROUP_DEVICE:
4358 reg = cur_regs(env) + BPF_REG_0;
4359 if (reg->type != SCALAR_VALUE) {
4360 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
4361 reg_type_str[reg->type]);
4365 if (!tnum_in(range, reg->var_off)) {
4368 verbose(env, "At program exit the register R0 ");
4369 if (!tnum_is_unknown(reg->var_off)) {
4370 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4371 verbose(env, "has value %s", tn_buf);
4373 verbose(env, "has unknown scalar value");
4375 tnum_strn(tn_buf, sizeof(tn_buf), range);
4376 verbose(env, " should have been in %s\n", tn_buf);
4382 /* non-recursive DFS pseudo code
4383 * 1 procedure DFS-iterative(G,v):
4384 * 2 label v as discovered
4385 * 3 let S be a stack
4387 * 5 while S is not empty
4389 * 7 if t is what we're looking for:
4391 * 9 for all edges e in G.adjacentEdges(t) do
4392 * 10 if edge e is already labelled
4393 * 11 continue with the next edge
4394 * 12 w <- G.adjacentVertex(t,e)
4395 * 13 if vertex w is not discovered and not explored
4396 * 14 label e as tree-edge
4397 * 15 label w as discovered
4400 * 18 else if vertex w is discovered
4401 * 19 label e as back-edge
4403 * 21 // vertex w is explored
4404 * 22 label e as forward- or cross-edge
4405 * 23 label t as explored
4410 * 0x11 - discovered and fall-through edge labelled
4411 * 0x12 - discovered and fall-through and branch edges labelled
4422 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
4424 static int *insn_stack; /* stack of insns to process */
4425 static int cur_stack; /* current stack index */
4426 static int *insn_state;
4428 /* t, w, e - match pseudo-code above:
4429 * t - index of current instruction
4430 * w - next instruction
4433 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
4435 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
4438 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
4441 if (w < 0 || w >= env->prog->len) {
4442 verbose(env, "jump out of range from insn %d to %d\n", t, w);
4447 /* mark branch target for state pruning */
4448 env->explored_states[w] = STATE_LIST_MARK;
4450 if (insn_state[w] == 0) {
4452 insn_state[t] = DISCOVERED | e;
4453 insn_state[w] = DISCOVERED;
4454 if (cur_stack >= env->prog->len)
4456 insn_stack[cur_stack++] = w;
4458 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4459 verbose(env, "back-edge from insn %d to %d\n", t, w);
4461 } else if (insn_state[w] == EXPLORED) {
4462 /* forward- or cross-edge */
4463 insn_state[t] = DISCOVERED | e;
4465 verbose(env, "insn state internal bug\n");
4471 /* non-recursive depth-first-search to detect loops in BPF program
4472 * loop == back-edge in directed graph
4474 static int check_cfg(struct bpf_verifier_env *env)
4476 struct bpf_insn *insns = env->prog->insnsi;
4477 int insn_cnt = env->prog->len;
4481 ret = check_subprogs(env);
4485 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4489 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4495 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4496 insn_stack[0] = 0; /* 0 is the first instruction */
4502 t = insn_stack[cur_stack - 1];
4504 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4505 u8 opcode = BPF_OP(insns[t].code);
4507 if (opcode == BPF_EXIT) {
4509 } else if (opcode == BPF_CALL) {
4510 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4515 if (t + 1 < insn_cnt)
4516 env->explored_states[t + 1] = STATE_LIST_MARK;
4517 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4518 env->explored_states[t] = STATE_LIST_MARK;
4519 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4525 } else if (opcode == BPF_JA) {
4526 if (BPF_SRC(insns[t].code) != BPF_K) {
4530 /* unconditional jump with single edge */
4531 ret = push_insn(t, t + insns[t].off + 1,
4537 /* tell verifier to check for equivalent states
4538 * after every call and jump
4540 if (t + 1 < insn_cnt)
4541 env->explored_states[t + 1] = STATE_LIST_MARK;
4543 /* conditional jump with two edges */
4544 env->explored_states[t] = STATE_LIST_MARK;
4545 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4551 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4558 /* all other non-branch instructions with single
4561 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4569 insn_state[t] = EXPLORED;
4570 if (cur_stack-- <= 0) {
4571 verbose(env, "pop stack internal bug\n");
4578 for (i = 0; i < insn_cnt; i++) {
4579 if (insn_state[i] != EXPLORED) {
4580 verbose(env, "unreachable insn %d\n", i);
4585 ret = 0; /* cfg looks good */
4593 /* check %cur's range satisfies %old's */
4594 static bool range_within(struct bpf_reg_state *old,
4595 struct bpf_reg_state *cur)
4597 return old->umin_value <= cur->umin_value &&
4598 old->umax_value >= cur->umax_value &&
4599 old->smin_value <= cur->smin_value &&
4600 old->smax_value >= cur->smax_value;
4603 /* Maximum number of register states that can exist at once */
4604 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4610 /* If in the old state two registers had the same id, then they need to have
4611 * the same id in the new state as well. But that id could be different from
4612 * the old state, so we need to track the mapping from old to new ids.
4613 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4614 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4615 * regs with a different old id could still have new id 9, we don't care about
4617 * So we look through our idmap to see if this old id has been seen before. If
4618 * so, we require the new id to match; otherwise, we add the id pair to the map.
4620 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4624 for (i = 0; i < ID_MAP_SIZE; i++) {
4625 if (!idmap[i].old) {
4626 /* Reached an empty slot; haven't seen this id before */
4627 idmap[i].old = old_id;
4628 idmap[i].cur = cur_id;
4631 if (idmap[i].old == old_id)
4632 return idmap[i].cur == cur_id;
4634 /* We ran out of idmap slots, which should be impossible */
4639 /* Returns true if (rold safe implies rcur safe) */
4640 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4641 struct idpair *idmap)
4645 if (!(rold->live & REG_LIVE_READ))
4646 /* explored state didn't use this */
4649 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
4651 if (rold->type == PTR_TO_STACK)
4652 /* two stack pointers are equal only if they're pointing to
4653 * the same stack frame, since fp-8 in foo != fp-8 in bar
4655 return equal && rold->frameno == rcur->frameno;
4660 if (rold->type == NOT_INIT)
4661 /* explored state can't have used this */
4663 if (rcur->type == NOT_INIT)
4665 switch (rold->type) {
4667 if (rcur->type == SCALAR_VALUE) {
4668 /* new val must satisfy old val knowledge */
4669 return range_within(rold, rcur) &&
4670 tnum_in(rold->var_off, rcur->var_off);
4672 /* We're trying to use a pointer in place of a scalar.
4673 * Even if the scalar was unbounded, this could lead to
4674 * pointer leaks because scalars are allowed to leak
4675 * while pointers are not. We could make this safe in
4676 * special cases if root is calling us, but it's
4677 * probably not worth the hassle.
4681 case PTR_TO_MAP_VALUE:
4682 /* If the new min/max/var_off satisfy the old ones and
4683 * everything else matches, we are OK.
4684 * We don't care about the 'id' value, because nothing
4685 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4687 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4688 range_within(rold, rcur) &&
4689 tnum_in(rold->var_off, rcur->var_off);
4690 case PTR_TO_MAP_VALUE_OR_NULL:
4691 /* a PTR_TO_MAP_VALUE could be safe to use as a
4692 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4693 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4694 * checked, doing so could have affected others with the same
4695 * id, and we can't check for that because we lost the id when
4696 * we converted to a PTR_TO_MAP_VALUE.
4698 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4700 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4702 /* Check our ids match any regs they're supposed to */
4703 return check_ids(rold->id, rcur->id, idmap);
4704 case PTR_TO_PACKET_META:
4706 if (rcur->type != rold->type)
4708 /* We must have at least as much range as the old ptr
4709 * did, so that any accesses which were safe before are
4710 * still safe. This is true even if old range < old off,
4711 * since someone could have accessed through (ptr - k), or
4712 * even done ptr -= k in a register, to get a safe access.
4714 if (rold->range > rcur->range)
4716 /* If the offsets don't match, we can't trust our alignment;
4717 * nor can we be sure that we won't fall out of range.
4719 if (rold->off != rcur->off)
4721 /* id relations must be preserved */
4722 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4724 /* new val must satisfy old val knowledge */
4725 return range_within(rold, rcur) &&
4726 tnum_in(rold->var_off, rcur->var_off);
4728 case CONST_PTR_TO_MAP:
4729 case PTR_TO_PACKET_END:
4730 /* Only valid matches are exact, which memcmp() above
4731 * would have accepted
4734 /* Don't know what's going on, just say it's not safe */
4738 /* Shouldn't get here; if we do, say it's not safe */
4743 static bool stacksafe(struct bpf_func_state *old,
4744 struct bpf_func_state *cur,
4745 struct idpair *idmap)
4749 /* if explored stack has more populated slots than current stack
4750 * such stacks are not equivalent
4752 if (old->allocated_stack > cur->allocated_stack)
4755 /* walk slots of the explored stack and ignore any additional
4756 * slots in the current stack, since explored(safe) state
4759 for (i = 0; i < old->allocated_stack; i++) {
4760 spi = i / BPF_REG_SIZE;
4762 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4763 /* explored state didn't use this */
4766 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4768 /* if old state was safe with misc data in the stack
4769 * it will be safe with zero-initialized stack.
4770 * The opposite is not true
4772 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4773 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4775 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4776 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4777 /* Ex: old explored (safe) state has STACK_SPILL in
4778 * this stack slot, but current has has STACK_MISC ->
4779 * this verifier states are not equivalent,
4780 * return false to continue verification of this path
4783 if (i % BPF_REG_SIZE)
4785 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4787 if (!regsafe(&old->stack[spi].spilled_ptr,
4788 &cur->stack[spi].spilled_ptr,
4790 /* when explored and current stack slot are both storing
4791 * spilled registers, check that stored pointers types
4792 * are the same as well.
4793 * Ex: explored safe path could have stored
4794 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4795 * but current path has stored:
4796 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4797 * such verifier states are not equivalent.
4798 * return false to continue verification of this path
4805 /* compare two verifier states
4807 * all states stored in state_list are known to be valid, since
4808 * verifier reached 'bpf_exit' instruction through them
4810 * this function is called when verifier exploring different branches of
4811 * execution popped from the state stack. If it sees an old state that has
4812 * more strict register state and more strict stack state then this execution
4813 * branch doesn't need to be explored further, since verifier already
4814 * concluded that more strict state leads to valid finish.
4816 * Therefore two states are equivalent if register state is more conservative
4817 * and explored stack state is more conservative than the current one.
4820 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
4821 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
4823 * In other words if current stack state (one being explored) has more
4824 * valid slots than old one that already passed validation, it means
4825 * the verifier can stop exploring and conclude that current state is valid too
4827 * Similarly with registers. If explored state has register type as invalid
4828 * whereas register type in current state is meaningful, it means that
4829 * the current state will reach 'bpf_exit' instruction safely
4831 static bool func_states_equal(struct bpf_func_state *old,
4832 struct bpf_func_state *cur)
4834 struct idpair *idmap;
4838 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4839 /* If we failed to allocate the idmap, just say it's not safe */
4843 for (i = 0; i < MAX_BPF_REG; i++) {
4844 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4848 if (!stacksafe(old, cur, idmap))
4856 static bool states_equal(struct bpf_verifier_env *env,
4857 struct bpf_verifier_state *old,
4858 struct bpf_verifier_state *cur)
4862 if (old->curframe != cur->curframe)
4865 /* Verification state from speculative execution simulation
4866 * must never prune a non-speculative execution one.
4868 if (old->speculative && !cur->speculative)
4871 /* for states to be equal callsites have to be the same
4872 * and all frame states need to be equivalent
4874 for (i = 0; i <= old->curframe; i++) {
4875 if (old->frame[i]->callsite != cur->frame[i]->callsite)
4877 if (!func_states_equal(old->frame[i], cur->frame[i]))
4883 /* A write screens off any subsequent reads; but write marks come from the
4884 * straight-line code between a state and its parent. When we arrive at an
4885 * equivalent state (jump target or such) we didn't arrive by the straight-line
4886 * code, so read marks in the state must propagate to the parent regardless
4887 * of the state's write marks. That's what 'parent == state->parent' comparison
4888 * in mark_reg_read() and mark_stack_slot_read() is for.
4890 static int propagate_liveness(struct bpf_verifier_env *env,
4891 const struct bpf_verifier_state *vstate,
4892 struct bpf_verifier_state *vparent)
4894 int i, frame, err = 0;
4895 struct bpf_func_state *state, *parent;
4897 if (vparent->curframe != vstate->curframe) {
4898 WARN(1, "propagate_live: parent frame %d current frame %d\n",
4899 vparent->curframe, vstate->curframe);
4902 /* Propagate read liveness of registers... */
4903 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4904 /* We don't need to worry about FP liveness because it's read-only */
4905 for (i = 0; i < BPF_REG_FP; i++) {
4906 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
4908 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
4909 err = mark_reg_read(env, vstate, vparent, i);
4915 /* ... and stack slots */
4916 for (frame = 0; frame <= vstate->curframe; frame++) {
4917 state = vstate->frame[frame];
4918 parent = vparent->frame[frame];
4919 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4920 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4921 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4923 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
4924 mark_stack_slot_read(env, vstate, vparent, i, frame);
4930 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4932 struct bpf_verifier_state_list *new_sl;
4933 struct bpf_verifier_state_list *sl;
4934 struct bpf_verifier_state *cur = env->cur_state;
4935 int i, j, err, states_cnt = 0;
4937 sl = env->explored_states[insn_idx];
4939 /* this 'insn_idx' instruction wasn't marked, so we will not
4940 * be doing state search here
4944 while (sl != STATE_LIST_MARK) {
4945 if (states_equal(env, &sl->state, cur)) {
4946 /* reached equivalent register/stack state,
4948 * Registers read by the continuation are read by us.
4949 * If we have any write marks in env->cur_state, they
4950 * will prevent corresponding reads in the continuation
4951 * from reaching our parent (an explored_state). Our
4952 * own state will get the read marks recorded, but
4953 * they'll be immediately forgotten as we're pruning
4954 * this state and will pop a new one.
4956 err = propagate_liveness(env, &sl->state, cur);
4965 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
4968 /* there were no equivalent states, remember current one.
4969 * technically the current state is not proven to be safe yet,
4970 * but it will either reach outer most bpf_exit (which means it's safe)
4971 * or it will be rejected. Since there are no loops, we won't be
4972 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
4973 * again on the way to bpf_exit
4975 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4979 /* add new state to the head of linked list */
4980 err = copy_verifier_state(&new_sl->state, cur);
4982 free_verifier_state(&new_sl->state, false);
4986 new_sl->next = env->explored_states[insn_idx];
4987 env->explored_states[insn_idx] = new_sl;
4988 /* connect new state to parentage chain */
4989 cur->parent = &new_sl->state;
4990 /* clear write marks in current state: the writes we did are not writes
4991 * our child did, so they don't screen off its reads from us.
4992 * (There are no read marks in current state, because reads always mark
4993 * their parent and current state never has children yet. Only
4994 * explored_states can get read marks.)
4996 for (i = 0; i < BPF_REG_FP; i++)
4997 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
4999 /* all stack frames are accessible from callee, clear them all */
5000 for (j = 0; j <= cur->curframe; j++) {
5001 struct bpf_func_state *frame = cur->frame[j];
5003 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
5004 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
5009 static int do_check(struct bpf_verifier_env *env)
5011 struct bpf_verifier_state *state;
5012 struct bpf_insn *insns = env->prog->insnsi;
5013 struct bpf_reg_state *regs;
5014 int insn_cnt = env->prog->len, i;
5015 int insn_processed = 0;
5016 bool do_print_state = false;
5018 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
5021 state->curframe = 0;
5022 state->speculative = false;
5023 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
5024 if (!state->frame[0]) {
5028 env->cur_state = state;
5029 init_func_state(env, state->frame[0],
5030 BPF_MAIN_FUNC /* callsite */,
5032 0 /* subprogno, zero == main subprog */);
5035 struct bpf_insn *insn;
5039 if (env->insn_idx >= insn_cnt) {
5040 verbose(env, "invalid insn idx %d insn_cnt %d\n",
5041 env->insn_idx, insn_cnt);
5045 insn = &insns[env->insn_idx];
5046 class = BPF_CLASS(insn->code);
5048 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
5050 "BPF program is too large. Processed %d insn\n",
5055 err = is_state_visited(env, env->insn_idx);
5059 /* found equivalent state, can prune the search */
5060 if (env->log.level) {
5062 verbose(env, "\nfrom %d to %d%s: safe\n",
5063 env->prev_insn_idx, env->insn_idx,
5064 env->cur_state->speculative ?
5065 " (speculative execution)" : "");
5067 verbose(env, "%d: safe\n", env->insn_idx);
5069 goto process_bpf_exit;
5072 if (signal_pending(current))
5078 if (env->log.level > 1 || (env->log.level && do_print_state)) {
5079 if (env->log.level > 1)
5080 verbose(env, "%d:", env->insn_idx);
5082 verbose(env, "\nfrom %d to %d%s:",
5083 env->prev_insn_idx, env->insn_idx,
5084 env->cur_state->speculative ?
5085 " (speculative execution)" : "");
5086 print_verifier_state(env, state->frame[state->curframe]);
5087 do_print_state = false;
5090 if (env->log.level) {
5091 const struct bpf_insn_cbs cbs = {
5092 .cb_print = verbose,
5093 .private_data = env,
5096 verbose(env, "%d: ", env->insn_idx);
5097 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
5100 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5101 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
5102 env->prev_insn_idx);
5107 regs = cur_regs(env);
5108 env->insn_aux_data[env->insn_idx].seen = true;
5110 if (class == BPF_ALU || class == BPF_ALU64) {
5111 err = check_alu_op(env, insn);
5115 } else if (class == BPF_LDX) {
5116 enum bpf_reg_type *prev_src_type, src_reg_type;
5118 /* check for reserved fields is already done */
5120 /* check src operand */
5121 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5125 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5129 src_reg_type = regs[insn->src_reg].type;
5131 /* check that memory (src_reg + off) is readable,
5132 * the state of dst_reg will be updated by this func
5134 err = check_mem_access(env, env->insn_idx, insn->src_reg,
5135 insn->off, BPF_SIZE(insn->code),
5136 BPF_READ, insn->dst_reg, false);
5140 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5142 if (*prev_src_type == NOT_INIT) {
5144 * dst_reg = *(u32 *)(src_reg + off)
5145 * save type to validate intersecting paths
5147 *prev_src_type = src_reg_type;
5149 } else if (src_reg_type != *prev_src_type &&
5150 (src_reg_type == PTR_TO_CTX ||
5151 *prev_src_type == PTR_TO_CTX)) {
5152 /* ABuser program is trying to use the same insn
5153 * dst_reg = *(u32*) (src_reg + off)
5154 * with different pointer types:
5155 * src_reg == ctx in one branch and
5156 * src_reg == stack|map in some other branch.
5159 verbose(env, "same insn cannot be used with different pointers\n");
5163 } else if (class == BPF_STX) {
5164 enum bpf_reg_type *prev_dst_type, dst_reg_type;
5166 if (BPF_MODE(insn->code) == BPF_XADD) {
5167 err = check_xadd(env, env->insn_idx, insn);
5174 /* check src1 operand */
5175 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5178 /* check src2 operand */
5179 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5183 dst_reg_type = regs[insn->dst_reg].type;
5185 /* check that memory (dst_reg + off) is writeable */
5186 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5187 insn->off, BPF_SIZE(insn->code),
5188 BPF_WRITE, insn->src_reg, false);
5192 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5194 if (*prev_dst_type == NOT_INIT) {
5195 *prev_dst_type = dst_reg_type;
5196 } else if (dst_reg_type != *prev_dst_type &&
5197 (dst_reg_type == PTR_TO_CTX ||
5198 *prev_dst_type == PTR_TO_CTX)) {
5199 verbose(env, "same insn cannot be used with different pointers\n");
5203 } else if (class == BPF_ST) {
5204 if (BPF_MODE(insn->code) != BPF_MEM ||
5205 insn->src_reg != BPF_REG_0) {
5206 verbose(env, "BPF_ST uses reserved fields\n");
5209 /* check src operand */
5210 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5214 if (is_ctx_reg(env, insn->dst_reg)) {
5215 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
5220 /* check that memory (dst_reg + off) is writeable */
5221 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5222 insn->off, BPF_SIZE(insn->code),
5223 BPF_WRITE, -1, false);
5227 } else if (class == BPF_JMP) {
5228 u8 opcode = BPF_OP(insn->code);
5230 if (opcode == BPF_CALL) {
5231 if (BPF_SRC(insn->code) != BPF_K ||
5233 (insn->src_reg != BPF_REG_0 &&
5234 insn->src_reg != BPF_PSEUDO_CALL) ||
5235 insn->dst_reg != BPF_REG_0) {
5236 verbose(env, "BPF_CALL uses reserved fields\n");
5240 if (insn->src_reg == BPF_PSEUDO_CALL)
5241 err = check_func_call(env, insn, &env->insn_idx);
5243 err = check_helper_call(env, insn->imm, env->insn_idx);
5247 } else if (opcode == BPF_JA) {
5248 if (BPF_SRC(insn->code) != BPF_K ||
5250 insn->src_reg != BPF_REG_0 ||
5251 insn->dst_reg != BPF_REG_0) {
5252 verbose(env, "BPF_JA uses reserved fields\n");
5256 env->insn_idx += insn->off + 1;
5259 } else if (opcode == BPF_EXIT) {
5260 if (BPF_SRC(insn->code) != BPF_K ||
5262 insn->src_reg != BPF_REG_0 ||
5263 insn->dst_reg != BPF_REG_0) {
5264 verbose(env, "BPF_EXIT uses reserved fields\n");
5268 if (state->curframe) {
5269 /* exit from nested function */
5270 env->prev_insn_idx = env->insn_idx;
5271 err = prepare_func_exit(env, &env->insn_idx);
5274 do_print_state = true;
5278 /* eBPF calling convetion is such that R0 is used
5279 * to return the value from eBPF program.
5280 * Make sure that it's readable at this time
5281 * of bpf_exit, which means that program wrote
5282 * something into it earlier
5284 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
5288 if (is_pointer_value(env, BPF_REG_0)) {
5289 verbose(env, "R0 leaks addr as return value\n");
5293 err = check_return_code(env);
5297 err = pop_stack(env, &env->prev_insn_idx,
5304 do_print_state = true;
5308 err = check_cond_jmp_op(env, insn, &env->insn_idx);
5312 } else if (class == BPF_LD) {
5313 u8 mode = BPF_MODE(insn->code);
5315 if (mode == BPF_ABS || mode == BPF_IND) {
5316 err = check_ld_abs(env, insn);
5320 } else if (mode == BPF_IMM) {
5321 err = check_ld_imm(env, insn);
5326 env->insn_aux_data[env->insn_idx].seen = true;
5328 verbose(env, "invalid BPF_LD mode\n");
5332 verbose(env, "unknown insn class %d\n", class);
5339 verbose(env, "processed %d insns (limit %d), stack depth ",
5340 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
5341 for (i = 0; i < env->subprog_cnt; i++) {
5342 u32 depth = env->subprog_info[i].stack_depth;
5344 verbose(env, "%d", depth);
5345 if (i + 1 < env->subprog_cnt)
5349 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
5353 static int check_map_prealloc(struct bpf_map *map)
5355 return (map->map_type != BPF_MAP_TYPE_HASH &&
5356 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
5357 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
5358 !(map->map_flags & BPF_F_NO_PREALLOC);
5361 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
5362 struct bpf_map *map,
5363 struct bpf_prog *prog)
5366 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
5367 * preallocated hash maps, since doing memory allocation
5368 * in overflow_handler can crash depending on where nmi got
5371 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
5372 if (!check_map_prealloc(map)) {
5373 verbose(env, "perf_event programs can only use preallocated hash map\n");
5376 if (map->inner_map_meta &&
5377 !check_map_prealloc(map->inner_map_meta)) {
5378 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
5383 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
5384 !bpf_offload_prog_map_match(prog, map)) {
5385 verbose(env, "offload device mismatch between prog and map\n");
5392 /* look for pseudo eBPF instructions that access map FDs and
5393 * replace them with actual map pointers
5395 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
5397 struct bpf_insn *insn = env->prog->insnsi;
5398 int insn_cnt = env->prog->len;
5401 err = bpf_prog_calc_tag(env->prog);
5405 for (i = 0; i < insn_cnt; i++, insn++) {
5406 if (BPF_CLASS(insn->code) == BPF_LDX &&
5407 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
5408 verbose(env, "BPF_LDX uses reserved fields\n");
5412 if (BPF_CLASS(insn->code) == BPF_STX &&
5413 ((BPF_MODE(insn->code) != BPF_MEM &&
5414 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
5415 verbose(env, "BPF_STX uses reserved fields\n");
5419 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
5420 struct bpf_map *map;
5423 if (i == insn_cnt - 1 || insn[1].code != 0 ||
5424 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
5426 verbose(env, "invalid bpf_ld_imm64 insn\n");
5430 if (insn->src_reg == 0)
5431 /* valid generic load 64-bit imm */
5434 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
5436 "unrecognized bpf_ld_imm64 insn\n");
5440 f = fdget(insn->imm);
5441 map = __bpf_map_get(f);
5443 verbose(env, "fd %d is not pointing to valid bpf_map\n",
5445 return PTR_ERR(map);
5448 err = check_map_prog_compatibility(env, map, env->prog);
5454 /* store map pointer inside BPF_LD_IMM64 instruction */
5455 insn[0].imm = (u32) (unsigned long) map;
5456 insn[1].imm = ((u64) (unsigned long) map) >> 32;
5458 /* check whether we recorded this map already */
5459 for (j = 0; j < env->used_map_cnt; j++)
5460 if (env->used_maps[j] == map) {
5465 if (env->used_map_cnt >= MAX_USED_MAPS) {
5470 /* hold the map. If the program is rejected by verifier,
5471 * the map will be released by release_maps() or it
5472 * will be used by the valid program until it's unloaded
5473 * and all maps are released in free_used_maps()
5475 map = bpf_map_inc(map, false);
5478 return PTR_ERR(map);
5480 env->used_maps[env->used_map_cnt++] = map;
5482 if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
5483 bpf_cgroup_storage_assign(env->prog, map)) {
5485 "only one cgroup storage is allowed\n");
5497 /* Basic sanity check before we invest more work here. */
5498 if (!bpf_opcode_in_insntable(insn->code)) {
5499 verbose(env, "unknown opcode %02x\n", insn->code);
5504 /* now all pseudo BPF_LD_IMM64 instructions load valid
5505 * 'struct bpf_map *' into a register instead of user map_fd.
5506 * These pointers will be used later by verifier to validate map access.
5511 /* drop refcnt of maps used by the rejected program */
5512 static void release_maps(struct bpf_verifier_env *env)
5516 if (env->prog->aux->cgroup_storage)
5517 bpf_cgroup_storage_release(env->prog,
5518 env->prog->aux->cgroup_storage);
5520 for (i = 0; i < env->used_map_cnt; i++)
5521 bpf_map_put(env->used_maps[i]);
5524 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5525 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5527 struct bpf_insn *insn = env->prog->insnsi;
5528 int insn_cnt = env->prog->len;
5531 for (i = 0; i < insn_cnt; i++, insn++)
5532 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5536 /* single env->prog->insni[off] instruction was replaced with the range
5537 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
5538 * [0, off) and [off, end) to new locations, so the patched range stays zero
5540 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5543 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5548 new_data = vzalloc(array_size(prog_len,
5549 sizeof(struct bpf_insn_aux_data)));
5552 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5553 memcpy(new_data + off + cnt - 1, old_data + off,
5554 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5555 for (i = off; i < off + cnt - 1; i++)
5556 new_data[i].seen = true;
5557 env->insn_aux_data = new_data;
5562 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5568 /* NOTE: fake 'exit' subprog should be updated as well. */
5569 for (i = 0; i <= env->subprog_cnt; i++) {
5570 if (env->subprog_info[i].start <= off)
5572 env->subprog_info[i].start += len - 1;
5576 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5577 const struct bpf_insn *patch, u32 len)
5579 struct bpf_prog *new_prog;
5581 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5584 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5586 adjust_subprog_starts(env, off, len);
5590 /* The verifier does more data flow analysis than llvm and will not
5591 * explore branches that are dead at run time. Malicious programs can
5592 * have dead code too. Therefore replace all dead at-run-time code
5595 * Just nops are not optimal, e.g. if they would sit at the end of the
5596 * program and through another bug we would manage to jump there, then
5597 * we'd execute beyond program memory otherwise. Returning exception
5598 * code also wouldn't work since we can have subprogs where the dead
5599 * code could be located.
5601 static void sanitize_dead_code(struct bpf_verifier_env *env)
5603 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5604 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5605 struct bpf_insn *insn = env->prog->insnsi;
5606 const int insn_cnt = env->prog->len;
5609 for (i = 0; i < insn_cnt; i++) {
5610 if (aux_data[i].seen)
5612 memcpy(insn + i, &trap, sizeof(trap));
5616 /* convert load instructions that access fields of 'struct __sk_buff'
5617 * into sequence of instructions that access fields of 'struct sk_buff'
5619 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5621 const struct bpf_verifier_ops *ops = env->ops;
5622 int i, cnt, size, ctx_field_size, delta = 0;
5623 const int insn_cnt = env->prog->len;
5624 struct bpf_insn insn_buf[16], *insn;
5625 u32 target_size, size_default, off;
5626 struct bpf_prog *new_prog;
5627 enum bpf_access_type type;
5628 bool is_narrower_load;
5630 if (ops->gen_prologue) {
5631 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5633 if (cnt >= ARRAY_SIZE(insn_buf)) {
5634 verbose(env, "bpf verifier is misconfigured\n");
5637 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5641 env->prog = new_prog;
5646 if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
5649 insn = env->prog->insnsi + delta;
5651 for (i = 0; i < insn_cnt; i++, insn++) {
5652 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5653 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5654 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5655 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5657 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5658 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5659 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5660 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5665 if (type == BPF_WRITE &&
5666 env->insn_aux_data[i + delta].sanitize_stack_off) {
5667 struct bpf_insn patch[] = {
5668 /* Sanitize suspicious stack slot with zero.
5669 * There are no memory dependencies for this store,
5670 * since it's only using frame pointer and immediate
5673 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
5674 env->insn_aux_data[i + delta].sanitize_stack_off,
5676 /* the original STX instruction will immediately
5677 * overwrite the same stack slot with appropriate value
5682 cnt = ARRAY_SIZE(patch);
5683 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
5688 env->prog = new_prog;
5689 insn = new_prog->insnsi + i + delta;
5693 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5696 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5697 size = BPF_LDST_BYTES(insn);
5699 /* If the read access is a narrower load of the field,
5700 * convert to a 4/8-byte load, to minimum program type specific
5701 * convert_ctx_access changes. If conversion is successful,
5702 * we will apply proper mask to the result.
5704 is_narrower_load = size < ctx_field_size;
5705 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
5707 if (is_narrower_load) {
5710 if (type == BPF_WRITE) {
5711 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5716 if (ctx_field_size == 4)
5718 else if (ctx_field_size == 8)
5721 insn->off = off & ~(size_default - 1);
5722 insn->code = BPF_LDX | BPF_MEM | size_code;
5726 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5728 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5729 (ctx_field_size && !target_size)) {
5730 verbose(env, "bpf verifier is misconfigured\n");
5734 if (is_narrower_load && size < target_size) {
5735 u8 shift = (off & (size_default - 1)) * 8;
5737 if (ctx_field_size <= 4) {
5739 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
5742 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5743 (1 << size * 8) - 1);
5746 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
5749 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5750 (1ULL << size * 8) - 1);
5754 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5760 /* keep walking new program and skip insns we just inserted */
5761 env->prog = new_prog;
5762 insn = new_prog->insnsi + i + delta;
5768 static int jit_subprogs(struct bpf_verifier_env *env)
5770 struct bpf_prog *prog = env->prog, **func, *tmp;
5771 int i, j, subprog_start, subprog_end = 0, len, subprog;
5772 struct bpf_insn *insn;
5776 if (env->subprog_cnt <= 1)
5779 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5780 if (insn->code != (BPF_JMP | BPF_CALL) ||
5781 insn->src_reg != BPF_PSEUDO_CALL)
5783 /* Upon error here we cannot fall back to interpreter but
5784 * need a hard reject of the program. Thus -EFAULT is
5785 * propagated in any case.
5787 subprog = find_subprog(env, i + insn->imm + 1);
5789 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5793 /* temporarily remember subprog id inside insn instead of
5794 * aux_data, since next loop will split up all insns into funcs
5796 insn->off = subprog;
5797 /* remember original imm in case JIT fails and fallback
5798 * to interpreter will be needed
5800 env->insn_aux_data[i].call_imm = insn->imm;
5801 /* point imm to __bpf_call_base+1 from JITs point of view */
5805 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
5809 for (i = 0; i < env->subprog_cnt; i++) {
5810 subprog_start = subprog_end;
5811 subprog_end = env->subprog_info[i + 1].start;
5813 len = subprog_end - subprog_start;
5814 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
5817 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
5818 len * sizeof(struct bpf_insn));
5819 func[i]->type = prog->type;
5821 if (bpf_prog_calc_tag(func[i]))
5823 func[i]->is_func = 1;
5824 /* Use bpf_prog_F_tag to indicate functions in stack traces.
5825 * Long term would need debug info to populate names
5827 func[i]->aux->name[0] = 'F';
5828 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
5829 func[i]->jit_requested = 1;
5830 func[i] = bpf_int_jit_compile(func[i]);
5831 if (!func[i]->jited) {
5837 /* at this point all bpf functions were successfully JITed
5838 * now populate all bpf_calls with correct addresses and
5839 * run last pass of JIT
5841 for (i = 0; i < env->subprog_cnt; i++) {
5842 insn = func[i]->insnsi;
5843 for (j = 0; j < func[i]->len; j++, insn++) {
5844 if (insn->code != (BPF_JMP | BPF_CALL) ||
5845 insn->src_reg != BPF_PSEUDO_CALL)
5847 subprog = insn->off;
5848 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5849 func[subprog]->bpf_func -
5853 /* we use the aux data to keep a list of the start addresses
5854 * of the JITed images for each function in the program
5856 * for some architectures, such as powerpc64, the imm field
5857 * might not be large enough to hold the offset of the start
5858 * address of the callee's JITed image from __bpf_call_base
5860 * in such cases, we can lookup the start address of a callee
5861 * by using its subprog id, available from the off field of
5862 * the call instruction, as an index for this list
5864 func[i]->aux->func = func;
5865 func[i]->aux->func_cnt = env->subprog_cnt;
5867 for (i = 0; i < env->subprog_cnt; i++) {
5868 old_bpf_func = func[i]->bpf_func;
5869 tmp = bpf_int_jit_compile(func[i]);
5870 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
5871 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
5878 /* finally lock prog and jit images for all functions and
5881 for (i = 0; i < env->subprog_cnt; i++) {
5882 bpf_prog_lock_ro(func[i]);
5883 bpf_prog_kallsyms_add(func[i]);
5886 /* Last step: make now unused interpreter insns from main
5887 * prog consistent for later dump requests, so they can
5888 * later look the same as if they were interpreted only.
5890 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5891 if (insn->code != (BPF_JMP | BPF_CALL) ||
5892 insn->src_reg != BPF_PSEUDO_CALL)
5894 insn->off = env->insn_aux_data[i].call_imm;
5895 subprog = find_subprog(env, i + insn->off + 1);
5896 insn->imm = subprog;
5900 prog->bpf_func = func[0]->bpf_func;
5901 prog->aux->func = func;
5902 prog->aux->func_cnt = env->subprog_cnt;
5905 for (i = 0; i < env->subprog_cnt; i++)
5907 bpf_jit_free(func[i]);
5910 /* cleanup main prog to be interpreted */
5911 prog->jit_requested = 0;
5912 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5913 if (insn->code != (BPF_JMP | BPF_CALL) ||
5914 insn->src_reg != BPF_PSEUDO_CALL)
5917 insn->imm = env->insn_aux_data[i].call_imm;
5922 static int fixup_call_args(struct bpf_verifier_env *env)
5924 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5925 struct bpf_prog *prog = env->prog;
5926 struct bpf_insn *insn = prog->insnsi;
5932 if (env->prog->jit_requested) {
5933 err = jit_subprogs(env);
5939 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5940 for (i = 0; i < prog->len; i++, insn++) {
5941 if (insn->code != (BPF_JMP | BPF_CALL) ||
5942 insn->src_reg != BPF_PSEUDO_CALL)
5944 depth = get_callee_stack_depth(env, insn, i);
5947 bpf_patch_call_args(insn, depth);
5954 /* fixup insn->imm field of bpf_call instructions
5955 * and inline eligible helpers as explicit sequence of BPF instructions
5957 * this function is called after eBPF program passed verification
5959 static int fixup_bpf_calls(struct bpf_verifier_env *env)
5961 struct bpf_prog *prog = env->prog;
5962 struct bpf_insn *insn = prog->insnsi;
5963 const struct bpf_func_proto *fn;
5964 const int insn_cnt = prog->len;
5965 const struct bpf_map_ops *ops;
5966 struct bpf_insn_aux_data *aux;
5967 struct bpf_insn insn_buf[16];
5968 struct bpf_prog *new_prog;
5969 struct bpf_map *map_ptr;
5970 int i, cnt, delta = 0;
5972 for (i = 0; i < insn_cnt; i++, insn++) {
5973 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
5974 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5975 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
5976 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5977 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
5978 struct bpf_insn mask_and_div[] = {
5979 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5981 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
5982 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
5983 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
5986 struct bpf_insn mask_and_mod[] = {
5987 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5988 /* Rx mod 0 -> Rx */
5989 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
5992 struct bpf_insn *patchlet;
5994 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5995 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5996 patchlet = mask_and_div + (is64 ? 1 : 0);
5997 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
5999 patchlet = mask_and_mod + (is64 ? 1 : 0);
6000 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
6003 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
6008 env->prog = prog = new_prog;
6009 insn = new_prog->insnsi + i + delta;
6013 if (BPF_CLASS(insn->code) == BPF_LD &&
6014 (BPF_MODE(insn->code) == BPF_ABS ||
6015 BPF_MODE(insn->code) == BPF_IND)) {
6016 cnt = env->ops->gen_ld_abs(insn, insn_buf);
6017 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6018 verbose(env, "bpf verifier is misconfigured\n");
6022 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6027 env->prog = prog = new_prog;
6028 insn = new_prog->insnsi + i + delta;
6032 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
6033 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
6034 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
6035 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
6036 struct bpf_insn insn_buf[16];
6037 struct bpf_insn *patch = &insn_buf[0];
6041 aux = &env->insn_aux_data[i + delta];
6042 if (!aux->alu_state ||
6043 aux->alu_state == BPF_ALU_NON_POINTER)
6046 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
6047 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
6048 BPF_ALU_SANITIZE_SRC;
6050 off_reg = issrc ? insn->src_reg : insn->dst_reg;
6052 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6053 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
6054 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
6055 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
6056 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
6057 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
6059 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
6061 insn->src_reg = BPF_REG_AX;
6063 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
6067 insn->code = insn->code == code_add ?
6068 code_sub : code_add;
6071 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6072 cnt = patch - insn_buf;
6074 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6079 env->prog = prog = new_prog;
6080 insn = new_prog->insnsi + i + delta;
6084 if (insn->code != (BPF_JMP | BPF_CALL))
6086 if (insn->src_reg == BPF_PSEUDO_CALL)
6089 if (insn->imm == BPF_FUNC_get_route_realm)
6090 prog->dst_needed = 1;
6091 if (insn->imm == BPF_FUNC_get_prandom_u32)
6092 bpf_user_rnd_init_once();
6093 if (insn->imm == BPF_FUNC_override_return)
6094 prog->kprobe_override = 1;
6095 if (insn->imm == BPF_FUNC_tail_call) {
6096 /* If we tail call into other programs, we
6097 * cannot make any assumptions since they can
6098 * be replaced dynamically during runtime in
6099 * the program array.
6101 prog->cb_access = 1;
6102 env->prog->aux->stack_depth = MAX_BPF_STACK;
6104 /* mark bpf_tail_call as different opcode to avoid
6105 * conditional branch in the interpeter for every normal
6106 * call and to prevent accidental JITing by JIT compiler
6107 * that doesn't support bpf_tail_call yet
6110 insn->code = BPF_JMP | BPF_TAIL_CALL;
6112 aux = &env->insn_aux_data[i + delta];
6113 if (!bpf_map_ptr_unpriv(aux))
6116 /* instead of changing every JIT dealing with tail_call
6117 * emit two extra insns:
6118 * if (index >= max_entries) goto out;
6119 * index &= array->index_mask;
6120 * to avoid out-of-bounds cpu speculation
6122 if (bpf_map_ptr_poisoned(aux)) {
6123 verbose(env, "tail_call abusing map_ptr\n");
6127 map_ptr = BPF_MAP_PTR(aux->map_state);
6128 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
6129 map_ptr->max_entries, 2);
6130 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
6131 container_of(map_ptr,
6134 insn_buf[2] = *insn;
6136 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6141 env->prog = prog = new_prog;
6142 insn = new_prog->insnsi + i + delta;
6146 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
6147 * and other inlining handlers are currently limited to 64 bit
6150 if (prog->jit_requested && BITS_PER_LONG == 64 &&
6151 (insn->imm == BPF_FUNC_map_lookup_elem ||
6152 insn->imm == BPF_FUNC_map_update_elem ||
6153 insn->imm == BPF_FUNC_map_delete_elem)) {
6154 aux = &env->insn_aux_data[i + delta];
6155 if (bpf_map_ptr_poisoned(aux))
6156 goto patch_call_imm;
6158 map_ptr = BPF_MAP_PTR(aux->map_state);
6160 if (insn->imm == BPF_FUNC_map_lookup_elem &&
6161 ops->map_gen_lookup) {
6162 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
6163 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6164 verbose(env, "bpf verifier is misconfigured\n");
6168 new_prog = bpf_patch_insn_data(env, i + delta,
6174 env->prog = prog = new_prog;
6175 insn = new_prog->insnsi + i + delta;
6179 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
6180 (void *(*)(struct bpf_map *map, void *key))NULL));
6181 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
6182 (int (*)(struct bpf_map *map, void *key))NULL));
6183 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
6184 (int (*)(struct bpf_map *map, void *key, void *value,
6186 switch (insn->imm) {
6187 case BPF_FUNC_map_lookup_elem:
6188 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
6191 case BPF_FUNC_map_update_elem:
6192 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
6195 case BPF_FUNC_map_delete_elem:
6196 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
6201 goto patch_call_imm;
6205 fn = env->ops->get_func_proto(insn->imm, env->prog);
6206 /* all functions that have prototype and verifier allowed
6207 * programs to call them, must be real in-kernel functions
6211 "kernel subsystem misconfigured func %s#%d\n",
6212 func_id_name(insn->imm), insn->imm);
6215 insn->imm = fn->func - __bpf_call_base;
6221 static void free_states(struct bpf_verifier_env *env)
6223 struct bpf_verifier_state_list *sl, *sln;
6226 if (!env->explored_states)
6229 for (i = 0; i < env->prog->len; i++) {
6230 sl = env->explored_states[i];
6233 while (sl != STATE_LIST_MARK) {
6235 free_verifier_state(&sl->state, false);
6241 kfree(env->explored_states);
6244 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
6246 struct bpf_verifier_env *env;
6247 struct bpf_verifier_log *log;
6250 /* no program is valid */
6251 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
6254 /* 'struct bpf_verifier_env' can be global, but since it's not small,
6255 * allocate/free it every time bpf_check() is called
6257 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
6262 env->insn_aux_data =
6263 vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
6266 if (!env->insn_aux_data)
6269 env->ops = bpf_verifier_ops[env->prog->type];
6271 /* grab the mutex to protect few globals used by verifier */
6272 mutex_lock(&bpf_verifier_lock);
6274 if (attr->log_level || attr->log_buf || attr->log_size) {
6275 /* user requested verbose verifier output
6276 * and supplied buffer to store the verification trace
6278 log->level = attr->log_level;
6279 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
6280 log->len_total = attr->log_size;
6283 /* log attributes have to be sane */
6284 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
6285 !log->level || !log->ubuf)
6289 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
6290 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
6291 env->strict_alignment = true;
6293 ret = replace_map_fd_with_map_ptr(env);
6295 goto skip_full_check;
6297 if (bpf_prog_is_dev_bound(env->prog->aux)) {
6298 ret = bpf_prog_offload_verifier_prep(env);
6300 goto skip_full_check;
6303 env->explored_states = kcalloc(env->prog->len,
6304 sizeof(struct bpf_verifier_state_list *),
6307 if (!env->explored_states)
6308 goto skip_full_check;
6310 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
6312 ret = check_cfg(env);
6314 goto skip_full_check;
6316 ret = do_check(env);
6317 if (env->cur_state) {
6318 free_verifier_state(env->cur_state, true);
6319 env->cur_state = NULL;
6323 while (!pop_stack(env, NULL, NULL));
6327 sanitize_dead_code(env);
6330 ret = check_max_stack_depth(env);
6333 /* program is valid, convert *(u32*)(ctx + off) accesses */
6334 ret = convert_ctx_accesses(env);
6337 ret = fixup_bpf_calls(env);
6340 ret = fixup_call_args(env);
6342 if (log->level && bpf_verifier_log_full(log))
6344 if (log->level && !log->ubuf) {
6346 goto err_release_maps;
6349 if (ret == 0 && env->used_map_cnt) {
6350 /* if program passed verifier, update used_maps in bpf_prog_info */
6351 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
6352 sizeof(env->used_maps[0]),
6355 if (!env->prog->aux->used_maps) {
6357 goto err_release_maps;
6360 memcpy(env->prog->aux->used_maps, env->used_maps,
6361 sizeof(env->used_maps[0]) * env->used_map_cnt);
6362 env->prog->aux->used_map_cnt = env->used_map_cnt;
6364 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
6365 * bpf_ld_imm64 instructions
6367 convert_pseudo_ld_imm64(env);
6371 if (!env->prog->aux->used_maps)
6372 /* if we didn't copy map pointers into bpf_prog_info, release
6373 * them now. Otherwise free_used_maps() will release them.
6378 mutex_unlock(&bpf_verifier_lock);
6379 vfree(env->insn_aux_data);