bpf: Prevent memory disambiguation attack
[linux/fpc-iii.git] / kernel / bpf / verifier.c
blob1a17e0d84347ec0a1a79313735341762a1bf20d3
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>
26 #include "disasm.h"
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #include <linux/bpf_types.h>
33 #undef BPF_PROG_TYPE
34 #undef BPF_MAP_TYPE
37 /* bpf_check() is a static code analyzer that walks eBPF program
38 * instruction by instruction and updates register/stack state.
39 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
41 * The first pass is depth-first-search to check that the program is a DAG.
42 * It rejects the following programs:
43 * - larger than BPF_MAXINSNS insns
44 * - if loop is present (detected via back-edge)
45 * - unreachable insns exist (shouldn't be a forest. program = one function)
46 * - out of bounds or malformed jumps
47 * The second pass is all possible path descent from the 1st insn.
48 * Since it's analyzing all pathes through the program, the length of the
49 * analysis is limited to 64k insn, which may be hit even if total number of
50 * insn is less then 4K, but there are too many branches that change stack/regs.
51 * Number of 'branches to be analyzed' is limited to 1k
53 * On entry to each instruction, each register has a type, and the instruction
54 * changes the types of the registers depending on instruction semantics.
55 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
56 * copied to R1.
58 * All registers are 64-bit.
59 * R0 - return register
60 * R1-R5 argument passing registers
61 * R6-R9 callee saved registers
62 * R10 - frame pointer read-only
64 * At the start of BPF program the register R1 contains a pointer to bpf_context
65 * and has type PTR_TO_CTX.
67 * Verifier tracks arithmetic operations on pointers in case:
68 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
69 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
70 * 1st insn copies R10 (which has FRAME_PTR) type into R1
71 * and 2nd arithmetic instruction is pattern matched to recognize
72 * that it wants to construct a pointer to some element within stack.
73 * So after 2nd insn, the register R1 has type PTR_TO_STACK
74 * (and -20 constant is saved for further stack bounds checking).
75 * Meaning that this reg is a pointer to stack plus known immediate constant.
77 * Most of the time the registers have SCALAR_VALUE type, which
78 * means the register has some value, but it's not a valid pointer.
79 * (like pointer plus pointer becomes SCALAR_VALUE type)
81 * When verifier sees load or store instructions the type of base register
82 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
83 * types recognized by check_mem_access() function.
85 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
86 * and the range of [ptr, ptr + map's value_size) is accessible.
88 * registers used to pass values to function calls are checked against
89 * function argument constraints.
91 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
92 * It means that the register type passed to this function must be
93 * PTR_TO_STACK and it will be used inside the function as
94 * 'pointer to map element key'
96 * For example the argument constraints for bpf_map_lookup_elem():
97 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
98 * .arg1_type = ARG_CONST_MAP_PTR,
99 * .arg2_type = ARG_PTR_TO_MAP_KEY,
101 * ret_type says that this function returns 'pointer to map elem value or null'
102 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
103 * 2nd argument should be a pointer to stack, which will be used inside
104 * the helper function as a pointer to map element key.
106 * On the kernel side the helper function looks like:
107 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
109 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
110 * void *key = (void *) (unsigned long) r2;
111 * void *value;
113 * here kernel can access 'key' and 'map' pointers safely, knowing that
114 * [key, key + map->key_size) bytes are valid and were initialized on
115 * the stack of eBPF program.
118 * Corresponding eBPF program may look like:
119 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
120 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
121 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
122 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
123 * here verifier looks at prototype of map_lookup_elem() and sees:
124 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
125 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
127 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
128 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
129 * and were initialized prior to this call.
130 * If it's ok, then verifier allows this BPF_CALL insn and looks at
131 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
132 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
133 * returns ether pointer to map value or NULL.
135 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
136 * insn, the register holding that pointer in the true branch changes state to
137 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
138 * branch. See check_cond_jmp_op().
140 * After the call R0 is set to return type of the function and registers R1-R5
141 * are set to NOT_INIT to indicate that they are no longer readable.
144 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
145 struct bpf_verifier_stack_elem {
146 /* verifer state is 'st'
147 * before processing instruction 'insn_idx'
148 * and after processing instruction 'prev_insn_idx'
150 struct bpf_verifier_state st;
151 int insn_idx;
152 int prev_insn_idx;
153 struct bpf_verifier_stack_elem *next;
156 #define BPF_COMPLEXITY_LIMIT_INSNS 131072
157 #define BPF_COMPLEXITY_LIMIT_STACK 1024
159 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
161 struct bpf_call_arg_meta {
162 struct bpf_map *map_ptr;
163 bool raw_mode;
164 bool pkt_access;
165 int regno;
166 int access_size;
169 static DEFINE_MUTEX(bpf_verifier_lock);
171 /* log_level controls verbosity level of eBPF verifier.
172 * bpf_verifier_log_write() is used to dump the verification trace to the log,
173 * so the user can figure out what's wrong with the program
175 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
176 const char *fmt, ...)
178 struct bpf_verifer_log *log = &env->log;
179 unsigned int n;
180 va_list args;
182 if (!log->level || !log->ubuf || bpf_verifier_log_full(log))
183 return;
185 va_start(args, fmt);
186 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
187 va_end(args);
189 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
190 "verifier log line truncated - local buffer too short\n");
192 n = min(log->len_total - log->len_used - 1, n);
193 log->kbuf[n] = '\0';
195 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
196 log->len_used += n;
197 else
198 log->ubuf = NULL;
200 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
201 /* Historically bpf_verifier_log_write was called verbose, but the name was too
202 * generic for symbol export. The function was renamed, but not the calls in
203 * the verifier to avoid complicating backports. Hence the alias below.
205 static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
206 const char *fmt, ...)
207 __attribute__((alias("bpf_verifier_log_write")));
209 static bool type_is_pkt_pointer(enum bpf_reg_type type)
211 return type == PTR_TO_PACKET ||
212 type == PTR_TO_PACKET_META;
215 /* string representation of 'enum bpf_reg_type' */
216 static const char * const reg_type_str[] = {
217 [NOT_INIT] = "?",
218 [SCALAR_VALUE] = "inv",
219 [PTR_TO_CTX] = "ctx",
220 [CONST_PTR_TO_MAP] = "map_ptr",
221 [PTR_TO_MAP_VALUE] = "map_value",
222 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
223 [PTR_TO_STACK] = "fp",
224 [PTR_TO_PACKET] = "pkt",
225 [PTR_TO_PACKET_META] = "pkt_meta",
226 [PTR_TO_PACKET_END] = "pkt_end",
229 static void print_liveness(struct bpf_verifier_env *env,
230 enum bpf_reg_liveness live)
232 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
233 verbose(env, "_");
234 if (live & REG_LIVE_READ)
235 verbose(env, "r");
236 if (live & REG_LIVE_WRITTEN)
237 verbose(env, "w");
240 static struct bpf_func_state *func(struct bpf_verifier_env *env,
241 const struct bpf_reg_state *reg)
243 struct bpf_verifier_state *cur = env->cur_state;
245 return cur->frame[reg->frameno];
248 static void print_verifier_state(struct bpf_verifier_env *env,
249 const struct bpf_func_state *state)
251 const struct bpf_reg_state *reg;
252 enum bpf_reg_type t;
253 int i;
255 if (state->frameno)
256 verbose(env, " frame%d:", state->frameno);
257 for (i = 0; i < MAX_BPF_REG; i++) {
258 reg = &state->regs[i];
259 t = reg->type;
260 if (t == NOT_INIT)
261 continue;
262 verbose(env, " R%d", i);
263 print_liveness(env, reg->live);
264 verbose(env, "=%s", reg_type_str[t]);
265 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
266 tnum_is_const(reg->var_off)) {
267 /* reg->off should be 0 for SCALAR_VALUE */
268 verbose(env, "%lld", reg->var_off.value + reg->off);
269 if (t == PTR_TO_STACK)
270 verbose(env, ",call_%d", func(env, reg)->callsite);
271 } else {
272 verbose(env, "(id=%d", reg->id);
273 if (t != SCALAR_VALUE)
274 verbose(env, ",off=%d", reg->off);
275 if (type_is_pkt_pointer(t))
276 verbose(env, ",r=%d", reg->range);
277 else if (t == CONST_PTR_TO_MAP ||
278 t == PTR_TO_MAP_VALUE ||
279 t == PTR_TO_MAP_VALUE_OR_NULL)
280 verbose(env, ",ks=%d,vs=%d",
281 reg->map_ptr->key_size,
282 reg->map_ptr->value_size);
283 if (tnum_is_const(reg->var_off)) {
284 /* Typically an immediate SCALAR_VALUE, but
285 * could be a pointer whose offset is too big
286 * for reg->off
288 verbose(env, ",imm=%llx", reg->var_off.value);
289 } else {
290 if (reg->smin_value != reg->umin_value &&
291 reg->smin_value != S64_MIN)
292 verbose(env, ",smin_value=%lld",
293 (long long)reg->smin_value);
294 if (reg->smax_value != reg->umax_value &&
295 reg->smax_value != S64_MAX)
296 verbose(env, ",smax_value=%lld",
297 (long long)reg->smax_value);
298 if (reg->umin_value != 0)
299 verbose(env, ",umin_value=%llu",
300 (unsigned long long)reg->umin_value);
301 if (reg->umax_value != U64_MAX)
302 verbose(env, ",umax_value=%llu",
303 (unsigned long long)reg->umax_value);
304 if (!tnum_is_unknown(reg->var_off)) {
305 char tn_buf[48];
307 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
308 verbose(env, ",var_off=%s", tn_buf);
311 verbose(env, ")");
314 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
315 if (state->stack[i].slot_type[0] == STACK_SPILL) {
316 verbose(env, " fp%d",
317 (-i - 1) * BPF_REG_SIZE);
318 print_liveness(env, state->stack[i].spilled_ptr.live);
319 verbose(env, "=%s",
320 reg_type_str[state->stack[i].spilled_ptr.type]);
322 if (state->stack[i].slot_type[0] == STACK_ZERO)
323 verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
325 verbose(env, "\n");
328 static int copy_stack_state(struct bpf_func_state *dst,
329 const struct bpf_func_state *src)
331 if (!src->stack)
332 return 0;
333 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
334 /* internal bug, make state invalid to reject the program */
335 memset(dst, 0, sizeof(*dst));
336 return -EFAULT;
338 memcpy(dst->stack, src->stack,
339 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
340 return 0;
343 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
344 * make it consume minimal amount of memory. check_stack_write() access from
345 * the program calls into realloc_func_state() to grow the stack size.
346 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
347 * which this function copies over. It points to previous bpf_verifier_state
348 * which is never reallocated
350 static int realloc_func_state(struct bpf_func_state *state, int size,
351 bool copy_old)
353 u32 old_size = state->allocated_stack;
354 struct bpf_stack_state *new_stack;
355 int slot = size / BPF_REG_SIZE;
357 if (size <= old_size || !size) {
358 if (copy_old)
359 return 0;
360 state->allocated_stack = slot * BPF_REG_SIZE;
361 if (!size && old_size) {
362 kfree(state->stack);
363 state->stack = NULL;
365 return 0;
367 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
368 GFP_KERNEL);
369 if (!new_stack)
370 return -ENOMEM;
371 if (copy_old) {
372 if (state->stack)
373 memcpy(new_stack, state->stack,
374 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
375 memset(new_stack + old_size / BPF_REG_SIZE, 0,
376 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
378 state->allocated_stack = slot * BPF_REG_SIZE;
379 kfree(state->stack);
380 state->stack = new_stack;
381 return 0;
384 static void free_func_state(struct bpf_func_state *state)
386 if (!state)
387 return;
388 kfree(state->stack);
389 kfree(state);
392 static void free_verifier_state(struct bpf_verifier_state *state,
393 bool free_self)
395 int i;
397 for (i = 0; i <= state->curframe; i++) {
398 free_func_state(state->frame[i]);
399 state->frame[i] = NULL;
401 if (free_self)
402 kfree(state);
405 /* copy verifier state from src to dst growing dst stack space
406 * when necessary to accommodate larger src stack
408 static int copy_func_state(struct bpf_func_state *dst,
409 const struct bpf_func_state *src)
411 int err;
413 err = realloc_func_state(dst, src->allocated_stack, false);
414 if (err)
415 return err;
416 memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
417 return copy_stack_state(dst, src);
420 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
421 const struct bpf_verifier_state *src)
423 struct bpf_func_state *dst;
424 int i, err;
426 /* if dst has more stack frames then src frame, free them */
427 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
428 free_func_state(dst_state->frame[i]);
429 dst_state->frame[i] = NULL;
431 dst_state->curframe = src->curframe;
432 dst_state->parent = src->parent;
433 for (i = 0; i <= src->curframe; i++) {
434 dst = dst_state->frame[i];
435 if (!dst) {
436 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
437 if (!dst)
438 return -ENOMEM;
439 dst_state->frame[i] = dst;
441 err = copy_func_state(dst, src->frame[i]);
442 if (err)
443 return err;
445 return 0;
448 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
449 int *insn_idx)
451 struct bpf_verifier_state *cur = env->cur_state;
452 struct bpf_verifier_stack_elem *elem, *head = env->head;
453 int err;
455 if (env->head == NULL)
456 return -ENOENT;
458 if (cur) {
459 err = copy_verifier_state(cur, &head->st);
460 if (err)
461 return err;
463 if (insn_idx)
464 *insn_idx = head->insn_idx;
465 if (prev_insn_idx)
466 *prev_insn_idx = head->prev_insn_idx;
467 elem = head->next;
468 free_verifier_state(&head->st, false);
469 kfree(head);
470 env->head = elem;
471 env->stack_size--;
472 return 0;
475 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
476 int insn_idx, int prev_insn_idx)
478 struct bpf_verifier_state *cur = env->cur_state;
479 struct bpf_verifier_stack_elem *elem;
480 int err;
482 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
483 if (!elem)
484 goto err;
486 elem->insn_idx = insn_idx;
487 elem->prev_insn_idx = prev_insn_idx;
488 elem->next = env->head;
489 env->head = elem;
490 env->stack_size++;
491 err = copy_verifier_state(&elem->st, cur);
492 if (err)
493 goto err;
494 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
495 verbose(env, "BPF program is too complex\n");
496 goto err;
498 return &elem->st;
499 err:
500 free_verifier_state(env->cur_state, true);
501 env->cur_state = NULL;
502 /* pop all elements and return */
503 while (!pop_stack(env, NULL, NULL));
504 return NULL;
507 #define CALLER_SAVED_REGS 6
508 static const int caller_saved[CALLER_SAVED_REGS] = {
509 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
511 #define CALLEE_SAVED_REGS 5
512 static const int callee_saved[CALLEE_SAVED_REGS] = {
513 BPF_REG_6, BPF_REG_7, BPF_REG_8, BPF_REG_9
516 static void __mark_reg_not_init(struct bpf_reg_state *reg);
518 /* Mark the unknown part of a register (variable offset or scalar value) as
519 * known to have the value @imm.
521 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
523 reg->id = 0;
524 reg->var_off = tnum_const(imm);
525 reg->smin_value = (s64)imm;
526 reg->smax_value = (s64)imm;
527 reg->umin_value = imm;
528 reg->umax_value = imm;
531 /* Mark the 'variable offset' part of a register as zero. This should be
532 * used only on registers holding a pointer type.
534 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
536 __mark_reg_known(reg, 0);
539 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
541 __mark_reg_known(reg, 0);
542 reg->off = 0;
543 reg->type = SCALAR_VALUE;
546 static void mark_reg_known_zero(struct bpf_verifier_env *env,
547 struct bpf_reg_state *regs, u32 regno)
549 if (WARN_ON(regno >= MAX_BPF_REG)) {
550 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
551 /* Something bad happened, let's kill all regs */
552 for (regno = 0; regno < MAX_BPF_REG; regno++)
553 __mark_reg_not_init(regs + regno);
554 return;
556 __mark_reg_known_zero(regs + regno);
559 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
561 return type_is_pkt_pointer(reg->type);
564 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
566 return reg_is_pkt_pointer(reg) ||
567 reg->type == PTR_TO_PACKET_END;
570 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
571 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
572 enum bpf_reg_type which)
574 /* The register can already have a range from prior markings.
575 * This is fine as long as it hasn't been advanced from its
576 * origin.
578 return reg->type == which &&
579 reg->id == 0 &&
580 reg->off == 0 &&
581 tnum_equals_const(reg->var_off, 0);
584 /* Attempts to improve min/max values based on var_off information */
585 static void __update_reg_bounds(struct bpf_reg_state *reg)
587 /* min signed is max(sign bit) | min(other bits) */
588 reg->smin_value = max_t(s64, reg->smin_value,
589 reg->var_off.value | (reg->var_off.mask & S64_MIN));
590 /* max signed is min(sign bit) | max(other bits) */
591 reg->smax_value = min_t(s64, reg->smax_value,
592 reg->var_off.value | (reg->var_off.mask & S64_MAX));
593 reg->umin_value = max(reg->umin_value, reg->var_off.value);
594 reg->umax_value = min(reg->umax_value,
595 reg->var_off.value | reg->var_off.mask);
598 /* Uses signed min/max values to inform unsigned, and vice-versa */
599 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
601 /* Learn sign from signed bounds.
602 * If we cannot cross the sign boundary, then signed and unsigned bounds
603 * are the same, so combine. This works even in the negative case, e.g.
604 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
606 if (reg->smin_value >= 0 || reg->smax_value < 0) {
607 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
608 reg->umin_value);
609 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
610 reg->umax_value);
611 return;
613 /* Learn sign from unsigned bounds. Signed bounds cross the sign
614 * boundary, so we must be careful.
616 if ((s64)reg->umax_value >= 0) {
617 /* Positive. We can't learn anything from the smin, but smax
618 * is positive, hence safe.
620 reg->smin_value = reg->umin_value;
621 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
622 reg->umax_value);
623 } else if ((s64)reg->umin_value < 0) {
624 /* Negative. We can't learn anything from the smax, but smin
625 * is negative, hence safe.
627 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
628 reg->umin_value);
629 reg->smax_value = reg->umax_value;
633 /* Attempts to improve var_off based on unsigned min/max information */
634 static void __reg_bound_offset(struct bpf_reg_state *reg)
636 reg->var_off = tnum_intersect(reg->var_off,
637 tnum_range(reg->umin_value,
638 reg->umax_value));
641 /* Reset the min/max bounds of a register */
642 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
644 reg->smin_value = S64_MIN;
645 reg->smax_value = S64_MAX;
646 reg->umin_value = 0;
647 reg->umax_value = U64_MAX;
650 /* Mark a register as having a completely unknown (scalar) value. */
651 static void __mark_reg_unknown(struct bpf_reg_state *reg)
653 reg->type = SCALAR_VALUE;
654 reg->id = 0;
655 reg->off = 0;
656 reg->var_off = tnum_unknown;
657 reg->frameno = 0;
658 __mark_reg_unbounded(reg);
661 static void mark_reg_unknown(struct bpf_verifier_env *env,
662 struct bpf_reg_state *regs, u32 regno)
664 if (WARN_ON(regno >= MAX_BPF_REG)) {
665 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
666 /* Something bad happened, let's kill all regs except FP */
667 for (regno = 0; regno < BPF_REG_FP; regno++)
668 __mark_reg_not_init(regs + regno);
669 return;
671 __mark_reg_unknown(regs + regno);
674 static void __mark_reg_not_init(struct bpf_reg_state *reg)
676 __mark_reg_unknown(reg);
677 reg->type = NOT_INIT;
680 static void mark_reg_not_init(struct bpf_verifier_env *env,
681 struct bpf_reg_state *regs, u32 regno)
683 if (WARN_ON(regno >= MAX_BPF_REG)) {
684 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
685 /* Something bad happened, let's kill all regs except FP */
686 for (regno = 0; regno < BPF_REG_FP; regno++)
687 __mark_reg_not_init(regs + regno);
688 return;
690 __mark_reg_not_init(regs + regno);
693 static void init_reg_state(struct bpf_verifier_env *env,
694 struct bpf_func_state *state)
696 struct bpf_reg_state *regs = state->regs;
697 int i;
699 for (i = 0; i < MAX_BPF_REG; i++) {
700 mark_reg_not_init(env, regs, i);
701 regs[i].live = REG_LIVE_NONE;
704 /* frame pointer */
705 regs[BPF_REG_FP].type = PTR_TO_STACK;
706 mark_reg_known_zero(env, regs, BPF_REG_FP);
707 regs[BPF_REG_FP].frameno = state->frameno;
709 /* 1st arg to a function */
710 regs[BPF_REG_1].type = PTR_TO_CTX;
711 mark_reg_known_zero(env, regs, BPF_REG_1);
714 #define BPF_MAIN_FUNC (-1)
715 static void init_func_state(struct bpf_verifier_env *env,
716 struct bpf_func_state *state,
717 int callsite, int frameno, int subprogno)
719 state->callsite = callsite;
720 state->frameno = frameno;
721 state->subprogno = subprogno;
722 init_reg_state(env, state);
725 enum reg_arg_type {
726 SRC_OP, /* register is used as source operand */
727 DST_OP, /* register is used as destination operand */
728 DST_OP_NO_MARK /* same as above, check only, don't mark */
731 static int cmp_subprogs(const void *a, const void *b)
733 return *(int *)a - *(int *)b;
736 static int find_subprog(struct bpf_verifier_env *env, int off)
738 u32 *p;
740 p = bsearch(&off, env->subprog_starts, env->subprog_cnt,
741 sizeof(env->subprog_starts[0]), cmp_subprogs);
742 if (!p)
743 return -ENOENT;
744 return p - env->subprog_starts;
748 static int add_subprog(struct bpf_verifier_env *env, int off)
750 int insn_cnt = env->prog->len;
751 int ret;
753 if (off >= insn_cnt || off < 0) {
754 verbose(env, "call to invalid destination\n");
755 return -EINVAL;
757 ret = find_subprog(env, off);
758 if (ret >= 0)
759 return 0;
760 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
761 verbose(env, "too many subprograms\n");
762 return -E2BIG;
764 env->subprog_starts[env->subprog_cnt++] = off;
765 sort(env->subprog_starts, env->subprog_cnt,
766 sizeof(env->subprog_starts[0]), cmp_subprogs, NULL);
767 return 0;
770 static int check_subprogs(struct bpf_verifier_env *env)
772 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
773 struct bpf_insn *insn = env->prog->insnsi;
774 int insn_cnt = env->prog->len;
776 /* determine subprog starts. The end is one before the next starts */
777 for (i = 0; i < insn_cnt; i++) {
778 if (insn[i].code != (BPF_JMP | BPF_CALL))
779 continue;
780 if (insn[i].src_reg != BPF_PSEUDO_CALL)
781 continue;
782 if (!env->allow_ptr_leaks) {
783 verbose(env, "function calls to other bpf functions are allowed for root only\n");
784 return -EPERM;
786 if (bpf_prog_is_dev_bound(env->prog->aux)) {
787 verbose(env, "function calls in offloaded programs are not supported yet\n");
788 return -EINVAL;
790 ret = add_subprog(env, i + insn[i].imm + 1);
791 if (ret < 0)
792 return ret;
795 if (env->log.level > 1)
796 for (i = 0; i < env->subprog_cnt; i++)
797 verbose(env, "func#%d @%d\n", i, env->subprog_starts[i]);
799 /* now check that all jumps are within the same subprog */
800 subprog_start = 0;
801 if (env->subprog_cnt == cur_subprog)
802 subprog_end = insn_cnt;
803 else
804 subprog_end = env->subprog_starts[cur_subprog++];
805 for (i = 0; i < insn_cnt; i++) {
806 u8 code = insn[i].code;
808 if (BPF_CLASS(code) != BPF_JMP)
809 goto next;
810 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
811 goto next;
812 off = i + insn[i].off + 1;
813 if (off < subprog_start || off >= subprog_end) {
814 verbose(env, "jump out of range from insn %d to %d\n", i, off);
815 return -EINVAL;
817 next:
818 if (i == subprog_end - 1) {
819 /* to avoid fall-through from one subprog into another
820 * the last insn of the subprog should be either exit
821 * or unconditional jump back
823 if (code != (BPF_JMP | BPF_EXIT) &&
824 code != (BPF_JMP | BPF_JA)) {
825 verbose(env, "last insn is not an exit or jmp\n");
826 return -EINVAL;
828 subprog_start = subprog_end;
829 if (env->subprog_cnt == cur_subprog)
830 subprog_end = insn_cnt;
831 else
832 subprog_end = env->subprog_starts[cur_subprog++];
835 return 0;
838 static
839 struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
840 const struct bpf_verifier_state *state,
841 struct bpf_verifier_state *parent,
842 u32 regno)
844 struct bpf_verifier_state *tmp = NULL;
846 /* 'parent' could be a state of caller and
847 * 'state' could be a state of callee. In such case
848 * parent->curframe < state->curframe
849 * and it's ok for r1 - r5 registers
851 * 'parent' could be a callee's state after it bpf_exit-ed.
852 * In such case parent->curframe > state->curframe
853 * and it's ok for r0 only
855 if (parent->curframe == state->curframe ||
856 (parent->curframe < state->curframe &&
857 regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
858 (parent->curframe > state->curframe &&
859 regno == BPF_REG_0))
860 return parent;
862 if (parent->curframe > state->curframe &&
863 regno >= BPF_REG_6) {
864 /* for callee saved regs we have to skip the whole chain
865 * of states that belong to callee and mark as LIVE_READ
866 * the registers before the call
868 tmp = parent;
869 while (tmp && tmp->curframe != state->curframe) {
870 tmp = tmp->parent;
872 if (!tmp)
873 goto bug;
874 parent = tmp;
875 } else {
876 goto bug;
878 return parent;
879 bug:
880 verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
881 verbose(env, "regno %d parent frame %d current frame %d\n",
882 regno, parent->curframe, state->curframe);
883 return NULL;
886 static int mark_reg_read(struct bpf_verifier_env *env,
887 const struct bpf_verifier_state *state,
888 struct bpf_verifier_state *parent,
889 u32 regno)
891 bool writes = parent == state->parent; /* Observe write marks */
893 if (regno == BPF_REG_FP)
894 /* We don't need to worry about FP liveness because it's read-only */
895 return 0;
897 while (parent) {
898 /* if read wasn't screened by an earlier write ... */
899 if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
900 break;
901 parent = skip_callee(env, state, parent, regno);
902 if (!parent)
903 return -EFAULT;
904 /* ... then we depend on parent's value */
905 parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
906 state = parent;
907 parent = state->parent;
908 writes = true;
910 return 0;
913 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
914 enum reg_arg_type t)
916 struct bpf_verifier_state *vstate = env->cur_state;
917 struct bpf_func_state *state = vstate->frame[vstate->curframe];
918 struct bpf_reg_state *regs = state->regs;
920 if (regno >= MAX_BPF_REG) {
921 verbose(env, "R%d is invalid\n", regno);
922 return -EINVAL;
925 if (t == SRC_OP) {
926 /* check whether register used as source operand can be read */
927 if (regs[regno].type == NOT_INIT) {
928 verbose(env, "R%d !read_ok\n", regno);
929 return -EACCES;
931 return mark_reg_read(env, vstate, vstate->parent, regno);
932 } else {
933 /* check whether register used as dest operand can be written to */
934 if (regno == BPF_REG_FP) {
935 verbose(env, "frame pointer is read only\n");
936 return -EACCES;
938 regs[regno].live |= REG_LIVE_WRITTEN;
939 if (t == DST_OP)
940 mark_reg_unknown(env, regs, regno);
942 return 0;
945 static bool is_spillable_regtype(enum bpf_reg_type type)
947 switch (type) {
948 case PTR_TO_MAP_VALUE:
949 case PTR_TO_MAP_VALUE_OR_NULL:
950 case PTR_TO_STACK:
951 case PTR_TO_CTX:
952 case PTR_TO_PACKET:
953 case PTR_TO_PACKET_META:
954 case PTR_TO_PACKET_END:
955 case CONST_PTR_TO_MAP:
956 return true;
957 default:
958 return false;
962 /* Does this register contain a constant zero? */
963 static bool register_is_null(struct bpf_reg_state *reg)
965 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
968 /* check_stack_read/write functions track spill/fill of registers,
969 * stack boundary and alignment are checked in check_mem_access()
971 static int check_stack_write(struct bpf_verifier_env *env,
972 struct bpf_func_state *state, /* func where register points to */
973 int off, int size, int value_regno, int insn_idx)
975 struct bpf_func_state *cur; /* state of the current function */
976 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
977 enum bpf_reg_type type;
979 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
980 true);
981 if (err)
982 return err;
983 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
984 * so it's aligned access and [off, off + size) are within stack limits
986 if (!env->allow_ptr_leaks &&
987 state->stack[spi].slot_type[0] == STACK_SPILL &&
988 size != BPF_REG_SIZE) {
989 verbose(env, "attempt to corrupt spilled pointer on stack\n");
990 return -EACCES;
993 cur = env->cur_state->frame[env->cur_state->curframe];
994 if (value_regno >= 0 &&
995 is_spillable_regtype((type = cur->regs[value_regno].type))) {
997 /* register containing pointer is being spilled into stack */
998 if (size != BPF_REG_SIZE) {
999 verbose(env, "invalid size of register spill\n");
1000 return -EACCES;
1003 if (state != cur && type == PTR_TO_STACK) {
1004 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1005 return -EINVAL;
1008 /* save register state */
1009 state->stack[spi].spilled_ptr = cur->regs[value_regno];
1010 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1012 for (i = 0; i < BPF_REG_SIZE; i++) {
1013 if (state->stack[spi].slot_type[i] == STACK_MISC &&
1014 !env->allow_ptr_leaks) {
1015 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
1016 int soff = (-spi - 1) * BPF_REG_SIZE;
1018 /* detected reuse of integer stack slot with a pointer
1019 * which means either llvm is reusing stack slot or
1020 * an attacker is trying to exploit CVE-2018-3639
1021 * (speculative store bypass)
1022 * Have to sanitize that slot with preemptive
1023 * store of zero.
1025 if (*poff && *poff != soff) {
1026 /* disallow programs where single insn stores
1027 * into two different stack slots, since verifier
1028 * cannot sanitize them
1030 verbose(env,
1031 "insn %d cannot access two stack slots fp%d and fp%d",
1032 insn_idx, *poff, soff);
1033 return -EINVAL;
1035 *poff = soff;
1037 state->stack[spi].slot_type[i] = STACK_SPILL;
1039 } else {
1040 u8 type = STACK_MISC;
1042 /* regular write of data into stack */
1043 state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
1045 /* only mark the slot as written if all 8 bytes were written
1046 * otherwise read propagation may incorrectly stop too soon
1047 * when stack slots are partially written.
1048 * This heuristic means that read propagation will be
1049 * conservative, since it will add reg_live_read marks
1050 * to stack slots all the way to first state when programs
1051 * writes+reads less than 8 bytes
1053 if (size == BPF_REG_SIZE)
1054 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1056 /* when we zero initialize stack slots mark them as such */
1057 if (value_regno >= 0 &&
1058 register_is_null(&cur->regs[value_regno]))
1059 type = STACK_ZERO;
1061 for (i = 0; i < size; i++)
1062 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1063 type;
1065 return 0;
1068 /* registers of every function are unique and mark_reg_read() propagates
1069 * the liveness in the following cases:
1070 * - from callee into caller for R1 - R5 that were used as arguments
1071 * - from caller into callee for R0 that used as result of the call
1072 * - from caller to the same caller skipping states of the callee for R6 - R9,
1073 * since R6 - R9 are callee saved by implicit function prologue and
1074 * caller's R6 != callee's R6, so when we propagate liveness up to
1075 * parent states we need to skip callee states for R6 - R9.
1077 * stack slot marking is different, since stacks of caller and callee are
1078 * accessible in both (since caller can pass a pointer to caller's stack to
1079 * callee which can pass it to another function), hence mark_stack_slot_read()
1080 * has to propagate the stack liveness to all parent states at given frame number.
1081 * Consider code:
1082 * f1() {
1083 * ptr = fp - 8;
1084 * *ptr = ctx;
1085 * call f2 {
1086 * .. = *ptr;
1088 * .. = *ptr;
1090 * First *ptr is reading from f1's stack and mark_stack_slot_read() has
1091 * to mark liveness at the f1's frame and not f2's frame.
1092 * Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
1093 * to propagate liveness to f2 states at f1's frame level and further into
1094 * f1 states at f1's frame level until write into that stack slot
1096 static void mark_stack_slot_read(struct bpf_verifier_env *env,
1097 const struct bpf_verifier_state *state,
1098 struct bpf_verifier_state *parent,
1099 int slot, int frameno)
1101 bool writes = parent == state->parent; /* Observe write marks */
1103 while (parent) {
1104 if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
1105 /* since LIVE_WRITTEN mark is only done for full 8-byte
1106 * write the read marks are conservative and parent
1107 * state may not even have the stack allocated. In such case
1108 * end the propagation, since the loop reached beginning
1109 * of the function
1111 break;
1112 /* if read wasn't screened by an earlier write ... */
1113 if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
1114 break;
1115 /* ... then we depend on parent's value */
1116 parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
1117 state = parent;
1118 parent = state->parent;
1119 writes = true;
1123 static int check_stack_read(struct bpf_verifier_env *env,
1124 struct bpf_func_state *reg_state /* func where register points to */,
1125 int off, int size, int value_regno)
1127 struct bpf_verifier_state *vstate = env->cur_state;
1128 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1129 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1130 u8 *stype;
1132 if (reg_state->allocated_stack <= slot) {
1133 verbose(env, "invalid read from stack off %d+0 size %d\n",
1134 off, size);
1135 return -EACCES;
1137 stype = reg_state->stack[spi].slot_type;
1139 if (stype[0] == STACK_SPILL) {
1140 if (size != BPF_REG_SIZE) {
1141 verbose(env, "invalid size of register spill\n");
1142 return -EACCES;
1144 for (i = 1; i < BPF_REG_SIZE; i++) {
1145 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1146 verbose(env, "corrupted spill memory\n");
1147 return -EACCES;
1151 if (value_regno >= 0) {
1152 /* restore register state from stack */
1153 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1154 /* mark reg as written since spilled pointer state likely
1155 * has its liveness marks cleared by is_state_visited()
1156 * which resets stack/reg liveness for state transitions
1158 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1160 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1161 reg_state->frameno);
1162 return 0;
1163 } else {
1164 int zeros = 0;
1166 for (i = 0; i < size; i++) {
1167 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1168 continue;
1169 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1170 zeros++;
1171 continue;
1173 verbose(env, "invalid read from stack off %d+%d size %d\n",
1174 off, i, size);
1175 return -EACCES;
1177 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1178 reg_state->frameno);
1179 if (value_regno >= 0) {
1180 if (zeros == size) {
1181 /* any size read into register is zero extended,
1182 * so the whole register == const_zero
1184 __mark_reg_const_zero(&state->regs[value_regno]);
1185 } else {
1186 /* have read misc data from the stack */
1187 mark_reg_unknown(env, state->regs, value_regno);
1189 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1191 return 0;
1195 /* check read/write into map element returned by bpf_map_lookup_elem() */
1196 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1197 int size, bool zero_size_allowed)
1199 struct bpf_reg_state *regs = cur_regs(env);
1200 struct bpf_map *map = regs[regno].map_ptr;
1202 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1203 off + size > map->value_size) {
1204 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1205 map->value_size, off, size);
1206 return -EACCES;
1208 return 0;
1211 /* check read/write into a map element with possible variable offset */
1212 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1213 int off, int size, bool zero_size_allowed)
1215 struct bpf_verifier_state *vstate = env->cur_state;
1216 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1217 struct bpf_reg_state *reg = &state->regs[regno];
1218 int err;
1220 /* We may have adjusted the register to this map value, so we
1221 * need to try adding each of min_value and max_value to off
1222 * to make sure our theoretical access will be safe.
1224 if (env->log.level)
1225 print_verifier_state(env, state);
1226 /* The minimum value is only important with signed
1227 * comparisons where we can't assume the floor of a
1228 * value is 0. If we are using signed variables for our
1229 * index'es we need to make sure that whatever we use
1230 * will have a set floor within our range.
1232 if (reg->smin_value < 0) {
1233 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1234 regno);
1235 return -EACCES;
1237 err = __check_map_access(env, regno, reg->smin_value + off, size,
1238 zero_size_allowed);
1239 if (err) {
1240 verbose(env, "R%d min value is outside of the array range\n",
1241 regno);
1242 return err;
1245 /* If we haven't set a max value then we need to bail since we can't be
1246 * sure we won't do bad things.
1247 * If reg->umax_value + off could overflow, treat that as unbounded too.
1249 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1250 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1251 regno);
1252 return -EACCES;
1254 err = __check_map_access(env, regno, reg->umax_value + off, size,
1255 zero_size_allowed);
1256 if (err)
1257 verbose(env, "R%d max value is outside of the array range\n",
1258 regno);
1259 return err;
1262 #define MAX_PACKET_OFF 0xffff
1264 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1265 const struct bpf_call_arg_meta *meta,
1266 enum bpf_access_type t)
1268 switch (env->prog->type) {
1269 case BPF_PROG_TYPE_LWT_IN:
1270 case BPF_PROG_TYPE_LWT_OUT:
1271 /* dst_input() and dst_output() can't write for now */
1272 if (t == BPF_WRITE)
1273 return false;
1274 /* fallthrough */
1275 case BPF_PROG_TYPE_SCHED_CLS:
1276 case BPF_PROG_TYPE_SCHED_ACT:
1277 case BPF_PROG_TYPE_XDP:
1278 case BPF_PROG_TYPE_LWT_XMIT:
1279 case BPF_PROG_TYPE_SK_SKB:
1280 if (meta)
1281 return meta->pkt_access;
1283 env->seen_direct_write = true;
1284 return true;
1285 default:
1286 return false;
1290 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1291 int off, int size, bool zero_size_allowed)
1293 struct bpf_reg_state *regs = cur_regs(env);
1294 struct bpf_reg_state *reg = &regs[regno];
1296 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1297 (u64)off + size > reg->range) {
1298 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1299 off, size, regno, reg->id, reg->off, reg->range);
1300 return -EACCES;
1302 return 0;
1305 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1306 int size, bool zero_size_allowed)
1308 struct bpf_reg_state *regs = cur_regs(env);
1309 struct bpf_reg_state *reg = &regs[regno];
1310 int err;
1312 /* We may have added a variable offset to the packet pointer; but any
1313 * reg->range we have comes after that. We are only checking the fixed
1314 * offset.
1317 /* We don't allow negative numbers, because we aren't tracking enough
1318 * detail to prove they're safe.
1320 if (reg->smin_value < 0) {
1321 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1322 regno);
1323 return -EACCES;
1325 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1326 if (err) {
1327 verbose(env, "R%d offset is outside of the packet\n", regno);
1328 return err;
1330 return err;
1333 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1334 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1335 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1337 struct bpf_insn_access_aux info = {
1338 .reg_type = *reg_type,
1341 if (env->ops->is_valid_access &&
1342 env->ops->is_valid_access(off, size, t, &info)) {
1343 /* A non zero info.ctx_field_size indicates that this field is a
1344 * candidate for later verifier transformation to load the whole
1345 * field and then apply a mask when accessed with a narrower
1346 * access than actual ctx access size. A zero info.ctx_field_size
1347 * will only allow for whole field access and rejects any other
1348 * type of narrower access.
1350 *reg_type = info.reg_type;
1352 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1353 /* remember the offset of last byte accessed in ctx */
1354 if (env->prog->aux->max_ctx_offset < off + size)
1355 env->prog->aux->max_ctx_offset = off + size;
1356 return 0;
1359 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1360 return -EACCES;
1363 static bool __is_pointer_value(bool allow_ptr_leaks,
1364 const struct bpf_reg_state *reg)
1366 if (allow_ptr_leaks)
1367 return false;
1369 return reg->type != SCALAR_VALUE;
1372 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1374 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1377 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1379 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1381 return reg->type == PTR_TO_CTX;
1384 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1386 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1388 return type_is_pkt_pointer(reg->type);
1391 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1392 const struct bpf_reg_state *reg,
1393 int off, int size, bool strict)
1395 struct tnum reg_off;
1396 int ip_align;
1398 /* Byte size accesses are always allowed. */
1399 if (!strict || size == 1)
1400 return 0;
1402 /* For platforms that do not have a Kconfig enabling
1403 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1404 * NET_IP_ALIGN is universally set to '2'. And on platforms
1405 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1406 * to this code only in strict mode where we want to emulate
1407 * the NET_IP_ALIGN==2 checking. Therefore use an
1408 * unconditional IP align value of '2'.
1410 ip_align = 2;
1412 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1413 if (!tnum_is_aligned(reg_off, size)) {
1414 char tn_buf[48];
1416 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1417 verbose(env,
1418 "misaligned packet access off %d+%s+%d+%d size %d\n",
1419 ip_align, tn_buf, reg->off, off, size);
1420 return -EACCES;
1423 return 0;
1426 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1427 const struct bpf_reg_state *reg,
1428 const char *pointer_desc,
1429 int off, int size, bool strict)
1431 struct tnum reg_off;
1433 /* Byte size accesses are always allowed. */
1434 if (!strict || size == 1)
1435 return 0;
1437 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1438 if (!tnum_is_aligned(reg_off, size)) {
1439 char tn_buf[48];
1441 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1442 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1443 pointer_desc, tn_buf, reg->off, off, size);
1444 return -EACCES;
1447 return 0;
1450 static int check_ptr_alignment(struct bpf_verifier_env *env,
1451 const struct bpf_reg_state *reg, int off,
1452 int size, bool strict_alignment_once)
1454 bool strict = env->strict_alignment || strict_alignment_once;
1455 const char *pointer_desc = "";
1457 switch (reg->type) {
1458 case PTR_TO_PACKET:
1459 case PTR_TO_PACKET_META:
1460 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1461 * right in front, treat it the very same way.
1463 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1464 case PTR_TO_MAP_VALUE:
1465 pointer_desc = "value ";
1466 break;
1467 case PTR_TO_CTX:
1468 pointer_desc = "context ";
1469 break;
1470 case PTR_TO_STACK:
1471 pointer_desc = "stack ";
1472 /* The stack spill tracking logic in check_stack_write()
1473 * and check_stack_read() relies on stack accesses being
1474 * aligned.
1476 strict = true;
1477 break;
1478 default:
1479 break;
1481 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1482 strict);
1485 static int update_stack_depth(struct bpf_verifier_env *env,
1486 const struct bpf_func_state *func,
1487 int off)
1489 u16 stack = env->subprog_stack_depth[func->subprogno];
1491 if (stack >= -off)
1492 return 0;
1494 /* update known max for given subprogram */
1495 env->subprog_stack_depth[func->subprogno] = -off;
1496 return 0;
1499 /* starting from main bpf function walk all instructions of the function
1500 * and recursively walk all callees that given function can call.
1501 * Ignore jump and exit insns.
1502 * Since recursion is prevented by check_cfg() this algorithm
1503 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1505 static int check_max_stack_depth(struct bpf_verifier_env *env)
1507 int depth = 0, frame = 0, subprog = 0, i = 0, subprog_end;
1508 struct bpf_insn *insn = env->prog->insnsi;
1509 int insn_cnt = env->prog->len;
1510 int ret_insn[MAX_CALL_FRAMES];
1511 int ret_prog[MAX_CALL_FRAMES];
1513 process_func:
1514 /* round up to 32-bytes, since this is granularity
1515 * of interpreter stack size
1517 depth += round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1518 if (depth > MAX_BPF_STACK) {
1519 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1520 frame + 1, depth);
1521 return -EACCES;
1523 continue_func:
1524 if (env->subprog_cnt == subprog)
1525 subprog_end = insn_cnt;
1526 else
1527 subprog_end = env->subprog_starts[subprog];
1528 for (; i < subprog_end; i++) {
1529 if (insn[i].code != (BPF_JMP | BPF_CALL))
1530 continue;
1531 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1532 continue;
1533 /* remember insn and function to return to */
1534 ret_insn[frame] = i + 1;
1535 ret_prog[frame] = subprog;
1537 /* find the callee */
1538 i = i + insn[i].imm + 1;
1539 subprog = find_subprog(env, i);
1540 if (subprog < 0) {
1541 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1543 return -EFAULT;
1545 subprog++;
1546 frame++;
1547 if (frame >= MAX_CALL_FRAMES) {
1548 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1549 return -EFAULT;
1551 goto process_func;
1553 /* end of for() loop means the last insn of the 'subprog'
1554 * was reached. Doesn't matter whether it was JA or EXIT
1556 if (frame == 0)
1557 return 0;
1558 depth -= round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1559 frame--;
1560 i = ret_insn[frame];
1561 subprog = ret_prog[frame];
1562 goto continue_func;
1565 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1566 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1567 const struct bpf_insn *insn, int idx)
1569 int start = idx + insn->imm + 1, subprog;
1571 subprog = find_subprog(env, start);
1572 if (subprog < 0) {
1573 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1574 start);
1575 return -EFAULT;
1577 subprog++;
1578 return env->subprog_stack_depth[subprog];
1580 #endif
1582 /* truncate register to smaller size (in bytes)
1583 * must be called with size < BPF_REG_SIZE
1585 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1587 u64 mask;
1589 /* clear high bits in bit representation */
1590 reg->var_off = tnum_cast(reg->var_off, size);
1592 /* fix arithmetic bounds */
1593 mask = ((u64)1 << (size * 8)) - 1;
1594 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1595 reg->umin_value &= mask;
1596 reg->umax_value &= mask;
1597 } else {
1598 reg->umin_value = 0;
1599 reg->umax_value = mask;
1601 reg->smin_value = reg->umin_value;
1602 reg->smax_value = reg->umax_value;
1605 /* check whether memory at (regno + off) is accessible for t = (read | write)
1606 * if t==write, value_regno is a register which value is stored into memory
1607 * if t==read, value_regno is a register which will receive the value from memory
1608 * if t==write && value_regno==-1, some unknown value is stored into memory
1609 * if t==read && value_regno==-1, don't care what we read from memory
1611 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1612 int off, int bpf_size, enum bpf_access_type t,
1613 int value_regno, bool strict_alignment_once)
1615 struct bpf_reg_state *regs = cur_regs(env);
1616 struct bpf_reg_state *reg = regs + regno;
1617 struct bpf_func_state *state;
1618 int size, err = 0;
1620 size = bpf_size_to_bytes(bpf_size);
1621 if (size < 0)
1622 return size;
1624 /* alignment checks will add in reg->off themselves */
1625 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1626 if (err)
1627 return err;
1629 /* for access checks, reg->off is just part of off */
1630 off += reg->off;
1632 if (reg->type == PTR_TO_MAP_VALUE) {
1633 if (t == BPF_WRITE && value_regno >= 0 &&
1634 is_pointer_value(env, value_regno)) {
1635 verbose(env, "R%d leaks addr into map\n", value_regno);
1636 return -EACCES;
1639 err = check_map_access(env, regno, off, size, false);
1640 if (!err && t == BPF_READ && value_regno >= 0)
1641 mark_reg_unknown(env, regs, value_regno);
1643 } else if (reg->type == PTR_TO_CTX) {
1644 enum bpf_reg_type reg_type = SCALAR_VALUE;
1646 if (t == BPF_WRITE && value_regno >= 0 &&
1647 is_pointer_value(env, value_regno)) {
1648 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1649 return -EACCES;
1651 /* ctx accesses must be at a fixed offset, so that we can
1652 * determine what type of data were returned.
1654 if (reg->off) {
1655 verbose(env,
1656 "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
1657 regno, reg->off, off - reg->off);
1658 return -EACCES;
1660 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1661 char tn_buf[48];
1663 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1664 verbose(env,
1665 "variable ctx access var_off=%s off=%d size=%d",
1666 tn_buf, off, size);
1667 return -EACCES;
1669 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
1670 if (!err && t == BPF_READ && value_regno >= 0) {
1671 /* ctx access returns either a scalar, or a
1672 * PTR_TO_PACKET[_META,_END]. In the latter
1673 * case, we know the offset is zero.
1675 if (reg_type == SCALAR_VALUE)
1676 mark_reg_unknown(env, regs, value_regno);
1677 else
1678 mark_reg_known_zero(env, regs,
1679 value_regno);
1680 regs[value_regno].id = 0;
1681 regs[value_regno].off = 0;
1682 regs[value_regno].range = 0;
1683 regs[value_regno].type = reg_type;
1686 } else if (reg->type == PTR_TO_STACK) {
1687 /* stack accesses must be at a fixed offset, so that we can
1688 * determine what type of data were returned.
1689 * See check_stack_read().
1691 if (!tnum_is_const(reg->var_off)) {
1692 char tn_buf[48];
1694 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1695 verbose(env, "variable stack access var_off=%s off=%d size=%d",
1696 tn_buf, off, size);
1697 return -EACCES;
1699 off += reg->var_off.value;
1700 if (off >= 0 || off < -MAX_BPF_STACK) {
1701 verbose(env, "invalid stack off=%d size=%d\n", off,
1702 size);
1703 return -EACCES;
1706 state = func(env, reg);
1707 err = update_stack_depth(env, state, off);
1708 if (err)
1709 return err;
1711 if (t == BPF_WRITE)
1712 err = check_stack_write(env, state, off, size,
1713 value_regno, insn_idx);
1714 else
1715 err = check_stack_read(env, state, off, size,
1716 value_regno);
1717 } else if (reg_is_pkt_pointer(reg)) {
1718 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1719 verbose(env, "cannot write into packet\n");
1720 return -EACCES;
1722 if (t == BPF_WRITE && value_regno >= 0 &&
1723 is_pointer_value(env, value_regno)) {
1724 verbose(env, "R%d leaks addr into packet\n",
1725 value_regno);
1726 return -EACCES;
1728 err = check_packet_access(env, regno, off, size, false);
1729 if (!err && t == BPF_READ && value_regno >= 0)
1730 mark_reg_unknown(env, regs, value_regno);
1731 } else {
1732 verbose(env, "R%d invalid mem access '%s'\n", regno,
1733 reg_type_str[reg->type]);
1734 return -EACCES;
1737 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1738 regs[value_regno].type == SCALAR_VALUE) {
1739 /* b/h/w load zero-extends, mark upper bits as known 0 */
1740 coerce_reg_to_size(&regs[value_regno], size);
1742 return err;
1745 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1747 int err;
1749 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1750 insn->imm != 0) {
1751 verbose(env, "BPF_XADD uses reserved fields\n");
1752 return -EINVAL;
1755 /* check src1 operand */
1756 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1757 if (err)
1758 return err;
1760 /* check src2 operand */
1761 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1762 if (err)
1763 return err;
1765 if (is_pointer_value(env, insn->src_reg)) {
1766 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1767 return -EACCES;
1770 if (is_ctx_reg(env, insn->dst_reg) ||
1771 is_pkt_reg(env, insn->dst_reg)) {
1772 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1773 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1774 "context" : "packet");
1775 return -EACCES;
1778 /* check whether atomic_add can read the memory */
1779 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1780 BPF_SIZE(insn->code), BPF_READ, -1, true);
1781 if (err)
1782 return err;
1784 /* check whether atomic_add can write into the same memory */
1785 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1786 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
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 off, i, 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))
1807 return 0;
1809 verbose(env, "R%d type=%s expected=%s\n", regno,
1810 reg_type_str[reg->type],
1811 reg_type_str[PTR_TO_STACK]);
1812 return -EACCES;
1815 /* Only allow fixed-offset stack reads */
1816 if (!tnum_is_const(reg->var_off)) {
1817 char tn_buf[48];
1819 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1820 verbose(env, "invalid variable stack read R%d var_off=%s\n",
1821 regno, tn_buf);
1822 return -EACCES;
1824 off = reg->off + reg->var_off.value;
1825 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1826 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1827 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1828 regno, off, access_size);
1829 return -EACCES;
1832 if (meta && meta->raw_mode) {
1833 meta->access_size = access_size;
1834 meta->regno = regno;
1835 return 0;
1838 for (i = 0; i < access_size; i++) {
1839 u8 *stype;
1841 slot = -(off + i) - 1;
1842 spi = slot / BPF_REG_SIZE;
1843 if (state->allocated_stack <= slot)
1844 goto err;
1845 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1846 if (*stype == STACK_MISC)
1847 goto mark;
1848 if (*stype == STACK_ZERO) {
1849 /* helper can write anything into the stack */
1850 *stype = STACK_MISC;
1851 goto mark;
1853 err:
1854 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1855 off, i, access_size);
1856 return -EACCES;
1857 mark:
1858 /* reading any byte out of 8-byte 'spill_slot' will cause
1859 * the whole slot to be marked as 'read'
1861 mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
1862 spi, state->frameno);
1864 return update_stack_depth(env, state, off);
1867 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1868 int access_size, bool zero_size_allowed,
1869 struct bpf_call_arg_meta *meta)
1871 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1873 switch (reg->type) {
1874 case PTR_TO_PACKET:
1875 case PTR_TO_PACKET_META:
1876 return check_packet_access(env, regno, reg->off, access_size,
1877 zero_size_allowed);
1878 case PTR_TO_MAP_VALUE:
1879 return check_map_access(env, regno, reg->off, access_size,
1880 zero_size_allowed);
1881 default: /* scalar_value|ptr_to_stack or invalid ptr */
1882 return check_stack_boundary(env, regno, access_size,
1883 zero_size_allowed, meta);
1887 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1889 return type == ARG_PTR_TO_MEM ||
1890 type == ARG_PTR_TO_MEM_OR_NULL ||
1891 type == ARG_PTR_TO_UNINIT_MEM;
1894 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1896 return type == ARG_CONST_SIZE ||
1897 type == ARG_CONST_SIZE_OR_ZERO;
1900 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1901 enum bpf_arg_type arg_type,
1902 struct bpf_call_arg_meta *meta)
1904 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1905 enum bpf_reg_type expected_type, type = reg->type;
1906 int err = 0;
1908 if (arg_type == ARG_DONTCARE)
1909 return 0;
1911 err = check_reg_arg(env, regno, SRC_OP);
1912 if (err)
1913 return err;
1915 if (arg_type == ARG_ANYTHING) {
1916 if (is_pointer_value(env, regno)) {
1917 verbose(env, "R%d leaks addr into helper function\n",
1918 regno);
1919 return -EACCES;
1921 return 0;
1924 if (type_is_pkt_pointer(type) &&
1925 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1926 verbose(env, "helper access to the packet is not allowed\n");
1927 return -EACCES;
1930 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1931 arg_type == ARG_PTR_TO_MAP_VALUE) {
1932 expected_type = PTR_TO_STACK;
1933 if (!type_is_pkt_pointer(type) &&
1934 type != expected_type)
1935 goto err_type;
1936 } else if (arg_type == ARG_CONST_SIZE ||
1937 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1938 expected_type = SCALAR_VALUE;
1939 if (type != expected_type)
1940 goto err_type;
1941 } else if (arg_type == ARG_CONST_MAP_PTR) {
1942 expected_type = CONST_PTR_TO_MAP;
1943 if (type != expected_type)
1944 goto err_type;
1945 } else if (arg_type == ARG_PTR_TO_CTX) {
1946 expected_type = PTR_TO_CTX;
1947 if (type != expected_type)
1948 goto err_type;
1949 } else if (arg_type_is_mem_ptr(arg_type)) {
1950 expected_type = PTR_TO_STACK;
1951 /* One exception here. In case function allows for NULL to be
1952 * passed in as argument, it's a SCALAR_VALUE type. Final test
1953 * happens during stack boundary checking.
1955 if (register_is_null(reg) &&
1956 arg_type == ARG_PTR_TO_MEM_OR_NULL)
1957 /* final test in check_stack_boundary() */;
1958 else if (!type_is_pkt_pointer(type) &&
1959 type != PTR_TO_MAP_VALUE &&
1960 type != expected_type)
1961 goto err_type;
1962 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1963 } else {
1964 verbose(env, "unsupported arg_type %d\n", arg_type);
1965 return -EFAULT;
1968 if (arg_type == ARG_CONST_MAP_PTR) {
1969 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1970 meta->map_ptr = reg->map_ptr;
1971 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1972 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1973 * check that [key, key + map->key_size) are within
1974 * stack limits and initialized
1976 if (!meta->map_ptr) {
1977 /* in function declaration map_ptr must come before
1978 * map_key, so that it's verified and known before
1979 * we have to check map_key here. Otherwise it means
1980 * that kernel subsystem misconfigured verifier
1982 verbose(env, "invalid map_ptr to access map->key\n");
1983 return -EACCES;
1985 if (type_is_pkt_pointer(type))
1986 err = check_packet_access(env, regno, reg->off,
1987 meta->map_ptr->key_size,
1988 false);
1989 else
1990 err = check_stack_boundary(env, regno,
1991 meta->map_ptr->key_size,
1992 false, NULL);
1993 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1994 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1995 * check [value, value + map->value_size) validity
1997 if (!meta->map_ptr) {
1998 /* kernel subsystem misconfigured verifier */
1999 verbose(env, "invalid map_ptr to access map->value\n");
2000 return -EACCES;
2002 if (type_is_pkt_pointer(type))
2003 err = check_packet_access(env, regno, reg->off,
2004 meta->map_ptr->value_size,
2005 false);
2006 else
2007 err = check_stack_boundary(env, regno,
2008 meta->map_ptr->value_size,
2009 false, NULL);
2010 } else if (arg_type_is_mem_size(arg_type)) {
2011 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
2013 /* The register is SCALAR_VALUE; the access check
2014 * happens using its boundaries.
2016 if (!tnum_is_const(reg->var_off))
2017 /* For unprivileged variable accesses, disable raw
2018 * mode so that the program is required to
2019 * initialize all the memory that the helper could
2020 * just partially fill up.
2022 meta = NULL;
2024 if (reg->smin_value < 0) {
2025 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2026 regno);
2027 return -EACCES;
2030 if (reg->umin_value == 0) {
2031 err = check_helper_mem_access(env, regno - 1, 0,
2032 zero_size_allowed,
2033 meta);
2034 if (err)
2035 return err;
2038 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2039 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2040 regno);
2041 return -EACCES;
2043 err = check_helper_mem_access(env, regno - 1,
2044 reg->umax_value,
2045 zero_size_allowed, meta);
2048 return err;
2049 err_type:
2050 verbose(env, "R%d type=%s expected=%s\n", regno,
2051 reg_type_str[type], reg_type_str[expected_type]);
2052 return -EACCES;
2055 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2056 struct bpf_map *map, int func_id)
2058 if (!map)
2059 return 0;
2061 /* We need a two way check, first is from map perspective ... */
2062 switch (map->map_type) {
2063 case BPF_MAP_TYPE_PROG_ARRAY:
2064 if (func_id != BPF_FUNC_tail_call)
2065 goto error;
2066 break;
2067 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2068 if (func_id != BPF_FUNC_perf_event_read &&
2069 func_id != BPF_FUNC_perf_event_output &&
2070 func_id != BPF_FUNC_perf_event_read_value)
2071 goto error;
2072 break;
2073 case BPF_MAP_TYPE_STACK_TRACE:
2074 if (func_id != BPF_FUNC_get_stackid)
2075 goto error;
2076 break;
2077 case BPF_MAP_TYPE_CGROUP_ARRAY:
2078 if (func_id != BPF_FUNC_skb_under_cgroup &&
2079 func_id != BPF_FUNC_current_task_under_cgroup)
2080 goto error;
2081 break;
2082 /* devmap returns a pointer to a live net_device ifindex that we cannot
2083 * allow to be modified from bpf side. So do not allow lookup elements
2084 * for now.
2086 case BPF_MAP_TYPE_DEVMAP:
2087 if (func_id != BPF_FUNC_redirect_map)
2088 goto error;
2089 break;
2090 /* Restrict bpf side of cpumap, open when use-cases appear */
2091 case BPF_MAP_TYPE_CPUMAP:
2092 if (func_id != BPF_FUNC_redirect_map)
2093 goto error;
2094 break;
2095 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2096 case BPF_MAP_TYPE_HASH_OF_MAPS:
2097 if (func_id != BPF_FUNC_map_lookup_elem)
2098 goto error;
2099 break;
2100 case BPF_MAP_TYPE_SOCKMAP:
2101 if (func_id != BPF_FUNC_sk_redirect_map &&
2102 func_id != BPF_FUNC_sock_map_update &&
2103 func_id != BPF_FUNC_map_delete_elem)
2104 goto error;
2105 break;
2106 default:
2107 break;
2110 /* ... and second from the function itself. */
2111 switch (func_id) {
2112 case BPF_FUNC_tail_call:
2113 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2114 goto error;
2115 if (env->subprog_cnt) {
2116 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2117 return -EINVAL;
2119 break;
2120 case BPF_FUNC_perf_event_read:
2121 case BPF_FUNC_perf_event_output:
2122 case BPF_FUNC_perf_event_read_value:
2123 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2124 goto error;
2125 break;
2126 case BPF_FUNC_get_stackid:
2127 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2128 goto error;
2129 break;
2130 case BPF_FUNC_current_task_under_cgroup:
2131 case BPF_FUNC_skb_under_cgroup:
2132 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2133 goto error;
2134 break;
2135 case BPF_FUNC_redirect_map:
2136 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2137 map->map_type != BPF_MAP_TYPE_CPUMAP)
2138 goto error;
2139 break;
2140 case BPF_FUNC_sk_redirect_map:
2141 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2142 goto error;
2143 break;
2144 case BPF_FUNC_sock_map_update:
2145 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2146 goto error;
2147 break;
2148 default:
2149 break;
2152 return 0;
2153 error:
2154 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2155 map->map_type, func_id_name(func_id), func_id);
2156 return -EINVAL;
2159 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2161 int count = 0;
2163 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2164 count++;
2165 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2166 count++;
2167 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2168 count++;
2169 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2170 count++;
2171 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2172 count++;
2174 /* We only support one arg being in raw mode at the moment,
2175 * which is sufficient for the helper functions we have
2176 * right now.
2178 return count <= 1;
2181 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2182 enum bpf_arg_type arg_next)
2184 return (arg_type_is_mem_ptr(arg_curr) &&
2185 !arg_type_is_mem_size(arg_next)) ||
2186 (!arg_type_is_mem_ptr(arg_curr) &&
2187 arg_type_is_mem_size(arg_next));
2190 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2192 /* bpf_xxx(..., buf, len) call will access 'len'
2193 * bytes from memory 'buf'. Both arg types need
2194 * to be paired, so make sure there's no buggy
2195 * helper function specification.
2197 if (arg_type_is_mem_size(fn->arg1_type) ||
2198 arg_type_is_mem_ptr(fn->arg5_type) ||
2199 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2200 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2201 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2202 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2203 return false;
2205 return true;
2208 static int check_func_proto(const struct bpf_func_proto *fn)
2210 return check_raw_mode_ok(fn) &&
2211 check_arg_pair_ok(fn) ? 0 : -EINVAL;
2214 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2215 * are now invalid, so turn them into unknown SCALAR_VALUE.
2217 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2218 struct bpf_func_state *state)
2220 struct bpf_reg_state *regs = state->regs, *reg;
2221 int i;
2223 for (i = 0; i < MAX_BPF_REG; i++)
2224 if (reg_is_pkt_pointer_any(&regs[i]))
2225 mark_reg_unknown(env, regs, i);
2227 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2228 if (state->stack[i].slot_type[0] != STACK_SPILL)
2229 continue;
2230 reg = &state->stack[i].spilled_ptr;
2231 if (reg_is_pkt_pointer_any(reg))
2232 __mark_reg_unknown(reg);
2236 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2238 struct bpf_verifier_state *vstate = env->cur_state;
2239 int i;
2241 for (i = 0; i <= vstate->curframe; i++)
2242 __clear_all_pkt_pointers(env, vstate->frame[i]);
2245 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2246 int *insn_idx)
2248 struct bpf_verifier_state *state = env->cur_state;
2249 struct bpf_func_state *caller, *callee;
2250 int i, subprog, target_insn;
2252 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2253 verbose(env, "the call stack of %d frames is too deep\n",
2254 state->curframe + 2);
2255 return -E2BIG;
2258 target_insn = *insn_idx + insn->imm;
2259 subprog = find_subprog(env, target_insn + 1);
2260 if (subprog < 0) {
2261 verbose(env, "verifier bug. No program starts at insn %d\n",
2262 target_insn + 1);
2263 return -EFAULT;
2266 caller = state->frame[state->curframe];
2267 if (state->frame[state->curframe + 1]) {
2268 verbose(env, "verifier bug. Frame %d already allocated\n",
2269 state->curframe + 1);
2270 return -EFAULT;
2273 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2274 if (!callee)
2275 return -ENOMEM;
2276 state->frame[state->curframe + 1] = callee;
2278 /* callee cannot access r0, r6 - r9 for reading and has to write
2279 * into its own stack before reading from it.
2280 * callee can read/write into caller's stack
2282 init_func_state(env, callee,
2283 /* remember the callsite, it will be used by bpf_exit */
2284 *insn_idx /* callsite */,
2285 state->curframe + 1 /* frameno within this callchain */,
2286 subprog + 1 /* subprog number within this prog */);
2288 /* copy r1 - r5 args that callee can access */
2289 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2290 callee->regs[i] = caller->regs[i];
2292 /* after the call regsiters r0 - r5 were scratched */
2293 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2294 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2295 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2298 /* only increment it after check_reg_arg() finished */
2299 state->curframe++;
2301 /* and go analyze first insn of the callee */
2302 *insn_idx = target_insn;
2304 if (env->log.level) {
2305 verbose(env, "caller:\n");
2306 print_verifier_state(env, caller);
2307 verbose(env, "callee:\n");
2308 print_verifier_state(env, callee);
2310 return 0;
2313 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2315 struct bpf_verifier_state *state = env->cur_state;
2316 struct bpf_func_state *caller, *callee;
2317 struct bpf_reg_state *r0;
2319 callee = state->frame[state->curframe];
2320 r0 = &callee->regs[BPF_REG_0];
2321 if (r0->type == PTR_TO_STACK) {
2322 /* technically it's ok to return caller's stack pointer
2323 * (or caller's caller's pointer) back to the caller,
2324 * since these pointers are valid. Only current stack
2325 * pointer will be invalid as soon as function exits,
2326 * but let's be conservative
2328 verbose(env, "cannot return stack pointer to the caller\n");
2329 return -EINVAL;
2332 state->curframe--;
2333 caller = state->frame[state->curframe];
2334 /* return to the caller whatever r0 had in the callee */
2335 caller->regs[BPF_REG_0] = *r0;
2337 *insn_idx = callee->callsite + 1;
2338 if (env->log.level) {
2339 verbose(env, "returning from callee:\n");
2340 print_verifier_state(env, callee);
2341 verbose(env, "to caller at %d:\n", *insn_idx);
2342 print_verifier_state(env, caller);
2344 /* clear everything in the callee */
2345 free_func_state(callee);
2346 state->frame[state->curframe + 1] = NULL;
2347 return 0;
2350 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2352 const struct bpf_func_proto *fn = NULL;
2353 struct bpf_reg_state *regs;
2354 struct bpf_call_arg_meta meta;
2355 bool changes_data;
2356 int i, err;
2358 /* find function prototype */
2359 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2360 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2361 func_id);
2362 return -EINVAL;
2365 if (env->ops->get_func_proto)
2366 fn = env->ops->get_func_proto(func_id);
2367 if (!fn) {
2368 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2369 func_id);
2370 return -EINVAL;
2373 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2374 if (!env->prog->gpl_compatible && fn->gpl_only) {
2375 verbose(env, "cannot call GPL only function from proprietary program\n");
2376 return -EINVAL;
2379 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2380 changes_data = bpf_helper_changes_pkt_data(fn->func);
2381 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2382 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2383 func_id_name(func_id), func_id);
2384 return -EINVAL;
2387 memset(&meta, 0, sizeof(meta));
2388 meta.pkt_access = fn->pkt_access;
2390 err = check_func_proto(fn);
2391 if (err) {
2392 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2393 func_id_name(func_id), func_id);
2394 return err;
2397 /* check args */
2398 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2399 if (err)
2400 return err;
2401 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2402 if (err)
2403 return err;
2404 if (func_id == BPF_FUNC_tail_call) {
2405 if (meta.map_ptr == NULL) {
2406 verbose(env, "verifier bug\n");
2407 return -EINVAL;
2409 env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
2411 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2412 if (err)
2413 return err;
2414 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2415 if (err)
2416 return err;
2417 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2418 if (err)
2419 return err;
2421 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2422 * is inferred from register state.
2424 for (i = 0; i < meta.access_size; i++) {
2425 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2426 BPF_WRITE, -1, false);
2427 if (err)
2428 return err;
2431 regs = cur_regs(env);
2432 /* reset caller saved regs */
2433 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2434 mark_reg_not_init(env, regs, caller_saved[i]);
2435 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2438 /* update return register (already marked as written above) */
2439 if (fn->ret_type == RET_INTEGER) {
2440 /* sets type to SCALAR_VALUE */
2441 mark_reg_unknown(env, regs, BPF_REG_0);
2442 } else if (fn->ret_type == RET_VOID) {
2443 regs[BPF_REG_0].type = NOT_INIT;
2444 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
2445 struct bpf_insn_aux_data *insn_aux;
2447 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2448 /* There is no offset yet applied, variable or fixed */
2449 mark_reg_known_zero(env, regs, BPF_REG_0);
2450 regs[BPF_REG_0].off = 0;
2451 /* remember map_ptr, so that check_map_access()
2452 * can check 'value_size' boundary of memory access
2453 * to map element returned from bpf_map_lookup_elem()
2455 if (meta.map_ptr == NULL) {
2456 verbose(env,
2457 "kernel subsystem misconfigured verifier\n");
2458 return -EINVAL;
2460 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2461 regs[BPF_REG_0].id = ++env->id_gen;
2462 insn_aux = &env->insn_aux_data[insn_idx];
2463 if (!insn_aux->map_ptr)
2464 insn_aux->map_ptr = meta.map_ptr;
2465 else if (insn_aux->map_ptr != meta.map_ptr)
2466 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
2467 } else {
2468 verbose(env, "unknown return type %d of func %s#%d\n",
2469 fn->ret_type, func_id_name(func_id), func_id);
2470 return -EINVAL;
2473 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2474 if (err)
2475 return err;
2477 if (changes_data)
2478 clear_all_pkt_pointers(env);
2479 return 0;
2482 static bool signed_add_overflows(s64 a, s64 b)
2484 /* Do the add in u64, where overflow is well-defined */
2485 s64 res = (s64)((u64)a + (u64)b);
2487 if (b < 0)
2488 return res > a;
2489 return res < a;
2492 static bool signed_sub_overflows(s64 a, s64 b)
2494 /* Do the sub in u64, where overflow is well-defined */
2495 s64 res = (s64)((u64)a - (u64)b);
2497 if (b < 0)
2498 return res < a;
2499 return res > a;
2502 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2503 const struct bpf_reg_state *reg,
2504 enum bpf_reg_type type)
2506 bool known = tnum_is_const(reg->var_off);
2507 s64 val = reg->var_off.value;
2508 s64 smin = reg->smin_value;
2510 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2511 verbose(env, "math between %s pointer and %lld is not allowed\n",
2512 reg_type_str[type], val);
2513 return false;
2516 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2517 verbose(env, "%s pointer offset %d is not allowed\n",
2518 reg_type_str[type], reg->off);
2519 return false;
2522 if (smin == S64_MIN) {
2523 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2524 reg_type_str[type]);
2525 return false;
2528 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2529 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2530 smin, reg_type_str[type]);
2531 return false;
2534 return true;
2537 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2538 * Caller should also handle BPF_MOV case separately.
2539 * If we return -EACCES, caller may want to try again treating pointer as a
2540 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
2542 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2543 struct bpf_insn *insn,
2544 const struct bpf_reg_state *ptr_reg,
2545 const struct bpf_reg_state *off_reg)
2547 struct bpf_verifier_state *vstate = env->cur_state;
2548 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2549 struct bpf_reg_state *regs = state->regs, *dst_reg;
2550 bool known = tnum_is_const(off_reg->var_off);
2551 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2552 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2553 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2554 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2555 u8 opcode = BPF_OP(insn->code);
2556 u32 dst = insn->dst_reg;
2558 dst_reg = &regs[dst];
2560 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2561 smin_val > smax_val || umin_val > umax_val) {
2562 /* Taint dst register if offset had invalid bounds derived from
2563 * e.g. dead branches.
2565 __mark_reg_unknown(dst_reg);
2566 return 0;
2569 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2570 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2571 verbose(env,
2572 "R%d 32-bit pointer arithmetic prohibited\n",
2573 dst);
2574 return -EACCES;
2577 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2578 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2579 dst);
2580 return -EACCES;
2582 if (ptr_reg->type == CONST_PTR_TO_MAP) {
2583 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2584 dst);
2585 return -EACCES;
2587 if (ptr_reg->type == PTR_TO_PACKET_END) {
2588 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2589 dst);
2590 return -EACCES;
2593 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2594 * The id may be overwritten later if we create a new variable offset.
2596 dst_reg->type = ptr_reg->type;
2597 dst_reg->id = ptr_reg->id;
2599 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2600 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2601 return -EINVAL;
2603 switch (opcode) {
2604 case BPF_ADD:
2605 /* We can take a fixed offset as long as it doesn't overflow
2606 * the s32 'off' field
2608 if (known && (ptr_reg->off + smin_val ==
2609 (s64)(s32)(ptr_reg->off + smin_val))) {
2610 /* pointer += K. Accumulate it into fixed offset */
2611 dst_reg->smin_value = smin_ptr;
2612 dst_reg->smax_value = smax_ptr;
2613 dst_reg->umin_value = umin_ptr;
2614 dst_reg->umax_value = umax_ptr;
2615 dst_reg->var_off = ptr_reg->var_off;
2616 dst_reg->off = ptr_reg->off + smin_val;
2617 dst_reg->range = ptr_reg->range;
2618 break;
2620 /* A new variable offset is created. Note that off_reg->off
2621 * == 0, since it's a scalar.
2622 * dst_reg gets the pointer type and since some positive
2623 * integer value was added to the pointer, give it a new 'id'
2624 * if it's a PTR_TO_PACKET.
2625 * this creates a new 'base' pointer, off_reg (variable) gets
2626 * added into the variable offset, and we copy the fixed offset
2627 * from ptr_reg.
2629 if (signed_add_overflows(smin_ptr, smin_val) ||
2630 signed_add_overflows(smax_ptr, smax_val)) {
2631 dst_reg->smin_value = S64_MIN;
2632 dst_reg->smax_value = S64_MAX;
2633 } else {
2634 dst_reg->smin_value = smin_ptr + smin_val;
2635 dst_reg->smax_value = smax_ptr + smax_val;
2637 if (umin_ptr + umin_val < umin_ptr ||
2638 umax_ptr + umax_val < umax_ptr) {
2639 dst_reg->umin_value = 0;
2640 dst_reg->umax_value = U64_MAX;
2641 } else {
2642 dst_reg->umin_value = umin_ptr + umin_val;
2643 dst_reg->umax_value = umax_ptr + umax_val;
2645 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2646 dst_reg->off = ptr_reg->off;
2647 if (reg_is_pkt_pointer(ptr_reg)) {
2648 dst_reg->id = ++env->id_gen;
2649 /* something was added to pkt_ptr, set range to zero */
2650 dst_reg->range = 0;
2652 break;
2653 case BPF_SUB:
2654 if (dst_reg == off_reg) {
2655 /* scalar -= pointer. Creates an unknown scalar */
2656 verbose(env, "R%d tried to subtract pointer from scalar\n",
2657 dst);
2658 return -EACCES;
2660 /* We don't allow subtraction from FP, because (according to
2661 * test_verifier.c test "invalid fp arithmetic", JITs might not
2662 * be able to deal with it.
2664 if (ptr_reg->type == PTR_TO_STACK) {
2665 verbose(env, "R%d subtraction from stack pointer prohibited\n",
2666 dst);
2667 return -EACCES;
2669 if (known && (ptr_reg->off - smin_val ==
2670 (s64)(s32)(ptr_reg->off - smin_val))) {
2671 /* pointer -= K. Subtract it from fixed offset */
2672 dst_reg->smin_value = smin_ptr;
2673 dst_reg->smax_value = smax_ptr;
2674 dst_reg->umin_value = umin_ptr;
2675 dst_reg->umax_value = umax_ptr;
2676 dst_reg->var_off = ptr_reg->var_off;
2677 dst_reg->id = ptr_reg->id;
2678 dst_reg->off = ptr_reg->off - smin_val;
2679 dst_reg->range = ptr_reg->range;
2680 break;
2682 /* A new variable offset is created. If the subtrahend is known
2683 * nonnegative, then any reg->range we had before is still good.
2685 if (signed_sub_overflows(smin_ptr, smax_val) ||
2686 signed_sub_overflows(smax_ptr, smin_val)) {
2687 /* Overflow possible, we know nothing */
2688 dst_reg->smin_value = S64_MIN;
2689 dst_reg->smax_value = S64_MAX;
2690 } else {
2691 dst_reg->smin_value = smin_ptr - smax_val;
2692 dst_reg->smax_value = smax_ptr - smin_val;
2694 if (umin_ptr < umax_val) {
2695 /* Overflow possible, we know nothing */
2696 dst_reg->umin_value = 0;
2697 dst_reg->umax_value = U64_MAX;
2698 } else {
2699 /* Cannot overflow (as long as bounds are consistent) */
2700 dst_reg->umin_value = umin_ptr - umax_val;
2701 dst_reg->umax_value = umax_ptr - umin_val;
2703 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2704 dst_reg->off = ptr_reg->off;
2705 if (reg_is_pkt_pointer(ptr_reg)) {
2706 dst_reg->id = ++env->id_gen;
2707 /* something was added to pkt_ptr, set range to zero */
2708 if (smin_val < 0)
2709 dst_reg->range = 0;
2711 break;
2712 case BPF_AND:
2713 case BPF_OR:
2714 case BPF_XOR:
2715 /* bitwise ops on pointers are troublesome, prohibit. */
2716 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
2717 dst, bpf_alu_string[opcode >> 4]);
2718 return -EACCES;
2719 default:
2720 /* other operators (e.g. MUL,LSH) produce non-pointer results */
2721 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
2722 dst, bpf_alu_string[opcode >> 4]);
2723 return -EACCES;
2726 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2727 return -EINVAL;
2729 __update_reg_bounds(dst_reg);
2730 __reg_deduce_bounds(dst_reg);
2731 __reg_bound_offset(dst_reg);
2732 return 0;
2735 /* WARNING: This function does calculations on 64-bit values, but the actual
2736 * execution may occur on 32-bit values. Therefore, things like bitshifts
2737 * need extra checks in the 32-bit case.
2739 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2740 struct bpf_insn *insn,
2741 struct bpf_reg_state *dst_reg,
2742 struct bpf_reg_state src_reg)
2744 struct bpf_reg_state *regs = cur_regs(env);
2745 u8 opcode = BPF_OP(insn->code);
2746 bool src_known, dst_known;
2747 s64 smin_val, smax_val;
2748 u64 umin_val, umax_val;
2749 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2751 smin_val = src_reg.smin_value;
2752 smax_val = src_reg.smax_value;
2753 umin_val = src_reg.umin_value;
2754 umax_val = src_reg.umax_value;
2755 src_known = tnum_is_const(src_reg.var_off);
2756 dst_known = tnum_is_const(dst_reg->var_off);
2758 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2759 smin_val > smax_val || umin_val > umax_val) {
2760 /* Taint dst register if offset had invalid bounds derived from
2761 * e.g. dead branches.
2763 __mark_reg_unknown(dst_reg);
2764 return 0;
2767 if (!src_known &&
2768 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2769 __mark_reg_unknown(dst_reg);
2770 return 0;
2773 switch (opcode) {
2774 case BPF_ADD:
2775 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2776 signed_add_overflows(dst_reg->smax_value, smax_val)) {
2777 dst_reg->smin_value = S64_MIN;
2778 dst_reg->smax_value = S64_MAX;
2779 } else {
2780 dst_reg->smin_value += smin_val;
2781 dst_reg->smax_value += smax_val;
2783 if (dst_reg->umin_value + umin_val < umin_val ||
2784 dst_reg->umax_value + umax_val < umax_val) {
2785 dst_reg->umin_value = 0;
2786 dst_reg->umax_value = U64_MAX;
2787 } else {
2788 dst_reg->umin_value += umin_val;
2789 dst_reg->umax_value += umax_val;
2791 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2792 break;
2793 case BPF_SUB:
2794 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2795 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2796 /* Overflow possible, we know nothing */
2797 dst_reg->smin_value = S64_MIN;
2798 dst_reg->smax_value = S64_MAX;
2799 } else {
2800 dst_reg->smin_value -= smax_val;
2801 dst_reg->smax_value -= smin_val;
2803 if (dst_reg->umin_value < umax_val) {
2804 /* Overflow possible, we know nothing */
2805 dst_reg->umin_value = 0;
2806 dst_reg->umax_value = U64_MAX;
2807 } else {
2808 /* Cannot overflow (as long as bounds are consistent) */
2809 dst_reg->umin_value -= umax_val;
2810 dst_reg->umax_value -= umin_val;
2812 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2813 break;
2814 case BPF_MUL:
2815 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2816 if (smin_val < 0 || dst_reg->smin_value < 0) {
2817 /* Ain't nobody got time to multiply that sign */
2818 __mark_reg_unbounded(dst_reg);
2819 __update_reg_bounds(dst_reg);
2820 break;
2822 /* Both values are positive, so we can work with unsigned and
2823 * copy the result to signed (unless it exceeds S64_MAX).
2825 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2826 /* Potential overflow, we know nothing */
2827 __mark_reg_unbounded(dst_reg);
2828 /* (except what we can learn from the var_off) */
2829 __update_reg_bounds(dst_reg);
2830 break;
2832 dst_reg->umin_value *= umin_val;
2833 dst_reg->umax_value *= umax_val;
2834 if (dst_reg->umax_value > S64_MAX) {
2835 /* Overflow possible, we know nothing */
2836 dst_reg->smin_value = S64_MIN;
2837 dst_reg->smax_value = S64_MAX;
2838 } else {
2839 dst_reg->smin_value = dst_reg->umin_value;
2840 dst_reg->smax_value = dst_reg->umax_value;
2842 break;
2843 case BPF_AND:
2844 if (src_known && dst_known) {
2845 __mark_reg_known(dst_reg, dst_reg->var_off.value &
2846 src_reg.var_off.value);
2847 break;
2849 /* We get our minimum from the var_off, since that's inherently
2850 * bitwise. Our maximum is the minimum of the operands' maxima.
2852 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2853 dst_reg->umin_value = dst_reg->var_off.value;
2854 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2855 if (dst_reg->smin_value < 0 || smin_val < 0) {
2856 /* Lose signed bounds when ANDing negative numbers,
2857 * ain't nobody got time for that.
2859 dst_reg->smin_value = S64_MIN;
2860 dst_reg->smax_value = S64_MAX;
2861 } else {
2862 /* ANDing two positives gives a positive, so safe to
2863 * cast result into s64.
2865 dst_reg->smin_value = dst_reg->umin_value;
2866 dst_reg->smax_value = dst_reg->umax_value;
2868 /* We may learn something more from the var_off */
2869 __update_reg_bounds(dst_reg);
2870 break;
2871 case BPF_OR:
2872 if (src_known && dst_known) {
2873 __mark_reg_known(dst_reg, dst_reg->var_off.value |
2874 src_reg.var_off.value);
2875 break;
2877 /* We get our maximum from the var_off, and our minimum is the
2878 * maximum of the operands' minima
2880 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2881 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2882 dst_reg->umax_value = dst_reg->var_off.value |
2883 dst_reg->var_off.mask;
2884 if (dst_reg->smin_value < 0 || smin_val < 0) {
2885 /* Lose signed bounds when ORing negative numbers,
2886 * ain't nobody got time for that.
2888 dst_reg->smin_value = S64_MIN;
2889 dst_reg->smax_value = S64_MAX;
2890 } else {
2891 /* ORing two positives gives a positive, so safe to
2892 * cast result into s64.
2894 dst_reg->smin_value = dst_reg->umin_value;
2895 dst_reg->smax_value = dst_reg->umax_value;
2897 /* We may learn something more from the var_off */
2898 __update_reg_bounds(dst_reg);
2899 break;
2900 case BPF_LSH:
2901 if (umax_val >= insn_bitness) {
2902 /* Shifts greater than 31 or 63 are undefined.
2903 * This includes shifts by a negative number.
2905 mark_reg_unknown(env, regs, insn->dst_reg);
2906 break;
2908 /* We lose all sign bit information (except what we can pick
2909 * up from var_off)
2911 dst_reg->smin_value = S64_MIN;
2912 dst_reg->smax_value = S64_MAX;
2913 /* If we might shift our top bit out, then we know nothing */
2914 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2915 dst_reg->umin_value = 0;
2916 dst_reg->umax_value = U64_MAX;
2917 } else {
2918 dst_reg->umin_value <<= umin_val;
2919 dst_reg->umax_value <<= umax_val;
2921 if (src_known)
2922 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2923 else
2924 dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2925 /* We may learn something more from the var_off */
2926 __update_reg_bounds(dst_reg);
2927 break;
2928 case BPF_RSH:
2929 if (umax_val >= insn_bitness) {
2930 /* Shifts greater than 31 or 63 are undefined.
2931 * This includes shifts by a negative number.
2933 mark_reg_unknown(env, regs, insn->dst_reg);
2934 break;
2936 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
2937 * be negative, then either:
2938 * 1) src_reg might be zero, so the sign bit of the result is
2939 * unknown, so we lose our signed bounds
2940 * 2) it's known negative, thus the unsigned bounds capture the
2941 * signed bounds
2942 * 3) the signed bounds cross zero, so they tell us nothing
2943 * about the result
2944 * If the value in dst_reg is known nonnegative, then again the
2945 * unsigned bounts capture the signed bounds.
2946 * Thus, in all cases it suffices to blow away our signed bounds
2947 * and rely on inferring new ones from the unsigned bounds and
2948 * var_off of the result.
2950 dst_reg->smin_value = S64_MIN;
2951 dst_reg->smax_value = S64_MAX;
2952 if (src_known)
2953 dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2954 umin_val);
2955 else
2956 dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2957 dst_reg->umin_value >>= umax_val;
2958 dst_reg->umax_value >>= umin_val;
2959 /* We may learn something more from the var_off */
2960 __update_reg_bounds(dst_reg);
2961 break;
2962 default:
2963 mark_reg_unknown(env, regs, insn->dst_reg);
2964 break;
2967 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2968 /* 32-bit ALU ops are (32,32)->32 */
2969 coerce_reg_to_size(dst_reg, 4);
2970 coerce_reg_to_size(&src_reg, 4);
2973 __reg_deduce_bounds(dst_reg);
2974 __reg_bound_offset(dst_reg);
2975 return 0;
2978 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2979 * and var_off.
2981 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2982 struct bpf_insn *insn)
2984 struct bpf_verifier_state *vstate = env->cur_state;
2985 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2986 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
2987 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2988 u8 opcode = BPF_OP(insn->code);
2990 dst_reg = &regs[insn->dst_reg];
2991 src_reg = NULL;
2992 if (dst_reg->type != SCALAR_VALUE)
2993 ptr_reg = dst_reg;
2994 if (BPF_SRC(insn->code) == BPF_X) {
2995 src_reg = &regs[insn->src_reg];
2996 if (src_reg->type != SCALAR_VALUE) {
2997 if (dst_reg->type != SCALAR_VALUE) {
2998 /* Combining two pointers by any ALU op yields
2999 * an arbitrary scalar. Disallow all math except
3000 * pointer subtraction
3002 if (opcode == BPF_SUB){
3003 mark_reg_unknown(env, regs, insn->dst_reg);
3004 return 0;
3006 verbose(env, "R%d pointer %s pointer prohibited\n",
3007 insn->dst_reg,
3008 bpf_alu_string[opcode >> 4]);
3009 return -EACCES;
3010 } else {
3011 /* scalar += pointer
3012 * This is legal, but we have to reverse our
3013 * src/dest handling in computing the range
3015 return adjust_ptr_min_max_vals(env, insn,
3016 src_reg, dst_reg);
3018 } else if (ptr_reg) {
3019 /* pointer += scalar */
3020 return adjust_ptr_min_max_vals(env, insn,
3021 dst_reg, src_reg);
3023 } else {
3024 /* Pretend the src is a reg with a known value, since we only
3025 * need to be able to read from this state.
3027 off_reg.type = SCALAR_VALUE;
3028 __mark_reg_known(&off_reg, insn->imm);
3029 src_reg = &off_reg;
3030 if (ptr_reg) /* pointer += K */
3031 return adjust_ptr_min_max_vals(env, insn,
3032 ptr_reg, src_reg);
3035 /* Got here implies adding two SCALAR_VALUEs */
3036 if (WARN_ON_ONCE(ptr_reg)) {
3037 print_verifier_state(env, state);
3038 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3039 return -EINVAL;
3041 if (WARN_ON(!src_reg)) {
3042 print_verifier_state(env, state);
3043 verbose(env, "verifier internal error: no src_reg\n");
3044 return -EINVAL;
3046 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3049 /* check validity of 32-bit and 64-bit arithmetic operations */
3050 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3052 struct bpf_reg_state *regs = cur_regs(env);
3053 u8 opcode = BPF_OP(insn->code);
3054 int err;
3056 if (opcode == BPF_END || opcode == BPF_NEG) {
3057 if (opcode == BPF_NEG) {
3058 if (BPF_SRC(insn->code) != 0 ||
3059 insn->src_reg != BPF_REG_0 ||
3060 insn->off != 0 || insn->imm != 0) {
3061 verbose(env, "BPF_NEG uses reserved fields\n");
3062 return -EINVAL;
3064 } else {
3065 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3066 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3067 BPF_CLASS(insn->code) == BPF_ALU64) {
3068 verbose(env, "BPF_END uses reserved fields\n");
3069 return -EINVAL;
3073 /* check src operand */
3074 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3075 if (err)
3076 return err;
3078 if (is_pointer_value(env, insn->dst_reg)) {
3079 verbose(env, "R%d pointer arithmetic prohibited\n",
3080 insn->dst_reg);
3081 return -EACCES;
3084 /* check dest operand */
3085 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3086 if (err)
3087 return err;
3089 } else if (opcode == BPF_MOV) {
3091 if (BPF_SRC(insn->code) == BPF_X) {
3092 if (insn->imm != 0 || insn->off != 0) {
3093 verbose(env, "BPF_MOV uses reserved fields\n");
3094 return -EINVAL;
3097 /* check src operand */
3098 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3099 if (err)
3100 return err;
3101 } else {
3102 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3103 verbose(env, "BPF_MOV uses reserved fields\n");
3104 return -EINVAL;
3108 /* check dest operand */
3109 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3110 if (err)
3111 return err;
3113 if (BPF_SRC(insn->code) == BPF_X) {
3114 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3115 /* case: R1 = R2
3116 * copy register state to dest reg
3118 regs[insn->dst_reg] = regs[insn->src_reg];
3119 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
3120 } else {
3121 /* R1 = (u32) R2 */
3122 if (is_pointer_value(env, insn->src_reg)) {
3123 verbose(env,
3124 "R%d partial copy of pointer\n",
3125 insn->src_reg);
3126 return -EACCES;
3128 mark_reg_unknown(env, regs, insn->dst_reg);
3129 coerce_reg_to_size(&regs[insn->dst_reg], 4);
3131 } else {
3132 /* case: R = imm
3133 * remember the value we stored into this reg
3135 regs[insn->dst_reg].type = SCALAR_VALUE;
3136 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3137 __mark_reg_known(regs + insn->dst_reg,
3138 insn->imm);
3139 } else {
3140 __mark_reg_known(regs + insn->dst_reg,
3141 (u32)insn->imm);
3145 } else if (opcode > BPF_END) {
3146 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3147 return -EINVAL;
3149 } else { /* all other ALU ops: and, sub, xor, add, ... */
3151 if (BPF_SRC(insn->code) == BPF_X) {
3152 if (insn->imm != 0 || insn->off != 0) {
3153 verbose(env, "BPF_ALU uses reserved fields\n");
3154 return -EINVAL;
3156 /* check src1 operand */
3157 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3158 if (err)
3159 return err;
3160 } else {
3161 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3162 verbose(env, "BPF_ALU uses reserved fields\n");
3163 return -EINVAL;
3167 /* check src2 operand */
3168 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3169 if (err)
3170 return err;
3172 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3173 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3174 verbose(env, "div by zero\n");
3175 return -EINVAL;
3178 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3179 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3180 return -EINVAL;
3183 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3184 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3185 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3187 if (insn->imm < 0 || insn->imm >= size) {
3188 verbose(env, "invalid shift %d\n", insn->imm);
3189 return -EINVAL;
3193 /* check dest operand */
3194 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3195 if (err)
3196 return err;
3198 return adjust_reg_min_max_vals(env, insn);
3201 return 0;
3204 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3205 struct bpf_reg_state *dst_reg,
3206 enum bpf_reg_type type,
3207 bool range_right_open)
3209 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3210 struct bpf_reg_state *regs = state->regs, *reg;
3211 u16 new_range;
3212 int i, j;
3214 if (dst_reg->off < 0 ||
3215 (dst_reg->off == 0 && range_right_open))
3216 /* This doesn't give us any range */
3217 return;
3219 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3220 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3221 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3222 * than pkt_end, but that's because it's also less than pkt.
3224 return;
3226 new_range = dst_reg->off;
3227 if (range_right_open)
3228 new_range--;
3230 /* Examples for register markings:
3232 * pkt_data in dst register:
3234 * r2 = r3;
3235 * r2 += 8;
3236 * if (r2 > pkt_end) goto <handle exception>
3237 * <access okay>
3239 * r2 = r3;
3240 * r2 += 8;
3241 * if (r2 < pkt_end) goto <access okay>
3242 * <handle exception>
3244 * Where:
3245 * r2 == dst_reg, pkt_end == src_reg
3246 * r2=pkt(id=n,off=8,r=0)
3247 * r3=pkt(id=n,off=0,r=0)
3249 * pkt_data in src register:
3251 * r2 = r3;
3252 * r2 += 8;
3253 * if (pkt_end >= r2) goto <access okay>
3254 * <handle exception>
3256 * r2 = r3;
3257 * r2 += 8;
3258 * if (pkt_end <= r2) goto <handle exception>
3259 * <access okay>
3261 * Where:
3262 * pkt_end == dst_reg, r2 == src_reg
3263 * r2=pkt(id=n,off=8,r=0)
3264 * r3=pkt(id=n,off=0,r=0)
3266 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3267 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3268 * and [r3, r3 + 8-1) respectively is safe to access depending on
3269 * the check.
3272 /* If our ids match, then we must have the same max_value. And we
3273 * don't care about the other reg's fixed offset, since if it's too big
3274 * the range won't allow anything.
3275 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3277 for (i = 0; i < MAX_BPF_REG; i++)
3278 if (regs[i].type == type && regs[i].id == dst_reg->id)
3279 /* keep the maximum range already checked */
3280 regs[i].range = max(regs[i].range, new_range);
3282 for (j = 0; j <= vstate->curframe; j++) {
3283 state = vstate->frame[j];
3284 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3285 if (state->stack[i].slot_type[0] != STACK_SPILL)
3286 continue;
3287 reg = &state->stack[i].spilled_ptr;
3288 if (reg->type == type && reg->id == dst_reg->id)
3289 reg->range = max(reg->range, new_range);
3294 /* Adjusts the register min/max values in the case that the dst_reg is the
3295 * variable register that we are working on, and src_reg is a constant or we're
3296 * simply doing a BPF_K check.
3297 * In JEQ/JNE cases we also adjust the var_off values.
3299 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3300 struct bpf_reg_state *false_reg, u64 val,
3301 u8 opcode)
3303 /* If the dst_reg is a pointer, we can't learn anything about its
3304 * variable offset from the compare (unless src_reg were a pointer into
3305 * the same object, but we don't bother with that.
3306 * Since false_reg and true_reg have the same type by construction, we
3307 * only need to check one of them for pointerness.
3309 if (__is_pointer_value(false, false_reg))
3310 return;
3312 switch (opcode) {
3313 case BPF_JEQ:
3314 /* If this is false then we know nothing Jon Snow, but if it is
3315 * true then we know for sure.
3317 __mark_reg_known(true_reg, val);
3318 break;
3319 case BPF_JNE:
3320 /* If this is true we know nothing Jon Snow, but if it is false
3321 * we know the value for sure;
3323 __mark_reg_known(false_reg, val);
3324 break;
3325 case BPF_JGT:
3326 false_reg->umax_value = min(false_reg->umax_value, val);
3327 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3328 break;
3329 case BPF_JSGT:
3330 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3331 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3332 break;
3333 case BPF_JLT:
3334 false_reg->umin_value = max(false_reg->umin_value, val);
3335 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3336 break;
3337 case BPF_JSLT:
3338 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3339 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3340 break;
3341 case BPF_JGE:
3342 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3343 true_reg->umin_value = max(true_reg->umin_value, val);
3344 break;
3345 case BPF_JSGE:
3346 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3347 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3348 break;
3349 case BPF_JLE:
3350 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3351 true_reg->umax_value = min(true_reg->umax_value, val);
3352 break;
3353 case BPF_JSLE:
3354 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3355 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3356 break;
3357 default:
3358 break;
3361 __reg_deduce_bounds(false_reg);
3362 __reg_deduce_bounds(true_reg);
3363 /* We might have learned some bits from the bounds. */
3364 __reg_bound_offset(false_reg);
3365 __reg_bound_offset(true_reg);
3366 /* Intersecting with the old var_off might have improved our bounds
3367 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3368 * then new var_off is (0; 0x7f...fc) which improves our umax.
3370 __update_reg_bounds(false_reg);
3371 __update_reg_bounds(true_reg);
3374 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3375 * the variable reg.
3377 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3378 struct bpf_reg_state *false_reg, u64 val,
3379 u8 opcode)
3381 if (__is_pointer_value(false, false_reg))
3382 return;
3384 switch (opcode) {
3385 case BPF_JEQ:
3386 /* If this is false then we know nothing Jon Snow, but if it is
3387 * true then we know for sure.
3389 __mark_reg_known(true_reg, val);
3390 break;
3391 case BPF_JNE:
3392 /* If this is true we know nothing Jon Snow, but if it is false
3393 * we know the value for sure;
3395 __mark_reg_known(false_reg, val);
3396 break;
3397 case BPF_JGT:
3398 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3399 false_reg->umin_value = max(false_reg->umin_value, val);
3400 break;
3401 case BPF_JSGT:
3402 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3403 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3404 break;
3405 case BPF_JLT:
3406 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3407 false_reg->umax_value = min(false_reg->umax_value, val);
3408 break;
3409 case BPF_JSLT:
3410 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3411 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3412 break;
3413 case BPF_JGE:
3414 true_reg->umax_value = min(true_reg->umax_value, val);
3415 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3416 break;
3417 case BPF_JSGE:
3418 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3419 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3420 break;
3421 case BPF_JLE:
3422 true_reg->umin_value = max(true_reg->umin_value, val);
3423 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3424 break;
3425 case BPF_JSLE:
3426 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3427 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3428 break;
3429 default:
3430 break;
3433 __reg_deduce_bounds(false_reg);
3434 __reg_deduce_bounds(true_reg);
3435 /* We might have learned some bits from the bounds. */
3436 __reg_bound_offset(false_reg);
3437 __reg_bound_offset(true_reg);
3438 /* Intersecting with the old var_off might have improved our bounds
3439 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3440 * then new var_off is (0; 0x7f...fc) which improves our umax.
3442 __update_reg_bounds(false_reg);
3443 __update_reg_bounds(true_reg);
3446 /* Regs are known to be equal, so intersect their min/max/var_off */
3447 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3448 struct bpf_reg_state *dst_reg)
3450 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3451 dst_reg->umin_value);
3452 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3453 dst_reg->umax_value);
3454 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3455 dst_reg->smin_value);
3456 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3457 dst_reg->smax_value);
3458 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3459 dst_reg->var_off);
3460 /* We might have learned new bounds from the var_off. */
3461 __update_reg_bounds(src_reg);
3462 __update_reg_bounds(dst_reg);
3463 /* We might have learned something about the sign bit. */
3464 __reg_deduce_bounds(src_reg);
3465 __reg_deduce_bounds(dst_reg);
3466 /* We might have learned some bits from the bounds. */
3467 __reg_bound_offset(src_reg);
3468 __reg_bound_offset(dst_reg);
3469 /* Intersecting with the old var_off might have improved our bounds
3470 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3471 * then new var_off is (0; 0x7f...fc) which improves our umax.
3473 __update_reg_bounds(src_reg);
3474 __update_reg_bounds(dst_reg);
3477 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3478 struct bpf_reg_state *true_dst,
3479 struct bpf_reg_state *false_src,
3480 struct bpf_reg_state *false_dst,
3481 u8 opcode)
3483 switch (opcode) {
3484 case BPF_JEQ:
3485 __reg_combine_min_max(true_src, true_dst);
3486 break;
3487 case BPF_JNE:
3488 __reg_combine_min_max(false_src, false_dst);
3489 break;
3493 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3494 bool is_null)
3496 struct bpf_reg_state *reg = &regs[regno];
3498 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3499 /* Old offset (both fixed and variable parts) should
3500 * have been known-zero, because we don't allow pointer
3501 * arithmetic on pointers that might be NULL.
3503 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3504 !tnum_equals_const(reg->var_off, 0) ||
3505 reg->off)) {
3506 __mark_reg_known_zero(reg);
3507 reg->off = 0;
3509 if (is_null) {
3510 reg->type = SCALAR_VALUE;
3511 } else if (reg->map_ptr->inner_map_meta) {
3512 reg->type = CONST_PTR_TO_MAP;
3513 reg->map_ptr = reg->map_ptr->inner_map_meta;
3514 } else {
3515 reg->type = PTR_TO_MAP_VALUE;
3517 /* We don't need id from this point onwards anymore, thus we
3518 * should better reset it, so that state pruning has chances
3519 * to take effect.
3521 reg->id = 0;
3525 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3526 * be folded together at some point.
3528 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
3529 bool is_null)
3531 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3532 struct bpf_reg_state *regs = state->regs;
3533 u32 id = regs[regno].id;
3534 int i, j;
3536 for (i = 0; i < MAX_BPF_REG; i++)
3537 mark_map_reg(regs, i, id, is_null);
3539 for (j = 0; j <= vstate->curframe; j++) {
3540 state = vstate->frame[j];
3541 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3542 if (state->stack[i].slot_type[0] != STACK_SPILL)
3543 continue;
3544 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3549 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
3550 struct bpf_reg_state *dst_reg,
3551 struct bpf_reg_state *src_reg,
3552 struct bpf_verifier_state *this_branch,
3553 struct bpf_verifier_state *other_branch)
3555 if (BPF_SRC(insn->code) != BPF_X)
3556 return false;
3558 switch (BPF_OP(insn->code)) {
3559 case BPF_JGT:
3560 if ((dst_reg->type == PTR_TO_PACKET &&
3561 src_reg->type == PTR_TO_PACKET_END) ||
3562 (dst_reg->type == PTR_TO_PACKET_META &&
3563 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3564 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
3565 find_good_pkt_pointers(this_branch, dst_reg,
3566 dst_reg->type, false);
3567 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3568 src_reg->type == PTR_TO_PACKET) ||
3569 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3570 src_reg->type == PTR_TO_PACKET_META)) {
3571 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
3572 find_good_pkt_pointers(other_branch, src_reg,
3573 src_reg->type, true);
3574 } else {
3575 return false;
3577 break;
3578 case BPF_JLT:
3579 if ((dst_reg->type == PTR_TO_PACKET &&
3580 src_reg->type == PTR_TO_PACKET_END) ||
3581 (dst_reg->type == PTR_TO_PACKET_META &&
3582 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3583 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
3584 find_good_pkt_pointers(other_branch, dst_reg,
3585 dst_reg->type, true);
3586 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3587 src_reg->type == PTR_TO_PACKET) ||
3588 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3589 src_reg->type == PTR_TO_PACKET_META)) {
3590 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
3591 find_good_pkt_pointers(this_branch, src_reg,
3592 src_reg->type, false);
3593 } else {
3594 return false;
3596 break;
3597 case BPF_JGE:
3598 if ((dst_reg->type == PTR_TO_PACKET &&
3599 src_reg->type == PTR_TO_PACKET_END) ||
3600 (dst_reg->type == PTR_TO_PACKET_META &&
3601 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3602 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
3603 find_good_pkt_pointers(this_branch, dst_reg,
3604 dst_reg->type, true);
3605 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3606 src_reg->type == PTR_TO_PACKET) ||
3607 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3608 src_reg->type == PTR_TO_PACKET_META)) {
3609 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
3610 find_good_pkt_pointers(other_branch, src_reg,
3611 src_reg->type, false);
3612 } else {
3613 return false;
3615 break;
3616 case BPF_JLE:
3617 if ((dst_reg->type == PTR_TO_PACKET &&
3618 src_reg->type == PTR_TO_PACKET_END) ||
3619 (dst_reg->type == PTR_TO_PACKET_META &&
3620 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3621 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
3622 find_good_pkt_pointers(other_branch, dst_reg,
3623 dst_reg->type, false);
3624 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3625 src_reg->type == PTR_TO_PACKET) ||
3626 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3627 src_reg->type == PTR_TO_PACKET_META)) {
3628 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
3629 find_good_pkt_pointers(this_branch, src_reg,
3630 src_reg->type, true);
3631 } else {
3632 return false;
3634 break;
3635 default:
3636 return false;
3639 return true;
3642 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3643 struct bpf_insn *insn, int *insn_idx)
3645 struct bpf_verifier_state *this_branch = env->cur_state;
3646 struct bpf_verifier_state *other_branch;
3647 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
3648 struct bpf_reg_state *dst_reg, *other_branch_regs;
3649 u8 opcode = BPF_OP(insn->code);
3650 int err;
3652 if (opcode > BPF_JSLE) {
3653 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
3654 return -EINVAL;
3657 if (BPF_SRC(insn->code) == BPF_X) {
3658 if (insn->imm != 0) {
3659 verbose(env, "BPF_JMP uses reserved fields\n");
3660 return -EINVAL;
3663 /* check src1 operand */
3664 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3665 if (err)
3666 return err;
3668 if (is_pointer_value(env, insn->src_reg)) {
3669 verbose(env, "R%d pointer comparison prohibited\n",
3670 insn->src_reg);
3671 return -EACCES;
3673 } else {
3674 if (insn->src_reg != BPF_REG_0) {
3675 verbose(env, "BPF_JMP uses reserved fields\n");
3676 return -EINVAL;
3680 /* check src2 operand */
3681 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3682 if (err)
3683 return err;
3685 dst_reg = &regs[insn->dst_reg];
3687 /* detect if R == 0 where R was initialized to zero earlier */
3688 if (BPF_SRC(insn->code) == BPF_K &&
3689 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3690 dst_reg->type == SCALAR_VALUE &&
3691 tnum_is_const(dst_reg->var_off)) {
3692 if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
3693 (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
3694 /* if (imm == imm) goto pc+off;
3695 * only follow the goto, ignore fall-through
3697 *insn_idx += insn->off;
3698 return 0;
3699 } else {
3700 /* if (imm != imm) goto pc+off;
3701 * only follow fall-through branch, since
3702 * that's where the program will go
3704 return 0;
3708 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
3709 if (!other_branch)
3710 return -EFAULT;
3711 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
3713 /* detect if we are comparing against a constant value so we can adjust
3714 * our min/max values for our dst register.
3715 * this is only legit if both are scalars (or pointers to the same
3716 * object, I suppose, but we don't support that right now), because
3717 * otherwise the different base pointers mean the offsets aren't
3718 * comparable.
3720 if (BPF_SRC(insn->code) == BPF_X) {
3721 if (dst_reg->type == SCALAR_VALUE &&
3722 regs[insn->src_reg].type == SCALAR_VALUE) {
3723 if (tnum_is_const(regs[insn->src_reg].var_off))
3724 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3725 dst_reg, regs[insn->src_reg].var_off.value,
3726 opcode);
3727 else if (tnum_is_const(dst_reg->var_off))
3728 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
3729 &regs[insn->src_reg],
3730 dst_reg->var_off.value, opcode);
3731 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3732 /* Comparing for equality, we can combine knowledge */
3733 reg_combine_min_max(&other_branch_regs[insn->src_reg],
3734 &other_branch_regs[insn->dst_reg],
3735 &regs[insn->src_reg],
3736 &regs[insn->dst_reg], opcode);
3738 } else if (dst_reg->type == SCALAR_VALUE) {
3739 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3740 dst_reg, insn->imm, opcode);
3743 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3744 if (BPF_SRC(insn->code) == BPF_K &&
3745 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3746 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3747 /* Mark all identical map registers in each branch as either
3748 * safe or unknown depending R == 0 or R != 0 conditional.
3750 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3751 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3752 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
3753 this_branch, other_branch) &&
3754 is_pointer_value(env, insn->dst_reg)) {
3755 verbose(env, "R%d pointer comparison prohibited\n",
3756 insn->dst_reg);
3757 return -EACCES;
3759 if (env->log.level)
3760 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
3761 return 0;
3764 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3765 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3767 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3769 return (struct bpf_map *) (unsigned long) imm64;
3772 /* verify BPF_LD_IMM64 instruction */
3773 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3775 struct bpf_reg_state *regs = cur_regs(env);
3776 int err;
3778 if (BPF_SIZE(insn->code) != BPF_DW) {
3779 verbose(env, "invalid BPF_LD_IMM insn\n");
3780 return -EINVAL;
3782 if (insn->off != 0) {
3783 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
3784 return -EINVAL;
3787 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3788 if (err)
3789 return err;
3791 if (insn->src_reg == 0) {
3792 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3794 regs[insn->dst_reg].type = SCALAR_VALUE;
3795 __mark_reg_known(&regs[insn->dst_reg], imm);
3796 return 0;
3799 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3800 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3802 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3803 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3804 return 0;
3807 static bool may_access_skb(enum bpf_prog_type type)
3809 switch (type) {
3810 case BPF_PROG_TYPE_SOCKET_FILTER:
3811 case BPF_PROG_TYPE_SCHED_CLS:
3812 case BPF_PROG_TYPE_SCHED_ACT:
3813 return true;
3814 default:
3815 return false;
3819 /* verify safety of LD_ABS|LD_IND instructions:
3820 * - they can only appear in the programs where ctx == skb
3821 * - since they are wrappers of function calls, they scratch R1-R5 registers,
3822 * preserve R6-R9, and store return value into R0
3824 * Implicit input:
3825 * ctx == skb == R6 == CTX
3827 * Explicit input:
3828 * SRC == any register
3829 * IMM == 32-bit immediate
3831 * Output:
3832 * R0 - 8/16/32-bit skb data converted to cpu endianness
3834 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3836 struct bpf_reg_state *regs = cur_regs(env);
3837 u8 mode = BPF_MODE(insn->code);
3838 int i, err;
3840 if (!may_access_skb(env->prog->type)) {
3841 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3842 return -EINVAL;
3845 if (env->subprog_cnt) {
3846 /* when program has LD_ABS insn JITs and interpreter assume
3847 * that r1 == ctx == skb which is not the case for callees
3848 * that can have arbitrary arguments. It's problematic
3849 * for main prog as well since JITs would need to analyze
3850 * all functions in order to make proper register save/restore
3851 * decisions in the main prog. Hence disallow LD_ABS with calls
3853 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
3854 return -EINVAL;
3857 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3858 BPF_SIZE(insn->code) == BPF_DW ||
3859 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3860 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
3861 return -EINVAL;
3864 /* check whether implicit source operand (register R6) is readable */
3865 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
3866 if (err)
3867 return err;
3869 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
3870 verbose(env,
3871 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3872 return -EINVAL;
3875 if (mode == BPF_IND) {
3876 /* check explicit source operand */
3877 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3878 if (err)
3879 return err;
3882 /* reset caller saved regs to unreadable */
3883 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3884 mark_reg_not_init(env, regs, caller_saved[i]);
3885 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3888 /* mark destination R0 register as readable, since it contains
3889 * the value fetched from the packet.
3890 * Already marked as written above.
3892 mark_reg_unknown(env, regs, BPF_REG_0);
3893 return 0;
3896 static int check_return_code(struct bpf_verifier_env *env)
3898 struct bpf_reg_state *reg;
3899 struct tnum range = tnum_range(0, 1);
3901 switch (env->prog->type) {
3902 case BPF_PROG_TYPE_CGROUP_SKB:
3903 case BPF_PROG_TYPE_CGROUP_SOCK:
3904 case BPF_PROG_TYPE_SOCK_OPS:
3905 case BPF_PROG_TYPE_CGROUP_DEVICE:
3906 break;
3907 default:
3908 return 0;
3911 reg = cur_regs(env) + BPF_REG_0;
3912 if (reg->type != SCALAR_VALUE) {
3913 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
3914 reg_type_str[reg->type]);
3915 return -EINVAL;
3918 if (!tnum_in(range, reg->var_off)) {
3919 verbose(env, "At program exit the register R0 ");
3920 if (!tnum_is_unknown(reg->var_off)) {
3921 char tn_buf[48];
3923 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3924 verbose(env, "has value %s", tn_buf);
3925 } else {
3926 verbose(env, "has unknown scalar value");
3928 verbose(env, " should have been 0 or 1\n");
3929 return -EINVAL;
3931 return 0;
3934 /* non-recursive DFS pseudo code
3935 * 1 procedure DFS-iterative(G,v):
3936 * 2 label v as discovered
3937 * 3 let S be a stack
3938 * 4 S.push(v)
3939 * 5 while S is not empty
3940 * 6 t <- S.pop()
3941 * 7 if t is what we're looking for:
3942 * 8 return t
3943 * 9 for all edges e in G.adjacentEdges(t) do
3944 * 10 if edge e is already labelled
3945 * 11 continue with the next edge
3946 * 12 w <- G.adjacentVertex(t,e)
3947 * 13 if vertex w is not discovered and not explored
3948 * 14 label e as tree-edge
3949 * 15 label w as discovered
3950 * 16 S.push(w)
3951 * 17 continue at 5
3952 * 18 else if vertex w is discovered
3953 * 19 label e as back-edge
3954 * 20 else
3955 * 21 // vertex w is explored
3956 * 22 label e as forward- or cross-edge
3957 * 23 label t as explored
3958 * 24 S.pop()
3960 * convention:
3961 * 0x10 - discovered
3962 * 0x11 - discovered and fall-through edge labelled
3963 * 0x12 - discovered and fall-through and branch edges labelled
3964 * 0x20 - explored
3967 enum {
3968 DISCOVERED = 0x10,
3969 EXPLORED = 0x20,
3970 FALLTHROUGH = 1,
3971 BRANCH = 2,
3974 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3976 static int *insn_stack; /* stack of insns to process */
3977 static int cur_stack; /* current stack index */
3978 static int *insn_state;
3980 /* t, w, e - match pseudo-code above:
3981 * t - index of current instruction
3982 * w - next instruction
3983 * e - edge
3985 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3987 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3988 return 0;
3990 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3991 return 0;
3993 if (w < 0 || w >= env->prog->len) {
3994 verbose(env, "jump out of range from insn %d to %d\n", t, w);
3995 return -EINVAL;
3998 if (e == BRANCH)
3999 /* mark branch target for state pruning */
4000 env->explored_states[w] = STATE_LIST_MARK;
4002 if (insn_state[w] == 0) {
4003 /* tree-edge */
4004 insn_state[t] = DISCOVERED | e;
4005 insn_state[w] = DISCOVERED;
4006 if (cur_stack >= env->prog->len)
4007 return -E2BIG;
4008 insn_stack[cur_stack++] = w;
4009 return 1;
4010 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4011 verbose(env, "back-edge from insn %d to %d\n", t, w);
4012 return -EINVAL;
4013 } else if (insn_state[w] == EXPLORED) {
4014 /* forward- or cross-edge */
4015 insn_state[t] = DISCOVERED | e;
4016 } else {
4017 verbose(env, "insn state internal bug\n");
4018 return -EFAULT;
4020 return 0;
4023 /* non-recursive depth-first-search to detect loops in BPF program
4024 * loop == back-edge in directed graph
4026 static int check_cfg(struct bpf_verifier_env *env)
4028 struct bpf_insn *insns = env->prog->insnsi;
4029 int insn_cnt = env->prog->len;
4030 int ret = 0;
4031 int i, t;
4033 ret = check_subprogs(env);
4034 if (ret < 0)
4035 return ret;
4037 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4038 if (!insn_state)
4039 return -ENOMEM;
4041 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4042 if (!insn_stack) {
4043 kfree(insn_state);
4044 return -ENOMEM;
4047 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4048 insn_stack[0] = 0; /* 0 is the first instruction */
4049 cur_stack = 1;
4051 peek_stack:
4052 if (cur_stack == 0)
4053 goto check_state;
4054 t = insn_stack[cur_stack - 1];
4056 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4057 u8 opcode = BPF_OP(insns[t].code);
4059 if (opcode == BPF_EXIT) {
4060 goto mark_explored;
4061 } else if (opcode == BPF_CALL) {
4062 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4063 if (ret == 1)
4064 goto peek_stack;
4065 else if (ret < 0)
4066 goto err_free;
4067 if (t + 1 < insn_cnt)
4068 env->explored_states[t + 1] = STATE_LIST_MARK;
4069 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4070 env->explored_states[t] = STATE_LIST_MARK;
4071 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4072 if (ret == 1)
4073 goto peek_stack;
4074 else if (ret < 0)
4075 goto err_free;
4077 } else if (opcode == BPF_JA) {
4078 if (BPF_SRC(insns[t].code) != BPF_K) {
4079 ret = -EINVAL;
4080 goto err_free;
4082 /* unconditional jump with single edge */
4083 ret = push_insn(t, t + insns[t].off + 1,
4084 FALLTHROUGH, env);
4085 if (ret == 1)
4086 goto peek_stack;
4087 else if (ret < 0)
4088 goto err_free;
4089 /* tell verifier to check for equivalent states
4090 * after every call and jump
4092 if (t + 1 < insn_cnt)
4093 env->explored_states[t + 1] = STATE_LIST_MARK;
4094 } else {
4095 /* conditional jump with two edges */
4096 env->explored_states[t] = STATE_LIST_MARK;
4097 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4098 if (ret == 1)
4099 goto peek_stack;
4100 else if (ret < 0)
4101 goto err_free;
4103 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4104 if (ret == 1)
4105 goto peek_stack;
4106 else if (ret < 0)
4107 goto err_free;
4109 } else {
4110 /* all other non-branch instructions with single
4111 * fall-through edge
4113 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4114 if (ret == 1)
4115 goto peek_stack;
4116 else if (ret < 0)
4117 goto err_free;
4120 mark_explored:
4121 insn_state[t] = EXPLORED;
4122 if (cur_stack-- <= 0) {
4123 verbose(env, "pop stack internal bug\n");
4124 ret = -EFAULT;
4125 goto err_free;
4127 goto peek_stack;
4129 check_state:
4130 for (i = 0; i < insn_cnt; i++) {
4131 if (insn_state[i] != EXPLORED) {
4132 verbose(env, "unreachable insn %d\n", i);
4133 ret = -EINVAL;
4134 goto err_free;
4137 ret = 0; /* cfg looks good */
4139 err_free:
4140 kfree(insn_state);
4141 kfree(insn_stack);
4142 return ret;
4145 /* check %cur's range satisfies %old's */
4146 static bool range_within(struct bpf_reg_state *old,
4147 struct bpf_reg_state *cur)
4149 return old->umin_value <= cur->umin_value &&
4150 old->umax_value >= cur->umax_value &&
4151 old->smin_value <= cur->smin_value &&
4152 old->smax_value >= cur->smax_value;
4155 /* Maximum number of register states that can exist at once */
4156 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4157 struct idpair {
4158 u32 old;
4159 u32 cur;
4162 /* If in the old state two registers had the same id, then they need to have
4163 * the same id in the new state as well. But that id could be different from
4164 * the old state, so we need to track the mapping from old to new ids.
4165 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4166 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4167 * regs with a different old id could still have new id 9, we don't care about
4168 * that.
4169 * So we look through our idmap to see if this old id has been seen before. If
4170 * so, we require the new id to match; otherwise, we add the id pair to the map.
4172 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4174 unsigned int i;
4176 for (i = 0; i < ID_MAP_SIZE; i++) {
4177 if (!idmap[i].old) {
4178 /* Reached an empty slot; haven't seen this id before */
4179 idmap[i].old = old_id;
4180 idmap[i].cur = cur_id;
4181 return true;
4183 if (idmap[i].old == old_id)
4184 return idmap[i].cur == cur_id;
4186 /* We ran out of idmap slots, which should be impossible */
4187 WARN_ON_ONCE(1);
4188 return false;
4191 /* Returns true if (rold safe implies rcur safe) */
4192 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4193 struct idpair *idmap)
4195 bool equal;
4197 if (!(rold->live & REG_LIVE_READ))
4198 /* explored state didn't use this */
4199 return true;
4201 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
4203 if (rold->type == PTR_TO_STACK)
4204 /* two stack pointers are equal only if they're pointing to
4205 * the same stack frame, since fp-8 in foo != fp-8 in bar
4207 return equal && rold->frameno == rcur->frameno;
4209 if (equal)
4210 return true;
4212 if (rold->type == NOT_INIT)
4213 /* explored state can't have used this */
4214 return true;
4215 if (rcur->type == NOT_INIT)
4216 return false;
4217 switch (rold->type) {
4218 case SCALAR_VALUE:
4219 if (rcur->type == SCALAR_VALUE) {
4220 /* new val must satisfy old val knowledge */
4221 return range_within(rold, rcur) &&
4222 tnum_in(rold->var_off, rcur->var_off);
4223 } else {
4224 /* We're trying to use a pointer in place of a scalar.
4225 * Even if the scalar was unbounded, this could lead to
4226 * pointer leaks because scalars are allowed to leak
4227 * while pointers are not. We could make this safe in
4228 * special cases if root is calling us, but it's
4229 * probably not worth the hassle.
4231 return false;
4233 case PTR_TO_MAP_VALUE:
4234 /* If the new min/max/var_off satisfy the old ones and
4235 * everything else matches, we are OK.
4236 * We don't care about the 'id' value, because nothing
4237 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4239 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4240 range_within(rold, rcur) &&
4241 tnum_in(rold->var_off, rcur->var_off);
4242 case PTR_TO_MAP_VALUE_OR_NULL:
4243 /* a PTR_TO_MAP_VALUE could be safe to use as a
4244 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4245 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4246 * checked, doing so could have affected others with the same
4247 * id, and we can't check for that because we lost the id when
4248 * we converted to a PTR_TO_MAP_VALUE.
4250 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4251 return false;
4252 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4253 return false;
4254 /* Check our ids match any regs they're supposed to */
4255 return check_ids(rold->id, rcur->id, idmap);
4256 case PTR_TO_PACKET_META:
4257 case PTR_TO_PACKET:
4258 if (rcur->type != rold->type)
4259 return false;
4260 /* We must have at least as much range as the old ptr
4261 * did, so that any accesses which were safe before are
4262 * still safe. This is true even if old range < old off,
4263 * since someone could have accessed through (ptr - k), or
4264 * even done ptr -= k in a register, to get a safe access.
4266 if (rold->range > rcur->range)
4267 return false;
4268 /* If the offsets don't match, we can't trust our alignment;
4269 * nor can we be sure that we won't fall out of range.
4271 if (rold->off != rcur->off)
4272 return false;
4273 /* id relations must be preserved */
4274 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4275 return false;
4276 /* new val must satisfy old val knowledge */
4277 return range_within(rold, rcur) &&
4278 tnum_in(rold->var_off, rcur->var_off);
4279 case PTR_TO_CTX:
4280 case CONST_PTR_TO_MAP:
4281 case PTR_TO_PACKET_END:
4282 /* Only valid matches are exact, which memcmp() above
4283 * would have accepted
4285 default:
4286 /* Don't know what's going on, just say it's not safe */
4287 return false;
4290 /* Shouldn't get here; if we do, say it's not safe */
4291 WARN_ON_ONCE(1);
4292 return false;
4295 static bool stacksafe(struct bpf_func_state *old,
4296 struct bpf_func_state *cur,
4297 struct idpair *idmap)
4299 int i, spi;
4301 /* if explored stack has more populated slots than current stack
4302 * such stacks are not equivalent
4304 if (old->allocated_stack > cur->allocated_stack)
4305 return false;
4307 /* walk slots of the explored stack and ignore any additional
4308 * slots in the current stack, since explored(safe) state
4309 * didn't use them
4311 for (i = 0; i < old->allocated_stack; i++) {
4312 spi = i / BPF_REG_SIZE;
4314 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4315 /* explored state didn't use this */
4316 continue;
4318 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4319 continue;
4320 /* if old state was safe with misc data in the stack
4321 * it will be safe with zero-initialized stack.
4322 * The opposite is not true
4324 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4325 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4326 continue;
4327 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4328 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4329 /* Ex: old explored (safe) state has STACK_SPILL in
4330 * this stack slot, but current has has STACK_MISC ->
4331 * this verifier states are not equivalent,
4332 * return false to continue verification of this path
4334 return false;
4335 if (i % BPF_REG_SIZE)
4336 continue;
4337 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4338 continue;
4339 if (!regsafe(&old->stack[spi].spilled_ptr,
4340 &cur->stack[spi].spilled_ptr,
4341 idmap))
4342 /* when explored and current stack slot are both storing
4343 * spilled registers, check that stored pointers types
4344 * are the same as well.
4345 * Ex: explored safe path could have stored
4346 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4347 * but current path has stored:
4348 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4349 * such verifier states are not equivalent.
4350 * return false to continue verification of this path
4352 return false;
4354 return true;
4357 /* compare two verifier states
4359 * all states stored in state_list are known to be valid, since
4360 * verifier reached 'bpf_exit' instruction through them
4362 * this function is called when verifier exploring different branches of
4363 * execution popped from the state stack. If it sees an old state that has
4364 * more strict register state and more strict stack state then this execution
4365 * branch doesn't need to be explored further, since verifier already
4366 * concluded that more strict state leads to valid finish.
4368 * Therefore two states are equivalent if register state is more conservative
4369 * and explored stack state is more conservative than the current one.
4370 * Example:
4371 * explored current
4372 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
4373 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
4375 * In other words if current stack state (one being explored) has more
4376 * valid slots than old one that already passed validation, it means
4377 * the verifier can stop exploring and conclude that current state is valid too
4379 * Similarly with registers. If explored state has register type as invalid
4380 * whereas register type in current state is meaningful, it means that
4381 * the current state will reach 'bpf_exit' instruction safely
4383 static bool func_states_equal(struct bpf_func_state *old,
4384 struct bpf_func_state *cur)
4386 struct idpair *idmap;
4387 bool ret = false;
4388 int i;
4390 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4391 /* If we failed to allocate the idmap, just say it's not safe */
4392 if (!idmap)
4393 return false;
4395 for (i = 0; i < MAX_BPF_REG; i++) {
4396 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4397 goto out_free;
4400 if (!stacksafe(old, cur, idmap))
4401 goto out_free;
4402 ret = true;
4403 out_free:
4404 kfree(idmap);
4405 return ret;
4408 static bool states_equal(struct bpf_verifier_env *env,
4409 struct bpf_verifier_state *old,
4410 struct bpf_verifier_state *cur)
4412 int i;
4414 if (old->curframe != cur->curframe)
4415 return false;
4417 /* for states to be equal callsites have to be the same
4418 * and all frame states need to be equivalent
4420 for (i = 0; i <= old->curframe; i++) {
4421 if (old->frame[i]->callsite != cur->frame[i]->callsite)
4422 return false;
4423 if (!func_states_equal(old->frame[i], cur->frame[i]))
4424 return false;
4426 return true;
4429 /* A write screens off any subsequent reads; but write marks come from the
4430 * straight-line code between a state and its parent. When we arrive at an
4431 * equivalent state (jump target or such) we didn't arrive by the straight-line
4432 * code, so read marks in the state must propagate to the parent regardless
4433 * of the state's write marks. That's what 'parent == state->parent' comparison
4434 * in mark_reg_read() and mark_stack_slot_read() is for.
4436 static int propagate_liveness(struct bpf_verifier_env *env,
4437 const struct bpf_verifier_state *vstate,
4438 struct bpf_verifier_state *vparent)
4440 int i, frame, err = 0;
4441 struct bpf_func_state *state, *parent;
4443 if (vparent->curframe != vstate->curframe) {
4444 WARN(1, "propagate_live: parent frame %d current frame %d\n",
4445 vparent->curframe, vstate->curframe);
4446 return -EFAULT;
4448 /* Propagate read liveness of registers... */
4449 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4450 /* We don't need to worry about FP liveness because it's read-only */
4451 for (i = 0; i < BPF_REG_FP; i++) {
4452 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
4453 continue;
4454 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
4455 err = mark_reg_read(env, vstate, vparent, i);
4456 if (err)
4457 return err;
4461 /* ... and stack slots */
4462 for (frame = 0; frame <= vstate->curframe; frame++) {
4463 state = vstate->frame[frame];
4464 parent = vparent->frame[frame];
4465 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4466 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4467 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4468 continue;
4469 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
4470 mark_stack_slot_read(env, vstate, vparent, i, frame);
4473 return err;
4476 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4478 struct bpf_verifier_state_list *new_sl;
4479 struct bpf_verifier_state_list *sl;
4480 struct bpf_verifier_state *cur = env->cur_state;
4481 int i, j, err;
4483 sl = env->explored_states[insn_idx];
4484 if (!sl)
4485 /* this 'insn_idx' instruction wasn't marked, so we will not
4486 * be doing state search here
4488 return 0;
4490 while (sl != STATE_LIST_MARK) {
4491 if (states_equal(env, &sl->state, cur)) {
4492 /* reached equivalent register/stack state,
4493 * prune the search.
4494 * Registers read by the continuation are read by us.
4495 * If we have any write marks in env->cur_state, they
4496 * will prevent corresponding reads in the continuation
4497 * from reaching our parent (an explored_state). Our
4498 * own state will get the read marks recorded, but
4499 * they'll be immediately forgotten as we're pruning
4500 * this state and will pop a new one.
4502 err = propagate_liveness(env, &sl->state, cur);
4503 if (err)
4504 return err;
4505 return 1;
4507 sl = sl->next;
4510 /* there were no equivalent states, remember current one.
4511 * technically the current state is not proven to be safe yet,
4512 * but it will either reach outer most bpf_exit (which means it's safe)
4513 * or it will be rejected. Since there are no loops, we won't be
4514 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
4515 * again on the way to bpf_exit
4517 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4518 if (!new_sl)
4519 return -ENOMEM;
4521 /* add new state to the head of linked list */
4522 err = copy_verifier_state(&new_sl->state, cur);
4523 if (err) {
4524 free_verifier_state(&new_sl->state, false);
4525 kfree(new_sl);
4526 return err;
4528 new_sl->next = env->explored_states[insn_idx];
4529 env->explored_states[insn_idx] = new_sl;
4530 /* connect new state to parentage chain */
4531 cur->parent = &new_sl->state;
4532 /* clear write marks in current state: the writes we did are not writes
4533 * our child did, so they don't screen off its reads from us.
4534 * (There are no read marks in current state, because reads always mark
4535 * their parent and current state never has children yet. Only
4536 * explored_states can get read marks.)
4538 for (i = 0; i < BPF_REG_FP; i++)
4539 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
4541 /* all stack frames are accessible from callee, clear them all */
4542 for (j = 0; j <= cur->curframe; j++) {
4543 struct bpf_func_state *frame = cur->frame[j];
4545 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
4546 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4548 return 0;
4551 static int do_check(struct bpf_verifier_env *env)
4553 struct bpf_verifier_state *state;
4554 struct bpf_insn *insns = env->prog->insnsi;
4555 struct bpf_reg_state *regs;
4556 int insn_cnt = env->prog->len, i;
4557 int insn_idx, prev_insn_idx = 0;
4558 int insn_processed = 0;
4559 bool do_print_state = false;
4561 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4562 if (!state)
4563 return -ENOMEM;
4564 state->curframe = 0;
4565 state->parent = NULL;
4566 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
4567 if (!state->frame[0]) {
4568 kfree(state);
4569 return -ENOMEM;
4571 env->cur_state = state;
4572 init_func_state(env, state->frame[0],
4573 BPF_MAIN_FUNC /* callsite */,
4574 0 /* frameno */,
4575 0 /* subprogno, zero == main subprog */);
4576 insn_idx = 0;
4577 for (;;) {
4578 struct bpf_insn *insn;
4579 u8 class;
4580 int err;
4582 if (insn_idx >= insn_cnt) {
4583 verbose(env, "invalid insn idx %d insn_cnt %d\n",
4584 insn_idx, insn_cnt);
4585 return -EFAULT;
4588 insn = &insns[insn_idx];
4589 class = BPF_CLASS(insn->code);
4591 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4592 verbose(env,
4593 "BPF program is too large. Processed %d insn\n",
4594 insn_processed);
4595 return -E2BIG;
4598 err = is_state_visited(env, insn_idx);
4599 if (err < 0)
4600 return err;
4601 if (err == 1) {
4602 /* found equivalent state, can prune the search */
4603 if (env->log.level) {
4604 if (do_print_state)
4605 verbose(env, "\nfrom %d to %d: safe\n",
4606 prev_insn_idx, insn_idx);
4607 else
4608 verbose(env, "%d: safe\n", insn_idx);
4610 goto process_bpf_exit;
4613 if (need_resched())
4614 cond_resched();
4616 if (env->log.level > 1 || (env->log.level && do_print_state)) {
4617 if (env->log.level > 1)
4618 verbose(env, "%d:", insn_idx);
4619 else
4620 verbose(env, "\nfrom %d to %d:",
4621 prev_insn_idx, insn_idx);
4622 print_verifier_state(env, state->frame[state->curframe]);
4623 do_print_state = false;
4626 if (env->log.level) {
4627 const struct bpf_insn_cbs cbs = {
4628 .cb_print = verbose,
4631 verbose(env, "%d: ", insn_idx);
4632 print_bpf_insn(&cbs, env, insn, env->allow_ptr_leaks);
4635 if (bpf_prog_is_dev_bound(env->prog->aux)) {
4636 err = bpf_prog_offload_verify_insn(env, insn_idx,
4637 prev_insn_idx);
4638 if (err)
4639 return err;
4642 regs = cur_regs(env);
4643 env->insn_aux_data[insn_idx].seen = true;
4644 if (class == BPF_ALU || class == BPF_ALU64) {
4645 err = check_alu_op(env, insn);
4646 if (err)
4647 return err;
4649 } else if (class == BPF_LDX) {
4650 enum bpf_reg_type *prev_src_type, src_reg_type;
4652 /* check for reserved fields is already done */
4654 /* check src operand */
4655 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4656 if (err)
4657 return err;
4659 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4660 if (err)
4661 return err;
4663 src_reg_type = regs[insn->src_reg].type;
4665 /* check that memory (src_reg + off) is readable,
4666 * the state of dst_reg will be updated by this func
4668 err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
4669 BPF_SIZE(insn->code), BPF_READ,
4670 insn->dst_reg, false);
4671 if (err)
4672 return err;
4674 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
4676 if (*prev_src_type == NOT_INIT) {
4677 /* saw a valid insn
4678 * dst_reg = *(u32 *)(src_reg + off)
4679 * save type to validate intersecting paths
4681 *prev_src_type = src_reg_type;
4683 } else if (src_reg_type != *prev_src_type &&
4684 (src_reg_type == PTR_TO_CTX ||
4685 *prev_src_type == PTR_TO_CTX)) {
4686 /* ABuser program is trying to use the same insn
4687 * dst_reg = *(u32*) (src_reg + off)
4688 * with different pointer types:
4689 * src_reg == ctx in one branch and
4690 * src_reg == stack|map in some other branch.
4691 * Reject it.
4693 verbose(env, "same insn cannot be used with different pointers\n");
4694 return -EINVAL;
4697 } else if (class == BPF_STX) {
4698 enum bpf_reg_type *prev_dst_type, dst_reg_type;
4700 if (BPF_MODE(insn->code) == BPF_XADD) {
4701 err = check_xadd(env, insn_idx, insn);
4702 if (err)
4703 return err;
4704 insn_idx++;
4705 continue;
4708 /* check src1 operand */
4709 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4710 if (err)
4711 return err;
4712 /* check src2 operand */
4713 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4714 if (err)
4715 return err;
4717 dst_reg_type = regs[insn->dst_reg].type;
4719 /* check that memory (dst_reg + off) is writeable */
4720 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4721 BPF_SIZE(insn->code), BPF_WRITE,
4722 insn->src_reg, false);
4723 if (err)
4724 return err;
4726 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
4728 if (*prev_dst_type == NOT_INIT) {
4729 *prev_dst_type = dst_reg_type;
4730 } else if (dst_reg_type != *prev_dst_type &&
4731 (dst_reg_type == PTR_TO_CTX ||
4732 *prev_dst_type == PTR_TO_CTX)) {
4733 verbose(env, "same insn cannot be used with different pointers\n");
4734 return -EINVAL;
4737 } else if (class == BPF_ST) {
4738 if (BPF_MODE(insn->code) != BPF_MEM ||
4739 insn->src_reg != BPF_REG_0) {
4740 verbose(env, "BPF_ST uses reserved fields\n");
4741 return -EINVAL;
4743 /* check src operand */
4744 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4745 if (err)
4746 return err;
4748 if (is_ctx_reg(env, insn->dst_reg)) {
4749 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
4750 insn->dst_reg);
4751 return -EACCES;
4754 /* check that memory (dst_reg + off) is writeable */
4755 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4756 BPF_SIZE(insn->code), BPF_WRITE,
4757 -1, false);
4758 if (err)
4759 return err;
4761 } else if (class == BPF_JMP) {
4762 u8 opcode = BPF_OP(insn->code);
4764 if (opcode == BPF_CALL) {
4765 if (BPF_SRC(insn->code) != BPF_K ||
4766 insn->off != 0 ||
4767 (insn->src_reg != BPF_REG_0 &&
4768 insn->src_reg != BPF_PSEUDO_CALL) ||
4769 insn->dst_reg != BPF_REG_0) {
4770 verbose(env, "BPF_CALL uses reserved fields\n");
4771 return -EINVAL;
4774 if (insn->src_reg == BPF_PSEUDO_CALL)
4775 err = check_func_call(env, insn, &insn_idx);
4776 else
4777 err = check_helper_call(env, insn->imm, insn_idx);
4778 if (err)
4779 return err;
4781 } else if (opcode == BPF_JA) {
4782 if (BPF_SRC(insn->code) != BPF_K ||
4783 insn->imm != 0 ||
4784 insn->src_reg != BPF_REG_0 ||
4785 insn->dst_reg != BPF_REG_0) {
4786 verbose(env, "BPF_JA uses reserved fields\n");
4787 return -EINVAL;
4790 insn_idx += insn->off + 1;
4791 continue;
4793 } else if (opcode == BPF_EXIT) {
4794 if (BPF_SRC(insn->code) != BPF_K ||
4795 insn->imm != 0 ||
4796 insn->src_reg != BPF_REG_0 ||
4797 insn->dst_reg != BPF_REG_0) {
4798 verbose(env, "BPF_EXIT uses reserved fields\n");
4799 return -EINVAL;
4802 if (state->curframe) {
4803 /* exit from nested function */
4804 prev_insn_idx = insn_idx;
4805 err = prepare_func_exit(env, &insn_idx);
4806 if (err)
4807 return err;
4808 do_print_state = true;
4809 continue;
4812 /* eBPF calling convetion is such that R0 is used
4813 * to return the value from eBPF program.
4814 * Make sure that it's readable at this time
4815 * of bpf_exit, which means that program wrote
4816 * something into it earlier
4818 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4819 if (err)
4820 return err;
4822 if (is_pointer_value(env, BPF_REG_0)) {
4823 verbose(env, "R0 leaks addr as return value\n");
4824 return -EACCES;
4827 err = check_return_code(env);
4828 if (err)
4829 return err;
4830 process_bpf_exit:
4831 err = pop_stack(env, &prev_insn_idx, &insn_idx);
4832 if (err < 0) {
4833 if (err != -ENOENT)
4834 return err;
4835 break;
4836 } else {
4837 do_print_state = true;
4838 continue;
4840 } else {
4841 err = check_cond_jmp_op(env, insn, &insn_idx);
4842 if (err)
4843 return err;
4845 } else if (class == BPF_LD) {
4846 u8 mode = BPF_MODE(insn->code);
4848 if (mode == BPF_ABS || mode == BPF_IND) {
4849 err = check_ld_abs(env, insn);
4850 if (err)
4851 return err;
4853 } else if (mode == BPF_IMM) {
4854 err = check_ld_imm(env, insn);
4855 if (err)
4856 return err;
4858 insn_idx++;
4859 env->insn_aux_data[insn_idx].seen = true;
4860 } else {
4861 verbose(env, "invalid BPF_LD mode\n");
4862 return -EINVAL;
4864 } else {
4865 verbose(env, "unknown insn class %d\n", class);
4866 return -EINVAL;
4869 insn_idx++;
4872 verbose(env, "processed %d insns (limit %d), stack depth ",
4873 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
4874 for (i = 0; i < env->subprog_cnt + 1; i++) {
4875 u32 depth = env->subprog_stack_depth[i];
4877 verbose(env, "%d", depth);
4878 if (i + 1 < env->subprog_cnt + 1)
4879 verbose(env, "+");
4881 verbose(env, "\n");
4882 env->prog->aux->stack_depth = env->subprog_stack_depth[0];
4883 return 0;
4886 static int check_map_prealloc(struct bpf_map *map)
4888 return (map->map_type != BPF_MAP_TYPE_HASH &&
4889 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4890 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4891 !(map->map_flags & BPF_F_NO_PREALLOC);
4894 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
4895 struct bpf_map *map,
4896 struct bpf_prog *prog)
4899 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4900 * preallocated hash maps, since doing memory allocation
4901 * in overflow_handler can crash depending on where nmi got
4902 * triggered.
4904 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4905 if (!check_map_prealloc(map)) {
4906 verbose(env, "perf_event programs can only use preallocated hash map\n");
4907 return -EINVAL;
4909 if (map->inner_map_meta &&
4910 !check_map_prealloc(map->inner_map_meta)) {
4911 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
4912 return -EINVAL;
4916 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
4917 !bpf_offload_dev_match(prog, map)) {
4918 verbose(env, "offload device mismatch between prog and map\n");
4919 return -EINVAL;
4922 return 0;
4925 /* look for pseudo eBPF instructions that access map FDs and
4926 * replace them with actual map pointers
4928 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4930 struct bpf_insn *insn = env->prog->insnsi;
4931 int insn_cnt = env->prog->len;
4932 int i, j, err;
4934 err = bpf_prog_calc_tag(env->prog);
4935 if (err)
4936 return err;
4938 for (i = 0; i < insn_cnt; i++, insn++) {
4939 if (BPF_CLASS(insn->code) == BPF_LDX &&
4940 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4941 verbose(env, "BPF_LDX uses reserved fields\n");
4942 return -EINVAL;
4945 if (BPF_CLASS(insn->code) == BPF_STX &&
4946 ((BPF_MODE(insn->code) != BPF_MEM &&
4947 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4948 verbose(env, "BPF_STX uses reserved fields\n");
4949 return -EINVAL;
4952 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4953 struct bpf_map *map;
4954 struct fd f;
4956 if (i == insn_cnt - 1 || insn[1].code != 0 ||
4957 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4958 insn[1].off != 0) {
4959 verbose(env, "invalid bpf_ld_imm64 insn\n");
4960 return -EINVAL;
4963 if (insn->src_reg == 0)
4964 /* valid generic load 64-bit imm */
4965 goto next_insn;
4967 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4968 verbose(env,
4969 "unrecognized bpf_ld_imm64 insn\n");
4970 return -EINVAL;
4973 f = fdget(insn->imm);
4974 map = __bpf_map_get(f);
4975 if (IS_ERR(map)) {
4976 verbose(env, "fd %d is not pointing to valid bpf_map\n",
4977 insn->imm);
4978 return PTR_ERR(map);
4981 err = check_map_prog_compatibility(env, map, env->prog);
4982 if (err) {
4983 fdput(f);
4984 return err;
4987 /* store map pointer inside BPF_LD_IMM64 instruction */
4988 insn[0].imm = (u32) (unsigned long) map;
4989 insn[1].imm = ((u64) (unsigned long) map) >> 32;
4991 /* check whether we recorded this map already */
4992 for (j = 0; j < env->used_map_cnt; j++)
4993 if (env->used_maps[j] == map) {
4994 fdput(f);
4995 goto next_insn;
4998 if (env->used_map_cnt >= MAX_USED_MAPS) {
4999 fdput(f);
5000 return -E2BIG;
5003 /* hold the map. If the program is rejected by verifier,
5004 * the map will be released by release_maps() or it
5005 * will be used by the valid program until it's unloaded
5006 * and all maps are released in free_bpf_prog_info()
5008 map = bpf_map_inc(map, false);
5009 if (IS_ERR(map)) {
5010 fdput(f);
5011 return PTR_ERR(map);
5013 env->used_maps[env->used_map_cnt++] = map;
5015 fdput(f);
5016 next_insn:
5017 insn++;
5018 i++;
5019 continue;
5022 /* Basic sanity check before we invest more work here. */
5023 if (!bpf_opcode_in_insntable(insn->code)) {
5024 verbose(env, "unknown opcode %02x\n", insn->code);
5025 return -EINVAL;
5029 /* now all pseudo BPF_LD_IMM64 instructions load valid
5030 * 'struct bpf_map *' into a register instead of user map_fd.
5031 * These pointers will be used later by verifier to validate map access.
5033 return 0;
5036 /* drop refcnt of maps used by the rejected program */
5037 static void release_maps(struct bpf_verifier_env *env)
5039 int i;
5041 for (i = 0; i < env->used_map_cnt; i++)
5042 bpf_map_put(env->used_maps[i]);
5045 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5046 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5048 struct bpf_insn *insn = env->prog->insnsi;
5049 int insn_cnt = env->prog->len;
5050 int i;
5052 for (i = 0; i < insn_cnt; i++, insn++)
5053 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5054 insn->src_reg = 0;
5057 /* single env->prog->insni[off] instruction was replaced with the range
5058 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
5059 * [0, off) and [off, end) to new locations, so the patched range stays zero
5061 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5062 u32 off, u32 cnt)
5064 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5065 int i;
5067 if (cnt == 1)
5068 return 0;
5069 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
5070 if (!new_data)
5071 return -ENOMEM;
5072 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5073 memcpy(new_data + off + cnt - 1, old_data + off,
5074 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5075 for (i = off; i < off + cnt - 1; i++)
5076 new_data[i].seen = true;
5077 env->insn_aux_data = new_data;
5078 vfree(old_data);
5079 return 0;
5082 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5084 int i;
5086 if (len == 1)
5087 return;
5088 for (i = 0; i < env->subprog_cnt; i++) {
5089 if (env->subprog_starts[i] < off)
5090 continue;
5091 env->subprog_starts[i] += len - 1;
5095 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5096 const struct bpf_insn *patch, u32 len)
5098 struct bpf_prog *new_prog;
5100 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5101 if (!new_prog)
5102 return NULL;
5103 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5104 return NULL;
5105 adjust_subprog_starts(env, off, len);
5106 return new_prog;
5109 /* The verifier does more data flow analysis than llvm and will not
5110 * explore branches that are dead at run time. Malicious programs can
5111 * have dead code too. Therefore replace all dead at-run-time code
5112 * with 'ja -1'.
5114 * Just nops are not optimal, e.g. if they would sit at the end of the
5115 * program and through another bug we would manage to jump there, then
5116 * we'd execute beyond program memory otherwise. Returning exception
5117 * code also wouldn't work since we can have subprogs where the dead
5118 * code could be located.
5120 static void sanitize_dead_code(struct bpf_verifier_env *env)
5122 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5123 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5124 struct bpf_insn *insn = env->prog->insnsi;
5125 const int insn_cnt = env->prog->len;
5126 int i;
5128 for (i = 0; i < insn_cnt; i++) {
5129 if (aux_data[i].seen)
5130 continue;
5131 memcpy(insn + i, &trap, sizeof(trap));
5135 /* convert load instructions that access fields of 'struct __sk_buff'
5136 * into sequence of instructions that access fields of 'struct sk_buff'
5138 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5140 const struct bpf_verifier_ops *ops = env->ops;
5141 int i, cnt, size, ctx_field_size, delta = 0;
5142 const int insn_cnt = env->prog->len;
5143 struct bpf_insn insn_buf[16], *insn;
5144 struct bpf_prog *new_prog;
5145 enum bpf_access_type type;
5146 bool is_narrower_load;
5147 u32 target_size;
5149 if (ops->gen_prologue) {
5150 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5151 env->prog);
5152 if (cnt >= ARRAY_SIZE(insn_buf)) {
5153 verbose(env, "bpf verifier is misconfigured\n");
5154 return -EINVAL;
5155 } else if (cnt) {
5156 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5157 if (!new_prog)
5158 return -ENOMEM;
5160 env->prog = new_prog;
5161 delta += cnt - 1;
5165 if (!ops->convert_ctx_access)
5166 return 0;
5168 insn = env->prog->insnsi + delta;
5170 for (i = 0; i < insn_cnt; i++, insn++) {
5171 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5172 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5173 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5174 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5175 type = BPF_READ;
5176 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5177 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5178 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5179 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5180 type = BPF_WRITE;
5181 else
5182 continue;
5184 if (type == BPF_WRITE &&
5185 env->insn_aux_data[i + delta].sanitize_stack_off) {
5186 struct bpf_insn patch[] = {
5187 /* Sanitize suspicious stack slot with zero.
5188 * There are no memory dependencies for this store,
5189 * since it's only using frame pointer and immediate
5190 * constant of zero
5192 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
5193 env->insn_aux_data[i + delta].sanitize_stack_off,
5195 /* the original STX instruction will immediately
5196 * overwrite the same stack slot with appropriate value
5198 *insn,
5201 cnt = ARRAY_SIZE(patch);
5202 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
5203 if (!new_prog)
5204 return -ENOMEM;
5206 delta += cnt - 1;
5207 env->prog = new_prog;
5208 insn = new_prog->insnsi + i + delta;
5209 continue;
5212 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5213 continue;
5215 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5216 size = BPF_LDST_BYTES(insn);
5218 /* If the read access is a narrower load of the field,
5219 * convert to a 4/8-byte load, to minimum program type specific
5220 * convert_ctx_access changes. If conversion is successful,
5221 * we will apply proper mask to the result.
5223 is_narrower_load = size < ctx_field_size;
5224 if (is_narrower_load) {
5225 u32 off = insn->off;
5226 u8 size_code;
5228 if (type == BPF_WRITE) {
5229 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5230 return -EINVAL;
5233 size_code = BPF_H;
5234 if (ctx_field_size == 4)
5235 size_code = BPF_W;
5236 else if (ctx_field_size == 8)
5237 size_code = BPF_DW;
5239 insn->off = off & ~(ctx_field_size - 1);
5240 insn->code = BPF_LDX | BPF_MEM | size_code;
5243 target_size = 0;
5244 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5245 &target_size);
5246 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5247 (ctx_field_size && !target_size)) {
5248 verbose(env, "bpf verifier is misconfigured\n");
5249 return -EINVAL;
5252 if (is_narrower_load && size < target_size) {
5253 if (ctx_field_size <= 4)
5254 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5255 (1 << size * 8) - 1);
5256 else
5257 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5258 (1 << size * 8) - 1);
5261 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5262 if (!new_prog)
5263 return -ENOMEM;
5265 delta += cnt - 1;
5267 /* keep walking new program and skip insns we just inserted */
5268 env->prog = new_prog;
5269 insn = new_prog->insnsi + i + delta;
5272 return 0;
5275 static int jit_subprogs(struct bpf_verifier_env *env)
5277 struct bpf_prog *prog = env->prog, **func, *tmp;
5278 int i, j, subprog_start, subprog_end = 0, len, subprog;
5279 struct bpf_insn *insn;
5280 void *old_bpf_func;
5281 int err = -ENOMEM;
5283 if (env->subprog_cnt == 0)
5284 return 0;
5286 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5287 if (insn->code != (BPF_JMP | BPF_CALL) ||
5288 insn->src_reg != BPF_PSEUDO_CALL)
5289 continue;
5290 subprog = find_subprog(env, i + insn->imm + 1);
5291 if (subprog < 0) {
5292 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5293 i + insn->imm + 1);
5294 return -EFAULT;
5296 /* temporarily remember subprog id inside insn instead of
5297 * aux_data, since next loop will split up all insns into funcs
5299 insn->off = subprog + 1;
5300 /* remember original imm in case JIT fails and fallback
5301 * to interpreter will be needed
5303 env->insn_aux_data[i].call_imm = insn->imm;
5304 /* point imm to __bpf_call_base+1 from JITs point of view */
5305 insn->imm = 1;
5308 func = kzalloc(sizeof(prog) * (env->subprog_cnt + 1), GFP_KERNEL);
5309 if (!func)
5310 return -ENOMEM;
5312 for (i = 0; i <= env->subprog_cnt; i++) {
5313 subprog_start = subprog_end;
5314 if (env->subprog_cnt == i)
5315 subprog_end = prog->len;
5316 else
5317 subprog_end = env->subprog_starts[i];
5319 len = subprog_end - subprog_start;
5320 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
5321 if (!func[i])
5322 goto out_free;
5323 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
5324 len * sizeof(struct bpf_insn));
5325 func[i]->type = prog->type;
5326 func[i]->len = len;
5327 if (bpf_prog_calc_tag(func[i]))
5328 goto out_free;
5329 func[i]->is_func = 1;
5330 /* Use bpf_prog_F_tag to indicate functions in stack traces.
5331 * Long term would need debug info to populate names
5333 func[i]->aux->name[0] = 'F';
5334 func[i]->aux->stack_depth = env->subprog_stack_depth[i];
5335 func[i]->jit_requested = 1;
5336 func[i] = bpf_int_jit_compile(func[i]);
5337 if (!func[i]->jited) {
5338 err = -ENOTSUPP;
5339 goto out_free;
5341 cond_resched();
5343 /* at this point all bpf functions were successfully JITed
5344 * now populate all bpf_calls with correct addresses and
5345 * run last pass of JIT
5347 for (i = 0; i <= env->subprog_cnt; i++) {
5348 insn = func[i]->insnsi;
5349 for (j = 0; j < func[i]->len; j++, insn++) {
5350 if (insn->code != (BPF_JMP | BPF_CALL) ||
5351 insn->src_reg != BPF_PSEUDO_CALL)
5352 continue;
5353 subprog = insn->off;
5354 insn->off = 0;
5355 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5356 func[subprog]->bpf_func -
5357 __bpf_call_base;
5360 for (i = 0; i <= env->subprog_cnt; i++) {
5361 old_bpf_func = func[i]->bpf_func;
5362 tmp = bpf_int_jit_compile(func[i]);
5363 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
5364 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
5365 err = -EFAULT;
5366 goto out_free;
5368 cond_resched();
5371 /* finally lock prog and jit images for all functions and
5372 * populate kallsysm
5374 for (i = 0; i <= env->subprog_cnt; i++) {
5375 bpf_prog_lock_ro(func[i]);
5376 bpf_prog_kallsyms_add(func[i]);
5379 /* Last step: make now unused interpreter insns from main
5380 * prog consistent for later dump requests, so they can
5381 * later look the same as if they were interpreted only.
5383 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5384 unsigned long addr;
5386 if (insn->code != (BPF_JMP | BPF_CALL) ||
5387 insn->src_reg != BPF_PSEUDO_CALL)
5388 continue;
5389 insn->off = env->insn_aux_data[i].call_imm;
5390 subprog = find_subprog(env, i + insn->off + 1);
5391 addr = (unsigned long)func[subprog + 1]->bpf_func;
5392 addr &= PAGE_MASK;
5393 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5394 addr - __bpf_call_base;
5397 prog->jited = 1;
5398 prog->bpf_func = func[0]->bpf_func;
5399 prog->aux->func = func;
5400 prog->aux->func_cnt = env->subprog_cnt + 1;
5401 return 0;
5402 out_free:
5403 for (i = 0; i <= env->subprog_cnt; i++)
5404 if (func[i])
5405 bpf_jit_free(func[i]);
5406 kfree(func);
5407 /* cleanup main prog to be interpreted */
5408 prog->jit_requested = 0;
5409 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5410 if (insn->code != (BPF_JMP | BPF_CALL) ||
5411 insn->src_reg != BPF_PSEUDO_CALL)
5412 continue;
5413 insn->off = 0;
5414 insn->imm = env->insn_aux_data[i].call_imm;
5416 return err;
5419 static int fixup_call_args(struct bpf_verifier_env *env)
5421 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5422 struct bpf_prog *prog = env->prog;
5423 struct bpf_insn *insn = prog->insnsi;
5424 int i, depth;
5425 #endif
5426 int err;
5428 err = 0;
5429 if (env->prog->jit_requested) {
5430 err = jit_subprogs(env);
5431 if (err == 0)
5432 return 0;
5434 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5435 for (i = 0; i < prog->len; i++, insn++) {
5436 if (insn->code != (BPF_JMP | BPF_CALL) ||
5437 insn->src_reg != BPF_PSEUDO_CALL)
5438 continue;
5439 depth = get_callee_stack_depth(env, insn, i);
5440 if (depth < 0)
5441 return depth;
5442 bpf_patch_call_args(insn, depth);
5444 err = 0;
5445 #endif
5446 return err;
5449 /* fixup insn->imm field of bpf_call instructions
5450 * and inline eligible helpers as explicit sequence of BPF instructions
5452 * this function is called after eBPF program passed verification
5454 static int fixup_bpf_calls(struct bpf_verifier_env *env)
5456 struct bpf_prog *prog = env->prog;
5457 struct bpf_insn *insn = prog->insnsi;
5458 const struct bpf_func_proto *fn;
5459 const int insn_cnt = prog->len;
5460 struct bpf_insn insn_buf[16];
5461 struct bpf_prog *new_prog;
5462 struct bpf_map *map_ptr;
5463 int i, cnt, delta = 0;
5465 for (i = 0; i < insn_cnt; i++, insn++) {
5466 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
5467 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5468 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
5469 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5470 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
5471 struct bpf_insn mask_and_div[] = {
5472 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5473 /* Rx div 0 -> 0 */
5474 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
5475 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
5476 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
5477 *insn,
5479 struct bpf_insn mask_and_mod[] = {
5480 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5481 /* Rx mod 0 -> Rx */
5482 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
5483 *insn,
5485 struct bpf_insn *patchlet;
5487 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5488 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5489 patchlet = mask_and_div + (is64 ? 1 : 0);
5490 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
5491 } else {
5492 patchlet = mask_and_mod + (is64 ? 1 : 0);
5493 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
5496 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
5497 if (!new_prog)
5498 return -ENOMEM;
5500 delta += cnt - 1;
5501 env->prog = prog = new_prog;
5502 insn = new_prog->insnsi + i + delta;
5503 continue;
5506 if (insn->code != (BPF_JMP | BPF_CALL))
5507 continue;
5508 if (insn->src_reg == BPF_PSEUDO_CALL)
5509 continue;
5511 if (insn->imm == BPF_FUNC_get_route_realm)
5512 prog->dst_needed = 1;
5513 if (insn->imm == BPF_FUNC_get_prandom_u32)
5514 bpf_user_rnd_init_once();
5515 if (insn->imm == BPF_FUNC_override_return)
5516 prog->kprobe_override = 1;
5517 if (insn->imm == BPF_FUNC_tail_call) {
5518 /* If we tail call into other programs, we
5519 * cannot make any assumptions since they can
5520 * be replaced dynamically during runtime in
5521 * the program array.
5523 prog->cb_access = 1;
5524 env->prog->aux->stack_depth = MAX_BPF_STACK;
5526 /* mark bpf_tail_call as different opcode to avoid
5527 * conditional branch in the interpeter for every normal
5528 * call and to prevent accidental JITing by JIT compiler
5529 * that doesn't support bpf_tail_call yet
5531 insn->imm = 0;
5532 insn->code = BPF_JMP | BPF_TAIL_CALL;
5534 /* instead of changing every JIT dealing with tail_call
5535 * emit two extra insns:
5536 * if (index >= max_entries) goto out;
5537 * index &= array->index_mask;
5538 * to avoid out-of-bounds cpu speculation
5540 map_ptr = env->insn_aux_data[i + delta].map_ptr;
5541 if (map_ptr == BPF_MAP_PTR_POISON) {
5542 verbose(env, "tail_call abusing map_ptr\n");
5543 return -EINVAL;
5545 if (!map_ptr->unpriv_array)
5546 continue;
5547 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
5548 map_ptr->max_entries, 2);
5549 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
5550 container_of(map_ptr,
5551 struct bpf_array,
5552 map)->index_mask);
5553 insn_buf[2] = *insn;
5554 cnt = 3;
5555 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5556 if (!new_prog)
5557 return -ENOMEM;
5559 delta += cnt - 1;
5560 env->prog = prog = new_prog;
5561 insn = new_prog->insnsi + i + delta;
5562 continue;
5565 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
5566 * handlers are currently limited to 64 bit only.
5568 if (prog->jit_requested && BITS_PER_LONG == 64 &&
5569 insn->imm == BPF_FUNC_map_lookup_elem) {
5570 map_ptr = env->insn_aux_data[i + delta].map_ptr;
5571 if (map_ptr == BPF_MAP_PTR_POISON ||
5572 !map_ptr->ops->map_gen_lookup)
5573 goto patch_call_imm;
5575 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
5576 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5577 verbose(env, "bpf verifier is misconfigured\n");
5578 return -EINVAL;
5581 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
5582 cnt);
5583 if (!new_prog)
5584 return -ENOMEM;
5586 delta += cnt - 1;
5588 /* keep walking new program and skip insns we just inserted */
5589 env->prog = prog = new_prog;
5590 insn = new_prog->insnsi + i + delta;
5591 continue;
5594 if (insn->imm == BPF_FUNC_redirect_map) {
5595 /* Note, we cannot use prog directly as imm as subsequent
5596 * rewrites would still change the prog pointer. The only
5597 * stable address we can use is aux, which also works with
5598 * prog clones during blinding.
5600 u64 addr = (unsigned long)prog->aux;
5601 struct bpf_insn r4_ld[] = {
5602 BPF_LD_IMM64(BPF_REG_4, addr),
5603 *insn,
5605 cnt = ARRAY_SIZE(r4_ld);
5607 new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
5608 if (!new_prog)
5609 return -ENOMEM;
5611 delta += cnt - 1;
5612 env->prog = prog = new_prog;
5613 insn = new_prog->insnsi + i + delta;
5615 patch_call_imm:
5616 fn = env->ops->get_func_proto(insn->imm);
5617 /* all functions that have prototype and verifier allowed
5618 * programs to call them, must be real in-kernel functions
5620 if (!fn->func) {
5621 verbose(env,
5622 "kernel subsystem misconfigured func %s#%d\n",
5623 func_id_name(insn->imm), insn->imm);
5624 return -EFAULT;
5626 insn->imm = fn->func - __bpf_call_base;
5629 return 0;
5632 static void free_states(struct bpf_verifier_env *env)
5634 struct bpf_verifier_state_list *sl, *sln;
5635 int i;
5637 if (!env->explored_states)
5638 return;
5640 for (i = 0; i < env->prog->len; i++) {
5641 sl = env->explored_states[i];
5643 if (sl)
5644 while (sl != STATE_LIST_MARK) {
5645 sln = sl->next;
5646 free_verifier_state(&sl->state, false);
5647 kfree(sl);
5648 sl = sln;
5652 kfree(env->explored_states);
5655 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5657 struct bpf_verifier_env *env;
5658 struct bpf_verifer_log *log;
5659 int ret = -EINVAL;
5661 /* no program is valid */
5662 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
5663 return -EINVAL;
5665 /* 'struct bpf_verifier_env' can be global, but since it's not small,
5666 * allocate/free it every time bpf_check() is called
5668 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5669 if (!env)
5670 return -ENOMEM;
5671 log = &env->log;
5673 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5674 (*prog)->len);
5675 ret = -ENOMEM;
5676 if (!env->insn_aux_data)
5677 goto err_free_env;
5678 env->prog = *prog;
5679 env->ops = bpf_verifier_ops[env->prog->type];
5681 /* grab the mutex to protect few globals used by verifier */
5682 mutex_lock(&bpf_verifier_lock);
5684 if (attr->log_level || attr->log_buf || attr->log_size) {
5685 /* user requested verbose verifier output
5686 * and supplied buffer to store the verification trace
5688 log->level = attr->log_level;
5689 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
5690 log->len_total = attr->log_size;
5692 ret = -EINVAL;
5693 /* log attributes have to be sane */
5694 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
5695 !log->level || !log->ubuf)
5696 goto err_unlock;
5699 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5700 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5701 env->strict_alignment = true;
5703 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5704 ret = bpf_prog_offload_verifier_prep(env);
5705 if (ret)
5706 goto err_unlock;
5709 ret = replace_map_fd_with_map_ptr(env);
5710 if (ret < 0)
5711 goto skip_full_check;
5713 env->explored_states = kcalloc(env->prog->len,
5714 sizeof(struct bpf_verifier_state_list *),
5715 GFP_USER);
5716 ret = -ENOMEM;
5717 if (!env->explored_states)
5718 goto skip_full_check;
5720 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5722 ret = check_cfg(env);
5723 if (ret < 0)
5724 goto skip_full_check;
5726 ret = do_check(env);
5727 if (env->cur_state) {
5728 free_verifier_state(env->cur_state, true);
5729 env->cur_state = NULL;
5732 skip_full_check:
5733 while (!pop_stack(env, NULL, NULL));
5734 free_states(env);
5736 if (ret == 0)
5737 sanitize_dead_code(env);
5739 if (ret == 0)
5740 ret = check_max_stack_depth(env);
5742 if (ret == 0)
5743 /* program is valid, convert *(u32*)(ctx + off) accesses */
5744 ret = convert_ctx_accesses(env);
5746 if (ret == 0)
5747 ret = fixup_bpf_calls(env);
5749 if (ret == 0)
5750 ret = fixup_call_args(env);
5752 if (log->level && bpf_verifier_log_full(log))
5753 ret = -ENOSPC;
5754 if (log->level && !log->ubuf) {
5755 ret = -EFAULT;
5756 goto err_release_maps;
5759 if (ret == 0 && env->used_map_cnt) {
5760 /* if program passed verifier, update used_maps in bpf_prog_info */
5761 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5762 sizeof(env->used_maps[0]),
5763 GFP_KERNEL);
5765 if (!env->prog->aux->used_maps) {
5766 ret = -ENOMEM;
5767 goto err_release_maps;
5770 memcpy(env->prog->aux->used_maps, env->used_maps,
5771 sizeof(env->used_maps[0]) * env->used_map_cnt);
5772 env->prog->aux->used_map_cnt = env->used_map_cnt;
5774 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
5775 * bpf_ld_imm64 instructions
5777 convert_pseudo_ld_imm64(env);
5780 err_release_maps:
5781 if (!env->prog->aux->used_maps)
5782 /* if we didn't copy map pointers into bpf_prog_info, release
5783 * them now. Otherwise free_bpf_prog_info() will release them.
5785 release_maps(env);
5786 *prog = env->prog;
5787 err_unlock:
5788 mutex_unlock(&bpf_verifier_lock);
5789 vfree(env->insn_aux_data);
5790 err_free_env:
5791 kfree(env);
5792 return ret;