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 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
1022 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
1025 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1026 !register_is_null(reg) && env->allow_ptr_leaks) {
1027 save_register_state(state, spi, reg);
1028 } else if (reg && is_spillable_regtype(reg->type)) {
1029 /* register containing pointer is being spilled into stack */
1030 if (size != BPF_REG_SIZE) {
1031 verbose(env, "invalid size of register spill\n");
1034 if (state != cur && reg->type == PTR_TO_STACK) {
1035 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1038 save_register_state(state, spi, reg);
1040 u8 type = STACK_MISC;
1042 /* regular write of data into stack destroys any spilled ptr */
1043 state->stack[spi].spilled_ptr.type = NOT_INIT;
1044 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1045 if (state->stack[spi].slot_type[0] == STACK_SPILL)
1046 for (i = 0; i < BPF_REG_SIZE; i++)
1047 state->stack[spi].slot_type[i] = STACK_MISC;
1049 /* only mark the slot as written if all 8 bytes were written
1050 * otherwise read propagation may incorrectly stop too soon
1051 * when stack slots are partially written.
1052 * This heuristic means that read propagation will be
1053 * conservative, since it will add reg_live_read marks
1054 * to stack slots all the way to first state when programs
1055 * writes+reads less than 8 bytes
1057 if (size == BPF_REG_SIZE)
1058 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1060 /* when we zero initialize stack slots mark them as such */
1061 if (reg && register_is_null(reg))
1064 /* Mark slots affected by this stack write. */
1065 for (i = 0; i < size; i++)
1066 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1072 static int check_stack_read(struct bpf_verifier_env *env,
1073 struct bpf_func_state *reg_state /* func where register points to */,
1074 int off, int size, int value_regno)
1076 struct bpf_verifier_state *vstate = env->cur_state;
1077 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1078 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1079 struct bpf_reg_state *reg;
1082 if (reg_state->allocated_stack <= slot) {
1083 verbose(env, "invalid read from stack off %d+0 size %d\n",
1087 stype = reg_state->stack[spi].slot_type;
1088 reg = ®_state->stack[spi].spilled_ptr;
1090 if (stype[0] == STACK_SPILL) {
1091 if (size != BPF_REG_SIZE) {
1092 if (reg->type != SCALAR_VALUE) {
1093 verbose(env, "invalid size of register fill\n");
1096 if (value_regno >= 0) {
1097 mark_reg_unknown(env, state->regs, value_regno);
1098 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1100 mark_reg_read(env, reg, reg->parent);
1103 for (i = 1; i < BPF_REG_SIZE; i++) {
1104 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1105 verbose(env, "corrupted spill memory\n");
1110 if (value_regno >= 0) {
1111 /* restore register state from stack */
1112 state->regs[value_regno] = *reg;
1113 /* mark reg as written since spilled pointer state likely
1114 * has its liveness marks cleared by is_state_visited()
1115 * which resets stack/reg liveness for state transitions
1117 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1119 mark_reg_read(env, reg, reg->parent);
1123 for (i = 0; i < size; i++) {
1124 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1126 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1130 verbose(env, "invalid read from stack off %d+%d size %d\n",
1134 mark_reg_read(env, reg, reg->parent);
1135 if (value_regno >= 0) {
1136 if (zeros == size) {
1137 /* any size read into register is zero extended,
1138 * so the whole register == const_zero
1140 __mark_reg_const_zero(&state->regs[value_regno]);
1142 /* have read misc data from the stack */
1143 mark_reg_unknown(env, state->regs, value_regno);
1145 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1151 static int check_stack_access(struct bpf_verifier_env *env,
1152 const struct bpf_reg_state *reg,
1155 /* Stack accesses must be at a fixed offset, so that we
1156 * can determine what type of data were returned. See
1157 * check_stack_read().
1159 if (!tnum_is_const(reg->var_off)) {
1162 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1163 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
1168 if (off >= 0 || off < -MAX_BPF_STACK) {
1169 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1176 /* check read/write into map element returned by bpf_map_lookup_elem() */
1177 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1178 int size, bool zero_size_allowed)
1180 struct bpf_reg_state *regs = cur_regs(env);
1181 struct bpf_map *map = regs[regno].map_ptr;
1183 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1184 off + size > map->value_size) {
1185 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1186 map->value_size, off, size);
1192 /* check read/write into a map element with possible variable offset */
1193 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1194 int off, int size, bool zero_size_allowed)
1196 struct bpf_verifier_state *vstate = env->cur_state;
1197 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1198 struct bpf_reg_state *reg = &state->regs[regno];
1201 /* We may have adjusted the register to this map value, so we
1202 * need to try adding each of min_value and max_value to off
1203 * to make sure our theoretical access will be safe.
1206 print_verifier_state(env, state);
1208 /* The minimum value is only important with signed
1209 * comparisons where we can't assume the floor of a
1210 * value is 0. If we are using signed variables for our
1211 * index'es we need to make sure that whatever we use
1212 * will have a set floor within our range.
1214 if (reg->smin_value < 0 &&
1215 (reg->smin_value == S64_MIN ||
1216 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1217 reg->smin_value + off < 0)) {
1218 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1222 err = __check_map_access(env, regno, reg->smin_value + off, size,
1225 verbose(env, "R%d min value is outside of the array range\n",
1230 /* If we haven't set a max value then we need to bail since we can't be
1231 * sure we won't do bad things.
1232 * If reg->umax_value + off could overflow, treat that as unbounded too.
1234 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1235 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1239 err = __check_map_access(env, regno, reg->umax_value + off, size,
1242 verbose(env, "R%d max value is outside of the array range\n",
1247 #define MAX_PACKET_OFF 0xffff
1249 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1250 const struct bpf_call_arg_meta *meta,
1251 enum bpf_access_type t)
1253 switch (env->prog->type) {
1254 case BPF_PROG_TYPE_LWT_IN:
1255 case BPF_PROG_TYPE_LWT_OUT:
1256 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1257 case BPF_PROG_TYPE_SK_REUSEPORT:
1258 /* dst_input() and dst_output() can't write for now */
1262 case BPF_PROG_TYPE_SCHED_CLS:
1263 case BPF_PROG_TYPE_SCHED_ACT:
1264 case BPF_PROG_TYPE_XDP:
1265 case BPF_PROG_TYPE_LWT_XMIT:
1266 case BPF_PROG_TYPE_SK_SKB:
1267 case BPF_PROG_TYPE_SK_MSG:
1269 return meta->pkt_access;
1271 env->seen_direct_write = true;
1278 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1279 int off, int size, bool zero_size_allowed)
1281 struct bpf_reg_state *regs = cur_regs(env);
1282 struct bpf_reg_state *reg = ®s[regno];
1284 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1285 (u64)off + size > reg->range) {
1286 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1287 off, size, regno, reg->id, reg->off, reg->range);
1293 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1294 int size, bool zero_size_allowed)
1296 struct bpf_reg_state *regs = cur_regs(env);
1297 struct bpf_reg_state *reg = ®s[regno];
1300 /* We may have added a variable offset to the packet pointer; but any
1301 * reg->range we have comes after that. We are only checking the fixed
1305 /* We don't allow negative numbers, because we aren't tracking enough
1306 * detail to prove they're safe.
1308 if (reg->smin_value < 0) {
1309 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1313 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1315 verbose(env, "R%d offset is outside of the packet\n", regno);
1321 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1322 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1323 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1325 struct bpf_insn_access_aux info = {
1326 .reg_type = *reg_type,
1329 if (env->ops->is_valid_access &&
1330 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1331 /* A non zero info.ctx_field_size indicates that this field is a
1332 * candidate for later verifier transformation to load the whole
1333 * field and then apply a mask when accessed with a narrower
1334 * access than actual ctx access size. A zero info.ctx_field_size
1335 * will only allow for whole field access and rejects any other
1336 * type of narrower access.
1338 *reg_type = info.reg_type;
1340 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1341 /* remember the offset of last byte accessed in ctx */
1342 if (env->prog->aux->max_ctx_offset < off + size)
1343 env->prog->aux->max_ctx_offset = off + size;
1347 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1351 static bool __is_pointer_value(bool allow_ptr_leaks,
1352 const struct bpf_reg_state *reg)
1354 if (allow_ptr_leaks)
1357 return reg->type != SCALAR_VALUE;
1360 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1362 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1365 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1367 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1369 return reg->type == PTR_TO_CTX;
1372 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1374 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1376 return type_is_pkt_pointer(reg->type);
1379 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1380 const struct bpf_reg_state *reg,
1381 int off, int size, bool strict)
1383 struct tnum reg_off;
1386 /* Byte size accesses are always allowed. */
1387 if (!strict || size == 1)
1390 /* For platforms that do not have a Kconfig enabling
1391 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1392 * NET_IP_ALIGN is universally set to '2'. And on platforms
1393 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1394 * to this code only in strict mode where we want to emulate
1395 * the NET_IP_ALIGN==2 checking. Therefore use an
1396 * unconditional IP align value of '2'.
1400 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1401 if (!tnum_is_aligned(reg_off, size)) {
1404 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1406 "misaligned packet access off %d+%s+%d+%d size %d\n",
1407 ip_align, tn_buf, reg->off, off, size);
1414 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1415 const struct bpf_reg_state *reg,
1416 const char *pointer_desc,
1417 int off, int size, bool strict)
1419 struct tnum reg_off;
1421 /* Byte size accesses are always allowed. */
1422 if (!strict || size == 1)
1425 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1426 if (!tnum_is_aligned(reg_off, size)) {
1429 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1430 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1431 pointer_desc, tn_buf, reg->off, off, size);
1438 static int check_ptr_alignment(struct bpf_verifier_env *env,
1439 const struct bpf_reg_state *reg, int off,
1440 int size, bool strict_alignment_once)
1442 bool strict = env->strict_alignment || strict_alignment_once;
1443 const char *pointer_desc = "";
1445 switch (reg->type) {
1447 case PTR_TO_PACKET_META:
1448 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1449 * right in front, treat it the very same way.
1451 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1452 case PTR_TO_MAP_VALUE:
1453 pointer_desc = "value ";
1456 pointer_desc = "context ";
1459 pointer_desc = "stack ";
1460 /* The stack spill tracking logic in check_stack_write()
1461 * and check_stack_read() relies on stack accesses being
1469 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1473 static int update_stack_depth(struct bpf_verifier_env *env,
1474 const struct bpf_func_state *func,
1477 u16 stack = env->subprog_info[func->subprogno].stack_depth;
1482 /* update known max for given subprogram */
1483 env->subprog_info[func->subprogno].stack_depth = -off;
1487 /* starting from main bpf function walk all instructions of the function
1488 * and recursively walk all callees that given function can call.
1489 * Ignore jump and exit insns.
1490 * Since recursion is prevented by check_cfg() this algorithm
1491 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1493 static int check_max_stack_depth(struct bpf_verifier_env *env)
1495 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1496 struct bpf_subprog_info *subprog = env->subprog_info;
1497 struct bpf_insn *insn = env->prog->insnsi;
1498 int ret_insn[MAX_CALL_FRAMES];
1499 int ret_prog[MAX_CALL_FRAMES];
1502 /* round up to 32-bytes, since this is granularity
1503 * of interpreter stack size
1505 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1506 if (depth > MAX_BPF_STACK) {
1507 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1512 subprog_end = subprog[idx + 1].start;
1513 for (; i < subprog_end; i++) {
1514 if (insn[i].code != (BPF_JMP | BPF_CALL))
1516 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1518 /* remember insn and function to return to */
1519 ret_insn[frame] = i + 1;
1520 ret_prog[frame] = idx;
1522 /* find the callee */
1523 i = i + insn[i].imm + 1;
1524 idx = find_subprog(env, i);
1526 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1531 if (frame >= MAX_CALL_FRAMES) {
1532 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1537 /* end of for() loop means the last insn of the 'subprog'
1538 * was reached. Doesn't matter whether it was JA or EXIT
1542 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1544 i = ret_insn[frame];
1545 idx = ret_prog[frame];
1549 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1550 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1551 const struct bpf_insn *insn, int idx)
1553 int start = idx + insn->imm + 1, subprog;
1555 subprog = find_subprog(env, start);
1557 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1561 return env->subprog_info[subprog].stack_depth;
1565 static int check_ctx_reg(struct bpf_verifier_env *env,
1566 const struct bpf_reg_state *reg, int regno)
1568 /* Access to ctx or passing it to a helper is only allowed in
1569 * its original, unmodified form.
1573 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1578 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1581 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1582 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1589 /* truncate register to smaller size (in bytes)
1590 * must be called with size < BPF_REG_SIZE
1592 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1596 /* clear high bits in bit representation */
1597 reg->var_off = tnum_cast(reg->var_off, size);
1599 /* fix arithmetic bounds */
1600 mask = ((u64)1 << (size * 8)) - 1;
1601 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1602 reg->umin_value &= mask;
1603 reg->umax_value &= mask;
1605 reg->umin_value = 0;
1606 reg->umax_value = mask;
1608 reg->smin_value = reg->umin_value;
1609 reg->smax_value = reg->umax_value;
1612 /* check whether memory at (regno + off) is accessible for t = (read | write)
1613 * if t==write, value_regno is a register which value is stored into memory
1614 * if t==read, value_regno is a register which will receive the value from memory
1615 * if t==write && value_regno==-1, some unknown value is stored into memory
1616 * if t==read && value_regno==-1, don't care what we read from memory
1618 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1619 int off, int bpf_size, enum bpf_access_type t,
1620 int value_regno, bool strict_alignment_once)
1622 struct bpf_reg_state *regs = cur_regs(env);
1623 struct bpf_reg_state *reg = regs + regno;
1624 struct bpf_func_state *state;
1627 size = bpf_size_to_bytes(bpf_size);
1631 /* alignment checks will add in reg->off themselves */
1632 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1636 /* for access checks, reg->off is just part of off */
1639 if (reg->type == PTR_TO_MAP_VALUE) {
1640 if (t == BPF_WRITE && value_regno >= 0 &&
1641 is_pointer_value(env, value_regno)) {
1642 verbose(env, "R%d leaks addr into map\n", value_regno);
1646 err = check_map_access(env, regno, off, size, false);
1647 if (!err && t == BPF_READ && value_regno >= 0)
1648 mark_reg_unknown(env, regs, value_regno);
1650 } else if (reg->type == PTR_TO_CTX) {
1651 enum bpf_reg_type reg_type = SCALAR_VALUE;
1653 if (t == BPF_WRITE && value_regno >= 0 &&
1654 is_pointer_value(env, value_regno)) {
1655 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1659 err = check_ctx_reg(env, reg, regno);
1663 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1664 if (!err && t == BPF_READ && value_regno >= 0) {
1665 /* ctx access returns either a scalar, or a
1666 * PTR_TO_PACKET[_META,_END]. In the latter
1667 * case, we know the offset is zero.
1669 if (reg_type == SCALAR_VALUE)
1670 mark_reg_unknown(env, regs, value_regno);
1672 mark_reg_known_zero(env, regs,
1674 regs[value_regno].type = reg_type;
1677 } else if (reg->type == PTR_TO_STACK) {
1678 off += reg->var_off.value;
1679 err = check_stack_access(env, reg, off, size);
1683 state = func(env, reg);
1684 err = update_stack_depth(env, state, off);
1689 err = check_stack_write(env, state, off, size,
1690 value_regno, insn_idx);
1692 err = check_stack_read(env, state, off, size,
1694 } else if (reg_is_pkt_pointer(reg)) {
1695 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1696 verbose(env, "cannot write into packet\n");
1699 if (t == BPF_WRITE && value_regno >= 0 &&
1700 is_pointer_value(env, value_regno)) {
1701 verbose(env, "R%d leaks addr into packet\n",
1705 err = check_packet_access(env, regno, off, size, false);
1706 if (!err && t == BPF_READ && value_regno >= 0)
1707 mark_reg_unknown(env, regs, value_regno);
1709 verbose(env, "R%d invalid mem access '%s'\n", regno,
1710 reg_type_str[reg->type]);
1714 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1715 regs[value_regno].type == SCALAR_VALUE) {
1716 /* b/h/w load zero-extends, mark upper bits as known 0 */
1717 coerce_reg_to_size(®s[value_regno], size);
1722 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1726 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1728 verbose(env, "BPF_XADD uses reserved fields\n");
1732 /* check src1 operand */
1733 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1737 /* check src2 operand */
1738 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1742 if (is_pointer_value(env, insn->src_reg)) {
1743 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1747 if (is_ctx_reg(env, insn->dst_reg) ||
1748 is_pkt_reg(env, insn->dst_reg)) {
1749 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1750 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1751 "context" : "packet");
1755 /* check whether atomic_add can read the memory */
1756 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1757 BPF_SIZE(insn->code), BPF_READ, -1, true);
1761 /* check whether atomic_add can write into the same memory */
1762 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1763 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1766 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
1767 int off, int access_size,
1768 bool zero_size_allowed)
1770 struct bpf_reg_state *reg = cur_regs(env) + regno;
1772 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1773 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1774 if (tnum_is_const(reg->var_off)) {
1775 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1776 regno, off, access_size);
1780 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1781 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
1782 regno, tn_buf, access_size);
1789 /* when register 'regno' is passed into function that will read 'access_size'
1790 * bytes from that pointer, make sure that it's within stack boundary
1791 * and all elements of stack are initialized.
1792 * Unlike most pointer bounds-checking functions, this one doesn't take an
1793 * 'off' argument, so it has to add in reg->off itself.
1795 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1796 int access_size, bool zero_size_allowed,
1797 struct bpf_call_arg_meta *meta)
1799 struct bpf_reg_state *reg = cur_regs(env) + regno;
1800 struct bpf_func_state *state = func(env, reg);
1801 int err, min_off, max_off, i, j, slot, spi;
1803 if (reg->type != PTR_TO_STACK) {
1804 /* Allow zero-byte read from NULL, regardless of pointer type */
1805 if (zero_size_allowed && access_size == 0 &&
1806 register_is_null(reg))
1809 verbose(env, "R%d type=%s expected=%s\n", regno,
1810 reg_type_str[reg->type],
1811 reg_type_str[PTR_TO_STACK]);
1815 if (tnum_is_const(reg->var_off)) {
1816 min_off = max_off = reg->var_off.value + reg->off;
1817 err = __check_stack_boundary(env, regno, min_off, access_size,
1822 /* Variable offset is prohibited for unprivileged mode for
1823 * simplicity since it requires corresponding support in
1824 * Spectre masking for stack ALU.
1825 * See also retrieve_ptr_limit().
1827 if (!env->allow_ptr_leaks) {
1830 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1831 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
1835 /* Only initialized buffer on stack is allowed to be accessed
1836 * with variable offset. With uninitialized buffer it's hard to
1837 * guarantee that whole memory is marked as initialized on
1838 * helper return since specific bounds are unknown what may
1839 * cause uninitialized stack leaking.
1841 if (meta && meta->raw_mode)
1844 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
1845 reg->smax_value <= -BPF_MAX_VAR_OFF) {
1846 verbose(env, "R%d unbounded indirect variable offset stack access\n",
1850 min_off = reg->smin_value + reg->off;
1851 max_off = reg->smax_value + reg->off;
1852 err = __check_stack_boundary(env, regno, min_off, access_size,
1855 verbose(env, "R%d min value is outside of stack bound\n",
1859 err = __check_stack_boundary(env, regno, max_off, access_size,
1862 verbose(env, "R%d max value is outside of stack bound\n",
1868 if (meta && meta->raw_mode) {
1869 meta->access_size = access_size;
1870 meta->regno = regno;
1874 for (i = min_off; i < max_off + access_size; i++) {
1878 spi = slot / BPF_REG_SIZE;
1879 if (state->allocated_stack <= slot)
1881 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1882 if (*stype == STACK_MISC)
1884 if (*stype == STACK_ZERO) {
1885 /* helper can write anything into the stack */
1886 *stype = STACK_MISC;
1889 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1890 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
1891 __mark_reg_unknown(&state->stack[spi].spilled_ptr);
1892 for (j = 0; j < BPF_REG_SIZE; j++)
1893 state->stack[spi].slot_type[j] = STACK_MISC;
1898 if (tnum_is_const(reg->var_off)) {
1899 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1900 min_off, i - min_off, access_size);
1904 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1905 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
1906 tn_buf, i - min_off, access_size);
1910 /* reading any byte out of 8-byte 'spill_slot' will cause
1911 * the whole slot to be marked as 'read'
1913 mark_reg_read(env, &state->stack[spi].spilled_ptr,
1914 state->stack[spi].spilled_ptr.parent);
1916 return update_stack_depth(env, state, min_off);
1919 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1920 int access_size, bool zero_size_allowed,
1921 struct bpf_call_arg_meta *meta)
1923 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1925 switch (reg->type) {
1927 case PTR_TO_PACKET_META:
1928 return check_packet_access(env, regno, reg->off, access_size,
1930 case PTR_TO_MAP_VALUE:
1931 return check_map_access(env, regno, reg->off, access_size,
1933 default: /* scalar_value|ptr_to_stack or invalid ptr */
1934 return check_stack_boundary(env, regno, access_size,
1935 zero_size_allowed, meta);
1939 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1941 return type == ARG_PTR_TO_MEM ||
1942 type == ARG_PTR_TO_MEM_OR_NULL ||
1943 type == ARG_PTR_TO_UNINIT_MEM;
1946 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1948 return type == ARG_CONST_SIZE ||
1949 type == ARG_CONST_SIZE_OR_ZERO;
1952 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1953 enum bpf_arg_type arg_type,
1954 struct bpf_call_arg_meta *meta)
1956 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1957 enum bpf_reg_type expected_type, type = reg->type;
1960 if (arg_type == ARG_DONTCARE)
1963 err = check_reg_arg(env, regno, SRC_OP);
1967 if (arg_type == ARG_ANYTHING) {
1968 if (is_pointer_value(env, regno)) {
1969 verbose(env, "R%d leaks addr into helper function\n",
1976 if (type_is_pkt_pointer(type) &&
1977 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1978 verbose(env, "helper access to the packet is not allowed\n");
1982 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1983 arg_type == ARG_PTR_TO_MAP_VALUE) {
1984 expected_type = PTR_TO_STACK;
1985 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
1986 type != expected_type)
1988 } else if (arg_type == ARG_CONST_SIZE ||
1989 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1990 expected_type = SCALAR_VALUE;
1991 if (type != expected_type)
1993 } else if (arg_type == ARG_CONST_MAP_PTR) {
1994 expected_type = CONST_PTR_TO_MAP;
1995 if (type != expected_type)
1997 } else if (arg_type == ARG_PTR_TO_CTX) {
1998 expected_type = PTR_TO_CTX;
1999 if (type != expected_type)
2001 err = check_ctx_reg(env, reg, regno);
2004 } else if (arg_type_is_mem_ptr(arg_type)) {
2005 expected_type = PTR_TO_STACK;
2006 /* One exception here. In case function allows for NULL to be
2007 * passed in as argument, it's a SCALAR_VALUE type. Final test
2008 * happens during stack boundary checking.
2010 if (register_is_null(reg) &&
2011 arg_type == ARG_PTR_TO_MEM_OR_NULL)
2012 /* final test in check_stack_boundary() */;
2013 else if (!type_is_pkt_pointer(type) &&
2014 type != PTR_TO_MAP_VALUE &&
2015 type != expected_type)
2017 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
2019 verbose(env, "unsupported arg_type %d\n", arg_type);
2023 if (arg_type == ARG_CONST_MAP_PTR) {
2024 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2025 meta->map_ptr = reg->map_ptr;
2026 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
2027 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2028 * check that [key, key + map->key_size) are within
2029 * stack limits and initialized
2031 if (!meta->map_ptr) {
2032 /* in function declaration map_ptr must come before
2033 * map_key, so that it's verified and known before
2034 * we have to check map_key here. Otherwise it means
2035 * that kernel subsystem misconfigured verifier
2037 verbose(env, "invalid map_ptr to access map->key\n");
2040 err = check_helper_mem_access(env, regno,
2041 meta->map_ptr->key_size, false,
2043 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
2044 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2045 * check [value, value + map->value_size) validity
2047 if (!meta->map_ptr) {
2048 /* kernel subsystem misconfigured verifier */
2049 verbose(env, "invalid map_ptr to access map->value\n");
2052 err = check_helper_mem_access(env, regno,
2053 meta->map_ptr->value_size, false,
2055 } else if (arg_type_is_mem_size(arg_type)) {
2056 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2058 /* remember the mem_size which may be used later
2059 * to refine return values.
2061 meta->msize_max_value = reg->umax_value;
2063 /* The register is SCALAR_VALUE; the access check
2064 * happens using its boundaries.
2066 if (!tnum_is_const(reg->var_off))
2067 /* For unprivileged variable accesses, disable raw
2068 * mode so that the program is required to
2069 * initialize all the memory that the helper could
2070 * just partially fill up.
2074 if (reg->smin_value < 0) {
2075 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2080 if (reg->umin_value == 0) {
2081 err = check_helper_mem_access(env, regno - 1, 0,
2088 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2089 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2093 err = check_helper_mem_access(env, regno - 1,
2095 zero_size_allowed, meta);
2100 verbose(env, "R%d type=%s expected=%s\n", regno,
2101 reg_type_str[type], reg_type_str[expected_type]);
2105 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2106 struct bpf_map *map, int func_id)
2111 /* We need a two way check, first is from map perspective ... */
2112 switch (map->map_type) {
2113 case BPF_MAP_TYPE_PROG_ARRAY:
2114 if (func_id != BPF_FUNC_tail_call)
2117 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2118 if (func_id != BPF_FUNC_perf_event_read &&
2119 func_id != BPF_FUNC_perf_event_output &&
2120 func_id != BPF_FUNC_perf_event_read_value)
2123 case BPF_MAP_TYPE_STACK_TRACE:
2124 if (func_id != BPF_FUNC_get_stackid)
2127 case BPF_MAP_TYPE_CGROUP_ARRAY:
2128 if (func_id != BPF_FUNC_skb_under_cgroup &&
2129 func_id != BPF_FUNC_current_task_under_cgroup)
2132 case BPF_MAP_TYPE_CGROUP_STORAGE:
2133 if (func_id != BPF_FUNC_get_local_storage)
2136 /* devmap returns a pointer to a live net_device ifindex that we cannot
2137 * allow to be modified from bpf side. So do not allow lookup elements
2140 case BPF_MAP_TYPE_DEVMAP:
2141 if (func_id != BPF_FUNC_redirect_map)
2144 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2147 case BPF_MAP_TYPE_CPUMAP:
2148 case BPF_MAP_TYPE_XSKMAP:
2149 if (func_id != BPF_FUNC_redirect_map)
2152 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2153 case BPF_MAP_TYPE_HASH_OF_MAPS:
2154 if (func_id != BPF_FUNC_map_lookup_elem)
2157 case BPF_MAP_TYPE_SOCKMAP:
2158 if (func_id != BPF_FUNC_sk_redirect_map &&
2159 func_id != BPF_FUNC_sock_map_update &&
2160 func_id != BPF_FUNC_map_delete_elem &&
2161 func_id != BPF_FUNC_msg_redirect_map)
2164 case BPF_MAP_TYPE_SOCKHASH:
2165 if (func_id != BPF_FUNC_sk_redirect_hash &&
2166 func_id != BPF_FUNC_sock_hash_update &&
2167 func_id != BPF_FUNC_map_delete_elem &&
2168 func_id != BPF_FUNC_msg_redirect_hash)
2171 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2172 if (func_id != BPF_FUNC_sk_select_reuseport)
2179 /* ... and second from the function itself. */
2181 case BPF_FUNC_tail_call:
2182 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2184 if (env->subprog_cnt > 1) {
2185 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2189 case BPF_FUNC_perf_event_read:
2190 case BPF_FUNC_perf_event_output:
2191 case BPF_FUNC_perf_event_read_value:
2192 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2195 case BPF_FUNC_get_stackid:
2196 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2199 case BPF_FUNC_current_task_under_cgroup:
2200 case BPF_FUNC_skb_under_cgroup:
2201 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2204 case BPF_FUNC_redirect_map:
2205 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2206 map->map_type != BPF_MAP_TYPE_CPUMAP &&
2207 map->map_type != BPF_MAP_TYPE_XSKMAP)
2210 case BPF_FUNC_sk_redirect_map:
2211 case BPF_FUNC_msg_redirect_map:
2212 case BPF_FUNC_sock_map_update:
2213 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2216 case BPF_FUNC_sk_redirect_hash:
2217 case BPF_FUNC_msg_redirect_hash:
2218 case BPF_FUNC_sock_hash_update:
2219 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2222 case BPF_FUNC_get_local_storage:
2223 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
2226 case BPF_FUNC_sk_select_reuseport:
2227 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2236 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2237 map->map_type, func_id_name(func_id), func_id);
2241 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2245 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2247 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2249 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2251 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2253 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2256 /* We only support one arg being in raw mode at the moment,
2257 * which is sufficient for the helper functions we have
2263 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2264 enum bpf_arg_type arg_next)
2266 return (arg_type_is_mem_ptr(arg_curr) &&
2267 !arg_type_is_mem_size(arg_next)) ||
2268 (!arg_type_is_mem_ptr(arg_curr) &&
2269 arg_type_is_mem_size(arg_next));
2272 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2274 /* bpf_xxx(..., buf, len) call will access 'len'
2275 * bytes from memory 'buf'. Both arg types need
2276 * to be paired, so make sure there's no buggy
2277 * helper function specification.
2279 if (arg_type_is_mem_size(fn->arg1_type) ||
2280 arg_type_is_mem_ptr(fn->arg5_type) ||
2281 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2282 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2283 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2284 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2290 static int check_func_proto(const struct bpf_func_proto *fn)
2292 return check_raw_mode_ok(fn) &&
2293 check_arg_pair_ok(fn) ? 0 : -EINVAL;
2296 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2297 * are now invalid, so turn them into unknown SCALAR_VALUE.
2299 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2300 struct bpf_func_state *state)
2302 struct bpf_reg_state *regs = state->regs, *reg;
2305 for (i = 0; i < MAX_BPF_REG; i++)
2306 if (reg_is_pkt_pointer_any(®s[i]))
2307 mark_reg_unknown(env, regs, i);
2309 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2310 if (state->stack[i].slot_type[0] != STACK_SPILL)
2312 reg = &state->stack[i].spilled_ptr;
2313 if (reg_is_pkt_pointer_any(reg))
2314 __mark_reg_unknown(reg);
2318 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2320 struct bpf_verifier_state *vstate = env->cur_state;
2323 for (i = 0; i <= vstate->curframe; i++)
2324 __clear_all_pkt_pointers(env, vstate->frame[i]);
2327 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2330 struct bpf_verifier_state *state = env->cur_state;
2331 struct bpf_func_state *caller, *callee;
2332 int i, subprog, target_insn;
2334 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2335 verbose(env, "the call stack of %d frames is too deep\n",
2336 state->curframe + 2);
2340 target_insn = *insn_idx + insn->imm;
2341 subprog = find_subprog(env, target_insn + 1);
2343 verbose(env, "verifier bug. No program starts at insn %d\n",
2348 caller = state->frame[state->curframe];
2349 if (state->frame[state->curframe + 1]) {
2350 verbose(env, "verifier bug. Frame %d already allocated\n",
2351 state->curframe + 1);
2355 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2358 state->frame[state->curframe + 1] = callee;
2360 /* callee cannot access r0, r6 - r9 for reading and has to write
2361 * into its own stack before reading from it.
2362 * callee can read/write into caller's stack
2364 init_func_state(env, callee,
2365 /* remember the callsite, it will be used by bpf_exit */
2366 *insn_idx /* callsite */,
2367 state->curframe + 1 /* frameno within this callchain */,
2368 subprog /* subprog number within this prog */);
2370 /* copy r1 - r5 args that callee can access. The copy includes parent
2371 * pointers, which connects us up to the liveness chain
2373 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2374 callee->regs[i] = caller->regs[i];
2376 /* after the call registers r0 - r5 were scratched */
2377 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2378 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2379 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2382 /* only increment it after check_reg_arg() finished */
2385 /* and go analyze first insn of the callee */
2386 *insn_idx = target_insn;
2388 if (env->log.level) {
2389 verbose(env, "caller:\n");
2390 print_verifier_state(env, caller);
2391 verbose(env, "callee:\n");
2392 print_verifier_state(env, callee);
2397 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2399 struct bpf_verifier_state *state = env->cur_state;
2400 struct bpf_func_state *caller, *callee;
2401 struct bpf_reg_state *r0;
2403 callee = state->frame[state->curframe];
2404 r0 = &callee->regs[BPF_REG_0];
2405 if (r0->type == PTR_TO_STACK) {
2406 /* technically it's ok to return caller's stack pointer
2407 * (or caller's caller's pointer) back to the caller,
2408 * since these pointers are valid. Only current stack
2409 * pointer will be invalid as soon as function exits,
2410 * but let's be conservative
2412 verbose(env, "cannot return stack pointer to the caller\n");
2417 caller = state->frame[state->curframe];
2418 /* return to the caller whatever r0 had in the callee */
2419 caller->regs[BPF_REG_0] = *r0;
2421 *insn_idx = callee->callsite + 1;
2422 if (env->log.level) {
2423 verbose(env, "returning from callee:\n");
2424 print_verifier_state(env, callee);
2425 verbose(env, "to caller at %d:\n", *insn_idx);
2426 print_verifier_state(env, caller);
2428 /* clear everything in the callee */
2429 free_func_state(callee);
2430 state->frame[state->curframe + 1] = NULL;
2434 static int do_refine_retval_range(struct bpf_verifier_env *env,
2435 struct bpf_reg_state *regs, int ret_type,
2436 int func_id, struct bpf_call_arg_meta *meta)
2438 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
2439 struct bpf_reg_state tmp_reg = *ret_reg;
2442 if (ret_type != RET_INTEGER ||
2443 (func_id != BPF_FUNC_get_stack &&
2444 func_id != BPF_FUNC_probe_read_str))
2447 /* Error case where ret is in interval [S32MIN, -1]. */
2448 ret_reg->smin_value = S32_MIN;
2449 ret_reg->smax_value = -1;
2451 __reg_deduce_bounds(ret_reg);
2452 __reg_bound_offset(ret_reg);
2453 __update_reg_bounds(ret_reg);
2455 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
2461 /* Success case where ret is in range [0, msize_max_value]. */
2462 ret_reg->smin_value = 0;
2463 ret_reg->smax_value = meta->msize_max_value;
2464 ret_reg->umin_value = ret_reg->smin_value;
2465 ret_reg->umax_value = ret_reg->smax_value;
2467 __reg_deduce_bounds(ret_reg);
2468 __reg_bound_offset(ret_reg);
2469 __update_reg_bounds(ret_reg);
2475 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2476 int func_id, int insn_idx)
2478 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2480 if (func_id != BPF_FUNC_tail_call &&
2481 func_id != BPF_FUNC_map_lookup_elem &&
2482 func_id != BPF_FUNC_map_update_elem &&
2483 func_id != BPF_FUNC_map_delete_elem)
2486 if (meta->map_ptr == NULL) {
2487 verbose(env, "kernel subsystem misconfigured verifier\n");
2491 if (!BPF_MAP_PTR(aux->map_state))
2492 bpf_map_ptr_store(aux, meta->map_ptr,
2493 meta->map_ptr->unpriv_array);
2494 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2495 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2496 meta->map_ptr->unpriv_array);
2500 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2502 const struct bpf_func_proto *fn = NULL;
2503 struct bpf_reg_state *regs;
2504 struct bpf_call_arg_meta meta;
2508 /* find function prototype */
2509 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2510 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2515 if (env->ops->get_func_proto)
2516 fn = env->ops->get_func_proto(func_id, env->prog);
2518 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2523 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2524 if (!env->prog->gpl_compatible && fn->gpl_only) {
2525 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2529 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2530 changes_data = bpf_helper_changes_pkt_data(fn->func);
2531 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2532 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2533 func_id_name(func_id), func_id);
2537 memset(&meta, 0, sizeof(meta));
2538 meta.pkt_access = fn->pkt_access;
2540 err = check_func_proto(fn);
2542 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2543 func_id_name(func_id), func_id);
2548 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2551 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2554 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2557 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2560 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2564 err = record_func_map(env, &meta, func_id, insn_idx);
2568 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2569 * is inferred from register state.
2571 for (i = 0; i < meta.access_size; i++) {
2572 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2573 BPF_WRITE, -1, false);
2578 regs = cur_regs(env);
2580 /* check that flags argument in get_local_storage(map, flags) is 0,
2581 * this is required because get_local_storage() can't return an error.
2583 if (func_id == BPF_FUNC_get_local_storage &&
2584 !register_is_null(®s[BPF_REG_2])) {
2585 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
2589 /* reset caller saved regs */
2590 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2591 mark_reg_not_init(env, regs, caller_saved[i]);
2592 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2595 /* update return register (already marked as written above) */
2596 if (fn->ret_type == RET_INTEGER) {
2597 /* sets type to SCALAR_VALUE */
2598 mark_reg_unknown(env, regs, BPF_REG_0);
2599 } else if (fn->ret_type == RET_VOID) {
2600 regs[BPF_REG_0].type = NOT_INIT;
2601 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
2602 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2603 if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
2604 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
2606 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2607 /* There is no offset yet applied, variable or fixed */
2608 mark_reg_known_zero(env, regs, BPF_REG_0);
2609 /* remember map_ptr, so that check_map_access()
2610 * can check 'value_size' boundary of memory access
2611 * to map element returned from bpf_map_lookup_elem()
2613 if (meta.map_ptr == NULL) {
2615 "kernel subsystem misconfigured verifier\n");
2618 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2619 regs[BPF_REG_0].id = ++env->id_gen;
2621 verbose(env, "unknown return type %d of func %s#%d\n",
2622 fn->ret_type, func_id_name(func_id), func_id);
2626 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
2630 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2634 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
2635 const char *err_str;
2637 #ifdef CONFIG_PERF_EVENTS
2638 err = get_callchain_buffers(sysctl_perf_event_max_stack);
2639 err_str = "cannot get callchain buffer for func %s#%d\n";
2642 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
2645 verbose(env, err_str, func_id_name(func_id), func_id);
2649 env->prog->has_callchain_buf = true;
2653 clear_all_pkt_pointers(env);
2657 static bool signed_add_overflows(s64 a, s64 b)
2659 /* Do the add in u64, where overflow is well-defined */
2660 s64 res = (s64)((u64)a + (u64)b);
2667 static bool signed_sub_overflows(s64 a, s64 b)
2669 /* Do the sub in u64, where overflow is well-defined */
2670 s64 res = (s64)((u64)a - (u64)b);
2677 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2678 const struct bpf_reg_state *reg,
2679 enum bpf_reg_type type)
2681 bool known = tnum_is_const(reg->var_off);
2682 s64 val = reg->var_off.value;
2683 s64 smin = reg->smin_value;
2685 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2686 verbose(env, "math between %s pointer and %lld is not allowed\n",
2687 reg_type_str[type], val);
2691 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2692 verbose(env, "%s pointer offset %d is not allowed\n",
2693 reg_type_str[type], reg->off);
2697 if (smin == S64_MIN) {
2698 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2699 reg_type_str[type]);
2703 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2704 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2705 smin, reg_type_str[type]);
2712 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
2714 return &env->insn_aux_data[env->insn_idx];
2725 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
2726 u32 *alu_limit, bool mask_to_left)
2728 u32 max = 0, ptr_limit = 0;
2730 switch (ptr_reg->type) {
2732 /* Offset 0 is out-of-bounds, but acceptable start for the
2733 * left direction, see BPF_REG_FP. Also, unknown scalar
2734 * offset where we would need to deal with min/max bounds is
2735 * currently prohibited for unprivileged.
2737 max = MAX_BPF_STACK + mask_to_left;
2738 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
2740 case PTR_TO_MAP_VALUE:
2741 max = ptr_reg->map_ptr->value_size;
2742 ptr_limit = (mask_to_left ?
2743 ptr_reg->smin_value :
2744 ptr_reg->umax_value) + ptr_reg->off;
2750 if (ptr_limit >= max)
2751 return REASON_LIMIT;
2752 *alu_limit = ptr_limit;
2756 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
2757 const struct bpf_insn *insn)
2759 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
2762 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
2763 u32 alu_state, u32 alu_limit)
2765 /* If we arrived here from different branches with different
2766 * state or limits to sanitize, then this won't work.
2768 if (aux->alu_state &&
2769 (aux->alu_state != alu_state ||
2770 aux->alu_limit != alu_limit))
2771 return REASON_PATHS;
2773 /* Corresponding fixup done in fixup_bpf_calls(). */
2774 aux->alu_state = alu_state;
2775 aux->alu_limit = alu_limit;
2779 static int sanitize_val_alu(struct bpf_verifier_env *env,
2780 struct bpf_insn *insn)
2782 struct bpf_insn_aux_data *aux = cur_aux(env);
2784 if (can_skip_alu_sanitation(env, insn))
2787 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
2790 static bool sanitize_needed(u8 opcode)
2792 return opcode == BPF_ADD || opcode == BPF_SUB;
2795 struct bpf_sanitize_info {
2796 struct bpf_insn_aux_data aux;
2800 static struct bpf_verifier_state *
2801 sanitize_speculative_path(struct bpf_verifier_env *env,
2802 const struct bpf_insn *insn,
2803 u32 next_idx, u32 curr_idx)
2805 struct bpf_verifier_state *branch;
2806 struct bpf_reg_state *regs;
2808 branch = push_stack(env, next_idx, curr_idx, true);
2809 if (branch && insn) {
2810 regs = branch->frame[branch->curframe]->regs;
2811 if (BPF_SRC(insn->code) == BPF_K) {
2812 mark_reg_unknown(env, regs, insn->dst_reg);
2813 } else if (BPF_SRC(insn->code) == BPF_X) {
2814 mark_reg_unknown(env, regs, insn->dst_reg);
2815 mark_reg_unknown(env, regs, insn->src_reg);
2821 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
2822 struct bpf_insn *insn,
2823 const struct bpf_reg_state *ptr_reg,
2824 const struct bpf_reg_state *off_reg,
2825 struct bpf_reg_state *dst_reg,
2826 struct bpf_sanitize_info *info,
2827 const bool commit_window)
2829 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
2830 struct bpf_verifier_state *vstate = env->cur_state;
2831 bool off_is_imm = tnum_is_const(off_reg->var_off);
2832 bool off_is_neg = off_reg->smin_value < 0;
2833 bool ptr_is_dst_reg = ptr_reg == dst_reg;
2834 u8 opcode = BPF_OP(insn->code);
2835 u32 alu_state, alu_limit;
2836 struct bpf_reg_state tmp;
2840 if (can_skip_alu_sanitation(env, insn))
2843 /* We already marked aux for masking from non-speculative
2844 * paths, thus we got here in the first place. We only care
2845 * to explore bad access from here.
2847 if (vstate->speculative)
2850 if (!commit_window) {
2851 if (!tnum_is_const(off_reg->var_off) &&
2852 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
2853 return REASON_BOUNDS;
2855 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
2856 (opcode == BPF_SUB && !off_is_neg);
2859 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
2863 if (commit_window) {
2864 /* In commit phase we narrow the masking window based on
2865 * the observed pointer move after the simulated operation.
2867 alu_state = info->aux.alu_state;
2868 alu_limit = abs(info->aux.alu_limit - alu_limit);
2870 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
2871 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
2872 alu_state |= ptr_is_dst_reg ?
2873 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
2875 /* Limit pruning on unknown scalars to enable deep search for
2876 * potential masking differences from other program paths.
2879 env->explore_alu_limits = true;
2882 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
2886 /* If we're in commit phase, we're done here given we already
2887 * pushed the truncated dst_reg into the speculative verification
2890 * Also, when register is a known constant, we rewrite register-based
2891 * operation to immediate-based, and thus do not need masking (and as
2892 * a consequence, do not need to simulate the zero-truncation either).
2894 if (commit_window || off_is_imm)
2897 /* Simulate and find potential out-of-bounds access under
2898 * speculative execution from truncation as a result of
2899 * masking when off was not within expected range. If off
2900 * sits in dst, then we temporarily need to move ptr there
2901 * to simulate dst (== 0) +/-= ptr. Needed, for example,
2902 * for cases where we use K-based arithmetic in one direction
2903 * and truncated reg-based in the other in order to explore
2906 if (!ptr_is_dst_reg) {
2908 *dst_reg = *ptr_reg;
2910 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
2912 if (!ptr_is_dst_reg && ret)
2914 return !ret ? REASON_STACK : 0;
2917 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
2919 struct bpf_verifier_state *vstate = env->cur_state;
2921 /* If we simulate paths under speculation, we don't update the
2922 * insn as 'seen' such that when we verify unreachable paths in
2923 * the non-speculative domain, sanitize_dead_code() can still
2924 * rewrite/sanitize them.
2926 if (!vstate->speculative)
2927 env->insn_aux_data[env->insn_idx].seen = true;
2930 static int sanitize_err(struct bpf_verifier_env *env,
2931 const struct bpf_insn *insn, int reason,
2932 const struct bpf_reg_state *off_reg,
2933 const struct bpf_reg_state *dst_reg)
2935 static const char *err = "pointer arithmetic with it prohibited for !root";
2936 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
2937 u32 dst = insn->dst_reg, src = insn->src_reg;
2941 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
2942 off_reg == dst_reg ? dst : src, err);
2945 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
2946 off_reg == dst_reg ? src : dst, err);
2949 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
2953 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
2957 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
2961 verbose(env, "verifier internal error: unknown reason (%d)\n",
2969 static int sanitize_check_bounds(struct bpf_verifier_env *env,
2970 const struct bpf_insn *insn,
2971 const struct bpf_reg_state *dst_reg)
2973 u32 dst = insn->dst_reg;
2975 /* For unprivileged we require that resulting offset must be in bounds
2976 * in order to be able to sanitize access later on.
2978 if (env->allow_ptr_leaks)
2981 switch (dst_reg->type) {
2983 if (check_stack_access(env, dst_reg, dst_reg->off +
2984 dst_reg->var_off.value, 1)) {
2985 verbose(env, "R%d stack pointer arithmetic goes out of range, "
2986 "prohibited for !root\n", dst);
2990 case PTR_TO_MAP_VALUE:
2991 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
2992 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
2993 "prohibited for !root\n", dst);
3004 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
3005 * Caller should also handle BPF_MOV case separately.
3006 * If we return -EACCES, caller may want to try again treating pointer as a
3007 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
3009 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
3010 struct bpf_insn *insn,
3011 const struct bpf_reg_state *ptr_reg,
3012 const struct bpf_reg_state *off_reg)
3014 struct bpf_verifier_state *vstate = env->cur_state;
3015 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3016 struct bpf_reg_state *regs = state->regs, *dst_reg;
3017 bool known = tnum_is_const(off_reg->var_off);
3018 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
3019 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
3020 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
3021 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3022 struct bpf_sanitize_info info = {};
3023 u8 opcode = BPF_OP(insn->code);
3024 u32 dst = insn->dst_reg;
3027 dst_reg = ®s[dst];
3029 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
3030 smin_val > smax_val || umin_val > umax_val) {
3031 /* Taint dst register if offset had invalid bounds derived from
3032 * e.g. dead branches.
3034 __mark_reg_unknown(dst_reg);
3038 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3039 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
3041 "R%d 32-bit pointer arithmetic prohibited\n",
3046 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3047 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
3051 if (ptr_reg->type == CONST_PTR_TO_MAP) {
3052 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
3056 if (ptr_reg->type == PTR_TO_PACKET_END) {
3057 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
3062 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3063 * The id may be overwritten later if we create a new variable offset.
3065 dst_reg->type = ptr_reg->type;
3066 dst_reg->id = ptr_reg->id;
3068 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3069 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3072 if (sanitize_needed(opcode)) {
3073 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3076 return sanitize_err(env, insn, ret, off_reg, dst_reg);
3081 /* We can take a fixed offset as long as it doesn't overflow
3082 * the s32 'off' field
3084 if (known && (ptr_reg->off + smin_val ==
3085 (s64)(s32)(ptr_reg->off + smin_val))) {
3086 /* pointer += K. Accumulate it into fixed offset */
3087 dst_reg->smin_value = smin_ptr;
3088 dst_reg->smax_value = smax_ptr;
3089 dst_reg->umin_value = umin_ptr;
3090 dst_reg->umax_value = umax_ptr;
3091 dst_reg->var_off = ptr_reg->var_off;
3092 dst_reg->off = ptr_reg->off + smin_val;
3093 dst_reg->raw = ptr_reg->raw;
3096 /* A new variable offset is created. Note that off_reg->off
3097 * == 0, since it's a scalar.
3098 * dst_reg gets the pointer type and since some positive
3099 * integer value was added to the pointer, give it a new 'id'
3100 * if it's a PTR_TO_PACKET.
3101 * this creates a new 'base' pointer, off_reg (variable) gets
3102 * added into the variable offset, and we copy the fixed offset
3105 if (signed_add_overflows(smin_ptr, smin_val) ||
3106 signed_add_overflows(smax_ptr, smax_val)) {
3107 dst_reg->smin_value = S64_MIN;
3108 dst_reg->smax_value = S64_MAX;
3110 dst_reg->smin_value = smin_ptr + smin_val;
3111 dst_reg->smax_value = smax_ptr + smax_val;
3113 if (umin_ptr + umin_val < umin_ptr ||
3114 umax_ptr + umax_val < umax_ptr) {
3115 dst_reg->umin_value = 0;
3116 dst_reg->umax_value = U64_MAX;
3118 dst_reg->umin_value = umin_ptr + umin_val;
3119 dst_reg->umax_value = umax_ptr + umax_val;
3121 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3122 dst_reg->off = ptr_reg->off;
3123 dst_reg->raw = ptr_reg->raw;
3124 if (reg_is_pkt_pointer(ptr_reg)) {
3125 dst_reg->id = ++env->id_gen;
3126 /* something was added to pkt_ptr, set range to zero */
3131 if (dst_reg == off_reg) {
3132 /* scalar -= pointer. Creates an unknown scalar */
3133 verbose(env, "R%d tried to subtract pointer from scalar\n",
3137 /* We don't allow subtraction from FP, because (according to
3138 * test_verifier.c test "invalid fp arithmetic", JITs might not
3139 * be able to deal with it.
3141 if (ptr_reg->type == PTR_TO_STACK) {
3142 verbose(env, "R%d subtraction from stack pointer prohibited\n",
3146 if (known && (ptr_reg->off - smin_val ==
3147 (s64)(s32)(ptr_reg->off - smin_val))) {
3148 /* pointer -= K. Subtract it from fixed offset */
3149 dst_reg->smin_value = smin_ptr;
3150 dst_reg->smax_value = smax_ptr;
3151 dst_reg->umin_value = umin_ptr;
3152 dst_reg->umax_value = umax_ptr;
3153 dst_reg->var_off = ptr_reg->var_off;
3154 dst_reg->id = ptr_reg->id;
3155 dst_reg->off = ptr_reg->off - smin_val;
3156 dst_reg->raw = ptr_reg->raw;
3159 /* A new variable offset is created. If the subtrahend is known
3160 * nonnegative, then any reg->range we had before is still good.
3162 if (signed_sub_overflows(smin_ptr, smax_val) ||
3163 signed_sub_overflows(smax_ptr, smin_val)) {
3164 /* Overflow possible, we know nothing */
3165 dst_reg->smin_value = S64_MIN;
3166 dst_reg->smax_value = S64_MAX;
3168 dst_reg->smin_value = smin_ptr - smax_val;
3169 dst_reg->smax_value = smax_ptr - smin_val;
3171 if (umin_ptr < umax_val) {
3172 /* Overflow possible, we know nothing */
3173 dst_reg->umin_value = 0;
3174 dst_reg->umax_value = U64_MAX;
3176 /* Cannot overflow (as long as bounds are consistent) */
3177 dst_reg->umin_value = umin_ptr - umax_val;
3178 dst_reg->umax_value = umax_ptr - umin_val;
3180 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3181 dst_reg->off = ptr_reg->off;
3182 dst_reg->raw = ptr_reg->raw;
3183 if (reg_is_pkt_pointer(ptr_reg)) {
3184 dst_reg->id = ++env->id_gen;
3185 /* something was added to pkt_ptr, set range to zero */
3193 /* bitwise ops on pointers are troublesome, prohibit. */
3194 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3195 dst, bpf_alu_string[opcode >> 4]);
3198 /* other operators (e.g. MUL,LSH) produce non-pointer results */
3199 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3200 dst, bpf_alu_string[opcode >> 4]);
3204 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3207 __update_reg_bounds(dst_reg);
3208 __reg_deduce_bounds(dst_reg);
3209 __reg_bound_offset(dst_reg);
3211 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
3213 if (sanitize_needed(opcode)) {
3214 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3217 return sanitize_err(env, insn, ret, off_reg, dst_reg);
3223 /* WARNING: This function does calculations on 64-bit values, but the actual
3224 * execution may occur on 32-bit values. Therefore, things like bitshifts
3225 * need extra checks in the 32-bit case.
3227 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3228 struct bpf_insn *insn,
3229 struct bpf_reg_state *dst_reg,
3230 struct bpf_reg_state src_reg)
3232 struct bpf_reg_state *regs = cur_regs(env);
3233 u8 opcode = BPF_OP(insn->code);
3234 bool src_known, dst_known;
3235 s64 smin_val, smax_val;
3236 u64 umin_val, umax_val;
3237 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3240 if (insn_bitness == 32) {
3241 /* Relevant for 32-bit RSH: Information can propagate towards
3242 * LSB, so it isn't sufficient to only truncate the output to
3245 coerce_reg_to_size(dst_reg, 4);
3246 coerce_reg_to_size(&src_reg, 4);
3249 smin_val = src_reg.smin_value;
3250 smax_val = src_reg.smax_value;
3251 umin_val = src_reg.umin_value;
3252 umax_val = src_reg.umax_value;
3253 src_known = tnum_is_const(src_reg.var_off);
3254 dst_known = tnum_is_const(dst_reg->var_off);
3256 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3257 smin_val > smax_val || umin_val > umax_val) {
3258 /* Taint dst register if offset had invalid bounds derived from
3259 * e.g. dead branches.
3261 __mark_reg_unknown(dst_reg);
3266 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3267 __mark_reg_unknown(dst_reg);
3271 if (sanitize_needed(opcode)) {
3272 ret = sanitize_val_alu(env, insn);
3274 return sanitize_err(env, insn, ret, NULL, NULL);
3279 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3280 signed_add_overflows(dst_reg->smax_value, smax_val)) {
3281 dst_reg->smin_value = S64_MIN;
3282 dst_reg->smax_value = S64_MAX;
3284 dst_reg->smin_value += smin_val;
3285 dst_reg->smax_value += smax_val;
3287 if (dst_reg->umin_value + umin_val < umin_val ||
3288 dst_reg->umax_value + umax_val < umax_val) {
3289 dst_reg->umin_value = 0;
3290 dst_reg->umax_value = U64_MAX;
3292 dst_reg->umin_value += umin_val;
3293 dst_reg->umax_value += umax_val;
3295 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
3298 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3299 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3300 /* Overflow possible, we know nothing */
3301 dst_reg->smin_value = S64_MIN;
3302 dst_reg->smax_value = S64_MAX;
3304 dst_reg->smin_value -= smax_val;
3305 dst_reg->smax_value -= smin_val;
3307 if (dst_reg->umin_value < umax_val) {
3308 /* Overflow possible, we know nothing */
3309 dst_reg->umin_value = 0;
3310 dst_reg->umax_value = U64_MAX;
3312 /* Cannot overflow (as long as bounds are consistent) */
3313 dst_reg->umin_value -= umax_val;
3314 dst_reg->umax_value -= umin_val;
3316 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
3319 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3320 if (smin_val < 0 || dst_reg->smin_value < 0) {
3321 /* Ain't nobody got time to multiply that sign */
3322 __mark_reg_unbounded(dst_reg);
3323 __update_reg_bounds(dst_reg);
3326 /* Both values are positive, so we can work with unsigned and
3327 * copy the result to signed (unless it exceeds S64_MAX).
3329 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3330 /* Potential overflow, we know nothing */
3331 __mark_reg_unbounded(dst_reg);
3332 /* (except what we can learn from the var_off) */
3333 __update_reg_bounds(dst_reg);
3336 dst_reg->umin_value *= umin_val;
3337 dst_reg->umax_value *= umax_val;
3338 if (dst_reg->umax_value > S64_MAX) {
3339 /* Overflow possible, we know nothing */
3340 dst_reg->smin_value = S64_MIN;
3341 dst_reg->smax_value = S64_MAX;
3343 dst_reg->smin_value = dst_reg->umin_value;
3344 dst_reg->smax_value = dst_reg->umax_value;
3348 if (src_known && dst_known) {
3349 __mark_reg_known(dst_reg, dst_reg->var_off.value &
3350 src_reg.var_off.value);
3353 /* We get our minimum from the var_off, since that's inherently
3354 * bitwise. Our maximum is the minimum of the operands' maxima.
3356 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
3357 dst_reg->umin_value = dst_reg->var_off.value;
3358 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3359 if (dst_reg->smin_value < 0 || smin_val < 0) {
3360 /* Lose signed bounds when ANDing negative numbers,
3361 * ain't nobody got time for that.
3363 dst_reg->smin_value = S64_MIN;
3364 dst_reg->smax_value = S64_MAX;
3366 /* ANDing two positives gives a positive, so safe to
3367 * cast result into s64.
3369 dst_reg->smin_value = dst_reg->umin_value;
3370 dst_reg->smax_value = dst_reg->umax_value;
3372 /* We may learn something more from the var_off */
3373 __update_reg_bounds(dst_reg);
3376 if (src_known && dst_known) {
3377 __mark_reg_known(dst_reg, dst_reg->var_off.value |
3378 src_reg.var_off.value);
3381 /* We get our maximum from the var_off, and our minimum is the
3382 * maximum of the operands' minima
3384 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
3385 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
3386 dst_reg->umax_value = dst_reg->var_off.value |
3387 dst_reg->var_off.mask;
3388 if (dst_reg->smin_value < 0 || smin_val < 0) {
3389 /* Lose signed bounds when ORing negative numbers,
3390 * ain't nobody got time for that.
3392 dst_reg->smin_value = S64_MIN;
3393 dst_reg->smax_value = S64_MAX;
3395 /* ORing two positives gives a positive, so safe to
3396 * cast result into s64.
3398 dst_reg->smin_value = dst_reg->umin_value;
3399 dst_reg->smax_value = dst_reg->umax_value;
3401 /* We may learn something more from the var_off */
3402 __update_reg_bounds(dst_reg);
3405 if (umax_val >= insn_bitness) {
3406 /* Shifts greater than 31 or 63 are undefined.
3407 * This includes shifts by a negative number.
3409 mark_reg_unknown(env, regs, insn->dst_reg);
3412 /* We lose all sign bit information (except what we can pick
3415 dst_reg->smin_value = S64_MIN;
3416 dst_reg->smax_value = S64_MAX;
3417 /* If we might shift our top bit out, then we know nothing */
3418 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
3419 dst_reg->umin_value = 0;
3420 dst_reg->umax_value = U64_MAX;
3422 dst_reg->umin_value <<= umin_val;
3423 dst_reg->umax_value <<= umax_val;
3425 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
3426 /* We may learn something more from the var_off */
3427 __update_reg_bounds(dst_reg);
3430 if (umax_val >= insn_bitness) {
3431 /* Shifts greater than 31 or 63 are undefined.
3432 * This includes shifts by a negative number.
3434 mark_reg_unknown(env, regs, insn->dst_reg);
3437 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
3438 * be negative, then either:
3439 * 1) src_reg might be zero, so the sign bit of the result is
3440 * unknown, so we lose our signed bounds
3441 * 2) it's known negative, thus the unsigned bounds capture the
3443 * 3) the signed bounds cross zero, so they tell us nothing
3445 * If the value in dst_reg is known nonnegative, then again the
3446 * unsigned bounts capture the signed bounds.
3447 * Thus, in all cases it suffices to blow away our signed bounds
3448 * and rely on inferring new ones from the unsigned bounds and
3449 * var_off of the result.
3451 dst_reg->smin_value = S64_MIN;
3452 dst_reg->smax_value = S64_MAX;
3453 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3454 dst_reg->umin_value >>= umax_val;
3455 dst_reg->umax_value >>= umin_val;
3456 /* We may learn something more from the var_off */
3457 __update_reg_bounds(dst_reg);
3460 if (umax_val >= insn_bitness) {
3461 /* Shifts greater than 31 or 63 are undefined.
3462 * This includes shifts by a negative number.
3464 mark_reg_unknown(env, regs, insn->dst_reg);
3468 /* Upon reaching here, src_known is true and
3469 * umax_val is equal to umin_val.
3471 if (insn_bitness == 32) {
3472 dst_reg->smin_value = (u32)(((s32)dst_reg->smin_value) >> umin_val);
3473 dst_reg->smax_value = (u32)(((s32)dst_reg->smax_value) >> umin_val);
3475 dst_reg->smin_value >>= umin_val;
3476 dst_reg->smax_value >>= umin_val;
3479 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val,
3482 /* blow away the dst_reg umin_value/umax_value and rely on
3483 * dst_reg var_off to refine the result.
3485 dst_reg->umin_value = 0;
3486 dst_reg->umax_value = U64_MAX;
3487 __update_reg_bounds(dst_reg);
3490 mark_reg_unknown(env, regs, insn->dst_reg);
3494 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3495 /* 32-bit ALU ops are (32,32)->32 */
3496 coerce_reg_to_size(dst_reg, 4);
3499 __reg_deduce_bounds(dst_reg);
3500 __reg_bound_offset(dst_reg);
3504 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3507 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3508 struct bpf_insn *insn)
3510 struct bpf_verifier_state *vstate = env->cur_state;
3511 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3512 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3513 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3514 u8 opcode = BPF_OP(insn->code);
3516 dst_reg = ®s[insn->dst_reg];
3518 if (dst_reg->type != SCALAR_VALUE)
3520 if (BPF_SRC(insn->code) == BPF_X) {
3521 src_reg = ®s[insn->src_reg];
3522 if (src_reg->type != SCALAR_VALUE) {
3523 if (dst_reg->type != SCALAR_VALUE) {
3524 /* Combining two pointers by any ALU op yields
3525 * an arbitrary scalar. Disallow all math except
3526 * pointer subtraction
3528 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
3529 mark_reg_unknown(env, regs, insn->dst_reg);
3532 verbose(env, "R%d pointer %s pointer prohibited\n",
3534 bpf_alu_string[opcode >> 4]);
3537 /* scalar += pointer
3538 * This is legal, but we have to reverse our
3539 * src/dest handling in computing the range
3541 return adjust_ptr_min_max_vals(env, insn,
3544 } else if (ptr_reg) {
3545 /* pointer += scalar */
3546 return adjust_ptr_min_max_vals(env, insn,
3550 /* Pretend the src is a reg with a known value, since we only
3551 * need to be able to read from this state.
3553 off_reg.type = SCALAR_VALUE;
3554 __mark_reg_known(&off_reg, insn->imm);
3556 if (ptr_reg) /* pointer += K */
3557 return adjust_ptr_min_max_vals(env, insn,
3561 /* Got here implies adding two SCALAR_VALUEs */
3562 if (WARN_ON_ONCE(ptr_reg)) {
3563 print_verifier_state(env, state);
3564 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3567 if (WARN_ON(!src_reg)) {
3568 print_verifier_state(env, state);
3569 verbose(env, "verifier internal error: no src_reg\n");
3572 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3575 /* check validity of 32-bit and 64-bit arithmetic operations */
3576 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3578 struct bpf_reg_state *regs = cur_regs(env);
3579 u8 opcode = BPF_OP(insn->code);
3582 if (opcode == BPF_END || opcode == BPF_NEG) {
3583 if (opcode == BPF_NEG) {
3584 if (BPF_SRC(insn->code) != 0 ||
3585 insn->src_reg != BPF_REG_0 ||
3586 insn->off != 0 || insn->imm != 0) {
3587 verbose(env, "BPF_NEG uses reserved fields\n");
3591 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3592 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3593 BPF_CLASS(insn->code) == BPF_ALU64) {
3594 verbose(env, "BPF_END uses reserved fields\n");
3599 /* check src operand */
3600 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3604 if (is_pointer_value(env, insn->dst_reg)) {
3605 verbose(env, "R%d pointer arithmetic prohibited\n",
3610 /* check dest operand */
3611 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3615 } else if (opcode == BPF_MOV) {
3617 if (BPF_SRC(insn->code) == BPF_X) {
3618 if (insn->imm != 0 || insn->off != 0) {
3619 verbose(env, "BPF_MOV uses reserved fields\n");
3623 /* check src operand */
3624 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3628 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3629 verbose(env, "BPF_MOV uses reserved fields\n");
3634 /* check dest operand, mark as required later */
3635 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3639 if (BPF_SRC(insn->code) == BPF_X) {
3640 struct bpf_reg_state *src_reg = regs + insn->src_reg;
3641 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
3643 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3645 * copy register state to dest reg
3647 *dst_reg = *src_reg;
3648 dst_reg->live |= REG_LIVE_WRITTEN;
3651 if (is_pointer_value(env, insn->src_reg)) {
3653 "R%d partial copy of pointer\n",
3656 } else if (src_reg->type == SCALAR_VALUE) {
3657 *dst_reg = *src_reg;
3658 dst_reg->live |= REG_LIVE_WRITTEN;
3660 mark_reg_unknown(env, regs,
3663 coerce_reg_to_size(dst_reg, 4);
3667 * remember the value we stored into this reg
3669 /* clear any state __mark_reg_known doesn't set */
3670 mark_reg_unknown(env, regs, insn->dst_reg);
3671 regs[insn->dst_reg].type = SCALAR_VALUE;
3672 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3673 __mark_reg_known(regs + insn->dst_reg,
3676 __mark_reg_known(regs + insn->dst_reg,
3681 } else if (opcode > BPF_END) {
3682 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3685 } else { /* all other ALU ops: and, sub, xor, add, ... */
3687 if (BPF_SRC(insn->code) == BPF_X) {
3688 if (insn->imm != 0 || insn->off != 0) {
3689 verbose(env, "BPF_ALU uses reserved fields\n");
3692 /* check src1 operand */
3693 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3697 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3698 verbose(env, "BPF_ALU uses reserved fields\n");
3703 /* check src2 operand */
3704 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3708 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3709 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3710 verbose(env, "div by zero\n");
3714 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3715 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3719 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3720 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3721 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3723 if (insn->imm < 0 || insn->imm >= size) {
3724 verbose(env, "invalid shift %d\n", insn->imm);
3729 /* check dest operand */
3730 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3734 return adjust_reg_min_max_vals(env, insn);
3740 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3741 struct bpf_reg_state *dst_reg,
3742 enum bpf_reg_type type,
3743 bool range_right_open)
3745 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3746 struct bpf_reg_state *regs = state->regs, *reg;
3750 if (dst_reg->off < 0 ||
3751 (dst_reg->off == 0 && range_right_open))
3752 /* This doesn't give us any range */
3755 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3756 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3757 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3758 * than pkt_end, but that's because it's also less than pkt.
3762 new_range = dst_reg->off;
3763 if (range_right_open)
3766 /* Examples for register markings:
3768 * pkt_data in dst register:
3772 * if (r2 > pkt_end) goto <handle exception>
3777 * if (r2 < pkt_end) goto <access okay>
3778 * <handle exception>
3781 * r2 == dst_reg, pkt_end == src_reg
3782 * r2=pkt(id=n,off=8,r=0)
3783 * r3=pkt(id=n,off=0,r=0)
3785 * pkt_data in src register:
3789 * if (pkt_end >= r2) goto <access okay>
3790 * <handle exception>
3794 * if (pkt_end <= r2) goto <handle exception>
3798 * pkt_end == dst_reg, r2 == src_reg
3799 * r2=pkt(id=n,off=8,r=0)
3800 * r3=pkt(id=n,off=0,r=0)
3802 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3803 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3804 * and [r3, r3 + 8-1) respectively is safe to access depending on
3808 /* If our ids match, then we must have the same max_value. And we
3809 * don't care about the other reg's fixed offset, since if it's too big
3810 * the range won't allow anything.
3811 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3813 for (i = 0; i < MAX_BPF_REG; i++)
3814 if (regs[i].type == type && regs[i].id == dst_reg->id)
3815 /* keep the maximum range already checked */
3816 regs[i].range = max(regs[i].range, new_range);
3818 for (j = 0; j <= vstate->curframe; j++) {
3819 state = vstate->frame[j];
3820 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3821 if (state->stack[i].slot_type[0] != STACK_SPILL)
3823 reg = &state->stack[i].spilled_ptr;
3824 if (reg->type == type && reg->id == dst_reg->id)
3825 reg->range = max(reg->range, new_range);
3830 /* compute branch direction of the expression "if (reg opcode val) goto target;"
3832 * 1 - branch will be taken and "goto target" will be executed
3833 * 0 - branch will not be taken and fall-through to next insn
3834 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
3836 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
3838 if (__is_pointer_value(false, reg))
3843 if (tnum_is_const(reg->var_off))
3844 return !!tnum_equals_const(reg->var_off, val);
3847 if (tnum_is_const(reg->var_off))
3848 return !tnum_equals_const(reg->var_off, val);
3851 if (reg->umin_value > val)
3853 else if (reg->umax_value <= val)
3857 if (reg->smin_value > (s64)val)
3859 else if (reg->smax_value < (s64)val)
3863 if (reg->umax_value < val)
3865 else if (reg->umin_value >= val)
3869 if (reg->smax_value < (s64)val)
3871 else if (reg->smin_value >= (s64)val)
3875 if (reg->umin_value >= val)
3877 else if (reg->umax_value < val)
3881 if (reg->smin_value >= (s64)val)
3883 else if (reg->smax_value < (s64)val)
3887 if (reg->umax_value <= val)
3889 else if (reg->umin_value > val)
3893 if (reg->smax_value <= (s64)val)
3895 else if (reg->smin_value > (s64)val)
3903 /* Adjusts the register min/max values in the case that the dst_reg is the
3904 * variable register that we are working on, and src_reg is a constant or we're
3905 * simply doing a BPF_K check.
3906 * In JEQ/JNE cases we also adjust the var_off values.
3908 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3909 struct bpf_reg_state *false_reg, u64 val,
3912 /* If the dst_reg is a pointer, we can't learn anything about its
3913 * variable offset from the compare (unless src_reg were a pointer into
3914 * the same object, but we don't bother with that.
3915 * Since false_reg and true_reg have the same type by construction, we
3916 * only need to check one of them for pointerness.
3918 if (__is_pointer_value(false, false_reg))
3923 /* If this is false then we know nothing Jon Snow, but if it is
3924 * true then we know for sure.
3926 __mark_reg_known(true_reg, val);
3929 /* If this is true we know nothing Jon Snow, but if it is false
3930 * we know the value for sure;
3932 __mark_reg_known(false_reg, val);
3935 false_reg->umax_value = min(false_reg->umax_value, val);
3936 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3939 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3940 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3943 false_reg->umin_value = max(false_reg->umin_value, val);
3944 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3947 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3948 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3951 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3952 true_reg->umin_value = max(true_reg->umin_value, val);
3955 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3956 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3959 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3960 true_reg->umax_value = min(true_reg->umax_value, val);
3963 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3964 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3970 __reg_deduce_bounds(false_reg);
3971 __reg_deduce_bounds(true_reg);
3972 /* We might have learned some bits from the bounds. */
3973 __reg_bound_offset(false_reg);
3974 __reg_bound_offset(true_reg);
3975 /* Intersecting with the old var_off might have improved our bounds
3976 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3977 * then new var_off is (0; 0x7f...fc) which improves our umax.
3979 __update_reg_bounds(false_reg);
3980 __update_reg_bounds(true_reg);
3983 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3986 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3987 struct bpf_reg_state *false_reg, u64 val,
3990 if (__is_pointer_value(false, false_reg))
3995 /* If this is false then we know nothing Jon Snow, but if it is
3996 * true then we know for sure.
3998 __mark_reg_known(true_reg, val);
4001 /* If this is true we know nothing Jon Snow, but if it is false
4002 * we know the value for sure;
4004 __mark_reg_known(false_reg, val);
4007 true_reg->umax_value = min(true_reg->umax_value, val - 1);
4008 false_reg->umin_value = max(false_reg->umin_value, val);
4011 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
4012 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
4015 true_reg->umin_value = max(true_reg->umin_value, val + 1);
4016 false_reg->umax_value = min(false_reg->umax_value, val);
4019 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
4020 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
4023 true_reg->umax_value = min(true_reg->umax_value, val);
4024 false_reg->umin_value = max(false_reg->umin_value, val + 1);
4027 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
4028 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
4031 true_reg->umin_value = max(true_reg->umin_value, val);
4032 false_reg->umax_value = min(false_reg->umax_value, val - 1);
4035 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
4036 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
4042 __reg_deduce_bounds(false_reg);
4043 __reg_deduce_bounds(true_reg);
4044 /* We might have learned some bits from the bounds. */
4045 __reg_bound_offset(false_reg);
4046 __reg_bound_offset(true_reg);
4047 /* Intersecting with the old var_off might have improved our bounds
4048 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4049 * then new var_off is (0; 0x7f...fc) which improves our umax.
4051 __update_reg_bounds(false_reg);
4052 __update_reg_bounds(true_reg);
4055 /* Regs are known to be equal, so intersect their min/max/var_off */
4056 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
4057 struct bpf_reg_state *dst_reg)
4059 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
4060 dst_reg->umin_value);
4061 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
4062 dst_reg->umax_value);
4063 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
4064 dst_reg->smin_value);
4065 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
4066 dst_reg->smax_value);
4067 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
4069 /* We might have learned new bounds from the var_off. */
4070 __update_reg_bounds(src_reg);
4071 __update_reg_bounds(dst_reg);
4072 /* We might have learned something about the sign bit. */
4073 __reg_deduce_bounds(src_reg);
4074 __reg_deduce_bounds(dst_reg);
4075 /* We might have learned some bits from the bounds. */
4076 __reg_bound_offset(src_reg);
4077 __reg_bound_offset(dst_reg);
4078 /* Intersecting with the old var_off might have improved our bounds
4079 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4080 * then new var_off is (0; 0x7f...fc) which improves our umax.
4082 __update_reg_bounds(src_reg);
4083 __update_reg_bounds(dst_reg);
4086 static void reg_combine_min_max(struct bpf_reg_state *true_src,
4087 struct bpf_reg_state *true_dst,
4088 struct bpf_reg_state *false_src,
4089 struct bpf_reg_state *false_dst,
4094 __reg_combine_min_max(true_src, true_dst);
4097 __reg_combine_min_max(false_src, false_dst);
4102 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
4105 struct bpf_reg_state *reg = ®s[regno];
4107 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
4108 /* Old offset (both fixed and variable parts) should
4109 * have been known-zero, because we don't allow pointer
4110 * arithmetic on pointers that might be NULL.
4112 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
4113 !tnum_equals_const(reg->var_off, 0) ||
4115 __mark_reg_known_zero(reg);
4119 reg->type = SCALAR_VALUE;
4120 } else if (reg->map_ptr->inner_map_meta) {
4121 reg->type = CONST_PTR_TO_MAP;
4122 reg->map_ptr = reg->map_ptr->inner_map_meta;
4124 reg->type = PTR_TO_MAP_VALUE;
4126 /* We don't need id from this point onwards anymore, thus we
4127 * should better reset it, so that state pruning has chances
4134 /* The logic is similar to find_good_pkt_pointers(), both could eventually
4135 * be folded together at some point.
4137 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
4140 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4141 struct bpf_reg_state *regs = state->regs;
4142 u32 id = regs[regno].id;
4145 for (i = 0; i < MAX_BPF_REG; i++)
4146 mark_map_reg(regs, i, id, is_null);
4148 for (j = 0; j <= vstate->curframe; j++) {
4149 state = vstate->frame[j];
4150 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
4151 if (state->stack[i].slot_type[0] != STACK_SPILL)
4153 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
4158 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
4159 struct bpf_reg_state *dst_reg,
4160 struct bpf_reg_state *src_reg,
4161 struct bpf_verifier_state *this_branch,
4162 struct bpf_verifier_state *other_branch)
4164 if (BPF_SRC(insn->code) != BPF_X)
4167 switch (BPF_OP(insn->code)) {
4169 if ((dst_reg->type == PTR_TO_PACKET &&
4170 src_reg->type == PTR_TO_PACKET_END) ||
4171 (dst_reg->type == PTR_TO_PACKET_META &&
4172 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4173 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4174 find_good_pkt_pointers(this_branch, dst_reg,
4175 dst_reg->type, false);
4176 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4177 src_reg->type == PTR_TO_PACKET) ||
4178 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4179 src_reg->type == PTR_TO_PACKET_META)) {
4180 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4181 find_good_pkt_pointers(other_branch, src_reg,
4182 src_reg->type, true);
4188 if ((dst_reg->type == PTR_TO_PACKET &&
4189 src_reg->type == PTR_TO_PACKET_END) ||
4190 (dst_reg->type == PTR_TO_PACKET_META &&
4191 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4192 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4193 find_good_pkt_pointers(other_branch, dst_reg,
4194 dst_reg->type, true);
4195 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4196 src_reg->type == PTR_TO_PACKET) ||
4197 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4198 src_reg->type == PTR_TO_PACKET_META)) {
4199 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
4200 find_good_pkt_pointers(this_branch, src_reg,
4201 src_reg->type, false);
4207 if ((dst_reg->type == PTR_TO_PACKET &&
4208 src_reg->type == PTR_TO_PACKET_END) ||
4209 (dst_reg->type == PTR_TO_PACKET_META &&
4210 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4211 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
4212 find_good_pkt_pointers(this_branch, dst_reg,
4213 dst_reg->type, true);
4214 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4215 src_reg->type == PTR_TO_PACKET) ||
4216 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4217 src_reg->type == PTR_TO_PACKET_META)) {
4218 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
4219 find_good_pkt_pointers(other_branch, src_reg,
4220 src_reg->type, false);
4226 if ((dst_reg->type == PTR_TO_PACKET &&
4227 src_reg->type == PTR_TO_PACKET_END) ||
4228 (dst_reg->type == PTR_TO_PACKET_META &&
4229 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4230 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
4231 find_good_pkt_pointers(other_branch, dst_reg,
4232 dst_reg->type, false);
4233 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4234 src_reg->type == PTR_TO_PACKET) ||
4235 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4236 src_reg->type == PTR_TO_PACKET_META)) {
4237 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
4238 find_good_pkt_pointers(this_branch, src_reg,
4239 src_reg->type, true);
4251 static int check_cond_jmp_op(struct bpf_verifier_env *env,
4252 struct bpf_insn *insn, int *insn_idx)
4254 struct bpf_verifier_state *this_branch = env->cur_state;
4255 struct bpf_verifier_state *other_branch;
4256 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
4257 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
4258 u8 opcode = BPF_OP(insn->code);
4262 if (opcode > BPF_JSLE) {
4263 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
4267 if (BPF_SRC(insn->code) == BPF_X) {
4268 if (insn->imm != 0) {
4269 verbose(env, "BPF_JMP uses reserved fields\n");
4273 /* check src1 operand */
4274 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4278 if (is_pointer_value(env, insn->src_reg)) {
4279 verbose(env, "R%d pointer comparison prohibited\n",
4283 src_reg = ®s[insn->src_reg];
4285 if (insn->src_reg != BPF_REG_0) {
4286 verbose(env, "BPF_JMP uses reserved fields\n");
4291 /* check src2 operand */
4292 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4296 dst_reg = ®s[insn->dst_reg];
4298 if (BPF_SRC(insn->code) == BPF_K)
4299 pred = is_branch_taken(dst_reg, insn->imm, opcode);
4300 else if (src_reg->type == SCALAR_VALUE &&
4301 tnum_is_const(src_reg->var_off))
4302 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
4306 /* Only follow the goto, ignore fall-through. If needed, push
4307 * the fall-through branch for simulation under speculative
4310 if (!env->allow_ptr_leaks &&
4311 !sanitize_speculative_path(env, insn, *insn_idx + 1,
4314 *insn_idx += insn->off;
4316 } else if (pred == 0) {
4317 /* Only follow the fall-through branch, since that's where the
4318 * program will go. If needed, push the goto branch for
4319 * simulation under speculative execution.
4321 if (!env->allow_ptr_leaks &&
4322 !sanitize_speculative_path(env, insn,
4323 *insn_idx + insn->off + 1,
4329 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
4333 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
4335 /* detect if we are comparing against a constant value so we can adjust
4336 * our min/max values for our dst register.
4337 * this is only legit if both are scalars (or pointers to the same
4338 * object, I suppose, but we don't support that right now), because
4339 * otherwise the different base pointers mean the offsets aren't
4342 if (BPF_SRC(insn->code) == BPF_X) {
4343 if (dst_reg->type == SCALAR_VALUE &&
4344 regs[insn->src_reg].type == SCALAR_VALUE) {
4345 if (tnum_is_const(regs[insn->src_reg].var_off))
4346 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4347 dst_reg, regs[insn->src_reg].var_off.value,
4349 else if (tnum_is_const(dst_reg->var_off))
4350 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
4351 ®s[insn->src_reg],
4352 dst_reg->var_off.value, opcode);
4353 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
4354 /* Comparing for equality, we can combine knowledge */
4355 reg_combine_min_max(&other_branch_regs[insn->src_reg],
4356 &other_branch_regs[insn->dst_reg],
4357 ®s[insn->src_reg],
4358 ®s[insn->dst_reg], opcode);
4360 } else if (dst_reg->type == SCALAR_VALUE) {
4361 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4362 dst_reg, insn->imm, opcode);
4365 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
4366 if (BPF_SRC(insn->code) == BPF_K &&
4367 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4368 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
4369 /* Mark all identical map registers in each branch as either
4370 * safe or unknown depending R == 0 or R != 0 conditional.
4372 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
4373 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
4374 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
4375 this_branch, other_branch) &&
4376 is_pointer_value(env, insn->dst_reg)) {
4377 verbose(env, "R%d pointer comparison prohibited\n",
4382 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
4386 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
4387 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
4389 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
4391 return (struct bpf_map *) (unsigned long) imm64;
4394 /* verify BPF_LD_IMM64 instruction */
4395 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
4397 struct bpf_reg_state *regs = cur_regs(env);
4400 if (BPF_SIZE(insn->code) != BPF_DW) {
4401 verbose(env, "invalid BPF_LD_IMM insn\n");
4404 if (insn->off != 0) {
4405 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
4409 err = check_reg_arg(env, insn->dst_reg, DST_OP);
4413 if (insn->src_reg == 0) {
4414 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
4416 regs[insn->dst_reg].type = SCALAR_VALUE;
4417 __mark_reg_known(®s[insn->dst_reg], imm);
4421 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
4422 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
4424 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
4425 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
4429 static bool may_access_skb(enum bpf_prog_type type)
4432 case BPF_PROG_TYPE_SOCKET_FILTER:
4433 case BPF_PROG_TYPE_SCHED_CLS:
4434 case BPF_PROG_TYPE_SCHED_ACT:
4441 /* verify safety of LD_ABS|LD_IND instructions:
4442 * - they can only appear in the programs where ctx == skb
4443 * - since they are wrappers of function calls, they scratch R1-R5 registers,
4444 * preserve R6-R9, and store return value into R0
4447 * ctx == skb == R6 == CTX
4450 * SRC == any register
4451 * IMM == 32-bit immediate
4454 * R0 - 8/16/32-bit skb data converted to cpu endianness
4456 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
4458 struct bpf_reg_state *regs = cur_regs(env);
4459 static const int ctx_reg = BPF_REG_6;
4460 u8 mode = BPF_MODE(insn->code);
4463 if (!may_access_skb(env->prog->type)) {
4464 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
4468 if (!env->ops->gen_ld_abs) {
4469 verbose(env, "bpf verifier is misconfigured\n");
4473 if (env->subprog_cnt > 1) {
4474 /* when program has LD_ABS insn JITs and interpreter assume
4475 * that r1 == ctx == skb which is not the case for callees
4476 * that can have arbitrary arguments. It's problematic
4477 * for main prog as well since JITs would need to analyze
4478 * all functions in order to make proper register save/restore
4479 * decisions in the main prog. Hence disallow LD_ABS with calls
4481 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
4485 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
4486 BPF_SIZE(insn->code) == BPF_DW ||
4487 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
4488 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
4492 /* check whether implicit source operand (register R6) is readable */
4493 err = check_reg_arg(env, ctx_reg, SRC_OP);
4497 if (regs[ctx_reg].type != PTR_TO_CTX) {
4499 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
4503 if (mode == BPF_IND) {
4504 /* check explicit source operand */
4505 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4510 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
4514 /* reset caller saved regs to unreadable */
4515 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4516 mark_reg_not_init(env, regs, caller_saved[i]);
4517 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4520 /* mark destination R0 register as readable, since it contains
4521 * the value fetched from the packet.
4522 * Already marked as written above.
4524 mark_reg_unknown(env, regs, BPF_REG_0);
4528 static int check_return_code(struct bpf_verifier_env *env)
4530 struct bpf_reg_state *reg;
4531 struct tnum range = tnum_range(0, 1);
4533 switch (env->prog->type) {
4534 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4535 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
4536 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
4537 range = tnum_range(1, 1);
4538 case BPF_PROG_TYPE_CGROUP_SKB:
4539 case BPF_PROG_TYPE_CGROUP_SOCK:
4540 case BPF_PROG_TYPE_SOCK_OPS:
4541 case BPF_PROG_TYPE_CGROUP_DEVICE:
4547 reg = cur_regs(env) + BPF_REG_0;
4548 if (reg->type != SCALAR_VALUE) {
4549 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
4550 reg_type_str[reg->type]);
4554 if (!tnum_in(range, reg->var_off)) {
4557 verbose(env, "At program exit the register R0 ");
4558 if (!tnum_is_unknown(reg->var_off)) {
4559 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4560 verbose(env, "has value %s", tn_buf);
4562 verbose(env, "has unknown scalar value");
4564 tnum_strn(tn_buf, sizeof(tn_buf), range);
4565 verbose(env, " should have been in %s\n", tn_buf);
4571 /* non-recursive DFS pseudo code
4572 * 1 procedure DFS-iterative(G,v):
4573 * 2 label v as discovered
4574 * 3 let S be a stack
4576 * 5 while S is not empty
4578 * 7 if t is what we're looking for:
4580 * 9 for all edges e in G.adjacentEdges(t) do
4581 * 10 if edge e is already labelled
4582 * 11 continue with the next edge
4583 * 12 w <- G.adjacentVertex(t,e)
4584 * 13 if vertex w is not discovered and not explored
4585 * 14 label e as tree-edge
4586 * 15 label w as discovered
4589 * 18 else if vertex w is discovered
4590 * 19 label e as back-edge
4592 * 21 // vertex w is explored
4593 * 22 label e as forward- or cross-edge
4594 * 23 label t as explored
4599 * 0x11 - discovered and fall-through edge labelled
4600 * 0x12 - discovered and fall-through and branch edges labelled
4611 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
4613 static int *insn_stack; /* stack of insns to process */
4614 static int cur_stack; /* current stack index */
4615 static int *insn_state;
4617 /* t, w, e - match pseudo-code above:
4618 * t - index of current instruction
4619 * w - next instruction
4622 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
4624 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
4627 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
4630 if (w < 0 || w >= env->prog->len) {
4631 verbose(env, "jump out of range from insn %d to %d\n", t, w);
4636 /* mark branch target for state pruning */
4637 env->explored_states[w] = STATE_LIST_MARK;
4639 if (insn_state[w] == 0) {
4641 insn_state[t] = DISCOVERED | e;
4642 insn_state[w] = DISCOVERED;
4643 if (cur_stack >= env->prog->len)
4645 insn_stack[cur_stack++] = w;
4647 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4648 verbose(env, "back-edge from insn %d to %d\n", t, w);
4650 } else if (insn_state[w] == EXPLORED) {
4651 /* forward- or cross-edge */
4652 insn_state[t] = DISCOVERED | e;
4654 verbose(env, "insn state internal bug\n");
4660 /* non-recursive depth-first-search to detect loops in BPF program
4661 * loop == back-edge in directed graph
4663 static int check_cfg(struct bpf_verifier_env *env)
4665 struct bpf_insn *insns = env->prog->insnsi;
4666 int insn_cnt = env->prog->len;
4670 ret = check_subprogs(env);
4674 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4678 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4684 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4685 insn_stack[0] = 0; /* 0 is the first instruction */
4691 t = insn_stack[cur_stack - 1];
4693 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4694 u8 opcode = BPF_OP(insns[t].code);
4696 if (opcode == BPF_EXIT) {
4698 } else if (opcode == BPF_CALL) {
4699 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4704 if (t + 1 < insn_cnt)
4705 env->explored_states[t + 1] = STATE_LIST_MARK;
4706 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4707 env->explored_states[t] = STATE_LIST_MARK;
4708 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4714 } else if (opcode == BPF_JA) {
4715 if (BPF_SRC(insns[t].code) != BPF_K) {
4719 /* unconditional jump with single edge */
4720 ret = push_insn(t, t + insns[t].off + 1,
4726 /* tell verifier to check for equivalent states
4727 * after every call and jump
4729 if (t + 1 < insn_cnt)
4730 env->explored_states[t + 1] = STATE_LIST_MARK;
4732 /* conditional jump with two edges */
4733 env->explored_states[t] = STATE_LIST_MARK;
4734 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4740 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4747 /* all other non-branch instructions with single
4750 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4758 insn_state[t] = EXPLORED;
4759 if (cur_stack-- <= 0) {
4760 verbose(env, "pop stack internal bug\n");
4767 for (i = 0; i < insn_cnt; i++) {
4768 if (insn_state[i] != EXPLORED) {
4769 verbose(env, "unreachable insn %d\n", i);
4774 ret = 0; /* cfg looks good */
4782 /* check %cur's range satisfies %old's */
4783 static bool range_within(struct bpf_reg_state *old,
4784 struct bpf_reg_state *cur)
4786 return old->umin_value <= cur->umin_value &&
4787 old->umax_value >= cur->umax_value &&
4788 old->smin_value <= cur->smin_value &&
4789 old->smax_value >= cur->smax_value;
4792 /* If in the old state two registers had the same id, then they need to have
4793 * the same id in the new state as well. But that id could be different from
4794 * the old state, so we need to track the mapping from old to new ids.
4795 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4796 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4797 * regs with a different old id could still have new id 9, we don't care about
4799 * So we look through our idmap to see if this old id has been seen before. If
4800 * so, we require the new id to match; otherwise, we add the id pair to the map.
4802 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
4806 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
4807 if (!idmap[i].old) {
4808 /* Reached an empty slot; haven't seen this id before */
4809 idmap[i].old = old_id;
4810 idmap[i].cur = cur_id;
4813 if (idmap[i].old == old_id)
4814 return idmap[i].cur == cur_id;
4816 /* We ran out of idmap slots, which should be impossible */
4821 /* Returns true if (rold safe implies rcur safe) */
4822 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
4823 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
4827 if (!(rold->live & REG_LIVE_READ))
4828 /* explored state didn't use this */
4831 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
4833 if (rold->type == PTR_TO_STACK)
4834 /* two stack pointers are equal only if they're pointing to
4835 * the same stack frame, since fp-8 in foo != fp-8 in bar
4837 return equal && rold->frameno == rcur->frameno;
4842 if (rold->type == NOT_INIT)
4843 /* explored state can't have used this */
4845 if (rcur->type == NOT_INIT)
4847 switch (rold->type) {
4849 if (env->explore_alu_limits)
4851 if (rcur->type == SCALAR_VALUE) {
4852 /* new val must satisfy old val knowledge */
4853 return range_within(rold, rcur) &&
4854 tnum_in(rold->var_off, rcur->var_off);
4856 /* We're trying to use a pointer in place of a scalar.
4857 * Even if the scalar was unbounded, this could lead to
4858 * pointer leaks because scalars are allowed to leak
4859 * while pointers are not. We could make this safe in
4860 * special cases if root is calling us, but it's
4861 * probably not worth the hassle.
4865 case PTR_TO_MAP_VALUE:
4866 /* If the new min/max/var_off satisfy the old ones and
4867 * everything else matches, we are OK.
4868 * We don't care about the 'id' value, because nothing
4869 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4871 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4872 range_within(rold, rcur) &&
4873 tnum_in(rold->var_off, rcur->var_off);
4874 case PTR_TO_MAP_VALUE_OR_NULL:
4875 /* a PTR_TO_MAP_VALUE could be safe to use as a
4876 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4877 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4878 * checked, doing so could have affected others with the same
4879 * id, and we can't check for that because we lost the id when
4880 * we converted to a PTR_TO_MAP_VALUE.
4882 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4884 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4886 /* Check our ids match any regs they're supposed to */
4887 return check_ids(rold->id, rcur->id, idmap);
4888 case PTR_TO_PACKET_META:
4890 if (rcur->type != rold->type)
4892 /* We must have at least as much range as the old ptr
4893 * did, so that any accesses which were safe before are
4894 * still safe. This is true even if old range < old off,
4895 * since someone could have accessed through (ptr - k), or
4896 * even done ptr -= k in a register, to get a safe access.
4898 if (rold->range > rcur->range)
4900 /* If the offsets don't match, we can't trust our alignment;
4901 * nor can we be sure that we won't fall out of range.
4903 if (rold->off != rcur->off)
4905 /* id relations must be preserved */
4906 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4908 /* new val must satisfy old val knowledge */
4909 return range_within(rold, rcur) &&
4910 tnum_in(rold->var_off, rcur->var_off);
4912 case CONST_PTR_TO_MAP:
4913 case PTR_TO_PACKET_END:
4914 /* Only valid matches are exact, which memcmp() above
4915 * would have accepted
4918 /* Don't know what's going on, just say it's not safe */
4922 /* Shouldn't get here; if we do, say it's not safe */
4927 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
4928 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
4932 /* if explored stack has more populated slots than current stack
4933 * such stacks are not equivalent
4935 if (old->allocated_stack > cur->allocated_stack)
4938 /* walk slots of the explored stack and ignore any additional
4939 * slots in the current stack, since explored(safe) state
4942 for (i = 0; i < old->allocated_stack; i++) {
4943 spi = i / BPF_REG_SIZE;
4945 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4946 /* explored state didn't use this */
4949 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4951 /* if old state was safe with misc data in the stack
4952 * it will be safe with zero-initialized stack.
4953 * The opposite is not true
4955 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4956 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4958 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4959 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4960 /* Ex: old explored (safe) state has STACK_SPILL in
4961 * this stack slot, but current has has STACK_MISC ->
4962 * this verifier states are not equivalent,
4963 * return false to continue verification of this path
4966 if (i % BPF_REG_SIZE)
4968 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4970 if (!regsafe(env, &old->stack[spi].spilled_ptr,
4971 &cur->stack[spi].spilled_ptr, idmap))
4972 /* when explored and current stack slot are both storing
4973 * spilled registers, check that stored pointers types
4974 * are the same as well.
4975 * Ex: explored safe path could have stored
4976 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4977 * but current path has stored:
4978 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4979 * such verifier states are not equivalent.
4980 * return false to continue verification of this path
4987 /* compare two verifier states
4989 * all states stored in state_list are known to be valid, since
4990 * verifier reached 'bpf_exit' instruction through them
4992 * this function is called when verifier exploring different branches of
4993 * execution popped from the state stack. If it sees an old state that has
4994 * more strict register state and more strict stack state then this execution
4995 * branch doesn't need to be explored further, since verifier already
4996 * concluded that more strict state leads to valid finish.
4998 * Therefore two states are equivalent if register state is more conservative
4999 * and explored stack state is more conservative than the current one.
5002 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
5003 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
5005 * In other words if current stack state (one being explored) has more
5006 * valid slots than old one that already passed validation, it means
5007 * the verifier can stop exploring and conclude that current state is valid too
5009 * Similarly with registers. If explored state has register type as invalid
5010 * whereas register type in current state is meaningful, it means that
5011 * the current state will reach 'bpf_exit' instruction safely
5013 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
5014 struct bpf_func_state *cur)
5018 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
5019 for (i = 0; i < MAX_BPF_REG; i++)
5020 if (!regsafe(env, &old->regs[i], &cur->regs[i],
5021 env->idmap_scratch))
5024 if (!stacksafe(env, old, cur, env->idmap_scratch))
5030 static bool states_equal(struct bpf_verifier_env *env,
5031 struct bpf_verifier_state *old,
5032 struct bpf_verifier_state *cur)
5036 if (old->curframe != cur->curframe)
5039 /* Verification state from speculative execution simulation
5040 * must never prune a non-speculative execution one.
5042 if (old->speculative && !cur->speculative)
5045 /* for states to be equal callsites have to be the same
5046 * and all frame states need to be equivalent
5048 for (i = 0; i <= old->curframe; i++) {
5049 if (old->frame[i]->callsite != cur->frame[i]->callsite)
5051 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
5057 /* A write screens off any subsequent reads; but write marks come from the
5058 * straight-line code between a state and its parent. When we arrive at an
5059 * equivalent state (jump target or such) we didn't arrive by the straight-line
5060 * code, so read marks in the state must propagate to the parent regardless
5061 * of the state's write marks. That's what 'parent == state->parent' comparison
5062 * in mark_reg_read() is for.
5064 static int propagate_liveness(struct bpf_verifier_env *env,
5065 const struct bpf_verifier_state *vstate,
5066 struct bpf_verifier_state *vparent)
5068 int i, frame, err = 0;
5069 struct bpf_func_state *state, *parent;
5071 if (vparent->curframe != vstate->curframe) {
5072 WARN(1, "propagate_live: parent frame %d current frame %d\n",
5073 vparent->curframe, vstate->curframe);
5076 /* Propagate read liveness of registers... */
5077 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
5078 /* We don't need to worry about FP liveness because it's read-only */
5079 for (i = 0; i < BPF_REG_FP; i++) {
5080 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
5082 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
5083 err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i],
5084 &vparent->frame[vstate->curframe]->regs[i]);
5090 /* ... and stack slots */
5091 for (frame = 0; frame <= vstate->curframe; frame++) {
5092 state = vstate->frame[frame];
5093 parent = vparent->frame[frame];
5094 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
5095 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
5096 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
5098 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
5099 mark_reg_read(env, &state->stack[i].spilled_ptr,
5100 &parent->stack[i].spilled_ptr);
5106 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
5108 struct bpf_verifier_state_list *new_sl;
5109 struct bpf_verifier_state_list *sl;
5110 struct bpf_verifier_state *cur = env->cur_state, *new;
5111 int i, j, err, states_cnt = 0;
5113 sl = env->explored_states[insn_idx];
5115 /* this 'insn_idx' instruction wasn't marked, so we will not
5116 * be doing state search here
5120 while (sl != STATE_LIST_MARK) {
5121 if (states_equal(env, &sl->state, cur)) {
5122 /* reached equivalent register/stack state,
5124 * Registers read by the continuation are read by us.
5125 * If we have any write marks in env->cur_state, they
5126 * will prevent corresponding reads in the continuation
5127 * from reaching our parent (an explored_state). Our
5128 * own state will get the read marks recorded, but
5129 * they'll be immediately forgotten as we're pruning
5130 * this state and will pop a new one.
5132 err = propagate_liveness(env, &sl->state, cur);
5141 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
5144 /* there were no equivalent states, remember current one.
5145 * technically the current state is not proven to be safe yet,
5146 * but it will either reach outer most bpf_exit (which means it's safe)
5147 * or it will be rejected. Since there are no loops, we won't be
5148 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
5149 * again on the way to bpf_exit
5151 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
5155 /* add new state to the head of linked list */
5156 new = &new_sl->state;
5157 err = copy_verifier_state(new, cur);
5159 free_verifier_state(new, false);
5163 new_sl->next = env->explored_states[insn_idx];
5164 env->explored_states[insn_idx] = new_sl;
5165 /* connect new state to parentage chain */
5166 for (i = 0; i < BPF_REG_FP; i++)
5167 cur_regs(env)[i].parent = &new->frame[new->curframe]->regs[i];
5168 /* clear write marks in current state: the writes we did are not writes
5169 * our child did, so they don't screen off its reads from us.
5170 * (There are no read marks in current state, because reads always mark
5171 * their parent and current state never has children yet. Only
5172 * explored_states can get read marks.)
5174 for (i = 0; i < BPF_REG_FP; i++)
5175 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
5177 /* all stack frames are accessible from callee, clear them all */
5178 for (j = 0; j <= cur->curframe; j++) {
5179 struct bpf_func_state *frame = cur->frame[j];
5180 struct bpf_func_state *newframe = new->frame[j];
5182 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
5183 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
5184 frame->stack[i].spilled_ptr.parent =
5185 &newframe->stack[i].spilled_ptr;
5191 static int do_check(struct bpf_verifier_env *env)
5193 struct bpf_verifier_state *state;
5194 struct bpf_insn *insns = env->prog->insnsi;
5195 struct bpf_reg_state *regs;
5196 int insn_cnt = env->prog->len, i;
5197 int insn_processed = 0;
5198 bool do_print_state = false;
5200 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
5203 state->curframe = 0;
5204 state->speculative = false;
5205 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
5206 if (!state->frame[0]) {
5210 env->cur_state = state;
5211 init_func_state(env, state->frame[0],
5212 BPF_MAIN_FUNC /* callsite */,
5214 0 /* subprogno, zero == main subprog */);
5217 struct bpf_insn *insn;
5221 if (env->insn_idx >= insn_cnt) {
5222 verbose(env, "invalid insn idx %d insn_cnt %d\n",
5223 env->insn_idx, insn_cnt);
5227 insn = &insns[env->insn_idx];
5228 class = BPF_CLASS(insn->code);
5230 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
5232 "BPF program is too large. Processed %d insn\n",
5237 err = is_state_visited(env, env->insn_idx);
5241 /* found equivalent state, can prune the search */
5242 if (env->log.level) {
5244 verbose(env, "\nfrom %d to %d%s: safe\n",
5245 env->prev_insn_idx, env->insn_idx,
5246 env->cur_state->speculative ?
5247 " (speculative execution)" : "");
5249 verbose(env, "%d: safe\n", env->insn_idx);
5251 goto process_bpf_exit;
5254 if (signal_pending(current))
5260 if (env->log.level > 1 || (env->log.level && do_print_state)) {
5261 if (env->log.level > 1)
5262 verbose(env, "%d:", env->insn_idx);
5264 verbose(env, "\nfrom %d to %d%s:",
5265 env->prev_insn_idx, env->insn_idx,
5266 env->cur_state->speculative ?
5267 " (speculative execution)" : "");
5268 print_verifier_state(env, state->frame[state->curframe]);
5269 do_print_state = false;
5272 if (env->log.level) {
5273 const struct bpf_insn_cbs cbs = {
5274 .cb_print = verbose,
5275 .private_data = env,
5278 verbose(env, "%d: ", env->insn_idx);
5279 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
5282 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5283 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
5284 env->prev_insn_idx);
5289 regs = cur_regs(env);
5290 sanitize_mark_insn_seen(env);
5292 if (class == BPF_ALU || class == BPF_ALU64) {
5293 err = check_alu_op(env, insn);
5297 } else if (class == BPF_LDX) {
5298 enum bpf_reg_type *prev_src_type, src_reg_type;
5300 /* check for reserved fields is already done */
5302 /* check src operand */
5303 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5307 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5311 src_reg_type = regs[insn->src_reg].type;
5313 /* check that memory (src_reg + off) is readable,
5314 * the state of dst_reg will be updated by this func
5316 err = check_mem_access(env, env->insn_idx, insn->src_reg,
5317 insn->off, BPF_SIZE(insn->code),
5318 BPF_READ, insn->dst_reg, false);
5322 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5324 if (*prev_src_type == NOT_INIT) {
5326 * dst_reg = *(u32 *)(src_reg + off)
5327 * save type to validate intersecting paths
5329 *prev_src_type = src_reg_type;
5331 } else if (src_reg_type != *prev_src_type &&
5332 (src_reg_type == PTR_TO_CTX ||
5333 *prev_src_type == PTR_TO_CTX)) {
5334 /* ABuser program is trying to use the same insn
5335 * dst_reg = *(u32*) (src_reg + off)
5336 * with different pointer types:
5337 * src_reg == ctx in one branch and
5338 * src_reg == stack|map in some other branch.
5341 verbose(env, "same insn cannot be used with different pointers\n");
5345 } else if (class == BPF_STX) {
5346 enum bpf_reg_type *prev_dst_type, dst_reg_type;
5348 if (BPF_MODE(insn->code) == BPF_XADD) {
5349 err = check_xadd(env, env->insn_idx, insn);
5356 /* check src1 operand */
5357 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5360 /* check src2 operand */
5361 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5365 dst_reg_type = regs[insn->dst_reg].type;
5367 /* check that memory (dst_reg + off) is writeable */
5368 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5369 insn->off, BPF_SIZE(insn->code),
5370 BPF_WRITE, insn->src_reg, false);
5374 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5376 if (*prev_dst_type == NOT_INIT) {
5377 *prev_dst_type = dst_reg_type;
5378 } else if (dst_reg_type != *prev_dst_type &&
5379 (dst_reg_type == PTR_TO_CTX ||
5380 *prev_dst_type == PTR_TO_CTX)) {
5381 verbose(env, "same insn cannot be used with different pointers\n");
5385 } else if (class == BPF_ST) {
5386 if (BPF_MODE(insn->code) != BPF_MEM ||
5387 insn->src_reg != BPF_REG_0) {
5388 verbose(env, "BPF_ST uses reserved fields\n");
5391 /* check src operand */
5392 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5396 if (is_ctx_reg(env, insn->dst_reg)) {
5397 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
5402 /* check that memory (dst_reg + off) is writeable */
5403 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5404 insn->off, BPF_SIZE(insn->code),
5405 BPF_WRITE, -1, false);
5409 } else if (class == BPF_JMP) {
5410 u8 opcode = BPF_OP(insn->code);
5412 if (opcode == BPF_CALL) {
5413 if (BPF_SRC(insn->code) != BPF_K ||
5415 (insn->src_reg != BPF_REG_0 &&
5416 insn->src_reg != BPF_PSEUDO_CALL) ||
5417 insn->dst_reg != BPF_REG_0) {
5418 verbose(env, "BPF_CALL uses reserved fields\n");
5422 if (insn->src_reg == BPF_PSEUDO_CALL)
5423 err = check_func_call(env, insn, &env->insn_idx);
5425 err = check_helper_call(env, insn->imm, env->insn_idx);
5429 } else if (opcode == BPF_JA) {
5430 if (BPF_SRC(insn->code) != BPF_K ||
5432 insn->src_reg != BPF_REG_0 ||
5433 insn->dst_reg != BPF_REG_0) {
5434 verbose(env, "BPF_JA uses reserved fields\n");
5438 env->insn_idx += insn->off + 1;
5441 } else if (opcode == BPF_EXIT) {
5442 if (BPF_SRC(insn->code) != BPF_K ||
5444 insn->src_reg != BPF_REG_0 ||
5445 insn->dst_reg != BPF_REG_0) {
5446 verbose(env, "BPF_EXIT uses reserved fields\n");
5450 if (state->curframe) {
5451 /* exit from nested function */
5452 env->prev_insn_idx = env->insn_idx;
5453 err = prepare_func_exit(env, &env->insn_idx);
5456 do_print_state = true;
5460 /* eBPF calling convetion is such that R0 is used
5461 * to return the value from eBPF program.
5462 * Make sure that it's readable at this time
5463 * of bpf_exit, which means that program wrote
5464 * something into it earlier
5466 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
5470 if (is_pointer_value(env, BPF_REG_0)) {
5471 verbose(env, "R0 leaks addr as return value\n");
5475 err = check_return_code(env);
5479 err = pop_stack(env, &env->prev_insn_idx,
5486 do_print_state = true;
5490 err = check_cond_jmp_op(env, insn, &env->insn_idx);
5494 } else if (class == BPF_LD) {
5495 u8 mode = BPF_MODE(insn->code);
5497 if (mode == BPF_ABS || mode == BPF_IND) {
5498 err = check_ld_abs(env, insn);
5502 } else if (mode == BPF_IMM) {
5503 err = check_ld_imm(env, insn);
5508 sanitize_mark_insn_seen(env);
5510 verbose(env, "invalid BPF_LD mode\n");
5514 verbose(env, "unknown insn class %d\n", class);
5521 verbose(env, "processed %d insns (limit %d), stack depth ",
5522 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
5523 for (i = 0; i < env->subprog_cnt; i++) {
5524 u32 depth = env->subprog_info[i].stack_depth;
5526 verbose(env, "%d", depth);
5527 if (i + 1 < env->subprog_cnt)
5531 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
5535 static int check_map_prealloc(struct bpf_map *map)
5537 return (map->map_type != BPF_MAP_TYPE_HASH &&
5538 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
5539 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
5540 !(map->map_flags & BPF_F_NO_PREALLOC);
5543 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
5544 struct bpf_map *map,
5545 struct bpf_prog *prog)
5548 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
5549 * preallocated hash maps, since doing memory allocation
5550 * in overflow_handler can crash depending on where nmi got
5553 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
5554 if (!check_map_prealloc(map)) {
5555 verbose(env, "perf_event programs can only use preallocated hash map\n");
5558 if (map->inner_map_meta &&
5559 !check_map_prealloc(map->inner_map_meta)) {
5560 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
5565 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
5566 !bpf_offload_prog_map_match(prog, map)) {
5567 verbose(env, "offload device mismatch between prog and map\n");
5574 /* look for pseudo eBPF instructions that access map FDs and
5575 * replace them with actual map pointers
5577 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
5579 struct bpf_insn *insn = env->prog->insnsi;
5580 int insn_cnt = env->prog->len;
5583 err = bpf_prog_calc_tag(env->prog);
5587 for (i = 0; i < insn_cnt; i++, insn++) {
5588 if (BPF_CLASS(insn->code) == BPF_LDX &&
5589 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
5590 verbose(env, "BPF_LDX uses reserved fields\n");
5594 if (BPF_CLASS(insn->code) == BPF_STX &&
5595 ((BPF_MODE(insn->code) != BPF_MEM &&
5596 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
5597 verbose(env, "BPF_STX uses reserved fields\n");
5601 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
5602 struct bpf_map *map;
5605 if (i == insn_cnt - 1 || insn[1].code != 0 ||
5606 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
5608 verbose(env, "invalid bpf_ld_imm64 insn\n");
5612 if (insn->src_reg == 0)
5613 /* valid generic load 64-bit imm */
5616 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
5618 "unrecognized bpf_ld_imm64 insn\n");
5622 f = fdget(insn->imm);
5623 map = __bpf_map_get(f);
5625 verbose(env, "fd %d is not pointing to valid bpf_map\n",
5627 return PTR_ERR(map);
5630 err = check_map_prog_compatibility(env, map, env->prog);
5636 /* store map pointer inside BPF_LD_IMM64 instruction */
5637 insn[0].imm = (u32) (unsigned long) map;
5638 insn[1].imm = ((u64) (unsigned long) map) >> 32;
5640 /* check whether we recorded this map already */
5641 for (j = 0; j < env->used_map_cnt; j++)
5642 if (env->used_maps[j] == map) {
5647 if (env->used_map_cnt >= MAX_USED_MAPS) {
5652 /* hold the map. If the program is rejected by verifier,
5653 * the map will be released by release_maps() or it
5654 * will be used by the valid program until it's unloaded
5655 * and all maps are released in free_used_maps()
5657 map = bpf_map_inc(map, false);
5660 return PTR_ERR(map);
5662 env->used_maps[env->used_map_cnt++] = map;
5664 if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
5665 bpf_cgroup_storage_assign(env->prog, map)) {
5667 "only one cgroup storage is allowed\n");
5679 /* Basic sanity check before we invest more work here. */
5680 if (!bpf_opcode_in_insntable(insn->code)) {
5681 verbose(env, "unknown opcode %02x\n", insn->code);
5686 /* now all pseudo BPF_LD_IMM64 instructions load valid
5687 * 'struct bpf_map *' into a register instead of user map_fd.
5688 * These pointers will be used later by verifier to validate map access.
5693 /* drop refcnt of maps used by the rejected program */
5694 static void release_maps(struct bpf_verifier_env *env)
5698 if (env->prog->aux->cgroup_storage)
5699 bpf_cgroup_storage_release(env->prog,
5700 env->prog->aux->cgroup_storage);
5702 for (i = 0; i < env->used_map_cnt; i++)
5703 bpf_map_put(env->used_maps[i]);
5706 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5707 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5709 struct bpf_insn *insn = env->prog->insnsi;
5710 int insn_cnt = env->prog->len;
5713 for (i = 0; i < insn_cnt; i++, insn++)
5714 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5718 /* single env->prog->insni[off] instruction was replaced with the range
5719 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
5720 * [0, off) and [off, end) to new locations, so the patched range stays zero
5722 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5725 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5726 bool old_seen = old_data[off].seen;
5731 new_data = vzalloc(array_size(prog_len,
5732 sizeof(struct bpf_insn_aux_data)));
5735 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5736 memcpy(new_data + off + cnt - 1, old_data + off,
5737 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5738 for (i = off; i < off + cnt - 1; i++) {
5739 /* Expand insni[off]'s seen count to the patched range. */
5740 new_data[i].seen = old_seen;
5742 env->insn_aux_data = new_data;
5747 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5753 /* NOTE: fake 'exit' subprog should be updated as well. */
5754 for (i = 0; i <= env->subprog_cnt; i++) {
5755 if (env->subprog_info[i].start <= off)
5757 env->subprog_info[i].start += len - 1;
5761 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5762 const struct bpf_insn *patch, u32 len)
5764 struct bpf_prog *new_prog;
5766 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5769 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5771 adjust_subprog_starts(env, off, len);
5775 /* The verifier does more data flow analysis than llvm and will not
5776 * explore branches that are dead at run time. Malicious programs can
5777 * have dead code too. Therefore replace all dead at-run-time code
5780 * Just nops are not optimal, e.g. if they would sit at the end of the
5781 * program and through another bug we would manage to jump there, then
5782 * we'd execute beyond program memory otherwise. Returning exception
5783 * code also wouldn't work since we can have subprogs where the dead
5784 * code could be located.
5786 static void sanitize_dead_code(struct bpf_verifier_env *env)
5788 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5789 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5790 struct bpf_insn *insn = env->prog->insnsi;
5791 const int insn_cnt = env->prog->len;
5794 for (i = 0; i < insn_cnt; i++) {
5795 if (aux_data[i].seen)
5797 memcpy(insn + i, &trap, sizeof(trap));
5801 /* convert load instructions that access fields of 'struct __sk_buff'
5802 * into sequence of instructions that access fields of 'struct sk_buff'
5804 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5806 const struct bpf_verifier_ops *ops = env->ops;
5807 int i, cnt, size, ctx_field_size, delta = 0;
5808 const int insn_cnt = env->prog->len;
5809 struct bpf_insn insn_buf[16], *insn;
5810 u32 target_size, size_default, off;
5811 struct bpf_prog *new_prog;
5812 enum bpf_access_type type;
5813 bool is_narrower_load;
5815 if (ops->gen_prologue) {
5816 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5818 if (cnt >= ARRAY_SIZE(insn_buf)) {
5819 verbose(env, "bpf verifier is misconfigured\n");
5822 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5826 env->prog = new_prog;
5831 if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
5834 insn = env->prog->insnsi + delta;
5836 for (i = 0; i < insn_cnt; i++, insn++) {
5839 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5840 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5841 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5842 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
5845 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5846 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5847 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5848 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
5849 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
5850 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
5851 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
5852 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
5854 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
5859 if (type == BPF_WRITE &&
5860 env->insn_aux_data[i + delta].sanitize_stack_spill) {
5861 struct bpf_insn patch[] = {
5866 cnt = ARRAY_SIZE(patch);
5867 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
5872 env->prog = new_prog;
5873 insn = new_prog->insnsi + i + delta;
5880 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5883 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5884 size = BPF_LDST_BYTES(insn);
5886 /* If the read access is a narrower load of the field,
5887 * convert to a 4/8-byte load, to minimum program type specific
5888 * convert_ctx_access changes. If conversion is successful,
5889 * we will apply proper mask to the result.
5891 is_narrower_load = size < ctx_field_size;
5892 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
5894 if (is_narrower_load) {
5897 if (type == BPF_WRITE) {
5898 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5903 if (ctx_field_size == 4)
5905 else if (ctx_field_size == 8)
5908 insn->off = off & ~(size_default - 1);
5909 insn->code = BPF_LDX | BPF_MEM | size_code;
5913 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5915 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5916 (ctx_field_size && !target_size)) {
5917 verbose(env, "bpf verifier is misconfigured\n");
5921 if (is_narrower_load && size < target_size) {
5922 u8 shift = (off & (size_default - 1)) * 8;
5924 if (ctx_field_size <= 4) {
5926 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
5929 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5930 (1 << size * 8) - 1);
5933 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
5936 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5937 (1ULL << size * 8) - 1);
5941 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5947 /* keep walking new program and skip insns we just inserted */
5948 env->prog = new_prog;
5949 insn = new_prog->insnsi + i + delta;
5955 static int jit_subprogs(struct bpf_verifier_env *env)
5957 struct bpf_prog *prog = env->prog, **func, *tmp;
5958 int i, j, subprog_start, subprog_end = 0, len, subprog;
5959 struct bpf_insn *insn;
5963 if (env->subprog_cnt <= 1)
5966 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5967 if (insn->code != (BPF_JMP | BPF_CALL) ||
5968 insn->src_reg != BPF_PSEUDO_CALL)
5970 /* Upon error here we cannot fall back to interpreter but
5971 * need a hard reject of the program. Thus -EFAULT is
5972 * propagated in any case.
5974 subprog = find_subprog(env, i + insn->imm + 1);
5976 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5980 /* temporarily remember subprog id inside insn instead of
5981 * aux_data, since next loop will split up all insns into funcs
5983 insn->off = subprog;
5984 /* remember original imm in case JIT fails and fallback
5985 * to interpreter will be needed
5987 env->insn_aux_data[i].call_imm = insn->imm;
5988 /* point imm to __bpf_call_base+1 from JITs point of view */
5992 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
5996 for (i = 0; i < env->subprog_cnt; i++) {
5997 subprog_start = subprog_end;
5998 subprog_end = env->subprog_info[i + 1].start;
6000 len = subprog_end - subprog_start;
6001 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
6004 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
6005 len * sizeof(struct bpf_insn));
6006 func[i]->type = prog->type;
6008 if (bpf_prog_calc_tag(func[i]))
6010 func[i]->is_func = 1;
6011 /* Use bpf_prog_F_tag to indicate functions in stack traces.
6012 * Long term would need debug info to populate names
6014 func[i]->aux->name[0] = 'F';
6015 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
6016 func[i]->jit_requested = 1;
6017 func[i] = bpf_int_jit_compile(func[i]);
6018 if (!func[i]->jited) {
6024 /* at this point all bpf functions were successfully JITed
6025 * now populate all bpf_calls with correct addresses and
6026 * run last pass of JIT
6028 for (i = 0; i < env->subprog_cnt; i++) {
6029 insn = func[i]->insnsi;
6030 for (j = 0; j < func[i]->len; j++, insn++) {
6031 if (insn->code != (BPF_JMP | BPF_CALL) ||
6032 insn->src_reg != BPF_PSEUDO_CALL)
6034 subprog = insn->off;
6035 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
6036 func[subprog]->bpf_func -
6040 /* we use the aux data to keep a list of the start addresses
6041 * of the JITed images for each function in the program
6043 * for some architectures, such as powerpc64, the imm field
6044 * might not be large enough to hold the offset of the start
6045 * address of the callee's JITed image from __bpf_call_base
6047 * in such cases, we can lookup the start address of a callee
6048 * by using its subprog id, available from the off field of
6049 * the call instruction, as an index for this list
6051 func[i]->aux->func = func;
6052 func[i]->aux->func_cnt = env->subprog_cnt;
6054 for (i = 0; i < env->subprog_cnt; i++) {
6055 old_bpf_func = func[i]->bpf_func;
6056 tmp = bpf_int_jit_compile(func[i]);
6057 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
6058 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
6065 /* finally lock prog and jit images for all functions and
6068 for (i = 0; i < env->subprog_cnt; i++) {
6069 bpf_prog_lock_ro(func[i]);
6070 bpf_prog_kallsyms_add(func[i]);
6073 /* Last step: make now unused interpreter insns from main
6074 * prog consistent for later dump requests, so they can
6075 * later look the same as if they were interpreted only.
6077 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6078 if (insn->code != (BPF_JMP | BPF_CALL) ||
6079 insn->src_reg != BPF_PSEUDO_CALL)
6081 insn->off = env->insn_aux_data[i].call_imm;
6082 subprog = find_subprog(env, i + insn->off + 1);
6083 insn->imm = subprog;
6087 prog->bpf_func = func[0]->bpf_func;
6088 prog->aux->func = func;
6089 prog->aux->func_cnt = env->subprog_cnt;
6092 for (i = 0; i < env->subprog_cnt; i++)
6094 bpf_jit_free(func[i]);
6097 /* cleanup main prog to be interpreted */
6098 prog->jit_requested = 0;
6099 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6100 if (insn->code != (BPF_JMP | BPF_CALL) ||
6101 insn->src_reg != BPF_PSEUDO_CALL)
6104 insn->imm = env->insn_aux_data[i].call_imm;
6109 static int fixup_call_args(struct bpf_verifier_env *env)
6111 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6112 struct bpf_prog *prog = env->prog;
6113 struct bpf_insn *insn = prog->insnsi;
6119 if (env->prog->jit_requested) {
6120 err = jit_subprogs(env);
6126 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6127 for (i = 0; i < prog->len; i++, insn++) {
6128 if (insn->code != (BPF_JMP | BPF_CALL) ||
6129 insn->src_reg != BPF_PSEUDO_CALL)
6131 depth = get_callee_stack_depth(env, insn, i);
6134 bpf_patch_call_args(insn, depth);
6141 /* fixup insn->imm field of bpf_call instructions
6142 * and inline eligible helpers as explicit sequence of BPF instructions
6144 * this function is called after eBPF program passed verification
6146 static int fixup_bpf_calls(struct bpf_verifier_env *env)
6148 struct bpf_prog *prog = env->prog;
6149 struct bpf_insn *insn = prog->insnsi;
6150 const struct bpf_func_proto *fn;
6151 const int insn_cnt = prog->len;
6152 const struct bpf_map_ops *ops;
6153 struct bpf_insn_aux_data *aux;
6154 struct bpf_insn insn_buf[16];
6155 struct bpf_prog *new_prog;
6156 struct bpf_map *map_ptr;
6157 int i, cnt, delta = 0;
6159 for (i = 0; i < insn_cnt; i++, insn++) {
6160 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
6161 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6162 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
6163 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6164 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
6165 struct bpf_insn mask_and_div[] = {
6166 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
6167 /* [R,W]x div 0 -> 0 */
6168 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 2),
6169 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
6170 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6171 BPF_ALU_REG(BPF_CLASS(insn->code), BPF_XOR, insn->dst_reg, insn->dst_reg),
6173 struct bpf_insn mask_and_mod[] = {
6174 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
6175 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 1 + (is64 ? 0 : 1)),
6176 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
6177 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6178 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
6180 struct bpf_insn *patchlet;
6182 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6183 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6184 patchlet = mask_and_div;
6185 cnt = ARRAY_SIZE(mask_and_div);
6187 patchlet = mask_and_mod;
6188 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 2 : 0);
6191 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
6196 env->prog = prog = new_prog;
6197 insn = new_prog->insnsi + i + delta;
6201 if (BPF_CLASS(insn->code) == BPF_LD &&
6202 (BPF_MODE(insn->code) == BPF_ABS ||
6203 BPF_MODE(insn->code) == BPF_IND)) {
6204 cnt = env->ops->gen_ld_abs(insn, insn_buf);
6205 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6206 verbose(env, "bpf verifier is misconfigured\n");
6210 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6215 env->prog = prog = new_prog;
6216 insn = new_prog->insnsi + i + delta;
6220 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
6221 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
6222 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
6223 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
6224 struct bpf_insn insn_buf[16];
6225 struct bpf_insn *patch = &insn_buf[0];
6226 bool issrc, isneg, isimm;
6229 aux = &env->insn_aux_data[i + delta];
6230 if (!aux->alu_state ||
6231 aux->alu_state == BPF_ALU_NON_POINTER)
6234 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
6235 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
6236 BPF_ALU_SANITIZE_SRC;
6237 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
6239 off_reg = issrc ? insn->src_reg : insn->dst_reg;
6241 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
6244 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6245 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
6246 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
6247 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
6248 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
6249 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
6250 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
6253 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
6254 insn->src_reg = BPF_REG_AX;
6256 insn->code = insn->code == code_add ?
6257 code_sub : code_add;
6259 if (issrc && isneg && !isimm)
6260 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6261 cnt = patch - insn_buf;
6263 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6268 env->prog = prog = new_prog;
6269 insn = new_prog->insnsi + i + delta;
6273 if (insn->code != (BPF_JMP | BPF_CALL))
6275 if (insn->src_reg == BPF_PSEUDO_CALL)
6278 if (insn->imm == BPF_FUNC_get_route_realm)
6279 prog->dst_needed = 1;
6280 if (insn->imm == BPF_FUNC_get_prandom_u32)
6281 bpf_user_rnd_init_once();
6282 if (insn->imm == BPF_FUNC_override_return)
6283 prog->kprobe_override = 1;
6284 if (insn->imm == BPF_FUNC_tail_call) {
6285 /* If we tail call into other programs, we
6286 * cannot make any assumptions since they can
6287 * be replaced dynamically during runtime in
6288 * the program array.
6290 prog->cb_access = 1;
6291 env->prog->aux->stack_depth = MAX_BPF_STACK;
6293 /* mark bpf_tail_call as different opcode to avoid
6294 * conditional branch in the interpeter for every normal
6295 * call and to prevent accidental JITing by JIT compiler
6296 * that doesn't support bpf_tail_call yet
6299 insn->code = BPF_JMP | BPF_TAIL_CALL;
6301 aux = &env->insn_aux_data[i + delta];
6302 if (!bpf_map_ptr_unpriv(aux))
6305 /* instead of changing every JIT dealing with tail_call
6306 * emit two extra insns:
6307 * if (index >= max_entries) goto out;
6308 * index &= array->index_mask;
6309 * to avoid out-of-bounds cpu speculation
6311 if (bpf_map_ptr_poisoned(aux)) {
6312 verbose(env, "tail_call abusing map_ptr\n");
6316 map_ptr = BPF_MAP_PTR(aux->map_state);
6317 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
6318 map_ptr->max_entries, 2);
6319 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
6320 container_of(map_ptr,
6323 insn_buf[2] = *insn;
6325 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6330 env->prog = prog = new_prog;
6331 insn = new_prog->insnsi + i + delta;
6335 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
6336 * and other inlining handlers are currently limited to 64 bit
6339 if (prog->jit_requested && BITS_PER_LONG == 64 &&
6340 (insn->imm == BPF_FUNC_map_lookup_elem ||
6341 insn->imm == BPF_FUNC_map_update_elem ||
6342 insn->imm == BPF_FUNC_map_delete_elem)) {
6343 aux = &env->insn_aux_data[i + delta];
6344 if (bpf_map_ptr_poisoned(aux))
6345 goto patch_call_imm;
6347 map_ptr = BPF_MAP_PTR(aux->map_state);
6349 if (insn->imm == BPF_FUNC_map_lookup_elem &&
6350 ops->map_gen_lookup) {
6351 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
6352 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6353 verbose(env, "bpf verifier is misconfigured\n");
6357 new_prog = bpf_patch_insn_data(env, i + delta,
6363 env->prog = prog = new_prog;
6364 insn = new_prog->insnsi + i + delta;
6368 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
6369 (void *(*)(struct bpf_map *map, void *key))NULL));
6370 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
6371 (int (*)(struct bpf_map *map, void *key))NULL));
6372 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
6373 (int (*)(struct bpf_map *map, void *key, void *value,
6375 switch (insn->imm) {
6376 case BPF_FUNC_map_lookup_elem:
6377 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
6380 case BPF_FUNC_map_update_elem:
6381 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
6384 case BPF_FUNC_map_delete_elem:
6385 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
6390 goto patch_call_imm;
6394 fn = env->ops->get_func_proto(insn->imm, env->prog);
6395 /* all functions that have prototype and verifier allowed
6396 * programs to call them, must be real in-kernel functions
6400 "kernel subsystem misconfigured func %s#%d\n",
6401 func_id_name(insn->imm), insn->imm);
6404 insn->imm = fn->func - __bpf_call_base;
6410 static void free_states(struct bpf_verifier_env *env)
6412 struct bpf_verifier_state_list *sl, *sln;
6415 if (!env->explored_states)
6418 for (i = 0; i < env->prog->len; i++) {
6419 sl = env->explored_states[i];
6422 while (sl != STATE_LIST_MARK) {
6424 free_verifier_state(&sl->state, false);
6430 kfree(env->explored_states);
6433 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
6435 struct bpf_verifier_env *env;
6436 struct bpf_verifier_log *log;
6439 /* no program is valid */
6440 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
6443 /* 'struct bpf_verifier_env' can be global, but since it's not small,
6444 * allocate/free it every time bpf_check() is called
6446 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
6451 env->insn_aux_data =
6452 vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
6455 if (!env->insn_aux_data)
6458 env->ops = bpf_verifier_ops[env->prog->type];
6460 /* grab the mutex to protect few globals used by verifier */
6461 mutex_lock(&bpf_verifier_lock);
6463 if (attr->log_level || attr->log_buf || attr->log_size) {
6464 /* user requested verbose verifier output
6465 * and supplied buffer to store the verification trace
6467 log->level = attr->log_level;
6468 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
6469 log->len_total = attr->log_size;
6472 /* log attributes have to be sane */
6473 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
6474 !log->level || !log->ubuf)
6478 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
6479 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
6480 env->strict_alignment = true;
6482 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
6483 env->strict_alignment = false;
6485 ret = replace_map_fd_with_map_ptr(env);
6487 goto skip_full_check;
6489 if (bpf_prog_is_dev_bound(env->prog->aux)) {
6490 ret = bpf_prog_offload_verifier_prep(env);
6492 goto skip_full_check;
6495 env->explored_states = kcalloc(env->prog->len,
6496 sizeof(struct bpf_verifier_state_list *),
6499 if (!env->explored_states)
6500 goto skip_full_check;
6502 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
6504 ret = check_cfg(env);
6506 goto skip_full_check;
6508 ret = do_check(env);
6509 if (env->cur_state) {
6510 free_verifier_state(env->cur_state, true);
6511 env->cur_state = NULL;
6515 while (!pop_stack(env, NULL, NULL));
6519 sanitize_dead_code(env);
6522 ret = check_max_stack_depth(env);
6525 /* program is valid, convert *(u32*)(ctx + off) accesses */
6526 ret = convert_ctx_accesses(env);
6529 ret = fixup_bpf_calls(env);
6532 ret = fixup_call_args(env);
6534 if (log->level && bpf_verifier_log_full(log))
6536 if (log->level && !log->ubuf) {
6538 goto err_release_maps;
6541 if (ret == 0 && env->used_map_cnt) {
6542 /* if program passed verifier, update used_maps in bpf_prog_info */
6543 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
6544 sizeof(env->used_maps[0]),
6547 if (!env->prog->aux->used_maps) {
6549 goto err_release_maps;
6552 memcpy(env->prog->aux->used_maps, env->used_maps,
6553 sizeof(env->used_maps[0]) * env->used_map_cnt);
6554 env->prog->aux->used_map_cnt = env->used_map_cnt;
6556 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
6557 * bpf_ld_imm64 instructions
6559 convert_pseudo_ld_imm64(env);
6563 if (!env->prog->aux->used_maps)
6564 /* if we didn't copy map pointers into bpf_prog_info, release
6565 * them now. Otherwise free_used_maps() will release them.
6570 mutex_unlock(&bpf_verifier_lock);
6571 vfree(env->insn_aux_data);