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;
194 static DEFINE_MUTEX(bpf_verifier_lock);
196 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
201 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
203 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
204 "verifier log line truncated - local buffer too short\n");
206 n = min(log->len_total - log->len_used - 1, n);
209 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
215 /* log_level controls verbosity level of eBPF verifier.
216 * bpf_verifier_log_write() is used to dump the verification trace to the log,
217 * so the user can figure out what's wrong with the program
219 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
220 const char *fmt, ...)
224 if (!bpf_verifier_log_needed(&env->log))
228 bpf_verifier_vlog(&env->log, fmt, args);
231 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
233 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
235 struct bpf_verifier_env *env = private_data;
238 if (!bpf_verifier_log_needed(&env->log))
242 bpf_verifier_vlog(&env->log, fmt, args);
246 static bool type_is_pkt_pointer(enum bpf_reg_type type)
248 return type == PTR_TO_PACKET ||
249 type == PTR_TO_PACKET_META;
252 /* string representation of 'enum bpf_reg_type' */
253 static const char * const reg_type_str[] = {
255 [SCALAR_VALUE] = "inv",
256 [PTR_TO_CTX] = "ctx",
257 [CONST_PTR_TO_MAP] = "map_ptr",
258 [PTR_TO_MAP_VALUE] = "map_value",
259 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
260 [PTR_TO_STACK] = "fp",
261 [PTR_TO_PACKET] = "pkt",
262 [PTR_TO_PACKET_META] = "pkt_meta",
263 [PTR_TO_PACKET_END] = "pkt_end",
266 static void print_liveness(struct bpf_verifier_env *env,
267 enum bpf_reg_liveness live)
269 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
271 if (live & REG_LIVE_READ)
273 if (live & REG_LIVE_WRITTEN)
277 static struct bpf_func_state *func(struct bpf_verifier_env *env,
278 const struct bpf_reg_state *reg)
280 struct bpf_verifier_state *cur = env->cur_state;
282 return cur->frame[reg->frameno];
285 static void print_verifier_state(struct bpf_verifier_env *env,
286 const struct bpf_func_state *state)
288 const struct bpf_reg_state *reg;
293 verbose(env, " frame%d:", state->frameno);
294 for (i = 0; i < MAX_BPF_REG; i++) {
295 reg = &state->regs[i];
299 verbose(env, " R%d", i);
300 print_liveness(env, reg->live);
301 verbose(env, "=%s", reg_type_str[t]);
302 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
303 tnum_is_const(reg->var_off)) {
304 /* reg->off should be 0 for SCALAR_VALUE */
305 verbose(env, "%lld", reg->var_off.value + reg->off);
306 if (t == PTR_TO_STACK)
307 verbose(env, ",call_%d", func(env, reg)->callsite);
309 verbose(env, "(id=%d", reg->id);
310 if (t != SCALAR_VALUE)
311 verbose(env, ",off=%d", reg->off);
312 if (type_is_pkt_pointer(t))
313 verbose(env, ",r=%d", reg->range);
314 else if (t == CONST_PTR_TO_MAP ||
315 t == PTR_TO_MAP_VALUE ||
316 t == PTR_TO_MAP_VALUE_OR_NULL)
317 verbose(env, ",ks=%d,vs=%d",
318 reg->map_ptr->key_size,
319 reg->map_ptr->value_size);
320 if (tnum_is_const(reg->var_off)) {
321 /* Typically an immediate SCALAR_VALUE, but
322 * could be a pointer whose offset is too big
325 verbose(env, ",imm=%llx", reg->var_off.value);
327 if (reg->smin_value != reg->umin_value &&
328 reg->smin_value != S64_MIN)
329 verbose(env, ",smin_value=%lld",
330 (long long)reg->smin_value);
331 if (reg->smax_value != reg->umax_value &&
332 reg->smax_value != S64_MAX)
333 verbose(env, ",smax_value=%lld",
334 (long long)reg->smax_value);
335 if (reg->umin_value != 0)
336 verbose(env, ",umin_value=%llu",
337 (unsigned long long)reg->umin_value);
338 if (reg->umax_value != U64_MAX)
339 verbose(env, ",umax_value=%llu",
340 (unsigned long long)reg->umax_value);
341 if (!tnum_is_unknown(reg->var_off)) {
344 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
345 verbose(env, ",var_off=%s", tn_buf);
351 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
352 if (state->stack[i].slot_type[0] == STACK_SPILL) {
353 verbose(env, " fp%d",
354 (-i - 1) * BPF_REG_SIZE);
355 print_liveness(env, state->stack[i].spilled_ptr.live);
357 reg_type_str[state->stack[i].spilled_ptr.type]);
359 if (state->stack[i].slot_type[0] == STACK_ZERO)
360 verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
365 static int copy_stack_state(struct bpf_func_state *dst,
366 const struct bpf_func_state *src)
370 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
371 /* internal bug, make state invalid to reject the program */
372 memset(dst, 0, sizeof(*dst));
375 memcpy(dst->stack, src->stack,
376 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
380 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
381 * make it consume minimal amount of memory. check_stack_write() access from
382 * the program calls into realloc_func_state() to grow the stack size.
383 * Note there is a non-zero parent pointer inside each reg of bpf_verifier_state
384 * which this function copies over. It points to corresponding reg in previous
385 * bpf_verifier_state which is never reallocated
387 static int realloc_func_state(struct bpf_func_state *state, int size,
390 u32 old_size = state->allocated_stack;
391 struct bpf_stack_state *new_stack;
392 int slot = size / BPF_REG_SIZE;
394 if (size <= old_size || !size) {
397 state->allocated_stack = slot * BPF_REG_SIZE;
398 if (!size && old_size) {
404 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
410 memcpy(new_stack, state->stack,
411 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
412 memset(new_stack + old_size / BPF_REG_SIZE, 0,
413 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
415 state->allocated_stack = slot * BPF_REG_SIZE;
417 state->stack = new_stack;
421 static void free_func_state(struct bpf_func_state *state)
429 static void free_verifier_state(struct bpf_verifier_state *state,
434 for (i = 0; i <= state->curframe; i++) {
435 free_func_state(state->frame[i]);
436 state->frame[i] = NULL;
442 /* copy verifier state from src to dst growing dst stack space
443 * when necessary to accommodate larger src stack
445 static int copy_func_state(struct bpf_func_state *dst,
446 const struct bpf_func_state *src)
450 err = realloc_func_state(dst, src->allocated_stack, false);
453 memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
454 return copy_stack_state(dst, src);
457 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
458 const struct bpf_verifier_state *src)
460 struct bpf_func_state *dst;
463 /* if dst has more stack frames then src frame, free them */
464 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
465 free_func_state(dst_state->frame[i]);
466 dst_state->frame[i] = NULL;
468 dst_state->speculative = src->speculative;
469 dst_state->curframe = src->curframe;
470 for (i = 0; i <= src->curframe; i++) {
471 dst = dst_state->frame[i];
473 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
476 dst_state->frame[i] = dst;
478 err = copy_func_state(dst, src->frame[i]);
485 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
488 struct bpf_verifier_state *cur = env->cur_state;
489 struct bpf_verifier_stack_elem *elem, *head = env->head;
492 if (env->head == NULL)
496 err = copy_verifier_state(cur, &head->st);
501 *insn_idx = head->insn_idx;
503 *prev_insn_idx = head->prev_insn_idx;
505 free_verifier_state(&head->st, false);
512 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
513 int insn_idx, int prev_insn_idx,
516 struct bpf_verifier_state *cur = env->cur_state;
517 struct bpf_verifier_stack_elem *elem;
520 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
524 elem->insn_idx = insn_idx;
525 elem->prev_insn_idx = prev_insn_idx;
526 elem->next = env->head;
529 err = copy_verifier_state(&elem->st, cur);
532 elem->st.speculative |= speculative;
533 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
534 verbose(env, "BPF program is too complex\n");
539 free_verifier_state(env->cur_state, true);
540 env->cur_state = NULL;
541 /* pop all elements and return */
542 while (!pop_stack(env, NULL, NULL));
546 #define CALLER_SAVED_REGS 6
547 static const int caller_saved[CALLER_SAVED_REGS] = {
548 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
551 static void __mark_reg_not_init(struct bpf_reg_state *reg);
553 /* Mark the unknown part of a register (variable offset or scalar value) as
554 * known to have the value @imm.
556 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
558 /* Clear id, off, and union(map_ptr, range) */
559 memset(((u8 *)reg) + sizeof(reg->type), 0,
560 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
561 reg->var_off = tnum_const(imm);
562 reg->smin_value = (s64)imm;
563 reg->smax_value = (s64)imm;
564 reg->umin_value = imm;
565 reg->umax_value = imm;
568 /* Mark the 'variable offset' part of a register as zero. This should be
569 * used only on registers holding a pointer type.
571 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
573 __mark_reg_known(reg, 0);
576 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
578 __mark_reg_known(reg, 0);
579 reg->type = SCALAR_VALUE;
582 static void mark_reg_known_zero(struct bpf_verifier_env *env,
583 struct bpf_reg_state *regs, u32 regno)
585 if (WARN_ON(regno >= MAX_BPF_REG)) {
586 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
587 /* Something bad happened, let's kill all regs */
588 for (regno = 0; regno < MAX_BPF_REG; regno++)
589 __mark_reg_not_init(regs + regno);
592 __mark_reg_known_zero(regs + regno);
595 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
597 return type_is_pkt_pointer(reg->type);
600 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
602 return reg_is_pkt_pointer(reg) ||
603 reg->type == PTR_TO_PACKET_END;
606 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
607 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
608 enum bpf_reg_type which)
610 /* The register can already have a range from prior markings.
611 * This is fine as long as it hasn't been advanced from its
614 return reg->type == which &&
617 tnum_equals_const(reg->var_off, 0);
620 /* Attempts to improve min/max values based on var_off information */
621 static void __update_reg_bounds(struct bpf_reg_state *reg)
623 /* min signed is max(sign bit) | min(other bits) */
624 reg->smin_value = max_t(s64, reg->smin_value,
625 reg->var_off.value | (reg->var_off.mask & S64_MIN));
626 /* max signed is min(sign bit) | max(other bits) */
627 reg->smax_value = min_t(s64, reg->smax_value,
628 reg->var_off.value | (reg->var_off.mask & S64_MAX));
629 reg->umin_value = max(reg->umin_value, reg->var_off.value);
630 reg->umax_value = min(reg->umax_value,
631 reg->var_off.value | reg->var_off.mask);
634 /* Uses signed min/max values to inform unsigned, and vice-versa */
635 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
637 /* Learn sign from signed bounds.
638 * If we cannot cross the sign boundary, then signed and unsigned bounds
639 * are the same, so combine. This works even in the negative case, e.g.
640 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
642 if (reg->smin_value >= 0 || reg->smax_value < 0) {
643 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
645 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
649 /* Learn sign from unsigned bounds. Signed bounds cross the sign
650 * boundary, so we must be careful.
652 if ((s64)reg->umax_value >= 0) {
653 /* Positive. We can't learn anything from the smin, but smax
654 * is positive, hence safe.
656 reg->smin_value = reg->umin_value;
657 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
659 } else if ((s64)reg->umin_value < 0) {
660 /* Negative. We can't learn anything from the smax, but smin
661 * is negative, hence safe.
663 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
665 reg->smax_value = reg->umax_value;
669 /* Attempts to improve var_off based on unsigned min/max information */
670 static void __reg_bound_offset(struct bpf_reg_state *reg)
672 reg->var_off = tnum_intersect(reg->var_off,
673 tnum_range(reg->umin_value,
677 /* Reset the min/max bounds of a register */
678 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
680 reg->smin_value = S64_MIN;
681 reg->smax_value = S64_MAX;
683 reg->umax_value = U64_MAX;
686 /* Mark a register as having a completely unknown (scalar) value. */
687 static void __mark_reg_unknown(struct bpf_reg_state *reg)
690 * Clear type, id, off, and union(map_ptr, range) and
691 * padding between 'type' and union
693 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
694 reg->type = SCALAR_VALUE;
695 reg->var_off = tnum_unknown;
697 __mark_reg_unbounded(reg);
700 static void mark_reg_unknown(struct bpf_verifier_env *env,
701 struct bpf_reg_state *regs, u32 regno)
703 if (WARN_ON(regno >= MAX_BPF_REG)) {
704 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
705 /* Something bad happened, let's kill all regs except FP */
706 for (regno = 0; regno < BPF_REG_FP; regno++)
707 __mark_reg_not_init(regs + regno);
710 __mark_reg_unknown(regs + regno);
713 static void __mark_reg_not_init(struct bpf_reg_state *reg)
715 __mark_reg_unknown(reg);
716 reg->type = NOT_INIT;
719 static void mark_reg_not_init(struct bpf_verifier_env *env,
720 struct bpf_reg_state *regs, u32 regno)
722 if (WARN_ON(regno >= MAX_BPF_REG)) {
723 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
724 /* Something bad happened, let's kill all regs except FP */
725 for (regno = 0; regno < BPF_REG_FP; regno++)
726 __mark_reg_not_init(regs + regno);
729 __mark_reg_not_init(regs + regno);
732 static void init_reg_state(struct bpf_verifier_env *env,
733 struct bpf_func_state *state)
735 struct bpf_reg_state *regs = state->regs;
738 for (i = 0; i < MAX_BPF_REG; i++) {
739 mark_reg_not_init(env, regs, i);
740 regs[i].live = REG_LIVE_NONE;
741 regs[i].parent = NULL;
745 regs[BPF_REG_FP].type = PTR_TO_STACK;
746 mark_reg_known_zero(env, regs, BPF_REG_FP);
747 regs[BPF_REG_FP].frameno = state->frameno;
749 /* 1st arg to a function */
750 regs[BPF_REG_1].type = PTR_TO_CTX;
751 mark_reg_known_zero(env, regs, BPF_REG_1);
754 #define BPF_MAIN_FUNC (-1)
755 static void init_func_state(struct bpf_verifier_env *env,
756 struct bpf_func_state *state,
757 int callsite, int frameno, int subprogno)
759 state->callsite = callsite;
760 state->frameno = frameno;
761 state->subprogno = subprogno;
762 init_reg_state(env, state);
766 SRC_OP, /* register is used as source operand */
767 DST_OP, /* register is used as destination operand */
768 DST_OP_NO_MARK /* same as above, check only, don't mark */
771 static int cmp_subprogs(const void *a, const void *b)
773 return ((struct bpf_subprog_info *)a)->start -
774 ((struct bpf_subprog_info *)b)->start;
777 static int find_subprog(struct bpf_verifier_env *env, int off)
779 struct bpf_subprog_info *p;
781 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
782 sizeof(env->subprog_info[0]), cmp_subprogs);
785 return p - env->subprog_info;
789 static int add_subprog(struct bpf_verifier_env *env, int off)
791 int insn_cnt = env->prog->len;
794 if (off >= insn_cnt || off < 0) {
795 verbose(env, "call to invalid destination\n");
798 ret = find_subprog(env, off);
801 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
802 verbose(env, "too many subprograms\n");
805 env->subprog_info[env->subprog_cnt++].start = off;
806 sort(env->subprog_info, env->subprog_cnt,
807 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
811 static int check_subprogs(struct bpf_verifier_env *env)
813 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
814 struct bpf_subprog_info *subprog = env->subprog_info;
815 struct bpf_insn *insn = env->prog->insnsi;
816 int insn_cnt = env->prog->len;
818 /* Add entry function. */
819 ret = add_subprog(env, 0);
823 /* determine subprog starts. The end is one before the next starts */
824 for (i = 0; i < insn_cnt; i++) {
825 if (insn[i].code != (BPF_JMP | BPF_CALL))
827 if (insn[i].src_reg != BPF_PSEUDO_CALL)
829 if (!env->allow_ptr_leaks) {
830 verbose(env, "function calls to other bpf functions are allowed for root only\n");
833 if (bpf_prog_is_dev_bound(env->prog->aux)) {
834 verbose(env, "function calls in offloaded programs are not supported yet\n");
837 ret = add_subprog(env, i + insn[i].imm + 1);
842 /* Add a fake 'exit' subprog which could simplify subprog iteration
843 * logic. 'subprog_cnt' should not be increased.
845 subprog[env->subprog_cnt].start = insn_cnt;
847 if (env->log.level > 1)
848 for (i = 0; i < env->subprog_cnt; i++)
849 verbose(env, "func#%d @%d\n", i, subprog[i].start);
851 /* now check that all jumps are within the same subprog */
852 subprog_start = subprog[cur_subprog].start;
853 subprog_end = subprog[cur_subprog + 1].start;
854 for (i = 0; i < insn_cnt; i++) {
855 u8 code = insn[i].code;
857 if (BPF_CLASS(code) != BPF_JMP)
859 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
861 off = i + insn[i].off + 1;
862 if (off < subprog_start || off >= subprog_end) {
863 verbose(env, "jump out of range from insn %d to %d\n", i, off);
867 if (i == subprog_end - 1) {
868 /* to avoid fall-through from one subprog into another
869 * the last insn of the subprog should be either exit
870 * or unconditional jump back
872 if (code != (BPF_JMP | BPF_EXIT) &&
873 code != (BPF_JMP | BPF_JA)) {
874 verbose(env, "last insn is not an exit or jmp\n");
877 subprog_start = subprog_end;
879 if (cur_subprog < env->subprog_cnt)
880 subprog_end = subprog[cur_subprog + 1].start;
886 /* Parentage chain of this register (or stack slot) should take care of all
887 * issues like callee-saved registers, stack slot allocation time, etc.
889 static int mark_reg_read(struct bpf_verifier_env *env,
890 const struct bpf_reg_state *state,
891 struct bpf_reg_state *parent)
893 bool writes = parent == state->parent; /* Observe write marks */
896 /* if read wasn't screened by an earlier write ... */
897 if (writes && state->live & REG_LIVE_WRITTEN)
899 /* ... then we depend on parent's value */
900 parent->live |= REG_LIVE_READ;
902 parent = state->parent;
908 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
911 struct bpf_verifier_state *vstate = env->cur_state;
912 struct bpf_func_state *state = vstate->frame[vstate->curframe];
913 struct bpf_reg_state *regs = state->regs;
915 if (regno >= MAX_BPF_REG) {
916 verbose(env, "R%d is invalid\n", regno);
921 /* check whether register used as source operand can be read */
922 if (regs[regno].type == NOT_INIT) {
923 verbose(env, "R%d !read_ok\n", regno);
926 /* We don't need to worry about FP liveness because it's read-only */
927 if (regno != BPF_REG_FP)
928 return mark_reg_read(env, ®s[regno],
931 /* check whether register used as dest operand can be written to */
932 if (regno == BPF_REG_FP) {
933 verbose(env, "frame pointer is read only\n");
936 regs[regno].live |= REG_LIVE_WRITTEN;
938 mark_reg_unknown(env, regs, regno);
943 static bool is_spillable_regtype(enum bpf_reg_type type)
946 case PTR_TO_MAP_VALUE:
947 case PTR_TO_MAP_VALUE_OR_NULL:
951 case PTR_TO_PACKET_META:
952 case PTR_TO_PACKET_END:
953 case CONST_PTR_TO_MAP:
960 /* Does this register contain a constant zero? */
961 static bool register_is_null(struct bpf_reg_state *reg)
963 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
966 static bool register_is_const(struct bpf_reg_state *reg)
968 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
971 static void save_register_state(struct bpf_func_state *state,
972 int spi, struct bpf_reg_state *reg)
976 state->stack[spi].spilled_ptr = *reg;
977 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
979 for (i = 0; i < BPF_REG_SIZE; i++)
980 state->stack[spi].slot_type[i] = STACK_SPILL;
983 /* check_stack_read/write functions track spill/fill of registers,
984 * stack boundary and alignment are checked in check_mem_access()
986 static int check_stack_write(struct bpf_verifier_env *env,
987 struct bpf_func_state *state, /* func where register points to */
988 int off, int size, int value_regno, int insn_idx)
990 struct bpf_func_state *cur; /* state of the current function */
991 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
992 struct bpf_reg_state *reg = NULL;
994 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
998 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
999 * so it's aligned access and [off, off + size) are within stack limits
1001 if (!env->allow_ptr_leaks &&
1002 state->stack[spi].slot_type[0] == STACK_SPILL &&
1003 size != BPF_REG_SIZE) {
1004 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1008 cur = env->cur_state->frame[env->cur_state->curframe];
1009 if (value_regno >= 0)
1010 reg = &cur->regs[value_regno];
1011 if (!env->allow_ptr_leaks) {
1012 bool sanitize = reg && is_spillable_regtype(reg->type);
1014 for (i = 0; i < size; i++) {
1015 u8 type = state->stack[spi].slot_type[i];
1017 if (type != STACK_MISC && type != STACK_ZERO) {
1024 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
1027 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1028 !register_is_null(reg) && env->allow_ptr_leaks) {
1029 save_register_state(state, spi, reg);
1030 } else if (reg && is_spillable_regtype(reg->type)) {
1031 /* register containing pointer is being spilled into stack */
1032 if (size != BPF_REG_SIZE) {
1033 verbose(env, "invalid size of register spill\n");
1036 if (state != cur && reg->type == PTR_TO_STACK) {
1037 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1040 save_register_state(state, spi, reg);
1042 u8 type = STACK_MISC;
1044 /* regular write of data into stack destroys any spilled ptr */
1045 state->stack[spi].spilled_ptr.type = NOT_INIT;
1046 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1047 if (state->stack[spi].slot_type[0] == STACK_SPILL)
1048 for (i = 0; i < BPF_REG_SIZE; i++)
1049 state->stack[spi].slot_type[i] = STACK_MISC;
1051 /* only mark the slot as written if all 8 bytes were written
1052 * otherwise read propagation may incorrectly stop too soon
1053 * when stack slots are partially written.
1054 * This heuristic means that read propagation will be
1055 * conservative, since it will add reg_live_read marks
1056 * to stack slots all the way to first state when programs
1057 * writes+reads less than 8 bytes
1059 if (size == BPF_REG_SIZE)
1060 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1062 /* when we zero initialize stack slots mark them as such */
1063 if (reg && register_is_null(reg))
1066 /* Mark slots affected by this stack write. */
1067 for (i = 0; i < size; i++)
1068 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1074 static int check_stack_read(struct bpf_verifier_env *env,
1075 struct bpf_func_state *reg_state /* func where register points to */,
1076 int off, int size, int value_regno)
1078 struct bpf_verifier_state *vstate = env->cur_state;
1079 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1080 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1081 struct bpf_reg_state *reg;
1084 if (reg_state->allocated_stack <= slot) {
1085 verbose(env, "invalid read from stack off %d+0 size %d\n",
1089 stype = reg_state->stack[spi].slot_type;
1090 reg = ®_state->stack[spi].spilled_ptr;
1092 if (stype[0] == STACK_SPILL) {
1093 if (size != BPF_REG_SIZE) {
1094 if (reg->type != SCALAR_VALUE) {
1095 verbose(env, "invalid size of register fill\n");
1098 if (value_regno >= 0) {
1099 mark_reg_unknown(env, state->regs, value_regno);
1100 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1102 mark_reg_read(env, reg, reg->parent);
1105 for (i = 1; i < BPF_REG_SIZE; i++) {
1106 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1107 verbose(env, "corrupted spill memory\n");
1112 if (value_regno >= 0) {
1113 /* restore register state from stack */
1114 state->regs[value_regno] = *reg;
1115 /* mark reg as written since spilled pointer state likely
1116 * has its liveness marks cleared by is_state_visited()
1117 * which resets stack/reg liveness for state transitions
1119 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1121 mark_reg_read(env, reg, reg->parent);
1125 for (i = 0; i < size; i++) {
1126 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1128 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1132 verbose(env, "invalid read from stack off %d+%d size %d\n",
1136 mark_reg_read(env, reg, reg->parent);
1137 if (value_regno >= 0) {
1138 if (zeros == size) {
1139 /* any size read into register is zero extended,
1140 * so the whole register == const_zero
1142 __mark_reg_const_zero(&state->regs[value_regno]);
1144 /* have read misc data from the stack */
1145 mark_reg_unknown(env, state->regs, value_regno);
1147 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1153 static int check_stack_access(struct bpf_verifier_env *env,
1154 const struct bpf_reg_state *reg,
1157 /* Stack accesses must be at a fixed offset, so that we
1158 * can determine what type of data were returned. See
1159 * check_stack_read().
1161 if (!tnum_is_const(reg->var_off)) {
1164 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1165 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
1170 if (off >= 0 || off < -MAX_BPF_STACK) {
1171 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1178 /* check read/write into map element returned by bpf_map_lookup_elem() */
1179 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1180 int size, bool zero_size_allowed)
1182 struct bpf_reg_state *regs = cur_regs(env);
1183 struct bpf_map *map = regs[regno].map_ptr;
1185 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1186 off + size > map->value_size) {
1187 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1188 map->value_size, off, size);
1194 /* check read/write into a map element with possible variable offset */
1195 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1196 int off, int size, bool zero_size_allowed)
1198 struct bpf_verifier_state *vstate = env->cur_state;
1199 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1200 struct bpf_reg_state *reg = &state->regs[regno];
1203 /* We may have adjusted the register to this map value, so we
1204 * need to try adding each of min_value and max_value to off
1205 * to make sure our theoretical access will be safe.
1208 print_verifier_state(env, state);
1210 /* The minimum value is only important with signed
1211 * comparisons where we can't assume the floor of a
1212 * value is 0. If we are using signed variables for our
1213 * index'es we need to make sure that whatever we use
1214 * will have a set floor within our range.
1216 if (reg->smin_value < 0 &&
1217 (reg->smin_value == S64_MIN ||
1218 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1219 reg->smin_value + off < 0)) {
1220 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1224 err = __check_map_access(env, regno, reg->smin_value + off, size,
1227 verbose(env, "R%d min value is outside of the array range\n",
1232 /* If we haven't set a max value then we need to bail since we can't be
1233 * sure we won't do bad things.
1234 * If reg->umax_value + off could overflow, treat that as unbounded too.
1236 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1237 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1241 err = __check_map_access(env, regno, reg->umax_value + off, size,
1244 verbose(env, "R%d max value is outside of the array range\n",
1249 #define MAX_PACKET_OFF 0xffff
1251 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1252 const struct bpf_call_arg_meta *meta,
1253 enum bpf_access_type t)
1255 switch (env->prog->type) {
1256 case BPF_PROG_TYPE_LWT_IN:
1257 case BPF_PROG_TYPE_LWT_OUT:
1258 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1259 case BPF_PROG_TYPE_SK_REUSEPORT:
1260 /* dst_input() and dst_output() can't write for now */
1264 case BPF_PROG_TYPE_SCHED_CLS:
1265 case BPF_PROG_TYPE_SCHED_ACT:
1266 case BPF_PROG_TYPE_XDP:
1267 case BPF_PROG_TYPE_LWT_XMIT:
1268 case BPF_PROG_TYPE_SK_SKB:
1269 case BPF_PROG_TYPE_SK_MSG:
1271 return meta->pkt_access;
1273 env->seen_direct_write = true;
1280 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1281 int off, int size, bool zero_size_allowed)
1283 struct bpf_reg_state *regs = cur_regs(env);
1284 struct bpf_reg_state *reg = ®s[regno];
1286 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1287 (u64)off + size > reg->range) {
1288 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1289 off, size, regno, reg->id, reg->off, reg->range);
1295 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1296 int size, bool zero_size_allowed)
1298 struct bpf_reg_state *regs = cur_regs(env);
1299 struct bpf_reg_state *reg = ®s[regno];
1302 /* We may have added a variable offset to the packet pointer; but any
1303 * reg->range we have comes after that. We are only checking the fixed
1307 /* We don't allow negative numbers, because we aren't tracking enough
1308 * detail to prove they're safe.
1310 if (reg->smin_value < 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_packet_access(env, regno, off, size, zero_size_allowed);
1317 verbose(env, "R%d offset is outside of the packet\n", regno);
1323 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1324 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1325 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1327 struct bpf_insn_access_aux info = {
1328 .reg_type = *reg_type,
1331 if (env->ops->is_valid_access &&
1332 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1333 /* A non zero info.ctx_field_size indicates that this field is a
1334 * candidate for later verifier transformation to load the whole
1335 * field and then apply a mask when accessed with a narrower
1336 * access than actual ctx access size. A zero info.ctx_field_size
1337 * will only allow for whole field access and rejects any other
1338 * type of narrower access.
1340 *reg_type = info.reg_type;
1342 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1343 /* remember the offset of last byte accessed in ctx */
1344 if (env->prog->aux->max_ctx_offset < off + size)
1345 env->prog->aux->max_ctx_offset = off + size;
1349 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1353 static bool __is_pointer_value(bool allow_ptr_leaks,
1354 const struct bpf_reg_state *reg)
1356 if (allow_ptr_leaks)
1359 return reg->type != SCALAR_VALUE;
1362 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1364 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1367 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1369 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1371 return reg->type == PTR_TO_CTX;
1374 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1376 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1378 return type_is_pkt_pointer(reg->type);
1381 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1382 const struct bpf_reg_state *reg,
1383 int off, int size, bool strict)
1385 struct tnum reg_off;
1388 /* Byte size accesses are always allowed. */
1389 if (!strict || size == 1)
1392 /* For platforms that do not have a Kconfig enabling
1393 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1394 * NET_IP_ALIGN is universally set to '2'. And on platforms
1395 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1396 * to this code only in strict mode where we want to emulate
1397 * the NET_IP_ALIGN==2 checking. Therefore use an
1398 * unconditional IP align value of '2'.
1402 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1403 if (!tnum_is_aligned(reg_off, size)) {
1406 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1408 "misaligned packet access off %d+%s+%d+%d size %d\n",
1409 ip_align, tn_buf, reg->off, off, size);
1416 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1417 const struct bpf_reg_state *reg,
1418 const char *pointer_desc,
1419 int off, int size, bool strict)
1421 struct tnum reg_off;
1423 /* Byte size accesses are always allowed. */
1424 if (!strict || size == 1)
1427 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1428 if (!tnum_is_aligned(reg_off, size)) {
1431 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1433 pointer_desc, tn_buf, reg->off, off, size);
1440 static int check_ptr_alignment(struct bpf_verifier_env *env,
1441 const struct bpf_reg_state *reg, int off,
1442 int size, bool strict_alignment_once)
1444 bool strict = env->strict_alignment || strict_alignment_once;
1445 const char *pointer_desc = "";
1447 switch (reg->type) {
1449 case PTR_TO_PACKET_META:
1450 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1451 * right in front, treat it the very same way.
1453 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1454 case PTR_TO_MAP_VALUE:
1455 pointer_desc = "value ";
1458 pointer_desc = "context ";
1461 pointer_desc = "stack ";
1462 /* The stack spill tracking logic in check_stack_write()
1463 * and check_stack_read() relies on stack accesses being
1471 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1475 static int update_stack_depth(struct bpf_verifier_env *env,
1476 const struct bpf_func_state *func,
1479 u16 stack = env->subprog_info[func->subprogno].stack_depth;
1484 /* update known max for given subprogram */
1485 env->subprog_info[func->subprogno].stack_depth = -off;
1489 /* starting from main bpf function walk all instructions of the function
1490 * and recursively walk all callees that given function can call.
1491 * Ignore jump and exit insns.
1492 * Since recursion is prevented by check_cfg() this algorithm
1493 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1495 static int check_max_stack_depth(struct bpf_verifier_env *env)
1497 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1498 struct bpf_subprog_info *subprog = env->subprog_info;
1499 struct bpf_insn *insn = env->prog->insnsi;
1500 int ret_insn[MAX_CALL_FRAMES];
1501 int ret_prog[MAX_CALL_FRAMES];
1504 /* round up to 32-bytes, since this is granularity
1505 * of interpreter stack size
1507 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1508 if (depth > MAX_BPF_STACK) {
1509 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1514 subprog_end = subprog[idx + 1].start;
1515 for (; i < subprog_end; i++) {
1516 if (insn[i].code != (BPF_JMP | BPF_CALL))
1518 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1520 /* remember insn and function to return to */
1521 ret_insn[frame] = i + 1;
1522 ret_prog[frame] = idx;
1524 /* find the callee */
1525 i = i + insn[i].imm + 1;
1526 idx = find_subprog(env, i);
1528 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1533 if (frame >= MAX_CALL_FRAMES) {
1534 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1539 /* end of for() loop means the last insn of the 'subprog'
1540 * was reached. Doesn't matter whether it was JA or EXIT
1544 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1546 i = ret_insn[frame];
1547 idx = ret_prog[frame];
1551 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1552 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1553 const struct bpf_insn *insn, int idx)
1555 int start = idx + insn->imm + 1, subprog;
1557 subprog = find_subprog(env, start);
1559 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1563 return env->subprog_info[subprog].stack_depth;
1567 static int check_ctx_reg(struct bpf_verifier_env *env,
1568 const struct bpf_reg_state *reg, int regno)
1570 /* Access to ctx or passing it to a helper is only allowed in
1571 * its original, unmodified form.
1575 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1580 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1583 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1584 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1591 /* truncate register to smaller size (in bytes)
1592 * must be called with size < BPF_REG_SIZE
1594 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1598 /* clear high bits in bit representation */
1599 reg->var_off = tnum_cast(reg->var_off, size);
1601 /* fix arithmetic bounds */
1602 mask = ((u64)1 << (size * 8)) - 1;
1603 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1604 reg->umin_value &= mask;
1605 reg->umax_value &= mask;
1607 reg->umin_value = 0;
1608 reg->umax_value = mask;
1610 reg->smin_value = reg->umin_value;
1611 reg->smax_value = reg->umax_value;
1614 /* check whether memory at (regno + off) is accessible for t = (read | write)
1615 * if t==write, value_regno is a register which value is stored into memory
1616 * if t==read, value_regno is a register which will receive the value from memory
1617 * if t==write && value_regno==-1, some unknown value is stored into memory
1618 * if t==read && value_regno==-1, don't care what we read from memory
1620 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1621 int off, int bpf_size, enum bpf_access_type t,
1622 int value_regno, bool strict_alignment_once)
1624 struct bpf_reg_state *regs = cur_regs(env);
1625 struct bpf_reg_state *reg = regs + regno;
1626 struct bpf_func_state *state;
1629 size = bpf_size_to_bytes(bpf_size);
1633 /* alignment checks will add in reg->off themselves */
1634 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1638 /* for access checks, reg->off is just part of off */
1641 if (reg->type == PTR_TO_MAP_VALUE) {
1642 if (t == BPF_WRITE && value_regno >= 0 &&
1643 is_pointer_value(env, value_regno)) {
1644 verbose(env, "R%d leaks addr into map\n", value_regno);
1648 err = check_map_access(env, regno, off, size, false);
1649 if (!err && t == BPF_READ && value_regno >= 0)
1650 mark_reg_unknown(env, regs, value_regno);
1652 } else if (reg->type == PTR_TO_CTX) {
1653 enum bpf_reg_type reg_type = SCALAR_VALUE;
1655 if (t == BPF_WRITE && value_regno >= 0 &&
1656 is_pointer_value(env, value_regno)) {
1657 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1661 err = check_ctx_reg(env, reg, regno);
1665 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1666 if (!err && t == BPF_READ && value_regno >= 0) {
1667 /* ctx access returns either a scalar, or a
1668 * PTR_TO_PACKET[_META,_END]. In the latter
1669 * case, we know the offset is zero.
1671 if (reg_type == SCALAR_VALUE)
1672 mark_reg_unknown(env, regs, value_regno);
1674 mark_reg_known_zero(env, regs,
1676 regs[value_regno].type = reg_type;
1679 } else if (reg->type == PTR_TO_STACK) {
1680 off += reg->var_off.value;
1681 err = check_stack_access(env, reg, off, size);
1685 state = func(env, reg);
1686 err = update_stack_depth(env, state, off);
1691 err = check_stack_write(env, state, off, size,
1692 value_regno, insn_idx);
1694 err = check_stack_read(env, state, off, size,
1696 } else if (reg_is_pkt_pointer(reg)) {
1697 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1698 verbose(env, "cannot write into packet\n");
1701 if (t == BPF_WRITE && value_regno >= 0 &&
1702 is_pointer_value(env, value_regno)) {
1703 verbose(env, "R%d leaks addr into packet\n",
1707 err = check_packet_access(env, regno, off, size, false);
1708 if (!err && t == BPF_READ && value_regno >= 0)
1709 mark_reg_unknown(env, regs, value_regno);
1711 verbose(env, "R%d invalid mem access '%s'\n", regno,
1712 reg_type_str[reg->type]);
1716 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1717 regs[value_regno].type == SCALAR_VALUE) {
1718 /* b/h/w load zero-extends, mark upper bits as known 0 */
1719 coerce_reg_to_size(®s[value_regno], size);
1724 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1728 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1730 verbose(env, "BPF_XADD uses reserved fields\n");
1734 /* check src1 operand */
1735 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1739 /* check src2 operand */
1740 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1744 if (is_pointer_value(env, insn->src_reg)) {
1745 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1749 if (is_ctx_reg(env, insn->dst_reg) ||
1750 is_pkt_reg(env, insn->dst_reg)) {
1751 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1752 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1753 "context" : "packet");
1757 /* check whether atomic_add can read the memory */
1758 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1759 BPF_SIZE(insn->code), BPF_READ, -1, true);
1763 /* check whether atomic_add can write into the same memory */
1764 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1765 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1768 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
1769 int off, int access_size,
1770 bool zero_size_allowed)
1772 struct bpf_reg_state *reg = cur_regs(env) + regno;
1774 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1775 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1776 if (tnum_is_const(reg->var_off)) {
1777 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1778 regno, off, access_size);
1782 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1783 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
1784 regno, tn_buf, access_size);
1791 /* when register 'regno' is passed into function that will read 'access_size'
1792 * bytes from that pointer, make sure that it's within stack boundary
1793 * and all elements of stack are initialized.
1794 * Unlike most pointer bounds-checking functions, this one doesn't take an
1795 * 'off' argument, so it has to add in reg->off itself.
1797 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1798 int access_size, bool zero_size_allowed,
1799 struct bpf_call_arg_meta *meta)
1801 struct bpf_reg_state *reg = cur_regs(env) + regno;
1802 struct bpf_func_state *state = func(env, reg);
1803 int err, min_off, max_off, i, j, slot, spi;
1805 if (reg->type != PTR_TO_STACK) {
1806 /* Allow zero-byte read from NULL, regardless of pointer type */
1807 if (zero_size_allowed && access_size == 0 &&
1808 register_is_null(reg))
1811 verbose(env, "R%d type=%s expected=%s\n", regno,
1812 reg_type_str[reg->type],
1813 reg_type_str[PTR_TO_STACK]);
1817 if (tnum_is_const(reg->var_off)) {
1818 min_off = max_off = reg->var_off.value + reg->off;
1819 err = __check_stack_boundary(env, regno, min_off, access_size,
1824 /* Variable offset is prohibited for unprivileged mode for
1825 * simplicity since it requires corresponding support in
1826 * Spectre masking for stack ALU.
1827 * See also retrieve_ptr_limit().
1829 if (!env->allow_ptr_leaks) {
1832 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1833 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
1837 /* Only initialized buffer on stack is allowed to be accessed
1838 * with variable offset. With uninitialized buffer it's hard to
1839 * guarantee that whole memory is marked as initialized on
1840 * helper return since specific bounds are unknown what may
1841 * cause uninitialized stack leaking.
1843 if (meta && meta->raw_mode)
1846 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
1847 reg->smax_value <= -BPF_MAX_VAR_OFF) {
1848 verbose(env, "R%d unbounded indirect variable offset stack access\n",
1852 min_off = reg->smin_value + reg->off;
1853 max_off = reg->smax_value + reg->off;
1854 err = __check_stack_boundary(env, regno, min_off, access_size,
1857 verbose(env, "R%d min value is outside of stack bound\n",
1861 err = __check_stack_boundary(env, regno, max_off, access_size,
1864 verbose(env, "R%d max value is outside of stack bound\n",
1870 if (meta && meta->raw_mode) {
1871 meta->access_size = access_size;
1872 meta->regno = regno;
1876 for (i = min_off; i < max_off + access_size; i++) {
1880 spi = slot / BPF_REG_SIZE;
1881 if (state->allocated_stack <= slot)
1883 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1884 if (*stype == STACK_MISC)
1886 if (*stype == STACK_ZERO) {
1887 /* helper can write anything into the stack */
1888 *stype = STACK_MISC;
1891 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1892 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
1893 __mark_reg_unknown(&state->stack[spi].spilled_ptr);
1894 for (j = 0; j < BPF_REG_SIZE; j++)
1895 state->stack[spi].slot_type[j] = STACK_MISC;
1900 if (tnum_is_const(reg->var_off)) {
1901 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1902 min_off, i - min_off, access_size);
1906 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1907 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
1908 tn_buf, i - min_off, access_size);
1912 /* reading any byte out of 8-byte 'spill_slot' will cause
1913 * the whole slot to be marked as 'read'
1915 mark_reg_read(env, &state->stack[spi].spilled_ptr,
1916 state->stack[spi].spilled_ptr.parent);
1918 return update_stack_depth(env, state, min_off);
1921 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1922 int access_size, bool zero_size_allowed,
1923 struct bpf_call_arg_meta *meta)
1925 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1927 switch (reg->type) {
1929 case PTR_TO_PACKET_META:
1930 return check_packet_access(env, regno, reg->off, access_size,
1932 case PTR_TO_MAP_VALUE:
1933 return check_map_access(env, regno, reg->off, access_size,
1935 default: /* scalar_value|ptr_to_stack or invalid ptr */
1936 return check_stack_boundary(env, regno, access_size,
1937 zero_size_allowed, meta);
1941 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1943 return type == ARG_PTR_TO_MEM ||
1944 type == ARG_PTR_TO_MEM_OR_NULL ||
1945 type == ARG_PTR_TO_UNINIT_MEM;
1948 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1950 return type == ARG_CONST_SIZE ||
1951 type == ARG_CONST_SIZE_OR_ZERO;
1954 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1955 enum bpf_arg_type arg_type,
1956 struct bpf_call_arg_meta *meta)
1958 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1959 enum bpf_reg_type expected_type, type = reg->type;
1962 if (arg_type == ARG_DONTCARE)
1965 err = check_reg_arg(env, regno, SRC_OP);
1969 if (arg_type == ARG_ANYTHING) {
1970 if (is_pointer_value(env, regno)) {
1971 verbose(env, "R%d leaks addr into helper function\n",
1978 if (type_is_pkt_pointer(type) &&
1979 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1980 verbose(env, "helper access to the packet is not allowed\n");
1984 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1985 arg_type == ARG_PTR_TO_MAP_VALUE) {
1986 expected_type = PTR_TO_STACK;
1987 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
1988 type != expected_type)
1990 } else if (arg_type == ARG_CONST_SIZE ||
1991 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1992 expected_type = SCALAR_VALUE;
1993 if (type != expected_type)
1995 } else if (arg_type == ARG_CONST_MAP_PTR) {
1996 expected_type = CONST_PTR_TO_MAP;
1997 if (type != expected_type)
1999 } else if (arg_type == ARG_PTR_TO_CTX) {
2000 expected_type = PTR_TO_CTX;
2001 if (type != expected_type)
2003 err = check_ctx_reg(env, reg, regno);
2006 } else if (arg_type_is_mem_ptr(arg_type)) {
2007 expected_type = PTR_TO_STACK;
2008 /* One exception here. In case function allows for NULL to be
2009 * passed in as argument, it's a SCALAR_VALUE type. Final test
2010 * happens during stack boundary checking.
2012 if (register_is_null(reg) &&
2013 arg_type == ARG_PTR_TO_MEM_OR_NULL)
2014 /* final test in check_stack_boundary() */;
2015 else if (!type_is_pkt_pointer(type) &&
2016 type != PTR_TO_MAP_VALUE &&
2017 type != expected_type)
2019 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
2021 verbose(env, "unsupported arg_type %d\n", arg_type);
2025 if (arg_type == ARG_CONST_MAP_PTR) {
2026 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2027 meta->map_ptr = reg->map_ptr;
2028 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2029 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2030 * check that [key, key + map->key_size) are within
2031 * stack limits and initialized
2033 if (!meta->map_ptr) {
2034 /* in function declaration map_ptr must come before
2035 * map_key, so that it's verified and known before
2036 * we have to check map_key here. Otherwise it means
2037 * that kernel subsystem misconfigured verifier
2039 verbose(env, "invalid map_ptr to access map->key\n");
2042 err = check_helper_mem_access(env, regno,
2043 meta->map_ptr->key_size, false,
2045 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
2046 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2047 * check [value, value + map->value_size) validity
2049 if (!meta->map_ptr) {
2050 /* kernel subsystem misconfigured verifier */
2051 verbose(env, "invalid map_ptr to access map->value\n");
2054 err = check_helper_mem_access(env, regno,
2055 meta->map_ptr->value_size, false,
2057 } else if (arg_type_is_mem_size(arg_type)) {
2058 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2060 /* remember the mem_size which may be used later
2061 * to refine return values.
2063 meta->msize_max_value = reg->umax_value;
2065 /* The register is SCALAR_VALUE; the access check
2066 * happens using its boundaries.
2068 if (!tnum_is_const(reg->var_off))
2069 /* For unprivileged variable accesses, disable raw
2070 * mode so that the program is required to
2071 * initialize all the memory that the helper could
2072 * just partially fill up.
2076 if (reg->smin_value < 0) {
2077 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2082 if (reg->umin_value == 0) {
2083 err = check_helper_mem_access(env, regno - 1, 0,
2090 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2091 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2095 err = check_helper_mem_access(env, regno - 1,
2097 zero_size_allowed, meta);
2102 verbose(env, "R%d type=%s expected=%s\n", regno,
2103 reg_type_str[type], reg_type_str[expected_type]);
2107 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2108 struct bpf_map *map, int func_id)
2113 /* We need a two way check, first is from map perspective ... */
2114 switch (map->map_type) {
2115 case BPF_MAP_TYPE_PROG_ARRAY:
2116 if (func_id != BPF_FUNC_tail_call)
2119 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2120 if (func_id != BPF_FUNC_perf_event_read &&
2121 func_id != BPF_FUNC_perf_event_output &&
2122 func_id != BPF_FUNC_perf_event_read_value)
2125 case BPF_MAP_TYPE_STACK_TRACE:
2126 if (func_id != BPF_FUNC_get_stackid)
2129 case BPF_MAP_TYPE_CGROUP_ARRAY:
2130 if (func_id != BPF_FUNC_skb_under_cgroup &&
2131 func_id != BPF_FUNC_current_task_under_cgroup)
2134 case BPF_MAP_TYPE_CGROUP_STORAGE:
2135 if (func_id != BPF_FUNC_get_local_storage)
2138 /* devmap returns a pointer to a live net_device ifindex that we cannot
2139 * allow to be modified from bpf side. So do not allow lookup elements
2142 case BPF_MAP_TYPE_DEVMAP:
2143 if (func_id != BPF_FUNC_redirect_map)
2146 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2149 case BPF_MAP_TYPE_CPUMAP:
2150 case BPF_MAP_TYPE_XSKMAP:
2151 if (func_id != BPF_FUNC_redirect_map)
2154 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2155 case BPF_MAP_TYPE_HASH_OF_MAPS:
2156 if (func_id != BPF_FUNC_map_lookup_elem)
2159 case BPF_MAP_TYPE_SOCKMAP:
2160 if (func_id != BPF_FUNC_sk_redirect_map &&
2161 func_id != BPF_FUNC_sock_map_update &&
2162 func_id != BPF_FUNC_map_delete_elem &&
2163 func_id != BPF_FUNC_msg_redirect_map)
2166 case BPF_MAP_TYPE_SOCKHASH:
2167 if (func_id != BPF_FUNC_sk_redirect_hash &&
2168 func_id != BPF_FUNC_sock_hash_update &&
2169 func_id != BPF_FUNC_map_delete_elem &&
2170 func_id != BPF_FUNC_msg_redirect_hash)
2173 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2174 if (func_id != BPF_FUNC_sk_select_reuseport)
2181 /* ... and second from the function itself. */
2183 case BPF_FUNC_tail_call:
2184 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2186 if (env->subprog_cnt > 1) {
2187 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2191 case BPF_FUNC_perf_event_read:
2192 case BPF_FUNC_perf_event_output:
2193 case BPF_FUNC_perf_event_read_value:
2194 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2197 case BPF_FUNC_get_stackid:
2198 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2201 case BPF_FUNC_current_task_under_cgroup:
2202 case BPF_FUNC_skb_under_cgroup:
2203 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2206 case BPF_FUNC_redirect_map:
2207 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2208 map->map_type != BPF_MAP_TYPE_CPUMAP &&
2209 map->map_type != BPF_MAP_TYPE_XSKMAP)
2212 case BPF_FUNC_sk_redirect_map:
2213 case BPF_FUNC_msg_redirect_map:
2214 case BPF_FUNC_sock_map_update:
2215 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2218 case BPF_FUNC_sk_redirect_hash:
2219 case BPF_FUNC_msg_redirect_hash:
2220 case BPF_FUNC_sock_hash_update:
2221 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2224 case BPF_FUNC_get_local_storage:
2225 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
2228 case BPF_FUNC_sk_select_reuseport:
2229 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2238 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2239 map->map_type, func_id_name(func_id), func_id);
2243 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2247 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2249 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2251 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2253 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2255 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2258 /* We only support one arg being in raw mode at the moment,
2259 * which is sufficient for the helper functions we have
2265 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2266 enum bpf_arg_type arg_next)
2268 return (arg_type_is_mem_ptr(arg_curr) &&
2269 !arg_type_is_mem_size(arg_next)) ||
2270 (!arg_type_is_mem_ptr(arg_curr) &&
2271 arg_type_is_mem_size(arg_next));
2274 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2276 /* bpf_xxx(..., buf, len) call will access 'len'
2277 * bytes from memory 'buf'. Both arg types need
2278 * to be paired, so make sure there's no buggy
2279 * helper function specification.
2281 if (arg_type_is_mem_size(fn->arg1_type) ||
2282 arg_type_is_mem_ptr(fn->arg5_type) ||
2283 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2284 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2285 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2286 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2292 static int check_func_proto(const struct bpf_func_proto *fn)
2294 return check_raw_mode_ok(fn) &&
2295 check_arg_pair_ok(fn) ? 0 : -EINVAL;
2298 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2299 * are now invalid, so turn them into unknown SCALAR_VALUE.
2301 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2302 struct bpf_func_state *state)
2304 struct bpf_reg_state *regs = state->regs, *reg;
2307 for (i = 0; i < MAX_BPF_REG; i++)
2308 if (reg_is_pkt_pointer_any(®s[i]))
2309 mark_reg_unknown(env, regs, i);
2311 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2312 if (state->stack[i].slot_type[0] != STACK_SPILL)
2314 reg = &state->stack[i].spilled_ptr;
2315 if (reg_is_pkt_pointer_any(reg))
2316 __mark_reg_unknown(reg);
2320 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2322 struct bpf_verifier_state *vstate = env->cur_state;
2325 for (i = 0; i <= vstate->curframe; i++)
2326 __clear_all_pkt_pointers(env, vstate->frame[i]);
2329 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2332 struct bpf_verifier_state *state = env->cur_state;
2333 struct bpf_func_state *caller, *callee;
2334 int i, subprog, target_insn;
2336 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2337 verbose(env, "the call stack of %d frames is too deep\n",
2338 state->curframe + 2);
2342 target_insn = *insn_idx + insn->imm;
2343 subprog = find_subprog(env, target_insn + 1);
2345 verbose(env, "verifier bug. No program starts at insn %d\n",
2350 caller = state->frame[state->curframe];
2351 if (state->frame[state->curframe + 1]) {
2352 verbose(env, "verifier bug. Frame %d already allocated\n",
2353 state->curframe + 1);
2357 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2360 state->frame[state->curframe + 1] = callee;
2362 /* callee cannot access r0, r6 - r9 for reading and has to write
2363 * into its own stack before reading from it.
2364 * callee can read/write into caller's stack
2366 init_func_state(env, callee,
2367 /* remember the callsite, it will be used by bpf_exit */
2368 *insn_idx /* callsite */,
2369 state->curframe + 1 /* frameno within this callchain */,
2370 subprog /* subprog number within this prog */);
2372 /* copy r1 - r5 args that callee can access. The copy includes parent
2373 * pointers, which connects us up to the liveness chain
2375 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2376 callee->regs[i] = caller->regs[i];
2378 /* after the call registers r0 - r5 were scratched */
2379 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2380 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2381 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2384 /* only increment it after check_reg_arg() finished */
2387 /* and go analyze first insn of the callee */
2388 *insn_idx = target_insn;
2390 if (env->log.level) {
2391 verbose(env, "caller:\n");
2392 print_verifier_state(env, caller);
2393 verbose(env, "callee:\n");
2394 print_verifier_state(env, callee);
2399 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2401 struct bpf_verifier_state *state = env->cur_state;
2402 struct bpf_func_state *caller, *callee;
2403 struct bpf_reg_state *r0;
2405 callee = state->frame[state->curframe];
2406 r0 = &callee->regs[BPF_REG_0];
2407 if (r0->type == PTR_TO_STACK) {
2408 /* technically it's ok to return caller's stack pointer
2409 * (or caller's caller's pointer) back to the caller,
2410 * since these pointers are valid. Only current stack
2411 * pointer will be invalid as soon as function exits,
2412 * but let's be conservative
2414 verbose(env, "cannot return stack pointer to the caller\n");
2419 caller = state->frame[state->curframe];
2420 /* return to the caller whatever r0 had in the callee */
2421 caller->regs[BPF_REG_0] = *r0;
2423 *insn_idx = callee->callsite + 1;
2424 if (env->log.level) {
2425 verbose(env, "returning from callee:\n");
2426 print_verifier_state(env, callee);
2427 verbose(env, "to caller at %d:\n", *insn_idx);
2428 print_verifier_state(env, caller);
2430 /* clear everything in the callee */
2431 free_func_state(callee);
2432 state->frame[state->curframe + 1] = NULL;
2436 static int do_refine_retval_range(struct bpf_verifier_env *env,
2437 struct bpf_reg_state *regs, int ret_type,
2438 int func_id, struct bpf_call_arg_meta *meta)
2440 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
2441 struct bpf_reg_state tmp_reg = *ret_reg;
2444 if (ret_type != RET_INTEGER ||
2445 (func_id != BPF_FUNC_get_stack &&
2446 func_id != BPF_FUNC_probe_read_str))
2449 /* Error case where ret is in interval [S32MIN, -1]. */
2450 ret_reg->smin_value = S32_MIN;
2451 ret_reg->smax_value = -1;
2453 __reg_deduce_bounds(ret_reg);
2454 __reg_bound_offset(ret_reg);
2455 __update_reg_bounds(ret_reg);
2457 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
2463 /* Success case where ret is in range [0, msize_max_value]. */
2464 ret_reg->smin_value = 0;
2465 ret_reg->smax_value = meta->msize_max_value;
2466 ret_reg->umin_value = ret_reg->smin_value;
2467 ret_reg->umax_value = ret_reg->smax_value;
2469 __reg_deduce_bounds(ret_reg);
2470 __reg_bound_offset(ret_reg);
2471 __update_reg_bounds(ret_reg);
2477 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2478 int func_id, int insn_idx)
2480 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2482 if (func_id != BPF_FUNC_tail_call &&
2483 func_id != BPF_FUNC_map_lookup_elem &&
2484 func_id != BPF_FUNC_map_update_elem &&
2485 func_id != BPF_FUNC_map_delete_elem)
2488 if (meta->map_ptr == NULL) {
2489 verbose(env, "kernel subsystem misconfigured verifier\n");
2493 if (!BPF_MAP_PTR(aux->map_state))
2494 bpf_map_ptr_store(aux, meta->map_ptr,
2495 meta->map_ptr->unpriv_array);
2496 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2497 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2498 meta->map_ptr->unpriv_array);
2502 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2504 const struct bpf_func_proto *fn = NULL;
2505 struct bpf_reg_state *regs;
2506 struct bpf_call_arg_meta meta;
2510 /* find function prototype */
2511 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2512 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2517 if (env->ops->get_func_proto)
2518 fn = env->ops->get_func_proto(func_id, env->prog);
2520 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2525 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2526 if (!env->prog->gpl_compatible && fn->gpl_only) {
2527 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2531 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2532 changes_data = bpf_helper_changes_pkt_data(fn->func);
2533 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2534 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2535 func_id_name(func_id), func_id);
2539 memset(&meta, 0, sizeof(meta));
2540 meta.pkt_access = fn->pkt_access;
2542 err = check_func_proto(fn);
2544 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2545 func_id_name(func_id), func_id);
2550 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2553 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2556 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2559 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2562 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2566 err = record_func_map(env, &meta, func_id, insn_idx);
2570 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2571 * is inferred from register state.
2573 for (i = 0; i < meta.access_size; i++) {
2574 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2575 BPF_WRITE, -1, false);
2580 regs = cur_regs(env);
2582 /* check that flags argument in get_local_storage(map, flags) is 0,
2583 * this is required because get_local_storage() can't return an error.
2585 if (func_id == BPF_FUNC_get_local_storage &&
2586 !register_is_null(®s[BPF_REG_2])) {
2587 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
2591 /* reset caller saved regs */
2592 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2593 mark_reg_not_init(env, regs, caller_saved[i]);
2594 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2597 /* update return register (already marked as written above) */
2598 if (fn->ret_type == RET_INTEGER) {
2599 /* sets type to SCALAR_VALUE */
2600 mark_reg_unknown(env, regs, BPF_REG_0);
2601 } else if (fn->ret_type == RET_VOID) {
2602 regs[BPF_REG_0].type = NOT_INIT;
2603 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
2604 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2605 if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
2606 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
2608 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2609 /* There is no offset yet applied, variable or fixed */
2610 mark_reg_known_zero(env, regs, BPF_REG_0);
2611 /* remember map_ptr, so that check_map_access()
2612 * can check 'value_size' boundary of memory access
2613 * to map element returned from bpf_map_lookup_elem()
2615 if (meta.map_ptr == NULL) {
2617 "kernel subsystem misconfigured verifier\n");
2620 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2621 regs[BPF_REG_0].id = ++env->id_gen;
2623 verbose(env, "unknown return type %d of func %s#%d\n",
2624 fn->ret_type, func_id_name(func_id), func_id);
2628 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
2632 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2636 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
2637 const char *err_str;
2639 #ifdef CONFIG_PERF_EVENTS
2640 err = get_callchain_buffers(sysctl_perf_event_max_stack);
2641 err_str = "cannot get callchain buffer for func %s#%d\n";
2644 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
2647 verbose(env, err_str, func_id_name(func_id), func_id);
2651 env->prog->has_callchain_buf = true;
2655 clear_all_pkt_pointers(env);
2659 static bool signed_add_overflows(s64 a, s64 b)
2661 /* Do the add in u64, where overflow is well-defined */
2662 s64 res = (s64)((u64)a + (u64)b);
2669 static bool signed_sub_overflows(s64 a, s64 b)
2671 /* Do the sub in u64, where overflow is well-defined */
2672 s64 res = (s64)((u64)a - (u64)b);
2679 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2680 const struct bpf_reg_state *reg,
2681 enum bpf_reg_type type)
2683 bool known = tnum_is_const(reg->var_off);
2684 s64 val = reg->var_off.value;
2685 s64 smin = reg->smin_value;
2687 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2688 verbose(env, "math between %s pointer and %lld is not allowed\n",
2689 reg_type_str[type], val);
2693 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2694 verbose(env, "%s pointer offset %d is not allowed\n",
2695 reg_type_str[type], reg->off);
2699 if (smin == S64_MIN) {
2700 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2701 reg_type_str[type]);
2705 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2706 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2707 smin, reg_type_str[type]);
2714 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
2716 return &env->insn_aux_data[env->insn_idx];
2727 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
2728 u32 *alu_limit, bool mask_to_left)
2730 u32 max = 0, ptr_limit = 0;
2732 switch (ptr_reg->type) {
2734 /* Offset 0 is out-of-bounds, but acceptable start for the
2735 * left direction, see BPF_REG_FP. Also, unknown scalar
2736 * offset where we would need to deal with min/max bounds is
2737 * currently prohibited for unprivileged.
2739 max = MAX_BPF_STACK + mask_to_left;
2740 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
2742 case PTR_TO_MAP_VALUE:
2743 max = ptr_reg->map_ptr->value_size;
2744 ptr_limit = (mask_to_left ?
2745 ptr_reg->smin_value :
2746 ptr_reg->umax_value) + ptr_reg->off;
2752 if (ptr_limit >= max)
2753 return REASON_LIMIT;
2754 *alu_limit = ptr_limit;
2758 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
2759 const struct bpf_insn *insn)
2761 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
2764 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
2765 u32 alu_state, u32 alu_limit)
2767 /* If we arrived here from different branches with different
2768 * state or limits to sanitize, then this won't work.
2770 if (aux->alu_state &&
2771 (aux->alu_state != alu_state ||
2772 aux->alu_limit != alu_limit))
2773 return REASON_PATHS;
2775 /* Corresponding fixup done in fixup_bpf_calls(). */
2776 aux->alu_state = alu_state;
2777 aux->alu_limit = alu_limit;
2781 static int sanitize_val_alu(struct bpf_verifier_env *env,
2782 struct bpf_insn *insn)
2784 struct bpf_insn_aux_data *aux = cur_aux(env);
2786 if (can_skip_alu_sanitation(env, insn))
2789 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
2792 static bool sanitize_needed(u8 opcode)
2794 return opcode == BPF_ADD || opcode == BPF_SUB;
2797 struct bpf_sanitize_info {
2798 struct bpf_insn_aux_data aux;
2802 static struct bpf_verifier_state *
2803 sanitize_speculative_path(struct bpf_verifier_env *env,
2804 const struct bpf_insn *insn,
2805 u32 next_idx, u32 curr_idx)
2807 struct bpf_verifier_state *branch;
2808 struct bpf_reg_state *regs;
2810 branch = push_stack(env, next_idx, curr_idx, true);
2811 if (branch && insn) {
2812 regs = branch->frame[branch->curframe]->regs;
2813 if (BPF_SRC(insn->code) == BPF_K) {
2814 mark_reg_unknown(env, regs, insn->dst_reg);
2815 } else if (BPF_SRC(insn->code) == BPF_X) {
2816 mark_reg_unknown(env, regs, insn->dst_reg);
2817 mark_reg_unknown(env, regs, insn->src_reg);
2823 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
2824 struct bpf_insn *insn,
2825 const struct bpf_reg_state *ptr_reg,
2826 const struct bpf_reg_state *off_reg,
2827 struct bpf_reg_state *dst_reg,
2828 struct bpf_sanitize_info *info,
2829 const bool commit_window)
2831 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
2832 struct bpf_verifier_state *vstate = env->cur_state;
2833 bool off_is_imm = tnum_is_const(off_reg->var_off);
2834 bool off_is_neg = off_reg->smin_value < 0;
2835 bool ptr_is_dst_reg = ptr_reg == dst_reg;
2836 u8 opcode = BPF_OP(insn->code);
2837 u32 alu_state, alu_limit;
2838 struct bpf_reg_state tmp;
2842 if (can_skip_alu_sanitation(env, insn))
2845 /* We already marked aux for masking from non-speculative
2846 * paths, thus we got here in the first place. We only care
2847 * to explore bad access from here.
2849 if (vstate->speculative)
2852 if (!commit_window) {
2853 if (!tnum_is_const(off_reg->var_off) &&
2854 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
2855 return REASON_BOUNDS;
2857 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
2858 (opcode == BPF_SUB && !off_is_neg);
2861 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
2865 if (commit_window) {
2866 /* In commit phase we narrow the masking window based on
2867 * the observed pointer move after the simulated operation.
2869 alu_state = info->aux.alu_state;
2870 alu_limit = abs(info->aux.alu_limit - alu_limit);
2872 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
2873 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
2874 alu_state |= ptr_is_dst_reg ?
2875 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
2877 /* Limit pruning on unknown scalars to enable deep search for
2878 * potential masking differences from other program paths.
2881 env->explore_alu_limits = true;
2884 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
2888 /* If we're in commit phase, we're done here given we already
2889 * pushed the truncated dst_reg into the speculative verification
2892 * Also, when register is a known constant, we rewrite register-based
2893 * operation to immediate-based, and thus do not need masking (and as
2894 * a consequence, do not need to simulate the zero-truncation either).
2896 if (commit_window || off_is_imm)
2899 /* Simulate and find potential out-of-bounds access under
2900 * speculative execution from truncation as a result of
2901 * masking when off was not within expected range. If off
2902 * sits in dst, then we temporarily need to move ptr there
2903 * to simulate dst (== 0) +/-= ptr. Needed, for example,
2904 * for cases where we use K-based arithmetic in one direction
2905 * and truncated reg-based in the other in order to explore
2908 if (!ptr_is_dst_reg) {
2910 *dst_reg = *ptr_reg;
2912 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
2914 if (!ptr_is_dst_reg && ret)
2916 return !ret ? REASON_STACK : 0;
2919 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
2921 struct bpf_verifier_state *vstate = env->cur_state;
2923 /* If we simulate paths under speculation, we don't update the
2924 * insn as 'seen' such that when we verify unreachable paths in
2925 * the non-speculative domain, sanitize_dead_code() can still
2926 * rewrite/sanitize them.
2928 if (!vstate->speculative)
2929 env->insn_aux_data[env->insn_idx].seen = true;
2932 static int sanitize_err(struct bpf_verifier_env *env,
2933 const struct bpf_insn *insn, int reason,
2934 const struct bpf_reg_state *off_reg,
2935 const struct bpf_reg_state *dst_reg)
2937 static const char *err = "pointer arithmetic with it prohibited for !root";
2938 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
2939 u32 dst = insn->dst_reg, src = insn->src_reg;
2943 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
2944 off_reg == dst_reg ? dst : src, err);
2947 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
2948 off_reg == dst_reg ? src : dst, err);
2951 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
2955 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
2959 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
2963 verbose(env, "verifier internal error: unknown reason (%d)\n",
2971 static int sanitize_check_bounds(struct bpf_verifier_env *env,
2972 const struct bpf_insn *insn,
2973 const struct bpf_reg_state *dst_reg)
2975 u32 dst = insn->dst_reg;
2977 /* For unprivileged we require that resulting offset must be in bounds
2978 * in order to be able to sanitize access later on.
2980 if (env->allow_ptr_leaks)
2983 switch (dst_reg->type) {
2985 if (check_stack_access(env, dst_reg, dst_reg->off +
2986 dst_reg->var_off.value, 1)) {
2987 verbose(env, "R%d stack pointer arithmetic goes out of range, "
2988 "prohibited for !root\n", dst);
2992 case PTR_TO_MAP_VALUE:
2993 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
2994 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
2995 "prohibited for !root\n", dst);
3006 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
3007 * Caller should also handle BPF_MOV case separately.
3008 * If we return -EACCES, caller may want to try again treating pointer as a
3009 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
3011 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
3012 struct bpf_insn *insn,
3013 const struct bpf_reg_state *ptr_reg,
3014 const struct bpf_reg_state *off_reg)
3016 struct bpf_verifier_state *vstate = env->cur_state;
3017 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3018 struct bpf_reg_state *regs = state->regs, *dst_reg;
3019 bool known = tnum_is_const(off_reg->var_off);
3020 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
3021 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
3022 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
3023 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3024 struct bpf_sanitize_info info = {};
3025 u8 opcode = BPF_OP(insn->code);
3026 u32 dst = insn->dst_reg;
3029 dst_reg = ®s[dst];
3031 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
3032 smin_val > smax_val || umin_val > umax_val) {
3033 /* Taint dst register if offset had invalid bounds derived from
3034 * e.g. dead branches.
3036 __mark_reg_unknown(dst_reg);
3040 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3041 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
3043 "R%d 32-bit pointer arithmetic prohibited\n",
3048 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3049 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
3053 if (ptr_reg->type == CONST_PTR_TO_MAP) {
3054 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
3058 if (ptr_reg->type == PTR_TO_PACKET_END) {
3059 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
3064 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3065 * The id may be overwritten later if we create a new variable offset.
3067 dst_reg->type = ptr_reg->type;
3068 dst_reg->id = ptr_reg->id;
3070 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3071 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3074 if (sanitize_needed(opcode)) {
3075 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3078 return sanitize_err(env, insn, ret, off_reg, dst_reg);
3083 /* We can take a fixed offset as long as it doesn't overflow
3084 * the s32 'off' field
3086 if (known && (ptr_reg->off + smin_val ==
3087 (s64)(s32)(ptr_reg->off + smin_val))) {
3088 /* pointer += K. Accumulate it into fixed offset */
3089 dst_reg->smin_value = smin_ptr;
3090 dst_reg->smax_value = smax_ptr;
3091 dst_reg->umin_value = umin_ptr;
3092 dst_reg->umax_value = umax_ptr;
3093 dst_reg->var_off = ptr_reg->var_off;
3094 dst_reg->off = ptr_reg->off + smin_val;
3095 dst_reg->raw = ptr_reg->raw;
3098 /* A new variable offset is created. Note that off_reg->off
3099 * == 0, since it's a scalar.
3100 * dst_reg gets the pointer type and since some positive
3101 * integer value was added to the pointer, give it a new 'id'
3102 * if it's a PTR_TO_PACKET.
3103 * this creates a new 'base' pointer, off_reg (variable) gets
3104 * added into the variable offset, and we copy the fixed offset
3107 if (signed_add_overflows(smin_ptr, smin_val) ||
3108 signed_add_overflows(smax_ptr, smax_val)) {
3109 dst_reg->smin_value = S64_MIN;
3110 dst_reg->smax_value = S64_MAX;
3112 dst_reg->smin_value = smin_ptr + smin_val;
3113 dst_reg->smax_value = smax_ptr + smax_val;
3115 if (umin_ptr + umin_val < umin_ptr ||
3116 umax_ptr + umax_val < umax_ptr) {
3117 dst_reg->umin_value = 0;
3118 dst_reg->umax_value = U64_MAX;
3120 dst_reg->umin_value = umin_ptr + umin_val;
3121 dst_reg->umax_value = umax_ptr + umax_val;
3123 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3124 dst_reg->off = ptr_reg->off;
3125 dst_reg->raw = ptr_reg->raw;
3126 if (reg_is_pkt_pointer(ptr_reg)) {
3127 dst_reg->id = ++env->id_gen;
3128 /* something was added to pkt_ptr, set range to zero */
3133 if (dst_reg == off_reg) {
3134 /* scalar -= pointer. Creates an unknown scalar */
3135 verbose(env, "R%d tried to subtract pointer from scalar\n",
3139 /* We don't allow subtraction from FP, because (according to
3140 * test_verifier.c test "invalid fp arithmetic", JITs might not
3141 * be able to deal with it.
3143 if (ptr_reg->type == PTR_TO_STACK) {
3144 verbose(env, "R%d subtraction from stack pointer prohibited\n",
3148 if (known && (ptr_reg->off - smin_val ==
3149 (s64)(s32)(ptr_reg->off - smin_val))) {
3150 /* pointer -= K. Subtract it from fixed offset */
3151 dst_reg->smin_value = smin_ptr;
3152 dst_reg->smax_value = smax_ptr;
3153 dst_reg->umin_value = umin_ptr;
3154 dst_reg->umax_value = umax_ptr;
3155 dst_reg->var_off = ptr_reg->var_off;
3156 dst_reg->id = ptr_reg->id;
3157 dst_reg->off = ptr_reg->off - smin_val;
3158 dst_reg->raw = ptr_reg->raw;
3161 /* A new variable offset is created. If the subtrahend is known
3162 * nonnegative, then any reg->range we had before is still good.
3164 if (signed_sub_overflows(smin_ptr, smax_val) ||
3165 signed_sub_overflows(smax_ptr, smin_val)) {
3166 /* Overflow possible, we know nothing */
3167 dst_reg->smin_value = S64_MIN;
3168 dst_reg->smax_value = S64_MAX;
3170 dst_reg->smin_value = smin_ptr - smax_val;
3171 dst_reg->smax_value = smax_ptr - smin_val;
3173 if (umin_ptr < umax_val) {
3174 /* Overflow possible, we know nothing */
3175 dst_reg->umin_value = 0;
3176 dst_reg->umax_value = U64_MAX;
3178 /* Cannot overflow (as long as bounds are consistent) */
3179 dst_reg->umin_value = umin_ptr - umax_val;
3180 dst_reg->umax_value = umax_ptr - umin_val;
3182 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3183 dst_reg->off = ptr_reg->off;
3184 dst_reg->raw = ptr_reg->raw;
3185 if (reg_is_pkt_pointer(ptr_reg)) {
3186 dst_reg->id = ++env->id_gen;
3187 /* something was added to pkt_ptr, set range to zero */
3195 /* bitwise ops on pointers are troublesome, prohibit. */
3196 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3197 dst, bpf_alu_string[opcode >> 4]);
3200 /* other operators (e.g. MUL,LSH) produce non-pointer results */
3201 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3202 dst, bpf_alu_string[opcode >> 4]);
3206 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3209 __update_reg_bounds(dst_reg);
3210 __reg_deduce_bounds(dst_reg);
3211 __reg_bound_offset(dst_reg);
3213 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
3215 if (sanitize_needed(opcode)) {
3216 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3219 return sanitize_err(env, insn, ret, off_reg, dst_reg);
3225 /* WARNING: This function does calculations on 64-bit values, but the actual
3226 * execution may occur on 32-bit values. Therefore, things like bitshifts
3227 * need extra checks in the 32-bit case.
3229 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3230 struct bpf_insn *insn,
3231 struct bpf_reg_state *dst_reg,
3232 struct bpf_reg_state src_reg)
3234 struct bpf_reg_state *regs = cur_regs(env);
3235 u8 opcode = BPF_OP(insn->code);
3236 bool src_known, dst_known;
3237 s64 smin_val, smax_val;
3238 u64 umin_val, umax_val;
3239 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3242 if (insn_bitness == 32) {
3243 /* Relevant for 32-bit RSH: Information can propagate towards
3244 * LSB, so it isn't sufficient to only truncate the output to
3247 coerce_reg_to_size(dst_reg, 4);
3248 coerce_reg_to_size(&src_reg, 4);
3251 smin_val = src_reg.smin_value;
3252 smax_val = src_reg.smax_value;
3253 umin_val = src_reg.umin_value;
3254 umax_val = src_reg.umax_value;
3255 src_known = tnum_is_const(src_reg.var_off);
3256 dst_known = tnum_is_const(dst_reg->var_off);
3258 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3259 smin_val > smax_val || umin_val > umax_val) {
3260 /* Taint dst register if offset had invalid bounds derived from
3261 * e.g. dead branches.
3263 __mark_reg_unknown(dst_reg);
3268 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3269 __mark_reg_unknown(dst_reg);
3273 if (sanitize_needed(opcode)) {
3274 ret = sanitize_val_alu(env, insn);
3276 return sanitize_err(env, insn, ret, NULL, NULL);
3281 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3282 signed_add_overflows(dst_reg->smax_value, smax_val)) {
3283 dst_reg->smin_value = S64_MIN;
3284 dst_reg->smax_value = S64_MAX;
3286 dst_reg->smin_value += smin_val;
3287 dst_reg->smax_value += smax_val;
3289 if (dst_reg->umin_value + umin_val < umin_val ||
3290 dst_reg->umax_value + umax_val < umax_val) {
3291 dst_reg->umin_value = 0;
3292 dst_reg->umax_value = U64_MAX;
3294 dst_reg->umin_value += umin_val;
3295 dst_reg->umax_value += umax_val;
3297 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
3300 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3301 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3302 /* Overflow possible, we know nothing */
3303 dst_reg->smin_value = S64_MIN;
3304 dst_reg->smax_value = S64_MAX;
3306 dst_reg->smin_value -= smax_val;
3307 dst_reg->smax_value -= smin_val;
3309 if (dst_reg->umin_value < umax_val) {
3310 /* Overflow possible, we know nothing */
3311 dst_reg->umin_value = 0;
3312 dst_reg->umax_value = U64_MAX;
3314 /* Cannot overflow (as long as bounds are consistent) */
3315 dst_reg->umin_value -= umax_val;
3316 dst_reg->umax_value -= umin_val;
3318 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
3321 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3322 if (smin_val < 0 || dst_reg->smin_value < 0) {
3323 /* Ain't nobody got time to multiply that sign */
3324 __mark_reg_unbounded(dst_reg);
3325 __update_reg_bounds(dst_reg);
3328 /* Both values are positive, so we can work with unsigned and
3329 * copy the result to signed (unless it exceeds S64_MAX).
3331 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3332 /* Potential overflow, we know nothing */
3333 __mark_reg_unbounded(dst_reg);
3334 /* (except what we can learn from the var_off) */
3335 __update_reg_bounds(dst_reg);
3338 dst_reg->umin_value *= umin_val;
3339 dst_reg->umax_value *= umax_val;
3340 if (dst_reg->umax_value > S64_MAX) {
3341 /* Overflow possible, we know nothing */
3342 dst_reg->smin_value = S64_MIN;
3343 dst_reg->smax_value = S64_MAX;
3345 dst_reg->smin_value = dst_reg->umin_value;
3346 dst_reg->smax_value = dst_reg->umax_value;
3350 if (src_known && dst_known) {
3351 __mark_reg_known(dst_reg, dst_reg->var_off.value &
3352 src_reg.var_off.value);
3355 /* We get our minimum from the var_off, since that's inherently
3356 * bitwise. Our maximum is the minimum of the operands' maxima.
3358 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
3359 dst_reg->umin_value = dst_reg->var_off.value;
3360 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3361 if (dst_reg->smin_value < 0 || smin_val < 0) {
3362 /* Lose signed bounds when ANDing negative numbers,
3363 * ain't nobody got time for that.
3365 dst_reg->smin_value = S64_MIN;
3366 dst_reg->smax_value = S64_MAX;
3368 /* ANDing two positives gives a positive, so safe to
3369 * cast result into s64.
3371 dst_reg->smin_value = dst_reg->umin_value;
3372 dst_reg->smax_value = dst_reg->umax_value;
3374 /* We may learn something more from the var_off */
3375 __update_reg_bounds(dst_reg);
3378 if (src_known && dst_known) {
3379 __mark_reg_known(dst_reg, dst_reg->var_off.value |
3380 src_reg.var_off.value);
3383 /* We get our maximum from the var_off, and our minimum is the
3384 * maximum of the operands' minima
3386 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
3387 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
3388 dst_reg->umax_value = dst_reg->var_off.value |
3389 dst_reg->var_off.mask;
3390 if (dst_reg->smin_value < 0 || smin_val < 0) {
3391 /* Lose signed bounds when ORing negative numbers,
3392 * ain't nobody got time for that.
3394 dst_reg->smin_value = S64_MIN;
3395 dst_reg->smax_value = S64_MAX;
3397 /* ORing two positives gives a positive, so safe to
3398 * cast result into s64.
3400 dst_reg->smin_value = dst_reg->umin_value;
3401 dst_reg->smax_value = dst_reg->umax_value;
3403 /* We may learn something more from the var_off */
3404 __update_reg_bounds(dst_reg);
3407 if (umax_val >= insn_bitness) {
3408 /* Shifts greater than 31 or 63 are undefined.
3409 * This includes shifts by a negative number.
3411 mark_reg_unknown(env, regs, insn->dst_reg);
3414 /* We lose all sign bit information (except what we can pick
3417 dst_reg->smin_value = S64_MIN;
3418 dst_reg->smax_value = S64_MAX;
3419 /* If we might shift our top bit out, then we know nothing */
3420 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
3421 dst_reg->umin_value = 0;
3422 dst_reg->umax_value = U64_MAX;
3424 dst_reg->umin_value <<= umin_val;
3425 dst_reg->umax_value <<= umax_val;
3427 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
3428 /* We may learn something more from the var_off */
3429 __update_reg_bounds(dst_reg);
3432 if (umax_val >= insn_bitness) {
3433 /* Shifts greater than 31 or 63 are undefined.
3434 * This includes shifts by a negative number.
3436 mark_reg_unknown(env, regs, insn->dst_reg);
3439 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
3440 * be negative, then either:
3441 * 1) src_reg might be zero, so the sign bit of the result is
3442 * unknown, so we lose our signed bounds
3443 * 2) it's known negative, thus the unsigned bounds capture the
3445 * 3) the signed bounds cross zero, so they tell us nothing
3447 * If the value in dst_reg is known nonnegative, then again the
3448 * unsigned bounts capture the signed bounds.
3449 * Thus, in all cases it suffices to blow away our signed bounds
3450 * and rely on inferring new ones from the unsigned bounds and
3451 * var_off of the result.
3453 dst_reg->smin_value = S64_MIN;
3454 dst_reg->smax_value = S64_MAX;
3455 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3456 dst_reg->umin_value >>= umax_val;
3457 dst_reg->umax_value >>= umin_val;
3458 /* We may learn something more from the var_off */
3459 __update_reg_bounds(dst_reg);
3462 if (umax_val >= insn_bitness) {
3463 /* Shifts greater than 31 or 63 are undefined.
3464 * This includes shifts by a negative number.
3466 mark_reg_unknown(env, regs, insn->dst_reg);
3470 /* Upon reaching here, src_known is true and
3471 * umax_val is equal to umin_val.
3473 if (insn_bitness == 32) {
3474 dst_reg->smin_value = (u32)(((s32)dst_reg->smin_value) >> umin_val);
3475 dst_reg->smax_value = (u32)(((s32)dst_reg->smax_value) >> umin_val);
3477 dst_reg->smin_value >>= umin_val;
3478 dst_reg->smax_value >>= umin_val;
3481 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val,
3484 /* blow away the dst_reg umin_value/umax_value and rely on
3485 * dst_reg var_off to refine the result.
3487 dst_reg->umin_value = 0;
3488 dst_reg->umax_value = U64_MAX;
3489 __update_reg_bounds(dst_reg);
3492 mark_reg_unknown(env, regs, insn->dst_reg);
3496 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3497 /* 32-bit ALU ops are (32,32)->32 */
3498 coerce_reg_to_size(dst_reg, 4);
3501 __update_reg_bounds(dst_reg);
3502 __reg_deduce_bounds(dst_reg);
3503 __reg_bound_offset(dst_reg);
3507 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3510 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3511 struct bpf_insn *insn)
3513 struct bpf_verifier_state *vstate = env->cur_state;
3514 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3515 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3516 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3517 u8 opcode = BPF_OP(insn->code);
3519 dst_reg = ®s[insn->dst_reg];
3521 if (dst_reg->type != SCALAR_VALUE)
3523 if (BPF_SRC(insn->code) == BPF_X) {
3524 src_reg = ®s[insn->src_reg];
3525 if (src_reg->type != SCALAR_VALUE) {
3526 if (dst_reg->type != SCALAR_VALUE) {
3527 /* Combining two pointers by any ALU op yields
3528 * an arbitrary scalar. Disallow all math except
3529 * pointer subtraction
3531 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
3532 mark_reg_unknown(env, regs, insn->dst_reg);
3535 verbose(env, "R%d pointer %s pointer prohibited\n",
3537 bpf_alu_string[opcode >> 4]);
3540 /* scalar += pointer
3541 * This is legal, but we have to reverse our
3542 * src/dest handling in computing the range
3544 return adjust_ptr_min_max_vals(env, insn,
3547 } else if (ptr_reg) {
3548 /* pointer += scalar */
3549 return adjust_ptr_min_max_vals(env, insn,
3553 /* Pretend the src is a reg with a known value, since we only
3554 * need to be able to read from this state.
3556 off_reg.type = SCALAR_VALUE;
3557 __mark_reg_known(&off_reg, insn->imm);
3559 if (ptr_reg) /* pointer += K */
3560 return adjust_ptr_min_max_vals(env, insn,
3564 /* Got here implies adding two SCALAR_VALUEs */
3565 if (WARN_ON_ONCE(ptr_reg)) {
3566 print_verifier_state(env, state);
3567 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3570 if (WARN_ON(!src_reg)) {
3571 print_verifier_state(env, state);
3572 verbose(env, "verifier internal error: no src_reg\n");
3575 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3578 /* check validity of 32-bit and 64-bit arithmetic operations */
3579 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3581 struct bpf_reg_state *regs = cur_regs(env);
3582 u8 opcode = BPF_OP(insn->code);
3585 if (opcode == BPF_END || opcode == BPF_NEG) {
3586 if (opcode == BPF_NEG) {
3587 if (BPF_SRC(insn->code) != 0 ||
3588 insn->src_reg != BPF_REG_0 ||
3589 insn->off != 0 || insn->imm != 0) {
3590 verbose(env, "BPF_NEG uses reserved fields\n");
3594 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3595 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3596 BPF_CLASS(insn->code) == BPF_ALU64) {
3597 verbose(env, "BPF_END uses reserved fields\n");
3602 /* check src operand */
3603 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3607 if (is_pointer_value(env, insn->dst_reg)) {
3608 verbose(env, "R%d pointer arithmetic prohibited\n",
3613 /* check dest operand */
3614 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3618 } else if (opcode == BPF_MOV) {
3620 if (BPF_SRC(insn->code) == BPF_X) {
3621 if (insn->imm != 0 || insn->off != 0) {
3622 verbose(env, "BPF_MOV uses reserved fields\n");
3626 /* check src operand */
3627 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3631 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3632 verbose(env, "BPF_MOV uses reserved fields\n");
3637 /* check dest operand, mark as required later */
3638 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3642 if (BPF_SRC(insn->code) == BPF_X) {
3643 struct bpf_reg_state *src_reg = regs + insn->src_reg;
3644 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
3646 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3648 * copy register state to dest reg
3650 *dst_reg = *src_reg;
3651 dst_reg->live |= REG_LIVE_WRITTEN;
3654 if (is_pointer_value(env, insn->src_reg)) {
3656 "R%d partial copy of pointer\n",
3659 } else if (src_reg->type == SCALAR_VALUE) {
3660 *dst_reg = *src_reg;
3661 dst_reg->live |= REG_LIVE_WRITTEN;
3663 mark_reg_unknown(env, regs,
3666 coerce_reg_to_size(dst_reg, 4);
3670 * remember the value we stored into this reg
3672 /* clear any state __mark_reg_known doesn't set */
3673 mark_reg_unknown(env, regs, insn->dst_reg);
3674 regs[insn->dst_reg].type = SCALAR_VALUE;
3675 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3676 __mark_reg_known(regs + insn->dst_reg,
3679 __mark_reg_known(regs + insn->dst_reg,
3684 } else if (opcode > BPF_END) {
3685 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3688 } else { /* all other ALU ops: and, sub, xor, add, ... */
3690 if (BPF_SRC(insn->code) == BPF_X) {
3691 if (insn->imm != 0 || insn->off != 0) {
3692 verbose(env, "BPF_ALU uses reserved fields\n");
3695 /* check src1 operand */
3696 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3700 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3701 verbose(env, "BPF_ALU uses reserved fields\n");
3706 /* check src2 operand */
3707 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3711 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3712 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3713 verbose(env, "div by zero\n");
3717 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3718 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3722 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3723 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3724 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3726 if (insn->imm < 0 || insn->imm >= size) {
3727 verbose(env, "invalid shift %d\n", insn->imm);
3732 /* check dest operand */
3733 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3737 return adjust_reg_min_max_vals(env, insn);
3743 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3744 struct bpf_reg_state *dst_reg,
3745 enum bpf_reg_type type,
3746 bool range_right_open)
3748 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3749 struct bpf_reg_state *regs = state->regs, *reg;
3753 if (dst_reg->off < 0 ||
3754 (dst_reg->off == 0 && range_right_open))
3755 /* This doesn't give us any range */
3758 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3759 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3760 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3761 * than pkt_end, but that's because it's also less than pkt.
3765 new_range = dst_reg->off;
3766 if (range_right_open)
3769 /* Examples for register markings:
3771 * pkt_data in dst register:
3775 * if (r2 > pkt_end) goto <handle exception>
3780 * if (r2 < pkt_end) goto <access okay>
3781 * <handle exception>
3784 * r2 == dst_reg, pkt_end == src_reg
3785 * r2=pkt(id=n,off=8,r=0)
3786 * r3=pkt(id=n,off=0,r=0)
3788 * pkt_data in src register:
3792 * if (pkt_end >= r2) goto <access okay>
3793 * <handle exception>
3797 * if (pkt_end <= r2) goto <handle exception>
3801 * pkt_end == dst_reg, r2 == src_reg
3802 * r2=pkt(id=n,off=8,r=0)
3803 * r3=pkt(id=n,off=0,r=0)
3805 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3806 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3807 * and [r3, r3 + 8-1) respectively is safe to access depending on
3811 /* If our ids match, then we must have the same max_value. And we
3812 * don't care about the other reg's fixed offset, since if it's too big
3813 * the range won't allow anything.
3814 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3816 for (i = 0; i < MAX_BPF_REG; i++)
3817 if (regs[i].type == type && regs[i].id == dst_reg->id)
3818 /* keep the maximum range already checked */
3819 regs[i].range = max(regs[i].range, new_range);
3821 for (j = 0; j <= vstate->curframe; j++) {
3822 state = vstate->frame[j];
3823 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3824 if (state->stack[i].slot_type[0] != STACK_SPILL)
3826 reg = &state->stack[i].spilled_ptr;
3827 if (reg->type == type && reg->id == dst_reg->id)
3828 reg->range = max(reg->range, new_range);
3833 /* compute branch direction of the expression "if (reg opcode val) goto target;"
3835 * 1 - branch will be taken and "goto target" will be executed
3836 * 0 - branch will not be taken and fall-through to next insn
3837 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
3839 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
3841 if (__is_pointer_value(false, reg))
3846 if (tnum_is_const(reg->var_off))
3847 return !!tnum_equals_const(reg->var_off, val);
3850 if (tnum_is_const(reg->var_off))
3851 return !tnum_equals_const(reg->var_off, val);
3854 if (reg->umin_value > val)
3856 else if (reg->umax_value <= val)
3860 if (reg->smin_value > (s64)val)
3862 else if (reg->smax_value < (s64)val)
3866 if (reg->umax_value < val)
3868 else if (reg->umin_value >= val)
3872 if (reg->smax_value < (s64)val)
3874 else if (reg->smin_value >= (s64)val)
3878 if (reg->umin_value >= val)
3880 else if (reg->umax_value < val)
3884 if (reg->smin_value >= (s64)val)
3886 else if (reg->smax_value < (s64)val)
3890 if (reg->umax_value <= val)
3892 else if (reg->umin_value > val)
3896 if (reg->smax_value <= (s64)val)
3898 else if (reg->smin_value > (s64)val)
3906 /* Adjusts the register min/max values in the case that the dst_reg is the
3907 * variable register that we are working on, and src_reg is a constant or we're
3908 * simply doing a BPF_K check.
3909 * In JEQ/JNE cases we also adjust the var_off values.
3911 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3912 struct bpf_reg_state *false_reg, u64 val,
3915 /* If the dst_reg is a pointer, we can't learn anything about its
3916 * variable offset from the compare (unless src_reg were a pointer into
3917 * the same object, but we don't bother with that.
3918 * Since false_reg and true_reg have the same type by construction, we
3919 * only need to check one of them for pointerness.
3921 if (__is_pointer_value(false, false_reg))
3926 /* If this is false then we know nothing Jon Snow, but if it is
3927 * true then we know for sure.
3929 __mark_reg_known(true_reg, val);
3932 /* If this is true we know nothing Jon Snow, but if it is false
3933 * we know the value for sure;
3935 __mark_reg_known(false_reg, val);
3938 false_reg->umax_value = min(false_reg->umax_value, val);
3939 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3942 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3943 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3946 false_reg->umin_value = max(false_reg->umin_value, val);
3947 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3950 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3951 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3954 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3955 true_reg->umin_value = max(true_reg->umin_value, val);
3958 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3959 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3962 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3963 true_reg->umax_value = min(true_reg->umax_value, val);
3966 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3967 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3973 __reg_deduce_bounds(false_reg);
3974 __reg_deduce_bounds(true_reg);
3975 /* We might have learned some bits from the bounds. */
3976 __reg_bound_offset(false_reg);
3977 __reg_bound_offset(true_reg);
3978 /* Intersecting with the old var_off might have improved our bounds
3979 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3980 * then new var_off is (0; 0x7f...fc) which improves our umax.
3982 __update_reg_bounds(false_reg);
3983 __update_reg_bounds(true_reg);
3986 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3989 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3990 struct bpf_reg_state *false_reg, u64 val,
3993 if (__is_pointer_value(false, false_reg))
3998 /* If this is false then we know nothing Jon Snow, but if it is
3999 * true then we know for sure.
4001 __mark_reg_known(true_reg, val);
4004 /* If this is true we know nothing Jon Snow, but if it is false
4005 * we know the value for sure;
4007 __mark_reg_known(false_reg, val);
4010 true_reg->umax_value = min(true_reg->umax_value, val - 1);
4011 false_reg->umin_value = max(false_reg->umin_value, val);
4014 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
4015 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
4018 true_reg->umin_value = max(true_reg->umin_value, val + 1);
4019 false_reg->umax_value = min(false_reg->umax_value, val);
4022 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
4023 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
4026 true_reg->umax_value = min(true_reg->umax_value, val);
4027 false_reg->umin_value = max(false_reg->umin_value, val + 1);
4030 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
4031 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
4034 true_reg->umin_value = max(true_reg->umin_value, val);
4035 false_reg->umax_value = min(false_reg->umax_value, val - 1);
4038 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
4039 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
4045 __reg_deduce_bounds(false_reg);
4046 __reg_deduce_bounds(true_reg);
4047 /* We might have learned some bits from the bounds. */
4048 __reg_bound_offset(false_reg);
4049 __reg_bound_offset(true_reg);
4050 /* Intersecting with the old var_off might have improved our bounds
4051 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4052 * then new var_off is (0; 0x7f...fc) which improves our umax.
4054 __update_reg_bounds(false_reg);
4055 __update_reg_bounds(true_reg);
4058 /* Regs are known to be equal, so intersect their min/max/var_off */
4059 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
4060 struct bpf_reg_state *dst_reg)
4062 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
4063 dst_reg->umin_value);
4064 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
4065 dst_reg->umax_value);
4066 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
4067 dst_reg->smin_value);
4068 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
4069 dst_reg->smax_value);
4070 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
4072 /* We might have learned new bounds from the var_off. */
4073 __update_reg_bounds(src_reg);
4074 __update_reg_bounds(dst_reg);
4075 /* We might have learned something about the sign bit. */
4076 __reg_deduce_bounds(src_reg);
4077 __reg_deduce_bounds(dst_reg);
4078 /* We might have learned some bits from the bounds. */
4079 __reg_bound_offset(src_reg);
4080 __reg_bound_offset(dst_reg);
4081 /* Intersecting with the old var_off might have improved our bounds
4082 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4083 * then new var_off is (0; 0x7f...fc) which improves our umax.
4085 __update_reg_bounds(src_reg);
4086 __update_reg_bounds(dst_reg);
4089 static void reg_combine_min_max(struct bpf_reg_state *true_src,
4090 struct bpf_reg_state *true_dst,
4091 struct bpf_reg_state *false_src,
4092 struct bpf_reg_state *false_dst,
4097 __reg_combine_min_max(true_src, true_dst);
4100 __reg_combine_min_max(false_src, false_dst);
4105 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
4108 struct bpf_reg_state *reg = ®s[regno];
4110 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
4111 /* Old offset (both fixed and variable parts) should
4112 * have been known-zero, because we don't allow pointer
4113 * arithmetic on pointers that might be NULL.
4115 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
4116 !tnum_equals_const(reg->var_off, 0) ||
4118 __mark_reg_known_zero(reg);
4122 reg->type = SCALAR_VALUE;
4123 } else if (reg->map_ptr->inner_map_meta) {
4124 reg->type = CONST_PTR_TO_MAP;
4125 reg->map_ptr = reg->map_ptr->inner_map_meta;
4127 reg->type = PTR_TO_MAP_VALUE;
4129 /* We don't need id from this point onwards anymore, thus we
4130 * should better reset it, so that state pruning has chances
4137 /* The logic is similar to find_good_pkt_pointers(), both could eventually
4138 * be folded together at some point.
4140 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
4143 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4144 struct bpf_reg_state *regs = state->regs;
4145 u32 id = regs[regno].id;
4148 for (i = 0; i < MAX_BPF_REG; i++)
4149 mark_map_reg(regs, i, id, is_null);
4151 for (j = 0; j <= vstate->curframe; j++) {
4152 state = vstate->frame[j];
4153 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
4154 if (state->stack[i].slot_type[0] != STACK_SPILL)
4156 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
4161 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
4162 struct bpf_reg_state *dst_reg,
4163 struct bpf_reg_state *src_reg,
4164 struct bpf_verifier_state *this_branch,
4165 struct bpf_verifier_state *other_branch)
4167 if (BPF_SRC(insn->code) != BPF_X)
4170 switch (BPF_OP(insn->code)) {
4172 if ((dst_reg->type == PTR_TO_PACKET &&
4173 src_reg->type == PTR_TO_PACKET_END) ||
4174 (dst_reg->type == PTR_TO_PACKET_META &&
4175 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4176 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4177 find_good_pkt_pointers(this_branch, dst_reg,
4178 dst_reg->type, false);
4179 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4180 src_reg->type == PTR_TO_PACKET) ||
4181 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4182 src_reg->type == PTR_TO_PACKET_META)) {
4183 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4184 find_good_pkt_pointers(other_branch, src_reg,
4185 src_reg->type, true);
4191 if ((dst_reg->type == PTR_TO_PACKET &&
4192 src_reg->type == PTR_TO_PACKET_END) ||
4193 (dst_reg->type == PTR_TO_PACKET_META &&
4194 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4195 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4196 find_good_pkt_pointers(other_branch, dst_reg,
4197 dst_reg->type, true);
4198 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4199 src_reg->type == PTR_TO_PACKET) ||
4200 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4201 src_reg->type == PTR_TO_PACKET_META)) {
4202 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
4203 find_good_pkt_pointers(this_branch, src_reg,
4204 src_reg->type, false);
4210 if ((dst_reg->type == PTR_TO_PACKET &&
4211 src_reg->type == PTR_TO_PACKET_END) ||
4212 (dst_reg->type == PTR_TO_PACKET_META &&
4213 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4214 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
4215 find_good_pkt_pointers(this_branch, dst_reg,
4216 dst_reg->type, true);
4217 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4218 src_reg->type == PTR_TO_PACKET) ||
4219 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4220 src_reg->type == PTR_TO_PACKET_META)) {
4221 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
4222 find_good_pkt_pointers(other_branch, src_reg,
4223 src_reg->type, false);
4229 if ((dst_reg->type == PTR_TO_PACKET &&
4230 src_reg->type == PTR_TO_PACKET_END) ||
4231 (dst_reg->type == PTR_TO_PACKET_META &&
4232 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4233 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
4234 find_good_pkt_pointers(other_branch, dst_reg,
4235 dst_reg->type, false);
4236 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4237 src_reg->type == PTR_TO_PACKET) ||
4238 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4239 src_reg->type == PTR_TO_PACKET_META)) {
4240 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
4241 find_good_pkt_pointers(this_branch, src_reg,
4242 src_reg->type, true);
4254 static int check_cond_jmp_op(struct bpf_verifier_env *env,
4255 struct bpf_insn *insn, int *insn_idx)
4257 struct bpf_verifier_state *this_branch = env->cur_state;
4258 struct bpf_verifier_state *other_branch;
4259 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
4260 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
4261 u8 opcode = BPF_OP(insn->code);
4265 if (opcode > BPF_JSLE) {
4266 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
4270 if (BPF_SRC(insn->code) == BPF_X) {
4271 if (insn->imm != 0) {
4272 verbose(env, "BPF_JMP uses reserved fields\n");
4276 /* check src1 operand */
4277 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4281 if (is_pointer_value(env, insn->src_reg)) {
4282 verbose(env, "R%d pointer comparison prohibited\n",
4286 src_reg = ®s[insn->src_reg];
4288 if (insn->src_reg != BPF_REG_0) {
4289 verbose(env, "BPF_JMP uses reserved fields\n");
4294 /* check src2 operand */
4295 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4299 dst_reg = ®s[insn->dst_reg];
4301 if (BPF_SRC(insn->code) == BPF_K)
4302 pred = is_branch_taken(dst_reg, insn->imm, opcode);
4303 else if (src_reg->type == SCALAR_VALUE &&
4304 tnum_is_const(src_reg->var_off))
4305 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
4309 /* Only follow the goto, ignore fall-through. If needed, push
4310 * the fall-through branch for simulation under speculative
4313 if (!env->allow_ptr_leaks &&
4314 !sanitize_speculative_path(env, insn, *insn_idx + 1,
4317 *insn_idx += insn->off;
4319 } else if (pred == 0) {
4320 /* Only follow the fall-through branch, since that's where the
4321 * program will go. If needed, push the goto branch for
4322 * simulation under speculative execution.
4324 if (!env->allow_ptr_leaks &&
4325 !sanitize_speculative_path(env, insn,
4326 *insn_idx + insn->off + 1,
4332 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
4336 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
4338 /* detect if we are comparing against a constant value so we can adjust
4339 * our min/max values for our dst register.
4340 * this is only legit if both are scalars (or pointers to the same
4341 * object, I suppose, but we don't support that right now), because
4342 * otherwise the different base pointers mean the offsets aren't
4345 if (BPF_SRC(insn->code) == BPF_X) {
4346 if (dst_reg->type == SCALAR_VALUE &&
4347 regs[insn->src_reg].type == SCALAR_VALUE) {
4348 if (tnum_is_const(regs[insn->src_reg].var_off))
4349 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4350 dst_reg, regs[insn->src_reg].var_off.value,
4352 else if (tnum_is_const(dst_reg->var_off))
4353 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
4354 ®s[insn->src_reg],
4355 dst_reg->var_off.value, opcode);
4356 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
4357 /* Comparing for equality, we can combine knowledge */
4358 reg_combine_min_max(&other_branch_regs[insn->src_reg],
4359 &other_branch_regs[insn->dst_reg],
4360 ®s[insn->src_reg],
4361 ®s[insn->dst_reg], opcode);
4363 } else if (dst_reg->type == SCALAR_VALUE) {
4364 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4365 dst_reg, insn->imm, opcode);
4368 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
4369 if (BPF_SRC(insn->code) == BPF_K &&
4370 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4371 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
4372 /* Mark all identical map registers in each branch as either
4373 * safe or unknown depending R == 0 or R != 0 conditional.
4375 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
4376 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
4377 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
4378 this_branch, other_branch) &&
4379 is_pointer_value(env, insn->dst_reg)) {
4380 verbose(env, "R%d pointer comparison prohibited\n",
4385 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
4389 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
4390 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
4392 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
4394 return (struct bpf_map *) (unsigned long) imm64;
4397 /* verify BPF_LD_IMM64 instruction */
4398 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
4400 struct bpf_reg_state *regs = cur_regs(env);
4403 if (BPF_SIZE(insn->code) != BPF_DW) {
4404 verbose(env, "invalid BPF_LD_IMM insn\n");
4407 if (insn->off != 0) {
4408 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
4412 err = check_reg_arg(env, insn->dst_reg, DST_OP);
4416 if (insn->src_reg == 0) {
4417 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
4419 regs[insn->dst_reg].type = SCALAR_VALUE;
4420 __mark_reg_known(®s[insn->dst_reg], imm);
4424 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
4425 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
4427 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
4428 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
4432 static bool may_access_skb(enum bpf_prog_type type)
4435 case BPF_PROG_TYPE_SOCKET_FILTER:
4436 case BPF_PROG_TYPE_SCHED_CLS:
4437 case BPF_PROG_TYPE_SCHED_ACT:
4444 /* verify safety of LD_ABS|LD_IND instructions:
4445 * - they can only appear in the programs where ctx == skb
4446 * - since they are wrappers of function calls, they scratch R1-R5 registers,
4447 * preserve R6-R9, and store return value into R0
4450 * ctx == skb == R6 == CTX
4453 * SRC == any register
4454 * IMM == 32-bit immediate
4457 * R0 - 8/16/32-bit skb data converted to cpu endianness
4459 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
4461 struct bpf_reg_state *regs = cur_regs(env);
4462 static const int ctx_reg = BPF_REG_6;
4463 u8 mode = BPF_MODE(insn->code);
4466 if (!may_access_skb(env->prog->type)) {
4467 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
4471 if (!env->ops->gen_ld_abs) {
4472 verbose(env, "bpf verifier is misconfigured\n");
4476 if (env->subprog_cnt > 1) {
4477 /* when program has LD_ABS insn JITs and interpreter assume
4478 * that r1 == ctx == skb which is not the case for callees
4479 * that can have arbitrary arguments. It's problematic
4480 * for main prog as well since JITs would need to analyze
4481 * all functions in order to make proper register save/restore
4482 * decisions in the main prog. Hence disallow LD_ABS with calls
4484 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
4488 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
4489 BPF_SIZE(insn->code) == BPF_DW ||
4490 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
4491 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
4495 /* check whether implicit source operand (register R6) is readable */
4496 err = check_reg_arg(env, ctx_reg, SRC_OP);
4500 if (regs[ctx_reg].type != PTR_TO_CTX) {
4502 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
4506 if (mode == BPF_IND) {
4507 /* check explicit source operand */
4508 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4513 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
4517 /* reset caller saved regs to unreadable */
4518 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4519 mark_reg_not_init(env, regs, caller_saved[i]);
4520 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4523 /* mark destination R0 register as readable, since it contains
4524 * the value fetched from the packet.
4525 * Already marked as written above.
4527 mark_reg_unknown(env, regs, BPF_REG_0);
4531 static int check_return_code(struct bpf_verifier_env *env)
4533 struct bpf_reg_state *reg;
4534 struct tnum range = tnum_range(0, 1);
4536 switch (env->prog->type) {
4537 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4538 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
4539 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
4540 range = tnum_range(1, 1);
4541 case BPF_PROG_TYPE_CGROUP_SKB:
4542 case BPF_PROG_TYPE_CGROUP_SOCK:
4543 case BPF_PROG_TYPE_SOCK_OPS:
4544 case BPF_PROG_TYPE_CGROUP_DEVICE:
4550 reg = cur_regs(env) + BPF_REG_0;
4551 if (reg->type != SCALAR_VALUE) {
4552 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
4553 reg_type_str[reg->type]);
4557 if (!tnum_in(range, reg->var_off)) {
4560 verbose(env, "At program exit the register R0 ");
4561 if (!tnum_is_unknown(reg->var_off)) {
4562 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4563 verbose(env, "has value %s", tn_buf);
4565 verbose(env, "has unknown scalar value");
4567 tnum_strn(tn_buf, sizeof(tn_buf), range);
4568 verbose(env, " should have been in %s\n", tn_buf);
4574 /* non-recursive DFS pseudo code
4575 * 1 procedure DFS-iterative(G,v):
4576 * 2 label v as discovered
4577 * 3 let S be a stack
4579 * 5 while S is not empty
4581 * 7 if t is what we're looking for:
4583 * 9 for all edges e in G.adjacentEdges(t) do
4584 * 10 if edge e is already labelled
4585 * 11 continue with the next edge
4586 * 12 w <- G.adjacentVertex(t,e)
4587 * 13 if vertex w is not discovered and not explored
4588 * 14 label e as tree-edge
4589 * 15 label w as discovered
4592 * 18 else if vertex w is discovered
4593 * 19 label e as back-edge
4595 * 21 // vertex w is explored
4596 * 22 label e as forward- or cross-edge
4597 * 23 label t as explored
4602 * 0x11 - discovered and fall-through edge labelled
4603 * 0x12 - discovered and fall-through and branch edges labelled
4614 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
4616 static int *insn_stack; /* stack of insns to process */
4617 static int cur_stack; /* current stack index */
4618 static int *insn_state;
4620 /* t, w, e - match pseudo-code above:
4621 * t - index of current instruction
4622 * w - next instruction
4625 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
4627 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
4630 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
4633 if (w < 0 || w >= env->prog->len) {
4634 verbose(env, "jump out of range from insn %d to %d\n", t, w);
4639 /* mark branch target for state pruning */
4640 env->explored_states[w] = STATE_LIST_MARK;
4642 if (insn_state[w] == 0) {
4644 insn_state[t] = DISCOVERED | e;
4645 insn_state[w] = DISCOVERED;
4646 if (cur_stack >= env->prog->len)
4648 insn_stack[cur_stack++] = w;
4650 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4651 verbose(env, "back-edge from insn %d to %d\n", t, w);
4653 } else if (insn_state[w] == EXPLORED) {
4654 /* forward- or cross-edge */
4655 insn_state[t] = DISCOVERED | e;
4657 verbose(env, "insn state internal bug\n");
4663 /* non-recursive depth-first-search to detect loops in BPF program
4664 * loop == back-edge in directed graph
4666 static int check_cfg(struct bpf_verifier_env *env)
4668 struct bpf_insn *insns = env->prog->insnsi;
4669 int insn_cnt = env->prog->len;
4673 ret = check_subprogs(env);
4677 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4681 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4687 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4688 insn_stack[0] = 0; /* 0 is the first instruction */
4694 t = insn_stack[cur_stack - 1];
4696 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4697 u8 opcode = BPF_OP(insns[t].code);
4699 if (opcode == BPF_EXIT) {
4701 } else if (opcode == BPF_CALL) {
4702 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4707 if (t + 1 < insn_cnt)
4708 env->explored_states[t + 1] = STATE_LIST_MARK;
4709 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4710 env->explored_states[t] = STATE_LIST_MARK;
4711 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4717 } else if (opcode == BPF_JA) {
4718 if (BPF_SRC(insns[t].code) != BPF_K) {
4722 /* unconditional jump with single edge */
4723 ret = push_insn(t, t + insns[t].off + 1,
4729 /* tell verifier to check for equivalent states
4730 * after every call and jump
4732 if (t + 1 < insn_cnt)
4733 env->explored_states[t + 1] = STATE_LIST_MARK;
4735 /* conditional jump with two edges */
4736 env->explored_states[t] = STATE_LIST_MARK;
4737 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4743 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4750 /* all other non-branch instructions with single
4753 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4761 insn_state[t] = EXPLORED;
4762 if (cur_stack-- <= 0) {
4763 verbose(env, "pop stack internal bug\n");
4770 for (i = 0; i < insn_cnt; i++) {
4771 if (insn_state[i] != EXPLORED) {
4772 verbose(env, "unreachable insn %d\n", i);
4777 ret = 0; /* cfg looks good */
4785 /* check %cur's range satisfies %old's */
4786 static bool range_within(struct bpf_reg_state *old,
4787 struct bpf_reg_state *cur)
4789 return old->umin_value <= cur->umin_value &&
4790 old->umax_value >= cur->umax_value &&
4791 old->smin_value <= cur->smin_value &&
4792 old->smax_value >= cur->smax_value;
4795 /* If in the old state two registers had the same id, then they need to have
4796 * the same id in the new state as well. But that id could be different from
4797 * the old state, so we need to track the mapping from old to new ids.
4798 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4799 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4800 * regs with a different old id could still have new id 9, we don't care about
4802 * So we look through our idmap to see if this old id has been seen before. If
4803 * so, we require the new id to match; otherwise, we add the id pair to the map.
4805 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
4809 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
4810 if (!idmap[i].old) {
4811 /* Reached an empty slot; haven't seen this id before */
4812 idmap[i].old = old_id;
4813 idmap[i].cur = cur_id;
4816 if (idmap[i].old == old_id)
4817 return idmap[i].cur == cur_id;
4819 /* We ran out of idmap slots, which should be impossible */
4824 /* Returns true if (rold safe implies rcur safe) */
4825 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
4826 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
4830 if (!(rold->live & REG_LIVE_READ))
4831 /* explored state didn't use this */
4834 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
4836 if (rold->type == PTR_TO_STACK)
4837 /* two stack pointers are equal only if they're pointing to
4838 * the same stack frame, since fp-8 in foo != fp-8 in bar
4840 return equal && rold->frameno == rcur->frameno;
4845 if (rold->type == NOT_INIT)
4846 /* explored state can't have used this */
4848 if (rcur->type == NOT_INIT)
4850 switch (rold->type) {
4852 if (env->explore_alu_limits)
4854 if (rcur->type == SCALAR_VALUE) {
4855 /* new val must satisfy old val knowledge */
4856 return range_within(rold, rcur) &&
4857 tnum_in(rold->var_off, rcur->var_off);
4859 /* We're trying to use a pointer in place of a scalar.
4860 * Even if the scalar was unbounded, this could lead to
4861 * pointer leaks because scalars are allowed to leak
4862 * while pointers are not. We could make this safe in
4863 * special cases if root is calling us, but it's
4864 * probably not worth the hassle.
4868 case PTR_TO_MAP_VALUE:
4869 /* If the new min/max/var_off satisfy the old ones and
4870 * everything else matches, we are OK.
4871 * We don't care about the 'id' value, because nothing
4872 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4874 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4875 range_within(rold, rcur) &&
4876 tnum_in(rold->var_off, rcur->var_off);
4877 case PTR_TO_MAP_VALUE_OR_NULL:
4878 /* a PTR_TO_MAP_VALUE could be safe to use as a
4879 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4880 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4881 * checked, doing so could have affected others with the same
4882 * id, and we can't check for that because we lost the id when
4883 * we converted to a PTR_TO_MAP_VALUE.
4885 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4887 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4889 /* Check our ids match any regs they're supposed to */
4890 return check_ids(rold->id, rcur->id, idmap);
4891 case PTR_TO_PACKET_META:
4893 if (rcur->type != rold->type)
4895 /* We must have at least as much range as the old ptr
4896 * did, so that any accesses which were safe before are
4897 * still safe. This is true even if old range < old off,
4898 * since someone could have accessed through (ptr - k), or
4899 * even done ptr -= k in a register, to get a safe access.
4901 if (rold->range > rcur->range)
4903 /* If the offsets don't match, we can't trust our alignment;
4904 * nor can we be sure that we won't fall out of range.
4906 if (rold->off != rcur->off)
4908 /* id relations must be preserved */
4909 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4911 /* new val must satisfy old val knowledge */
4912 return range_within(rold, rcur) &&
4913 tnum_in(rold->var_off, rcur->var_off);
4915 case CONST_PTR_TO_MAP:
4916 case PTR_TO_PACKET_END:
4917 /* Only valid matches are exact, which memcmp() above
4918 * would have accepted
4921 /* Don't know what's going on, just say it's not safe */
4925 /* Shouldn't get here; if we do, say it's not safe */
4930 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
4931 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
4935 /* if explored stack has more populated slots than current stack
4936 * such stacks are not equivalent
4938 if (old->allocated_stack > cur->allocated_stack)
4941 /* walk slots of the explored stack and ignore any additional
4942 * slots in the current stack, since explored(safe) state
4945 for (i = 0; i < old->allocated_stack; i++) {
4946 spi = i / BPF_REG_SIZE;
4948 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4949 /* explored state didn't use this */
4952 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4954 /* if old state was safe with misc data in the stack
4955 * it will be safe with zero-initialized stack.
4956 * The opposite is not true
4958 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4959 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4961 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4962 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4963 /* Ex: old explored (safe) state has STACK_SPILL in
4964 * this stack slot, but current has has STACK_MISC ->
4965 * this verifier states are not equivalent,
4966 * return false to continue verification of this path
4969 if (i % BPF_REG_SIZE)
4971 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4973 if (!regsafe(env, &old->stack[spi].spilled_ptr,
4974 &cur->stack[spi].spilled_ptr, idmap))
4975 /* when explored and current stack slot are both storing
4976 * spilled registers, check that stored pointers types
4977 * are the same as well.
4978 * Ex: explored safe path could have stored
4979 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4980 * but current path has stored:
4981 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4982 * such verifier states are not equivalent.
4983 * return false to continue verification of this path
4990 /* compare two verifier states
4992 * all states stored in state_list are known to be valid, since
4993 * verifier reached 'bpf_exit' instruction through them
4995 * this function is called when verifier exploring different branches of
4996 * execution popped from the state stack. If it sees an old state that has
4997 * more strict register state and more strict stack state then this execution
4998 * branch doesn't need to be explored further, since verifier already
4999 * concluded that more strict state leads to valid finish.
5001 * Therefore two states are equivalent if register state is more conservative
5002 * and explored stack state is more conservative than the current one.
5005 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
5006 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
5008 * In other words if current stack state (one being explored) has more
5009 * valid slots than old one that already passed validation, it means
5010 * the verifier can stop exploring and conclude that current state is valid too
5012 * Similarly with registers. If explored state has register type as invalid
5013 * whereas register type in current state is meaningful, it means that
5014 * the current state will reach 'bpf_exit' instruction safely
5016 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
5017 struct bpf_func_state *cur)
5021 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
5022 for (i = 0; i < MAX_BPF_REG; i++)
5023 if (!regsafe(env, &old->regs[i], &cur->regs[i],
5024 env->idmap_scratch))
5027 if (!stacksafe(env, old, cur, env->idmap_scratch))
5033 static bool states_equal(struct bpf_verifier_env *env,
5034 struct bpf_verifier_state *old,
5035 struct bpf_verifier_state *cur)
5039 if (old->curframe != cur->curframe)
5042 /* Verification state from speculative execution simulation
5043 * must never prune a non-speculative execution one.
5045 if (old->speculative && !cur->speculative)
5048 /* for states to be equal callsites have to be the same
5049 * and all frame states need to be equivalent
5051 for (i = 0; i <= old->curframe; i++) {
5052 if (old->frame[i]->callsite != cur->frame[i]->callsite)
5054 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
5060 /* A write screens off any subsequent reads; but write marks come from the
5061 * straight-line code between a state and its parent. When we arrive at an
5062 * equivalent state (jump target or such) we didn't arrive by the straight-line
5063 * code, so read marks in the state must propagate to the parent regardless
5064 * of the state's write marks. That's what 'parent == state->parent' comparison
5065 * in mark_reg_read() is for.
5067 static int propagate_liveness(struct bpf_verifier_env *env,
5068 const struct bpf_verifier_state *vstate,
5069 struct bpf_verifier_state *vparent)
5071 int i, frame, err = 0;
5072 struct bpf_func_state *state, *parent;
5074 if (vparent->curframe != vstate->curframe) {
5075 WARN(1, "propagate_live: parent frame %d current frame %d\n",
5076 vparent->curframe, vstate->curframe);
5079 /* Propagate read liveness of registers... */
5080 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
5081 /* We don't need to worry about FP liveness because it's read-only */
5082 for (i = 0; i < BPF_REG_FP; i++) {
5083 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
5085 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
5086 err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i],
5087 &vparent->frame[vstate->curframe]->regs[i]);
5093 /* ... and stack slots */
5094 for (frame = 0; frame <= vstate->curframe; frame++) {
5095 state = vstate->frame[frame];
5096 parent = vparent->frame[frame];
5097 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
5098 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
5099 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
5101 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
5102 mark_reg_read(env, &state->stack[i].spilled_ptr,
5103 &parent->stack[i].spilled_ptr);
5109 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
5111 struct bpf_verifier_state_list *new_sl;
5112 struct bpf_verifier_state_list *sl;
5113 struct bpf_verifier_state *cur = env->cur_state, *new;
5114 int i, j, err, states_cnt = 0;
5116 sl = env->explored_states[insn_idx];
5118 /* this 'insn_idx' instruction wasn't marked, so we will not
5119 * be doing state search here
5123 while (sl != STATE_LIST_MARK) {
5124 if (states_equal(env, &sl->state, cur)) {
5125 /* reached equivalent register/stack state,
5127 * Registers read by the continuation are read by us.
5128 * If we have any write marks in env->cur_state, they
5129 * will prevent corresponding reads in the continuation
5130 * from reaching our parent (an explored_state). Our
5131 * own state will get the read marks recorded, but
5132 * they'll be immediately forgotten as we're pruning
5133 * this state and will pop a new one.
5135 err = propagate_liveness(env, &sl->state, cur);
5144 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
5147 /* there were no equivalent states, remember current one.
5148 * technically the current state is not proven to be safe yet,
5149 * but it will either reach outer most bpf_exit (which means it's safe)
5150 * or it will be rejected. Since there are no loops, we won't be
5151 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
5152 * again on the way to bpf_exit
5154 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
5158 /* add new state to the head of linked list */
5159 new = &new_sl->state;
5160 err = copy_verifier_state(new, cur);
5162 free_verifier_state(new, false);
5166 new_sl->next = env->explored_states[insn_idx];
5167 env->explored_states[insn_idx] = new_sl;
5168 /* connect new state to parentage chain */
5169 for (i = 0; i < BPF_REG_FP; i++)
5170 cur_regs(env)[i].parent = &new->frame[new->curframe]->regs[i];
5171 /* clear write marks in current state: the writes we did are not writes
5172 * our child did, so they don't screen off its reads from us.
5173 * (There are no read marks in current state, because reads always mark
5174 * their parent and current state never has children yet. Only
5175 * explored_states can get read marks.)
5177 for (i = 0; i < BPF_REG_FP; i++)
5178 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
5180 /* all stack frames are accessible from callee, clear them all */
5181 for (j = 0; j <= cur->curframe; j++) {
5182 struct bpf_func_state *frame = cur->frame[j];
5183 struct bpf_func_state *newframe = new->frame[j];
5185 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
5186 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
5187 frame->stack[i].spilled_ptr.parent =
5188 &newframe->stack[i].spilled_ptr;
5194 static int do_check(struct bpf_verifier_env *env)
5196 struct bpf_verifier_state *state;
5197 struct bpf_insn *insns = env->prog->insnsi;
5198 struct bpf_reg_state *regs;
5199 int insn_cnt = env->prog->len, i;
5200 int insn_processed = 0;
5201 bool do_print_state = false;
5203 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
5206 state->curframe = 0;
5207 state->speculative = false;
5208 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
5209 if (!state->frame[0]) {
5213 env->cur_state = state;
5214 init_func_state(env, state->frame[0],
5215 BPF_MAIN_FUNC /* callsite */,
5217 0 /* subprogno, zero == main subprog */);
5220 struct bpf_insn *insn;
5224 if (env->insn_idx >= insn_cnt) {
5225 verbose(env, "invalid insn idx %d insn_cnt %d\n",
5226 env->insn_idx, insn_cnt);
5230 insn = &insns[env->insn_idx];
5231 class = BPF_CLASS(insn->code);
5233 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
5235 "BPF program is too large. Processed %d insn\n",
5240 err = is_state_visited(env, env->insn_idx);
5244 /* found equivalent state, can prune the search */
5245 if (env->log.level) {
5247 verbose(env, "\nfrom %d to %d%s: safe\n",
5248 env->prev_insn_idx, env->insn_idx,
5249 env->cur_state->speculative ?
5250 " (speculative execution)" : "");
5252 verbose(env, "%d: safe\n", env->insn_idx);
5254 goto process_bpf_exit;
5257 if (signal_pending(current))
5263 if (env->log.level > 1 || (env->log.level && do_print_state)) {
5264 if (env->log.level > 1)
5265 verbose(env, "%d:", env->insn_idx);
5267 verbose(env, "\nfrom %d to %d%s:",
5268 env->prev_insn_idx, env->insn_idx,
5269 env->cur_state->speculative ?
5270 " (speculative execution)" : "");
5271 print_verifier_state(env, state->frame[state->curframe]);
5272 do_print_state = false;
5275 if (env->log.level) {
5276 const struct bpf_insn_cbs cbs = {
5277 .cb_print = verbose,
5278 .private_data = env,
5281 verbose(env, "%d: ", env->insn_idx);
5282 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
5285 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5286 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
5287 env->prev_insn_idx);
5292 regs = cur_regs(env);
5293 sanitize_mark_insn_seen(env);
5295 if (class == BPF_ALU || class == BPF_ALU64) {
5296 err = check_alu_op(env, insn);
5300 } else if (class == BPF_LDX) {
5301 enum bpf_reg_type *prev_src_type, src_reg_type;
5303 /* check for reserved fields is already done */
5305 /* check src operand */
5306 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5310 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5314 src_reg_type = regs[insn->src_reg].type;
5316 /* check that memory (src_reg + off) is readable,
5317 * the state of dst_reg will be updated by this func
5319 err = check_mem_access(env, env->insn_idx, insn->src_reg,
5320 insn->off, BPF_SIZE(insn->code),
5321 BPF_READ, insn->dst_reg, false);
5325 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5327 if (*prev_src_type == NOT_INIT) {
5329 * dst_reg = *(u32 *)(src_reg + off)
5330 * save type to validate intersecting paths
5332 *prev_src_type = src_reg_type;
5334 } else if (src_reg_type != *prev_src_type &&
5335 (src_reg_type == PTR_TO_CTX ||
5336 *prev_src_type == PTR_TO_CTX)) {
5337 /* ABuser program is trying to use the same insn
5338 * dst_reg = *(u32*) (src_reg + off)
5339 * with different pointer types:
5340 * src_reg == ctx in one branch and
5341 * src_reg == stack|map in some other branch.
5344 verbose(env, "same insn cannot be used with different pointers\n");
5348 } else if (class == BPF_STX) {
5349 enum bpf_reg_type *prev_dst_type, dst_reg_type;
5351 if (BPF_MODE(insn->code) == BPF_XADD) {
5352 err = check_xadd(env, env->insn_idx, insn);
5359 /* check src1 operand */
5360 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5363 /* check src2 operand */
5364 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5368 dst_reg_type = regs[insn->dst_reg].type;
5370 /* check that memory (dst_reg + off) is writeable */
5371 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5372 insn->off, BPF_SIZE(insn->code),
5373 BPF_WRITE, insn->src_reg, false);
5377 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5379 if (*prev_dst_type == NOT_INIT) {
5380 *prev_dst_type = dst_reg_type;
5381 } else if (dst_reg_type != *prev_dst_type &&
5382 (dst_reg_type == PTR_TO_CTX ||
5383 *prev_dst_type == PTR_TO_CTX)) {
5384 verbose(env, "same insn cannot be used with different pointers\n");
5388 } else if (class == BPF_ST) {
5389 if (BPF_MODE(insn->code) != BPF_MEM ||
5390 insn->src_reg != BPF_REG_0) {
5391 verbose(env, "BPF_ST uses reserved fields\n");
5394 /* check src operand */
5395 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5399 if (is_ctx_reg(env, insn->dst_reg)) {
5400 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
5405 /* check that memory (dst_reg + off) is writeable */
5406 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5407 insn->off, BPF_SIZE(insn->code),
5408 BPF_WRITE, -1, false);
5412 } else if (class == BPF_JMP) {
5413 u8 opcode = BPF_OP(insn->code);
5415 if (opcode == BPF_CALL) {
5416 if (BPF_SRC(insn->code) != BPF_K ||
5418 (insn->src_reg != BPF_REG_0 &&
5419 insn->src_reg != BPF_PSEUDO_CALL) ||
5420 insn->dst_reg != BPF_REG_0) {
5421 verbose(env, "BPF_CALL uses reserved fields\n");
5425 if (insn->src_reg == BPF_PSEUDO_CALL)
5426 err = check_func_call(env, insn, &env->insn_idx);
5428 err = check_helper_call(env, insn->imm, env->insn_idx);
5432 } else if (opcode == BPF_JA) {
5433 if (BPF_SRC(insn->code) != BPF_K ||
5435 insn->src_reg != BPF_REG_0 ||
5436 insn->dst_reg != BPF_REG_0) {
5437 verbose(env, "BPF_JA uses reserved fields\n");
5441 env->insn_idx += insn->off + 1;
5444 } else if (opcode == BPF_EXIT) {
5445 if (BPF_SRC(insn->code) != BPF_K ||
5447 insn->src_reg != BPF_REG_0 ||
5448 insn->dst_reg != BPF_REG_0) {
5449 verbose(env, "BPF_EXIT uses reserved fields\n");
5453 if (state->curframe) {
5454 /* exit from nested function */
5455 env->prev_insn_idx = env->insn_idx;
5456 err = prepare_func_exit(env, &env->insn_idx);
5459 do_print_state = true;
5463 /* eBPF calling convetion is such that R0 is used
5464 * to return the value from eBPF program.
5465 * Make sure that it's readable at this time
5466 * of bpf_exit, which means that program wrote
5467 * something into it earlier
5469 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
5473 if (is_pointer_value(env, BPF_REG_0)) {
5474 verbose(env, "R0 leaks addr as return value\n");
5478 err = check_return_code(env);
5482 err = pop_stack(env, &env->prev_insn_idx,
5489 do_print_state = true;
5493 err = check_cond_jmp_op(env, insn, &env->insn_idx);
5497 } else if (class == BPF_LD) {
5498 u8 mode = BPF_MODE(insn->code);
5500 if (mode == BPF_ABS || mode == BPF_IND) {
5501 err = check_ld_abs(env, insn);
5505 } else if (mode == BPF_IMM) {
5506 err = check_ld_imm(env, insn);
5511 sanitize_mark_insn_seen(env);
5513 verbose(env, "invalid BPF_LD mode\n");
5517 verbose(env, "unknown insn class %d\n", class);
5524 verbose(env, "processed %d insns (limit %d), stack depth ",
5525 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
5526 for (i = 0; i < env->subprog_cnt; i++) {
5527 u32 depth = env->subprog_info[i].stack_depth;
5529 verbose(env, "%d", depth);
5530 if (i + 1 < env->subprog_cnt)
5534 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
5538 static int check_map_prealloc(struct bpf_map *map)
5540 return (map->map_type != BPF_MAP_TYPE_HASH &&
5541 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
5542 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
5543 !(map->map_flags & BPF_F_NO_PREALLOC);
5546 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
5547 struct bpf_map *map,
5548 struct bpf_prog *prog)
5551 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
5552 * preallocated hash maps, since doing memory allocation
5553 * in overflow_handler can crash depending on where nmi got
5556 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
5557 if (!check_map_prealloc(map)) {
5558 verbose(env, "perf_event programs can only use preallocated hash map\n");
5561 if (map->inner_map_meta &&
5562 !check_map_prealloc(map->inner_map_meta)) {
5563 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
5568 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
5569 !bpf_offload_prog_map_match(prog, map)) {
5570 verbose(env, "offload device mismatch between prog and map\n");
5577 /* look for pseudo eBPF instructions that access map FDs and
5578 * replace them with actual map pointers
5580 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
5582 struct bpf_insn *insn = env->prog->insnsi;
5583 int insn_cnt = env->prog->len;
5586 err = bpf_prog_calc_tag(env->prog);
5590 for (i = 0; i < insn_cnt; i++, insn++) {
5591 if (BPF_CLASS(insn->code) == BPF_LDX &&
5592 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
5593 verbose(env, "BPF_LDX uses reserved fields\n");
5597 if (BPF_CLASS(insn->code) == BPF_STX &&
5598 ((BPF_MODE(insn->code) != BPF_MEM &&
5599 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
5600 verbose(env, "BPF_STX uses reserved fields\n");
5604 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
5605 struct bpf_map *map;
5608 if (i == insn_cnt - 1 || insn[1].code != 0 ||
5609 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
5611 verbose(env, "invalid bpf_ld_imm64 insn\n");
5615 if (insn->src_reg == 0)
5616 /* valid generic load 64-bit imm */
5619 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
5621 "unrecognized bpf_ld_imm64 insn\n");
5625 f = fdget(insn->imm);
5626 map = __bpf_map_get(f);
5628 verbose(env, "fd %d is not pointing to valid bpf_map\n",
5630 return PTR_ERR(map);
5633 err = check_map_prog_compatibility(env, map, env->prog);
5639 /* store map pointer inside BPF_LD_IMM64 instruction */
5640 insn[0].imm = (u32) (unsigned long) map;
5641 insn[1].imm = ((u64) (unsigned long) map) >> 32;
5643 /* check whether we recorded this map already */
5644 for (j = 0; j < env->used_map_cnt; j++)
5645 if (env->used_maps[j] == map) {
5650 if (env->used_map_cnt >= MAX_USED_MAPS) {
5655 /* hold the map. If the program is rejected by verifier,
5656 * the map will be released by release_maps() or it
5657 * will be used by the valid program until it's unloaded
5658 * and all maps are released in free_used_maps()
5660 map = bpf_map_inc(map, false);
5663 return PTR_ERR(map);
5665 env->used_maps[env->used_map_cnt++] = map;
5667 if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
5668 bpf_cgroup_storage_assign(env->prog, map)) {
5670 "only one cgroup storage is allowed\n");
5682 /* Basic sanity check before we invest more work here. */
5683 if (!bpf_opcode_in_insntable(insn->code)) {
5684 verbose(env, "unknown opcode %02x\n", insn->code);
5689 /* now all pseudo BPF_LD_IMM64 instructions load valid
5690 * 'struct bpf_map *' into a register instead of user map_fd.
5691 * These pointers will be used later by verifier to validate map access.
5696 /* drop refcnt of maps used by the rejected program */
5697 static void release_maps(struct bpf_verifier_env *env)
5701 if (env->prog->aux->cgroup_storage)
5702 bpf_cgroup_storage_release(env->prog,
5703 env->prog->aux->cgroup_storage);
5705 for (i = 0; i < env->used_map_cnt; i++)
5706 bpf_map_put(env->used_maps[i]);
5709 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5710 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5712 struct bpf_insn *insn = env->prog->insnsi;
5713 int insn_cnt = env->prog->len;
5716 for (i = 0; i < insn_cnt; i++, insn++)
5717 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5721 /* single env->prog->insni[off] instruction was replaced with the range
5722 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
5723 * [0, off) and [off, end) to new locations, so the patched range stays zero
5725 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5728 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5729 bool old_seen = old_data[off].seen;
5734 new_data = vzalloc(array_size(prog_len,
5735 sizeof(struct bpf_insn_aux_data)));
5738 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5739 memcpy(new_data + off + cnt - 1, old_data + off,
5740 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5741 for (i = off; i < off + cnt - 1; i++) {
5742 /* Expand insni[off]'s seen count to the patched range. */
5743 new_data[i].seen = old_seen;
5745 env->insn_aux_data = new_data;
5750 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5756 /* NOTE: fake 'exit' subprog should be updated as well. */
5757 for (i = 0; i <= env->subprog_cnt; i++) {
5758 if (env->subprog_info[i].start <= off)
5760 env->subprog_info[i].start += len - 1;
5764 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5765 const struct bpf_insn *patch, u32 len)
5767 struct bpf_prog *new_prog;
5769 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5772 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5774 adjust_subprog_starts(env, off, len);
5778 /* The verifier does more data flow analysis than llvm and will not
5779 * explore branches that are dead at run time. Malicious programs can
5780 * have dead code too. Therefore replace all dead at-run-time code
5783 * Just nops are not optimal, e.g. if they would sit at the end of the
5784 * program and through another bug we would manage to jump there, then
5785 * we'd execute beyond program memory otherwise. Returning exception
5786 * code also wouldn't work since we can have subprogs where the dead
5787 * code could be located.
5789 static void sanitize_dead_code(struct bpf_verifier_env *env)
5791 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5792 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5793 struct bpf_insn *insn = env->prog->insnsi;
5794 const int insn_cnt = env->prog->len;
5797 for (i = 0; i < insn_cnt; i++) {
5798 if (aux_data[i].seen)
5800 memcpy(insn + i, &trap, sizeof(trap));
5804 /* convert load instructions that access fields of 'struct __sk_buff'
5805 * into sequence of instructions that access fields of 'struct sk_buff'
5807 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5809 const struct bpf_verifier_ops *ops = env->ops;
5810 int i, cnt, size, ctx_field_size, delta = 0;
5811 const int insn_cnt = env->prog->len;
5812 struct bpf_insn insn_buf[16], *insn;
5813 u32 target_size, size_default, off;
5814 struct bpf_prog *new_prog;
5815 enum bpf_access_type type;
5816 bool is_narrower_load;
5818 if (ops->gen_prologue) {
5819 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5821 if (cnt >= ARRAY_SIZE(insn_buf)) {
5822 verbose(env, "bpf verifier is misconfigured\n");
5825 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5829 env->prog = new_prog;
5834 if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
5837 insn = env->prog->insnsi + delta;
5839 for (i = 0; i < insn_cnt; i++, insn++) {
5842 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5843 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5844 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5845 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
5848 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5849 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5850 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5851 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
5852 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
5853 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
5854 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
5855 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
5857 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
5862 if (type == BPF_WRITE &&
5863 env->insn_aux_data[i + delta].sanitize_stack_spill) {
5864 struct bpf_insn patch[] = {
5869 cnt = ARRAY_SIZE(patch);
5870 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
5875 env->prog = new_prog;
5876 insn = new_prog->insnsi + i + delta;
5883 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5886 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5887 size = BPF_LDST_BYTES(insn);
5889 /* If the read access is a narrower load of the field,
5890 * convert to a 4/8-byte load, to minimum program type specific
5891 * convert_ctx_access changes. If conversion is successful,
5892 * we will apply proper mask to the result.
5894 is_narrower_load = size < ctx_field_size;
5895 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
5897 if (is_narrower_load) {
5900 if (type == BPF_WRITE) {
5901 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5906 if (ctx_field_size == 4)
5908 else if (ctx_field_size == 8)
5911 insn->off = off & ~(size_default - 1);
5912 insn->code = BPF_LDX | BPF_MEM | size_code;
5916 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5918 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5919 (ctx_field_size && !target_size)) {
5920 verbose(env, "bpf verifier is misconfigured\n");
5924 if (is_narrower_load && size < target_size) {
5925 u8 shift = (off & (size_default - 1)) * 8;
5927 if (ctx_field_size <= 4) {
5929 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
5932 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5933 (1 << size * 8) - 1);
5936 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
5939 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5940 (1ULL << size * 8) - 1);
5944 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5950 /* keep walking new program and skip insns we just inserted */
5951 env->prog = new_prog;
5952 insn = new_prog->insnsi + i + delta;
5958 static int jit_subprogs(struct bpf_verifier_env *env)
5960 struct bpf_prog *prog = env->prog, **func, *tmp;
5961 int i, j, subprog_start, subprog_end = 0, len, subprog;
5962 struct bpf_insn *insn;
5966 if (env->subprog_cnt <= 1)
5969 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5970 if (insn->code != (BPF_JMP | BPF_CALL) ||
5971 insn->src_reg != BPF_PSEUDO_CALL)
5973 /* Upon error here we cannot fall back to interpreter but
5974 * need a hard reject of the program. Thus -EFAULT is
5975 * propagated in any case.
5977 subprog = find_subprog(env, i + insn->imm + 1);
5979 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5983 /* temporarily remember subprog id inside insn instead of
5984 * aux_data, since next loop will split up all insns into funcs
5986 insn->off = subprog;
5987 /* remember original imm in case JIT fails and fallback
5988 * to interpreter will be needed
5990 env->insn_aux_data[i].call_imm = insn->imm;
5991 /* point imm to __bpf_call_base+1 from JITs point of view */
5995 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
5999 for (i = 0; i < env->subprog_cnt; i++) {
6000 subprog_start = subprog_end;
6001 subprog_end = env->subprog_info[i + 1].start;
6003 len = subprog_end - subprog_start;
6004 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
6007 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
6008 len * sizeof(struct bpf_insn));
6009 func[i]->type = prog->type;
6011 if (bpf_prog_calc_tag(func[i]))
6013 func[i]->is_func = 1;
6014 /* Use bpf_prog_F_tag to indicate functions in stack traces.
6015 * Long term would need debug info to populate names
6017 func[i]->aux->name[0] = 'F';
6018 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
6019 func[i]->jit_requested = 1;
6020 func[i] = bpf_int_jit_compile(func[i]);
6021 if (!func[i]->jited) {
6027 /* at this point all bpf functions were successfully JITed
6028 * now populate all bpf_calls with correct addresses and
6029 * run last pass of JIT
6031 for (i = 0; i < env->subprog_cnt; i++) {
6032 insn = func[i]->insnsi;
6033 for (j = 0; j < func[i]->len; j++, insn++) {
6034 if (insn->code != (BPF_JMP | BPF_CALL) ||
6035 insn->src_reg != BPF_PSEUDO_CALL)
6037 subprog = insn->off;
6038 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
6039 func[subprog]->bpf_func -
6043 /* we use the aux data to keep a list of the start addresses
6044 * of the JITed images for each function in the program
6046 * for some architectures, such as powerpc64, the imm field
6047 * might not be large enough to hold the offset of the start
6048 * address of the callee's JITed image from __bpf_call_base
6050 * in such cases, we can lookup the start address of a callee
6051 * by using its subprog id, available from the off field of
6052 * the call instruction, as an index for this list
6054 func[i]->aux->func = func;
6055 func[i]->aux->func_cnt = env->subprog_cnt;
6057 for (i = 0; i < env->subprog_cnt; i++) {
6058 old_bpf_func = func[i]->bpf_func;
6059 tmp = bpf_int_jit_compile(func[i]);
6060 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
6061 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
6068 /* finally lock prog and jit images for all functions and
6071 for (i = 0; i < env->subprog_cnt; i++) {
6072 bpf_prog_lock_ro(func[i]);
6073 bpf_prog_kallsyms_add(func[i]);
6076 /* Last step: make now unused interpreter insns from main
6077 * prog consistent for later dump requests, so they can
6078 * later look the same as if they were interpreted only.
6080 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6081 if (insn->code != (BPF_JMP | BPF_CALL) ||
6082 insn->src_reg != BPF_PSEUDO_CALL)
6084 insn->off = env->insn_aux_data[i].call_imm;
6085 subprog = find_subprog(env, i + insn->off + 1);
6086 insn->imm = subprog;
6090 prog->bpf_func = func[0]->bpf_func;
6091 prog->aux->func = func;
6092 prog->aux->func_cnt = env->subprog_cnt;
6095 for (i = 0; i < env->subprog_cnt; i++)
6097 bpf_jit_free(func[i]);
6100 /* cleanup main prog to be interpreted */
6101 prog->jit_requested = 0;
6102 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6103 if (insn->code != (BPF_JMP | BPF_CALL) ||
6104 insn->src_reg != BPF_PSEUDO_CALL)
6107 insn->imm = env->insn_aux_data[i].call_imm;
6112 static int fixup_call_args(struct bpf_verifier_env *env)
6114 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6115 struct bpf_prog *prog = env->prog;
6116 struct bpf_insn *insn = prog->insnsi;
6122 if (env->prog->jit_requested) {
6123 err = jit_subprogs(env);
6129 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6130 for (i = 0; i < prog->len; i++, insn++) {
6131 if (insn->code != (BPF_JMP | BPF_CALL) ||
6132 insn->src_reg != BPF_PSEUDO_CALL)
6134 depth = get_callee_stack_depth(env, insn, i);
6137 bpf_patch_call_args(insn, depth);
6144 /* fixup insn->imm field of bpf_call instructions
6145 * and inline eligible helpers as explicit sequence of BPF instructions
6147 * this function is called after eBPF program passed verification
6149 static int fixup_bpf_calls(struct bpf_verifier_env *env)
6151 struct bpf_prog *prog = env->prog;
6152 struct bpf_insn *insn = prog->insnsi;
6153 const struct bpf_func_proto *fn;
6154 const int insn_cnt = prog->len;
6155 const struct bpf_map_ops *ops;
6156 struct bpf_insn_aux_data *aux;
6157 struct bpf_insn insn_buf[16];
6158 struct bpf_prog *new_prog;
6159 struct bpf_map *map_ptr;
6160 int i, cnt, delta = 0;
6162 for (i = 0; i < insn_cnt; i++, insn++) {
6163 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
6164 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6165 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
6166 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6167 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
6168 struct bpf_insn mask_and_div[] = {
6169 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
6170 /* [R,W]x div 0 -> 0 */
6171 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 2),
6172 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
6173 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6174 BPF_ALU_REG(BPF_CLASS(insn->code), BPF_XOR, insn->dst_reg, insn->dst_reg),
6176 struct bpf_insn mask_and_mod[] = {
6177 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
6178 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 1 + (is64 ? 0 : 1)),
6179 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
6180 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6181 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
6183 struct bpf_insn *patchlet;
6185 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6186 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6187 patchlet = mask_and_div;
6188 cnt = ARRAY_SIZE(mask_and_div);
6190 patchlet = mask_and_mod;
6191 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 2 : 0);
6194 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
6199 env->prog = prog = new_prog;
6200 insn = new_prog->insnsi + i + delta;
6204 if (BPF_CLASS(insn->code) == BPF_LD &&
6205 (BPF_MODE(insn->code) == BPF_ABS ||
6206 BPF_MODE(insn->code) == BPF_IND)) {
6207 cnt = env->ops->gen_ld_abs(insn, insn_buf);
6208 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6209 verbose(env, "bpf verifier is misconfigured\n");
6213 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6218 env->prog = prog = new_prog;
6219 insn = new_prog->insnsi + i + delta;
6223 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
6224 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
6225 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
6226 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
6227 struct bpf_insn insn_buf[16];
6228 struct bpf_insn *patch = &insn_buf[0];
6229 bool issrc, isneg, isimm;
6232 aux = &env->insn_aux_data[i + delta];
6233 if (!aux->alu_state ||
6234 aux->alu_state == BPF_ALU_NON_POINTER)
6237 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
6238 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
6239 BPF_ALU_SANITIZE_SRC;
6240 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
6242 off_reg = issrc ? insn->src_reg : insn->dst_reg;
6244 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
6247 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6248 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
6249 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
6250 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
6251 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
6252 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
6253 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
6256 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
6257 insn->src_reg = BPF_REG_AX;
6259 insn->code = insn->code == code_add ?
6260 code_sub : code_add;
6262 if (issrc && isneg && !isimm)
6263 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6264 cnt = patch - insn_buf;
6266 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6271 env->prog = prog = new_prog;
6272 insn = new_prog->insnsi + i + delta;
6276 if (insn->code != (BPF_JMP | BPF_CALL))
6278 if (insn->src_reg == BPF_PSEUDO_CALL)
6281 if (insn->imm == BPF_FUNC_get_route_realm)
6282 prog->dst_needed = 1;
6283 if (insn->imm == BPF_FUNC_get_prandom_u32)
6284 bpf_user_rnd_init_once();
6285 if (insn->imm == BPF_FUNC_override_return)
6286 prog->kprobe_override = 1;
6287 if (insn->imm == BPF_FUNC_tail_call) {
6288 /* If we tail call into other programs, we
6289 * cannot make any assumptions since they can
6290 * be replaced dynamically during runtime in
6291 * the program array.
6293 prog->cb_access = 1;
6294 env->prog->aux->stack_depth = MAX_BPF_STACK;
6296 /* mark bpf_tail_call as different opcode to avoid
6297 * conditional branch in the interpeter for every normal
6298 * call and to prevent accidental JITing by JIT compiler
6299 * that doesn't support bpf_tail_call yet
6302 insn->code = BPF_JMP | BPF_TAIL_CALL;
6304 aux = &env->insn_aux_data[i + delta];
6305 if (!bpf_map_ptr_unpriv(aux))
6308 /* instead of changing every JIT dealing with tail_call
6309 * emit two extra insns:
6310 * if (index >= max_entries) goto out;
6311 * index &= array->index_mask;
6312 * to avoid out-of-bounds cpu speculation
6314 if (bpf_map_ptr_poisoned(aux)) {
6315 verbose(env, "tail_call abusing map_ptr\n");
6319 map_ptr = BPF_MAP_PTR(aux->map_state);
6320 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
6321 map_ptr->max_entries, 2);
6322 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
6323 container_of(map_ptr,
6326 insn_buf[2] = *insn;
6328 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6333 env->prog = prog = new_prog;
6334 insn = new_prog->insnsi + i + delta;
6338 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
6339 * and other inlining handlers are currently limited to 64 bit
6342 if (prog->jit_requested && BITS_PER_LONG == 64 &&
6343 (insn->imm == BPF_FUNC_map_lookup_elem ||
6344 insn->imm == BPF_FUNC_map_update_elem ||
6345 insn->imm == BPF_FUNC_map_delete_elem)) {
6346 aux = &env->insn_aux_data[i + delta];
6347 if (bpf_map_ptr_poisoned(aux))
6348 goto patch_call_imm;
6350 map_ptr = BPF_MAP_PTR(aux->map_state);
6352 if (insn->imm == BPF_FUNC_map_lookup_elem &&
6353 ops->map_gen_lookup) {
6354 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
6355 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6356 verbose(env, "bpf verifier is misconfigured\n");
6360 new_prog = bpf_patch_insn_data(env, i + delta,
6366 env->prog = prog = new_prog;
6367 insn = new_prog->insnsi + i + delta;
6371 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
6372 (void *(*)(struct bpf_map *map, void *key))NULL));
6373 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
6374 (int (*)(struct bpf_map *map, void *key))NULL));
6375 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
6376 (int (*)(struct bpf_map *map, void *key, void *value,
6378 switch (insn->imm) {
6379 case BPF_FUNC_map_lookup_elem:
6380 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
6383 case BPF_FUNC_map_update_elem:
6384 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
6387 case BPF_FUNC_map_delete_elem:
6388 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
6393 goto patch_call_imm;
6397 fn = env->ops->get_func_proto(insn->imm, env->prog);
6398 /* all functions that have prototype and verifier allowed
6399 * programs to call them, must be real in-kernel functions
6403 "kernel subsystem misconfigured func %s#%d\n",
6404 func_id_name(insn->imm), insn->imm);
6407 insn->imm = fn->func - __bpf_call_base;
6413 static void free_states(struct bpf_verifier_env *env)
6415 struct bpf_verifier_state_list *sl, *sln;
6418 if (!env->explored_states)
6421 for (i = 0; i < env->prog->len; i++) {
6422 sl = env->explored_states[i];
6425 while (sl != STATE_LIST_MARK) {
6427 free_verifier_state(&sl->state, false);
6433 kfree(env->explored_states);
6436 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
6438 struct bpf_verifier_env *env;
6439 struct bpf_verifier_log *log;
6442 /* no program is valid */
6443 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
6446 /* 'struct bpf_verifier_env' can be global, but since it's not small,
6447 * allocate/free it every time bpf_check() is called
6449 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
6454 env->insn_aux_data =
6455 vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
6458 if (!env->insn_aux_data)
6461 env->ops = bpf_verifier_ops[env->prog->type];
6463 /* grab the mutex to protect few globals used by verifier */
6464 mutex_lock(&bpf_verifier_lock);
6466 if (attr->log_level || attr->log_buf || attr->log_size) {
6467 /* user requested verbose verifier output
6468 * and supplied buffer to store the verification trace
6470 log->level = attr->log_level;
6471 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
6472 log->len_total = attr->log_size;
6475 /* log attributes have to be sane */
6476 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
6477 !log->level || !log->ubuf)
6481 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
6482 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
6483 env->strict_alignment = true;
6485 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
6486 env->strict_alignment = false;
6488 ret = replace_map_fd_with_map_ptr(env);
6490 goto skip_full_check;
6492 if (bpf_prog_is_dev_bound(env->prog->aux)) {
6493 ret = bpf_prog_offload_verifier_prep(env);
6495 goto skip_full_check;
6498 env->explored_states = kcalloc(env->prog->len,
6499 sizeof(struct bpf_verifier_state_list *),
6502 if (!env->explored_states)
6503 goto skip_full_check;
6505 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
6507 ret = check_cfg(env);
6509 goto skip_full_check;
6511 ret = do_check(env);
6512 if (env->cur_state) {
6513 free_verifier_state(env->cur_state, true);
6514 env->cur_state = NULL;
6518 while (!pop_stack(env, NULL, NULL));
6522 sanitize_dead_code(env);
6525 ret = check_max_stack_depth(env);
6528 /* program is valid, convert *(u32*)(ctx + off) accesses */
6529 ret = convert_ctx_accesses(env);
6532 ret = fixup_bpf_calls(env);
6535 ret = fixup_call_args(env);
6537 if (log->level && bpf_verifier_log_full(log))
6539 if (log->level && !log->ubuf) {
6541 goto err_release_maps;
6544 if (ret == 0 && env->used_map_cnt) {
6545 /* if program passed verifier, update used_maps in bpf_prog_info */
6546 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
6547 sizeof(env->used_maps[0]),
6550 if (!env->prog->aux->used_maps) {
6552 goto err_release_maps;
6555 memcpy(env->prog->aux->used_maps, env->used_maps,
6556 sizeof(env->used_maps[0]) * env->used_map_cnt);
6557 env->prog->aux->used_map_cnt = env->used_map_cnt;
6559 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
6560 * bpf_ld_imm64 instructions
6562 convert_pseudo_ld_imm64(env);
6566 if (!env->prog->aux->used_maps)
6567 /* if we didn't copy map pointers into bpf_prog_info, release
6568 * them now. Otherwise free_used_maps() will release them.
6573 mutex_unlock(&bpf_verifier_lock);
6574 vfree(env->insn_aux_data);