1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 * Copyright (c) 2016 Facebook
3 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 2 of the GNU General Public
7 * License as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 #include <uapi/linux/btf.h>
15 #include <linux/kernel.h>
16 #include <linux/types.h>
17 #include <linux/slab.h>
18 #include <linux/bpf.h>
19 #include <linux/btf.h>
20 #include <linux/bpf_verifier.h>
21 #include <linux/filter.h>
22 #include <net/netlink.h>
23 #include <linux/file.h>
24 #include <linux/vmalloc.h>
25 #include <linux/stringify.h>
26 #include <linux/bsearch.h>
27 #include <linux/sort.h>
28 #include <linux/perf_event.h>
29 #include <linux/ctype.h>
33 static const struct bpf_verifier_ops
* const bpf_verifier_ops
[] = {
34 #define BPF_PROG_TYPE(_id, _name) \
35 [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #include <linux/bpf_types.h>
42 /* bpf_check() is a static code analyzer that walks eBPF program
43 * instruction by instruction and updates register/stack state.
44 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46 * The first pass is depth-first-search to check that the program is a DAG.
47 * It rejects the following programs:
48 * - larger than BPF_MAXINSNS insns
49 * - if loop is present (detected via back-edge)
50 * - unreachable insns exist (shouldn't be a forest. program = one function)
51 * - out of bounds or malformed jumps
52 * The second pass is all possible path descent from the 1st insn.
53 * Since it's analyzing all pathes through the program, the length of the
54 * analysis is limited to 64k insn, which may be hit even if total number of
55 * insn is less then 4K, but there are too many branches that change stack/regs.
56 * Number of 'branches to be analyzed' is limited to 1k
58 * On entry to each instruction, each register has a type, and the instruction
59 * changes the types of the registers depending on instruction semantics.
60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63 * All registers are 64-bit.
64 * R0 - return register
65 * R1-R5 argument passing registers
66 * R6-R9 callee saved registers
67 * R10 - frame pointer read-only
69 * At the start of BPF program the register R1 contains a pointer to bpf_context
70 * and has type PTR_TO_CTX.
72 * Verifier tracks arithmetic operations on pointers in case:
73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
75 * 1st insn copies R10 (which has FRAME_PTR) type into R1
76 * and 2nd arithmetic instruction is pattern matched to recognize
77 * that it wants to construct a pointer to some element within stack.
78 * So after 2nd insn, the register R1 has type PTR_TO_STACK
79 * (and -20 constant is saved for further stack bounds checking).
80 * Meaning that this reg is a pointer to stack plus known immediate constant.
82 * Most of the time the registers have SCALAR_VALUE type, which
83 * means the register has some value, but it's not a valid pointer.
84 * (like pointer plus pointer becomes SCALAR_VALUE type)
86 * When verifier sees load or store instructions the type of base register
87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
88 * four pointer types recognized by check_mem_access() function.
90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
91 * and the range of [ptr, ptr + map's value_size) is accessible.
93 * registers used to pass values to function calls are checked against
94 * function argument constraints.
96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
97 * It means that the register type passed to this function must be
98 * PTR_TO_STACK and it will be used inside the function as
99 * 'pointer to map element key'
101 * For example the argument constraints for bpf_map_lookup_elem():
102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
103 * .arg1_type = ARG_CONST_MAP_PTR,
104 * .arg2_type = ARG_PTR_TO_MAP_KEY,
106 * ret_type says that this function returns 'pointer to map elem value or null'
107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
108 * 2nd argument should be a pointer to stack, which will be used inside
109 * the helper function as a pointer to map element key.
111 * On the kernel side the helper function looks like:
112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
115 * void *key = (void *) (unsigned long) r2;
118 * here kernel can access 'key' and 'map' pointers safely, knowing that
119 * [key, key + map->key_size) bytes are valid and were initialized on
120 * the stack of eBPF program.
123 * Corresponding eBPF program may look like:
124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
128 * here verifier looks at prototype of map_lookup_elem() and sees:
129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
134 * and were initialized prior to this call.
135 * If it's ok, then verifier allows this BPF_CALL insn and looks at
136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
138 * returns ether pointer to map value or NULL.
140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
141 * insn, the register holding that pointer in the true branch changes state to
142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
143 * branch. See check_cond_jmp_op().
145 * After the call R0 is set to return type of the function and registers R1-R5
146 * are set to NOT_INIT to indicate that they are no longer readable.
148 * The following reference types represent a potential reference to a kernel
149 * resource which, after first being allocated, must be checked and freed by
151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153 * When the verifier sees a helper call return a reference type, it allocates a
154 * pointer id for the reference and stores it in the current function state.
155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
157 * passes through a NULL-check conditional. For the branch wherein the state is
158 * changed to CONST_IMM, the verifier releases the reference.
160 * For each helper function that allocates a reference, such as
161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
162 * bpf_sk_release(). When a reference type passes into the release function,
163 * the verifier also releases the reference. If any unchecked or unreleased
164 * reference remains at the end of the program, the verifier rejects it.
167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
168 struct bpf_verifier_stack_elem
{
169 /* verifer state is 'st'
170 * before processing instruction 'insn_idx'
171 * and after processing instruction 'prev_insn_idx'
173 struct bpf_verifier_state st
;
176 struct bpf_verifier_stack_elem
*next
;
179 #define BPF_COMPLEXITY_LIMIT_STACK 1024
180 #define BPF_COMPLEXITY_LIMIT_STATES 64
182 #define BPF_MAP_PTR_UNPRIV 1UL
183 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
184 POISON_POINTER_DELTA))
185 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
187 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data
*aux
)
189 return BPF_MAP_PTR(aux
->map_state
) == BPF_MAP_PTR_POISON
;
192 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data
*aux
)
194 return aux
->map_state
& BPF_MAP_PTR_UNPRIV
;
197 static void bpf_map_ptr_store(struct bpf_insn_aux_data
*aux
,
198 const struct bpf_map
*map
, bool unpriv
)
200 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON
& BPF_MAP_PTR_UNPRIV
);
201 unpriv
|= bpf_map_ptr_unpriv(aux
);
202 aux
->map_state
= (unsigned long)map
|
203 (unpriv
? BPF_MAP_PTR_UNPRIV
: 0UL);
206 struct bpf_call_arg_meta
{
207 struct bpf_map
*map_ptr
;
212 s64 msize_smax_value
;
213 u64 msize_umax_value
;
218 static DEFINE_MUTEX(bpf_verifier_lock
);
220 static const struct bpf_line_info
*
221 find_linfo(const struct bpf_verifier_env
*env
, u32 insn_off
)
223 const struct bpf_line_info
*linfo
;
224 const struct bpf_prog
*prog
;
228 nr_linfo
= prog
->aux
->nr_linfo
;
230 if (!nr_linfo
|| insn_off
>= prog
->len
)
233 linfo
= prog
->aux
->linfo
;
234 for (i
= 1; i
< nr_linfo
; i
++)
235 if (insn_off
< linfo
[i
].insn_off
)
238 return &linfo
[i
- 1];
241 void bpf_verifier_vlog(struct bpf_verifier_log
*log
, const char *fmt
,
246 n
= vscnprintf(log
->kbuf
, BPF_VERIFIER_TMP_LOG_SIZE
, fmt
, args
);
248 WARN_ONCE(n
>= BPF_VERIFIER_TMP_LOG_SIZE
- 1,
249 "verifier log line truncated - local buffer too short\n");
251 n
= min(log
->len_total
- log
->len_used
- 1, n
);
254 if (!copy_to_user(log
->ubuf
+ log
->len_used
, log
->kbuf
, n
+ 1))
260 /* log_level controls verbosity level of eBPF verifier.
261 * bpf_verifier_log_write() is used to dump the verification trace to the log,
262 * so the user can figure out what's wrong with the program
264 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env
*env
,
265 const char *fmt
, ...)
269 if (!bpf_verifier_log_needed(&env
->log
))
273 bpf_verifier_vlog(&env
->log
, fmt
, args
);
276 EXPORT_SYMBOL_GPL(bpf_verifier_log_write
);
278 __printf(2, 3) static void verbose(void *private_data
, const char *fmt
, ...)
280 struct bpf_verifier_env
*env
= private_data
;
283 if (!bpf_verifier_log_needed(&env
->log
))
287 bpf_verifier_vlog(&env
->log
, fmt
, args
);
291 static const char *ltrim(const char *s
)
299 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env
*env
,
301 const char *prefix_fmt
, ...)
303 const struct bpf_line_info
*linfo
;
305 if (!bpf_verifier_log_needed(&env
->log
))
308 linfo
= find_linfo(env
, insn_off
);
309 if (!linfo
|| linfo
== env
->prev_linfo
)
315 va_start(args
, prefix_fmt
);
316 bpf_verifier_vlog(&env
->log
, prefix_fmt
, args
);
321 ltrim(btf_name_by_offset(env
->prog
->aux
->btf
,
324 env
->prev_linfo
= linfo
;
327 static bool type_is_pkt_pointer(enum bpf_reg_type type
)
329 return type
== PTR_TO_PACKET
||
330 type
== PTR_TO_PACKET_META
;
333 static bool type_is_sk_pointer(enum bpf_reg_type type
)
335 return type
== PTR_TO_SOCKET
||
336 type
== PTR_TO_SOCK_COMMON
||
337 type
== PTR_TO_TCP_SOCK
;
340 static bool reg_type_may_be_null(enum bpf_reg_type type
)
342 return type
== PTR_TO_MAP_VALUE_OR_NULL
||
343 type
== PTR_TO_SOCKET_OR_NULL
||
344 type
== PTR_TO_SOCK_COMMON_OR_NULL
||
345 type
== PTR_TO_TCP_SOCK_OR_NULL
;
348 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state
*reg
)
350 return reg
->type
== PTR_TO_MAP_VALUE
&&
351 map_value_has_spin_lock(reg
->map_ptr
);
354 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type
)
356 return type
== PTR_TO_SOCKET
||
357 type
== PTR_TO_SOCKET_OR_NULL
||
358 type
== PTR_TO_TCP_SOCK
||
359 type
== PTR_TO_TCP_SOCK_OR_NULL
;
362 static bool arg_type_may_be_refcounted(enum bpf_arg_type type
)
364 return type
== ARG_PTR_TO_SOCK_COMMON
;
367 /* Determine whether the function releases some resources allocated by another
368 * function call. The first reference type argument will be assumed to be
369 * released by release_reference().
371 static bool is_release_function(enum bpf_func_id func_id
)
373 return func_id
== BPF_FUNC_sk_release
;
376 static bool is_acquire_function(enum bpf_func_id func_id
)
378 return func_id
== BPF_FUNC_sk_lookup_tcp
||
379 func_id
== BPF_FUNC_sk_lookup_udp
||
380 func_id
== BPF_FUNC_skc_lookup_tcp
;
383 static bool is_ptr_cast_function(enum bpf_func_id func_id
)
385 return func_id
== BPF_FUNC_tcp_sock
||
386 func_id
== BPF_FUNC_sk_fullsock
;
389 /* string representation of 'enum bpf_reg_type' */
390 static const char * const reg_type_str
[] = {
392 [SCALAR_VALUE
] = "inv",
393 [PTR_TO_CTX
] = "ctx",
394 [CONST_PTR_TO_MAP
] = "map_ptr",
395 [PTR_TO_MAP_VALUE
] = "map_value",
396 [PTR_TO_MAP_VALUE_OR_NULL
] = "map_value_or_null",
397 [PTR_TO_STACK
] = "fp",
398 [PTR_TO_PACKET
] = "pkt",
399 [PTR_TO_PACKET_META
] = "pkt_meta",
400 [PTR_TO_PACKET_END
] = "pkt_end",
401 [PTR_TO_FLOW_KEYS
] = "flow_keys",
402 [PTR_TO_SOCKET
] = "sock",
403 [PTR_TO_SOCKET_OR_NULL
] = "sock_or_null",
404 [PTR_TO_SOCK_COMMON
] = "sock_common",
405 [PTR_TO_SOCK_COMMON_OR_NULL
] = "sock_common_or_null",
406 [PTR_TO_TCP_SOCK
] = "tcp_sock",
407 [PTR_TO_TCP_SOCK_OR_NULL
] = "tcp_sock_or_null",
408 [PTR_TO_TP_BUFFER
] = "tp_buffer",
411 static char slot_type_char
[] = {
412 [STACK_INVALID
] = '?',
418 static void print_liveness(struct bpf_verifier_env
*env
,
419 enum bpf_reg_liveness live
)
421 if (live
& (REG_LIVE_READ
| REG_LIVE_WRITTEN
| REG_LIVE_DONE
))
423 if (live
& REG_LIVE_READ
)
425 if (live
& REG_LIVE_WRITTEN
)
427 if (live
& REG_LIVE_DONE
)
431 static struct bpf_func_state
*func(struct bpf_verifier_env
*env
,
432 const struct bpf_reg_state
*reg
)
434 struct bpf_verifier_state
*cur
= env
->cur_state
;
436 return cur
->frame
[reg
->frameno
];
439 static void print_verifier_state(struct bpf_verifier_env
*env
,
440 const struct bpf_func_state
*state
)
442 const struct bpf_reg_state
*reg
;
447 verbose(env
, " frame%d:", state
->frameno
);
448 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
449 reg
= &state
->regs
[i
];
453 verbose(env
, " R%d", i
);
454 print_liveness(env
, reg
->live
);
455 verbose(env
, "=%s", reg_type_str
[t
]);
456 if ((t
== SCALAR_VALUE
|| t
== PTR_TO_STACK
) &&
457 tnum_is_const(reg
->var_off
)) {
458 /* reg->off should be 0 for SCALAR_VALUE */
459 verbose(env
, "%lld", reg
->var_off
.value
+ reg
->off
);
460 if (t
== PTR_TO_STACK
)
461 verbose(env
, ",call_%d", func(env
, reg
)->callsite
);
463 verbose(env
, "(id=%d", reg
->id
);
464 if (reg_type_may_be_refcounted_or_null(t
))
465 verbose(env
, ",ref_obj_id=%d", reg
->ref_obj_id
);
466 if (t
!= SCALAR_VALUE
)
467 verbose(env
, ",off=%d", reg
->off
);
468 if (type_is_pkt_pointer(t
))
469 verbose(env
, ",r=%d", reg
->range
);
470 else if (t
== CONST_PTR_TO_MAP
||
471 t
== PTR_TO_MAP_VALUE
||
472 t
== PTR_TO_MAP_VALUE_OR_NULL
)
473 verbose(env
, ",ks=%d,vs=%d",
474 reg
->map_ptr
->key_size
,
475 reg
->map_ptr
->value_size
);
476 if (tnum_is_const(reg
->var_off
)) {
477 /* Typically an immediate SCALAR_VALUE, but
478 * could be a pointer whose offset is too big
481 verbose(env
, ",imm=%llx", reg
->var_off
.value
);
483 if (reg
->smin_value
!= reg
->umin_value
&&
484 reg
->smin_value
!= S64_MIN
)
485 verbose(env
, ",smin_value=%lld",
486 (long long)reg
->smin_value
);
487 if (reg
->smax_value
!= reg
->umax_value
&&
488 reg
->smax_value
!= S64_MAX
)
489 verbose(env
, ",smax_value=%lld",
490 (long long)reg
->smax_value
);
491 if (reg
->umin_value
!= 0)
492 verbose(env
, ",umin_value=%llu",
493 (unsigned long long)reg
->umin_value
);
494 if (reg
->umax_value
!= U64_MAX
)
495 verbose(env
, ",umax_value=%llu",
496 (unsigned long long)reg
->umax_value
);
497 if (!tnum_is_unknown(reg
->var_off
)) {
500 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
501 verbose(env
, ",var_off=%s", tn_buf
);
507 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
508 char types_buf
[BPF_REG_SIZE
+ 1];
512 for (j
= 0; j
< BPF_REG_SIZE
; j
++) {
513 if (state
->stack
[i
].slot_type
[j
] != STACK_INVALID
)
515 types_buf
[j
] = slot_type_char
[
516 state
->stack
[i
].slot_type
[j
]];
518 types_buf
[BPF_REG_SIZE
] = 0;
521 verbose(env
, " fp%d", (-i
- 1) * BPF_REG_SIZE
);
522 print_liveness(env
, state
->stack
[i
].spilled_ptr
.live
);
523 if (state
->stack
[i
].slot_type
[0] == STACK_SPILL
)
525 reg_type_str
[state
->stack
[i
].spilled_ptr
.type
]);
527 verbose(env
, "=%s", types_buf
);
529 if (state
->acquired_refs
&& state
->refs
[0].id
) {
530 verbose(env
, " refs=%d", state
->refs
[0].id
);
531 for (i
= 1; i
< state
->acquired_refs
; i
++)
532 if (state
->refs
[i
].id
)
533 verbose(env
, ",%d", state
->refs
[i
].id
);
538 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
539 static int copy_##NAME##_state(struct bpf_func_state *dst, \
540 const struct bpf_func_state *src) \
544 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
545 /* internal bug, make state invalid to reject the program */ \
546 memset(dst, 0, sizeof(*dst)); \
549 memcpy(dst->FIELD, src->FIELD, \
550 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
553 /* copy_reference_state() */
554 COPY_STATE_FN(reference
, acquired_refs
, refs
, 1)
555 /* copy_stack_state() */
556 COPY_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
559 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
560 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
563 u32 old_size = state->COUNT; \
564 struct bpf_##NAME##_state *new_##FIELD; \
565 int slot = size / SIZE; \
567 if (size <= old_size || !size) { \
570 state->COUNT = slot * SIZE; \
571 if (!size && old_size) { \
572 kfree(state->FIELD); \
573 state->FIELD = NULL; \
577 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
583 memcpy(new_##FIELD, state->FIELD, \
584 sizeof(*new_##FIELD) * (old_size / SIZE)); \
585 memset(new_##FIELD + old_size / SIZE, 0, \
586 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
588 state->COUNT = slot * SIZE; \
589 kfree(state->FIELD); \
590 state->FIELD = new_##FIELD; \
593 /* realloc_reference_state() */
594 REALLOC_STATE_FN(reference
, acquired_refs
, refs
, 1)
595 /* realloc_stack_state() */
596 REALLOC_STATE_FN(stack
, allocated_stack
, stack
, BPF_REG_SIZE
)
597 #undef REALLOC_STATE_FN
599 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
600 * make it consume minimal amount of memory. check_stack_write() access from
601 * the program calls into realloc_func_state() to grow the stack size.
602 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
603 * which realloc_stack_state() copies over. It points to previous
604 * bpf_verifier_state which is never reallocated.
606 static int realloc_func_state(struct bpf_func_state
*state
, int stack_size
,
607 int refs_size
, bool copy_old
)
609 int err
= realloc_reference_state(state
, refs_size
, copy_old
);
612 return realloc_stack_state(state
, stack_size
, copy_old
);
615 /* Acquire a pointer id from the env and update the state->refs to include
616 * this new pointer reference.
617 * On success, returns a valid pointer id to associate with the register
618 * On failure, returns a negative errno.
620 static int acquire_reference_state(struct bpf_verifier_env
*env
, int insn_idx
)
622 struct bpf_func_state
*state
= cur_func(env
);
623 int new_ofs
= state
->acquired_refs
;
626 err
= realloc_reference_state(state
, state
->acquired_refs
+ 1, true);
630 state
->refs
[new_ofs
].id
= id
;
631 state
->refs
[new_ofs
].insn_idx
= insn_idx
;
636 /* release function corresponding to acquire_reference_state(). Idempotent. */
637 static int release_reference_state(struct bpf_func_state
*state
, int ptr_id
)
641 last_idx
= state
->acquired_refs
- 1;
642 for (i
= 0; i
< state
->acquired_refs
; i
++) {
643 if (state
->refs
[i
].id
== ptr_id
) {
644 if (last_idx
&& i
!= last_idx
)
645 memcpy(&state
->refs
[i
], &state
->refs
[last_idx
],
646 sizeof(*state
->refs
));
647 memset(&state
->refs
[last_idx
], 0, sizeof(*state
->refs
));
648 state
->acquired_refs
--;
655 static int transfer_reference_state(struct bpf_func_state
*dst
,
656 struct bpf_func_state
*src
)
658 int err
= realloc_reference_state(dst
, src
->acquired_refs
, false);
661 err
= copy_reference_state(dst
, src
);
667 static void free_func_state(struct bpf_func_state
*state
)
676 static void free_verifier_state(struct bpf_verifier_state
*state
,
681 for (i
= 0; i
<= state
->curframe
; i
++) {
682 free_func_state(state
->frame
[i
]);
683 state
->frame
[i
] = NULL
;
689 /* copy verifier state from src to dst growing dst stack space
690 * when necessary to accommodate larger src stack
692 static int copy_func_state(struct bpf_func_state
*dst
,
693 const struct bpf_func_state
*src
)
697 err
= realloc_func_state(dst
, src
->allocated_stack
, src
->acquired_refs
,
701 memcpy(dst
, src
, offsetof(struct bpf_func_state
, acquired_refs
));
702 err
= copy_reference_state(dst
, src
);
705 return copy_stack_state(dst
, src
);
708 static int copy_verifier_state(struct bpf_verifier_state
*dst_state
,
709 const struct bpf_verifier_state
*src
)
711 struct bpf_func_state
*dst
;
714 /* if dst has more stack frames then src frame, free them */
715 for (i
= src
->curframe
+ 1; i
<= dst_state
->curframe
; i
++) {
716 free_func_state(dst_state
->frame
[i
]);
717 dst_state
->frame
[i
] = NULL
;
719 dst_state
->speculative
= src
->speculative
;
720 dst_state
->curframe
= src
->curframe
;
721 dst_state
->active_spin_lock
= src
->active_spin_lock
;
722 for (i
= 0; i
<= src
->curframe
; i
++) {
723 dst
= dst_state
->frame
[i
];
725 dst
= kzalloc(sizeof(*dst
), GFP_KERNEL
);
728 dst_state
->frame
[i
] = dst
;
730 err
= copy_func_state(dst
, src
->frame
[i
]);
737 static int pop_stack(struct bpf_verifier_env
*env
, int *prev_insn_idx
,
740 struct bpf_verifier_state
*cur
= env
->cur_state
;
741 struct bpf_verifier_stack_elem
*elem
, *head
= env
->head
;
744 if (env
->head
== NULL
)
748 err
= copy_verifier_state(cur
, &head
->st
);
753 *insn_idx
= head
->insn_idx
;
755 *prev_insn_idx
= head
->prev_insn_idx
;
757 free_verifier_state(&head
->st
, false);
764 static struct bpf_verifier_state
*push_stack(struct bpf_verifier_env
*env
,
765 int insn_idx
, int prev_insn_idx
,
768 struct bpf_verifier_state
*cur
= env
->cur_state
;
769 struct bpf_verifier_stack_elem
*elem
;
772 elem
= kzalloc(sizeof(struct bpf_verifier_stack_elem
), GFP_KERNEL
);
776 elem
->insn_idx
= insn_idx
;
777 elem
->prev_insn_idx
= prev_insn_idx
;
778 elem
->next
= env
->head
;
781 err
= copy_verifier_state(&elem
->st
, cur
);
784 elem
->st
.speculative
|= speculative
;
785 if (env
->stack_size
> BPF_COMPLEXITY_LIMIT_STACK
) {
786 verbose(env
, "BPF program is too complex\n");
791 free_verifier_state(env
->cur_state
, true);
792 env
->cur_state
= NULL
;
793 /* pop all elements and return */
794 while (!pop_stack(env
, NULL
, NULL
));
798 #define CALLER_SAVED_REGS 6
799 static const int caller_saved
[CALLER_SAVED_REGS
] = {
800 BPF_REG_0
, BPF_REG_1
, BPF_REG_2
, BPF_REG_3
, BPF_REG_4
, BPF_REG_5
803 static void __mark_reg_not_init(struct bpf_reg_state
*reg
);
805 /* Mark the unknown part of a register (variable offset or scalar value) as
806 * known to have the value @imm.
808 static void __mark_reg_known(struct bpf_reg_state
*reg
, u64 imm
)
810 /* Clear id, off, and union(map_ptr, range) */
811 memset(((u8
*)reg
) + sizeof(reg
->type
), 0,
812 offsetof(struct bpf_reg_state
, var_off
) - sizeof(reg
->type
));
813 reg
->var_off
= tnum_const(imm
);
814 reg
->smin_value
= (s64
)imm
;
815 reg
->smax_value
= (s64
)imm
;
816 reg
->umin_value
= imm
;
817 reg
->umax_value
= imm
;
820 /* Mark the 'variable offset' part of a register as zero. This should be
821 * used only on registers holding a pointer type.
823 static void __mark_reg_known_zero(struct bpf_reg_state
*reg
)
825 __mark_reg_known(reg
, 0);
828 static void __mark_reg_const_zero(struct bpf_reg_state
*reg
)
830 __mark_reg_known(reg
, 0);
831 reg
->type
= SCALAR_VALUE
;
834 static void mark_reg_known_zero(struct bpf_verifier_env
*env
,
835 struct bpf_reg_state
*regs
, u32 regno
)
837 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
838 verbose(env
, "mark_reg_known_zero(regs, %u)\n", regno
);
839 /* Something bad happened, let's kill all regs */
840 for (regno
= 0; regno
< MAX_BPF_REG
; regno
++)
841 __mark_reg_not_init(regs
+ regno
);
844 __mark_reg_known_zero(regs
+ regno
);
847 static bool reg_is_pkt_pointer(const struct bpf_reg_state
*reg
)
849 return type_is_pkt_pointer(reg
->type
);
852 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state
*reg
)
854 return reg_is_pkt_pointer(reg
) ||
855 reg
->type
== PTR_TO_PACKET_END
;
858 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
859 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state
*reg
,
860 enum bpf_reg_type which
)
862 /* The register can already have a range from prior markings.
863 * This is fine as long as it hasn't been advanced from its
866 return reg
->type
== which
&&
869 tnum_equals_const(reg
->var_off
, 0);
872 /* Attempts to improve min/max values based on var_off information */
873 static void __update_reg_bounds(struct bpf_reg_state
*reg
)
875 /* min signed is max(sign bit) | min(other bits) */
876 reg
->smin_value
= max_t(s64
, reg
->smin_value
,
877 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MIN
));
878 /* max signed is min(sign bit) | max(other bits) */
879 reg
->smax_value
= min_t(s64
, reg
->smax_value
,
880 reg
->var_off
.value
| (reg
->var_off
.mask
& S64_MAX
));
881 reg
->umin_value
= max(reg
->umin_value
, reg
->var_off
.value
);
882 reg
->umax_value
= min(reg
->umax_value
,
883 reg
->var_off
.value
| reg
->var_off
.mask
);
886 /* Uses signed min/max values to inform unsigned, and vice-versa */
887 static void __reg_deduce_bounds(struct bpf_reg_state
*reg
)
889 /* Learn sign from signed bounds.
890 * If we cannot cross the sign boundary, then signed and unsigned bounds
891 * are the same, so combine. This works even in the negative case, e.g.
892 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
894 if (reg
->smin_value
>= 0 || reg
->smax_value
< 0) {
895 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
897 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
901 /* Learn sign from unsigned bounds. Signed bounds cross the sign
902 * boundary, so we must be careful.
904 if ((s64
)reg
->umax_value
>= 0) {
905 /* Positive. We can't learn anything from the smin, but smax
906 * is positive, hence safe.
908 reg
->smin_value
= reg
->umin_value
;
909 reg
->smax_value
= reg
->umax_value
= min_t(u64
, reg
->smax_value
,
911 } else if ((s64
)reg
->umin_value
< 0) {
912 /* Negative. We can't learn anything from the smax, but smin
913 * is negative, hence safe.
915 reg
->smin_value
= reg
->umin_value
= max_t(u64
, reg
->smin_value
,
917 reg
->smax_value
= reg
->umax_value
;
921 /* Attempts to improve var_off based on unsigned min/max information */
922 static void __reg_bound_offset(struct bpf_reg_state
*reg
)
924 reg
->var_off
= tnum_intersect(reg
->var_off
,
925 tnum_range(reg
->umin_value
,
929 /* Reset the min/max bounds of a register */
930 static void __mark_reg_unbounded(struct bpf_reg_state
*reg
)
932 reg
->smin_value
= S64_MIN
;
933 reg
->smax_value
= S64_MAX
;
935 reg
->umax_value
= U64_MAX
;
938 /* Mark a register as having a completely unknown (scalar) value. */
939 static void __mark_reg_unknown(struct bpf_reg_state
*reg
)
942 * Clear type, id, off, and union(map_ptr, range) and
943 * padding between 'type' and union
945 memset(reg
, 0, offsetof(struct bpf_reg_state
, var_off
));
946 reg
->type
= SCALAR_VALUE
;
947 reg
->var_off
= tnum_unknown
;
949 __mark_reg_unbounded(reg
);
952 static void mark_reg_unknown(struct bpf_verifier_env
*env
,
953 struct bpf_reg_state
*regs
, u32 regno
)
955 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
956 verbose(env
, "mark_reg_unknown(regs, %u)\n", regno
);
957 /* Something bad happened, let's kill all regs except FP */
958 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
959 __mark_reg_not_init(regs
+ regno
);
962 __mark_reg_unknown(regs
+ regno
);
965 static void __mark_reg_not_init(struct bpf_reg_state
*reg
)
967 __mark_reg_unknown(reg
);
968 reg
->type
= NOT_INIT
;
971 static void mark_reg_not_init(struct bpf_verifier_env
*env
,
972 struct bpf_reg_state
*regs
, u32 regno
)
974 if (WARN_ON(regno
>= MAX_BPF_REG
)) {
975 verbose(env
, "mark_reg_not_init(regs, %u)\n", regno
);
976 /* Something bad happened, let's kill all regs except FP */
977 for (regno
= 0; regno
< BPF_REG_FP
; regno
++)
978 __mark_reg_not_init(regs
+ regno
);
981 __mark_reg_not_init(regs
+ regno
);
984 static void init_reg_state(struct bpf_verifier_env
*env
,
985 struct bpf_func_state
*state
)
987 struct bpf_reg_state
*regs
= state
->regs
;
990 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
991 mark_reg_not_init(env
, regs
, i
);
992 regs
[i
].live
= REG_LIVE_NONE
;
993 regs
[i
].parent
= NULL
;
997 regs
[BPF_REG_FP
].type
= PTR_TO_STACK
;
998 mark_reg_known_zero(env
, regs
, BPF_REG_FP
);
999 regs
[BPF_REG_FP
].frameno
= state
->frameno
;
1001 /* 1st arg to a function */
1002 regs
[BPF_REG_1
].type
= PTR_TO_CTX
;
1003 mark_reg_known_zero(env
, regs
, BPF_REG_1
);
1006 #define BPF_MAIN_FUNC (-1)
1007 static void init_func_state(struct bpf_verifier_env
*env
,
1008 struct bpf_func_state
*state
,
1009 int callsite
, int frameno
, int subprogno
)
1011 state
->callsite
= callsite
;
1012 state
->frameno
= frameno
;
1013 state
->subprogno
= subprogno
;
1014 init_reg_state(env
, state
);
1018 SRC_OP
, /* register is used as source operand */
1019 DST_OP
, /* register is used as destination operand */
1020 DST_OP_NO_MARK
/* same as above, check only, don't mark */
1023 static int cmp_subprogs(const void *a
, const void *b
)
1025 return ((struct bpf_subprog_info
*)a
)->start
-
1026 ((struct bpf_subprog_info
*)b
)->start
;
1029 static int find_subprog(struct bpf_verifier_env
*env
, int off
)
1031 struct bpf_subprog_info
*p
;
1033 p
= bsearch(&off
, env
->subprog_info
, env
->subprog_cnt
,
1034 sizeof(env
->subprog_info
[0]), cmp_subprogs
);
1037 return p
- env
->subprog_info
;
1041 static int add_subprog(struct bpf_verifier_env
*env
, int off
)
1043 int insn_cnt
= env
->prog
->len
;
1046 if (off
>= insn_cnt
|| off
< 0) {
1047 verbose(env
, "call to invalid destination\n");
1050 ret
= find_subprog(env
, off
);
1053 if (env
->subprog_cnt
>= BPF_MAX_SUBPROGS
) {
1054 verbose(env
, "too many subprograms\n");
1057 env
->subprog_info
[env
->subprog_cnt
++].start
= off
;
1058 sort(env
->subprog_info
, env
->subprog_cnt
,
1059 sizeof(env
->subprog_info
[0]), cmp_subprogs
, NULL
);
1063 static int check_subprogs(struct bpf_verifier_env
*env
)
1065 int i
, ret
, subprog_start
, subprog_end
, off
, cur_subprog
= 0;
1066 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
1067 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1068 int insn_cnt
= env
->prog
->len
;
1070 /* Add entry function. */
1071 ret
= add_subprog(env
, 0);
1075 /* determine subprog starts. The end is one before the next starts */
1076 for (i
= 0; i
< insn_cnt
; i
++) {
1077 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
1079 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1081 if (!env
->allow_ptr_leaks
) {
1082 verbose(env
, "function calls to other bpf functions are allowed for root only\n");
1085 ret
= add_subprog(env
, i
+ insn
[i
].imm
+ 1);
1090 /* Add a fake 'exit' subprog which could simplify subprog iteration
1091 * logic. 'subprog_cnt' should not be increased.
1093 subprog
[env
->subprog_cnt
].start
= insn_cnt
;
1095 if (env
->log
.level
& BPF_LOG_LEVEL2
)
1096 for (i
= 0; i
< env
->subprog_cnt
; i
++)
1097 verbose(env
, "func#%d @%d\n", i
, subprog
[i
].start
);
1099 /* now check that all jumps are within the same subprog */
1100 subprog_start
= subprog
[cur_subprog
].start
;
1101 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1102 for (i
= 0; i
< insn_cnt
; i
++) {
1103 u8 code
= insn
[i
].code
;
1105 if (BPF_CLASS(code
) != BPF_JMP
&& BPF_CLASS(code
) != BPF_JMP32
)
1107 if (BPF_OP(code
) == BPF_EXIT
|| BPF_OP(code
) == BPF_CALL
)
1109 off
= i
+ insn
[i
].off
+ 1;
1110 if (off
< subprog_start
|| off
>= subprog_end
) {
1111 verbose(env
, "jump out of range from insn %d to %d\n", i
, off
);
1115 if (i
== subprog_end
- 1) {
1116 /* to avoid fall-through from one subprog into another
1117 * the last insn of the subprog should be either exit
1118 * or unconditional jump back
1120 if (code
!= (BPF_JMP
| BPF_EXIT
) &&
1121 code
!= (BPF_JMP
| BPF_JA
)) {
1122 verbose(env
, "last insn is not an exit or jmp\n");
1125 subprog_start
= subprog_end
;
1127 if (cur_subprog
< env
->subprog_cnt
)
1128 subprog_end
= subprog
[cur_subprog
+ 1].start
;
1134 /* Parentage chain of this register (or stack slot) should take care of all
1135 * issues like callee-saved registers, stack slot allocation time, etc.
1137 static int mark_reg_read(struct bpf_verifier_env
*env
,
1138 const struct bpf_reg_state
*state
,
1139 struct bpf_reg_state
*parent
)
1141 bool writes
= parent
== state
->parent
; /* Observe write marks */
1145 /* if read wasn't screened by an earlier write ... */
1146 if (writes
&& state
->live
& REG_LIVE_WRITTEN
)
1148 if (parent
->live
& REG_LIVE_DONE
) {
1149 verbose(env
, "verifier BUG type %s var_off %lld off %d\n",
1150 reg_type_str
[parent
->type
],
1151 parent
->var_off
.value
, parent
->off
);
1154 if (parent
->live
& REG_LIVE_READ
)
1155 /* The parentage chain never changes and
1156 * this parent was already marked as LIVE_READ.
1157 * There is no need to keep walking the chain again and
1158 * keep re-marking all parents as LIVE_READ.
1159 * This case happens when the same register is read
1160 * multiple times without writes into it in-between.
1163 /* ... then we depend on parent's value */
1164 parent
->live
|= REG_LIVE_READ
;
1166 parent
= state
->parent
;
1171 if (env
->longest_mark_read_walk
< cnt
)
1172 env
->longest_mark_read_walk
= cnt
;
1176 static int check_reg_arg(struct bpf_verifier_env
*env
, u32 regno
,
1177 enum reg_arg_type t
)
1179 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1180 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1181 struct bpf_reg_state
*reg
, *regs
= state
->regs
;
1183 if (regno
>= MAX_BPF_REG
) {
1184 verbose(env
, "R%d is invalid\n", regno
);
1190 /* check whether register used as source operand can be read */
1191 if (reg
->type
== NOT_INIT
) {
1192 verbose(env
, "R%d !read_ok\n", regno
);
1195 /* We don't need to worry about FP liveness because it's read-only */
1196 if (regno
== BPF_REG_FP
)
1199 return mark_reg_read(env
, reg
, reg
->parent
);
1201 /* check whether register used as dest operand can be written to */
1202 if (regno
== BPF_REG_FP
) {
1203 verbose(env
, "frame pointer is read only\n");
1206 reg
->live
|= REG_LIVE_WRITTEN
;
1208 mark_reg_unknown(env
, regs
, regno
);
1213 static bool is_spillable_regtype(enum bpf_reg_type type
)
1216 case PTR_TO_MAP_VALUE
:
1217 case PTR_TO_MAP_VALUE_OR_NULL
:
1221 case PTR_TO_PACKET_META
:
1222 case PTR_TO_PACKET_END
:
1223 case PTR_TO_FLOW_KEYS
:
1224 case CONST_PTR_TO_MAP
:
1226 case PTR_TO_SOCKET_OR_NULL
:
1227 case PTR_TO_SOCK_COMMON
:
1228 case PTR_TO_SOCK_COMMON_OR_NULL
:
1229 case PTR_TO_TCP_SOCK
:
1230 case PTR_TO_TCP_SOCK_OR_NULL
:
1237 /* Does this register contain a constant zero? */
1238 static bool register_is_null(struct bpf_reg_state
*reg
)
1240 return reg
->type
== SCALAR_VALUE
&& tnum_equals_const(reg
->var_off
, 0);
1243 /* check_stack_read/write functions track spill/fill of registers,
1244 * stack boundary and alignment are checked in check_mem_access()
1246 static int check_stack_write(struct bpf_verifier_env
*env
,
1247 struct bpf_func_state
*state
, /* func where register points to */
1248 int off
, int size
, int value_regno
, int insn_idx
)
1250 struct bpf_func_state
*cur
; /* state of the current function */
1251 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
, err
;
1252 enum bpf_reg_type type
;
1254 err
= realloc_func_state(state
, round_up(slot
+ 1, BPF_REG_SIZE
),
1255 state
->acquired_refs
, true);
1258 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1259 * so it's aligned access and [off, off + size) are within stack limits
1261 if (!env
->allow_ptr_leaks
&&
1262 state
->stack
[spi
].slot_type
[0] == STACK_SPILL
&&
1263 size
!= BPF_REG_SIZE
) {
1264 verbose(env
, "attempt to corrupt spilled pointer on stack\n");
1268 cur
= env
->cur_state
->frame
[env
->cur_state
->curframe
];
1269 if (value_regno
>= 0 &&
1270 is_spillable_regtype((type
= cur
->regs
[value_regno
].type
))) {
1272 /* register containing pointer is being spilled into stack */
1273 if (size
!= BPF_REG_SIZE
) {
1274 verbose(env
, "invalid size of register spill\n");
1278 if (state
!= cur
&& type
== PTR_TO_STACK
) {
1279 verbose(env
, "cannot spill pointers to stack into stack frame of the caller\n");
1283 /* save register state */
1284 state
->stack
[spi
].spilled_ptr
= cur
->regs
[value_regno
];
1285 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
1287 for (i
= 0; i
< BPF_REG_SIZE
; i
++) {
1288 if (state
->stack
[spi
].slot_type
[i
] == STACK_MISC
&&
1289 !env
->allow_ptr_leaks
) {
1290 int *poff
= &env
->insn_aux_data
[insn_idx
].sanitize_stack_off
;
1291 int soff
= (-spi
- 1) * BPF_REG_SIZE
;
1293 /* detected reuse of integer stack slot with a pointer
1294 * which means either llvm is reusing stack slot or
1295 * an attacker is trying to exploit CVE-2018-3639
1296 * (speculative store bypass)
1297 * Have to sanitize that slot with preemptive
1300 if (*poff
&& *poff
!= soff
) {
1301 /* disallow programs where single insn stores
1302 * into two different stack slots, since verifier
1303 * cannot sanitize them
1306 "insn %d cannot access two stack slots fp%d and fp%d",
1307 insn_idx
, *poff
, soff
);
1312 state
->stack
[spi
].slot_type
[i
] = STACK_SPILL
;
1315 u8 type
= STACK_MISC
;
1317 /* regular write of data into stack destroys any spilled ptr */
1318 state
->stack
[spi
].spilled_ptr
.type
= NOT_INIT
;
1319 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1320 if (state
->stack
[spi
].slot_type
[0] == STACK_SPILL
)
1321 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
1322 state
->stack
[spi
].slot_type
[i
] = STACK_MISC
;
1324 /* only mark the slot as written if all 8 bytes were written
1325 * otherwise read propagation may incorrectly stop too soon
1326 * when stack slots are partially written.
1327 * This heuristic means that read propagation will be
1328 * conservative, since it will add reg_live_read marks
1329 * to stack slots all the way to first state when programs
1330 * writes+reads less than 8 bytes
1332 if (size
== BPF_REG_SIZE
)
1333 state
->stack
[spi
].spilled_ptr
.live
|= REG_LIVE_WRITTEN
;
1335 /* when we zero initialize stack slots mark them as such */
1336 if (value_regno
>= 0 &&
1337 register_is_null(&cur
->regs
[value_regno
]))
1340 /* Mark slots affected by this stack write. */
1341 for (i
= 0; i
< size
; i
++)
1342 state
->stack
[spi
].slot_type
[(slot
- i
) % BPF_REG_SIZE
] =
1348 static int check_stack_read(struct bpf_verifier_env
*env
,
1349 struct bpf_func_state
*reg_state
/* func where register points to */,
1350 int off
, int size
, int value_regno
)
1352 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1353 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1354 int i
, slot
= -off
- 1, spi
= slot
/ BPF_REG_SIZE
;
1357 if (reg_state
->allocated_stack
<= slot
) {
1358 verbose(env
, "invalid read from stack off %d+0 size %d\n",
1362 stype
= reg_state
->stack
[spi
].slot_type
;
1364 if (stype
[0] == STACK_SPILL
) {
1365 if (size
!= BPF_REG_SIZE
) {
1366 verbose(env
, "invalid size of register spill\n");
1369 for (i
= 1; i
< BPF_REG_SIZE
; i
++) {
1370 if (stype
[(slot
- i
) % BPF_REG_SIZE
] != STACK_SPILL
) {
1371 verbose(env
, "corrupted spill memory\n");
1376 if (value_regno
>= 0) {
1377 /* restore register state from stack */
1378 state
->regs
[value_regno
] = reg_state
->stack
[spi
].spilled_ptr
;
1379 /* mark reg as written since spilled pointer state likely
1380 * has its liveness marks cleared by is_state_visited()
1381 * which resets stack/reg liveness for state transitions
1383 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
1385 mark_reg_read(env
, ®_state
->stack
[spi
].spilled_ptr
,
1386 reg_state
->stack
[spi
].spilled_ptr
.parent
);
1391 for (i
= 0; i
< size
; i
++) {
1392 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_MISC
)
1394 if (stype
[(slot
- i
) % BPF_REG_SIZE
] == STACK_ZERO
) {
1398 verbose(env
, "invalid read from stack off %d+%d size %d\n",
1402 mark_reg_read(env
, ®_state
->stack
[spi
].spilled_ptr
,
1403 reg_state
->stack
[spi
].spilled_ptr
.parent
);
1404 if (value_regno
>= 0) {
1405 if (zeros
== size
) {
1406 /* any size read into register is zero extended,
1407 * so the whole register == const_zero
1409 __mark_reg_const_zero(&state
->regs
[value_regno
]);
1411 /* have read misc data from the stack */
1412 mark_reg_unknown(env
, state
->regs
, value_regno
);
1414 state
->regs
[value_regno
].live
|= REG_LIVE_WRITTEN
;
1420 static int check_stack_access(struct bpf_verifier_env
*env
,
1421 const struct bpf_reg_state
*reg
,
1424 /* Stack accesses must be at a fixed offset, so that we
1425 * can determine what type of data were returned. See
1426 * check_stack_read().
1428 if (!tnum_is_const(reg
->var_off
)) {
1431 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
1432 verbose(env
, "variable stack access var_off=%s off=%d size=%d\n",
1437 if (off
>= 0 || off
< -MAX_BPF_STACK
) {
1438 verbose(env
, "invalid stack off=%d size=%d\n", off
, size
);
1445 static int check_map_access_type(struct bpf_verifier_env
*env
, u32 regno
,
1446 int off
, int size
, enum bpf_access_type type
)
1448 struct bpf_reg_state
*regs
= cur_regs(env
);
1449 struct bpf_map
*map
= regs
[regno
].map_ptr
;
1450 u32 cap
= bpf_map_flags_to_cap(map
);
1452 if (type
== BPF_WRITE
&& !(cap
& BPF_MAP_CAN_WRITE
)) {
1453 verbose(env
, "write into map forbidden, value_size=%d off=%d size=%d\n",
1454 map
->value_size
, off
, size
);
1458 if (type
== BPF_READ
&& !(cap
& BPF_MAP_CAN_READ
)) {
1459 verbose(env
, "read from map forbidden, value_size=%d off=%d size=%d\n",
1460 map
->value_size
, off
, size
);
1467 /* check read/write into map element returned by bpf_map_lookup_elem() */
1468 static int __check_map_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
1469 int size
, bool zero_size_allowed
)
1471 struct bpf_reg_state
*regs
= cur_regs(env
);
1472 struct bpf_map
*map
= regs
[regno
].map_ptr
;
1474 if (off
< 0 || size
< 0 || (size
== 0 && !zero_size_allowed
) ||
1475 off
+ size
> map
->value_size
) {
1476 verbose(env
, "invalid access to map value, value_size=%d off=%d size=%d\n",
1477 map
->value_size
, off
, size
);
1483 /* check read/write into a map element with possible variable offset */
1484 static int check_map_access(struct bpf_verifier_env
*env
, u32 regno
,
1485 int off
, int size
, bool zero_size_allowed
)
1487 struct bpf_verifier_state
*vstate
= env
->cur_state
;
1488 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
1489 struct bpf_reg_state
*reg
= &state
->regs
[regno
];
1492 /* We may have adjusted the register to this map value, so we
1493 * need to try adding each of min_value and max_value to off
1494 * to make sure our theoretical access will be safe.
1496 if (env
->log
.level
& BPF_LOG_LEVEL
)
1497 print_verifier_state(env
, state
);
1499 /* The minimum value is only important with signed
1500 * comparisons where we can't assume the floor of a
1501 * value is 0. If we are using signed variables for our
1502 * index'es we need to make sure that whatever we use
1503 * will have a set floor within our range.
1505 if (reg
->smin_value
< 0 &&
1506 (reg
->smin_value
== S64_MIN
||
1507 (off
+ reg
->smin_value
!= (s64
)(s32
)(off
+ reg
->smin_value
)) ||
1508 reg
->smin_value
+ off
< 0)) {
1509 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1513 err
= __check_map_access(env
, regno
, reg
->smin_value
+ off
, size
,
1516 verbose(env
, "R%d min value is outside of the array range\n",
1521 /* If we haven't set a max value then we need to bail since we can't be
1522 * sure we won't do bad things.
1523 * If reg->umax_value + off could overflow, treat that as unbounded too.
1525 if (reg
->umax_value
>= BPF_MAX_VAR_OFF
) {
1526 verbose(env
, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1530 err
= __check_map_access(env
, regno
, reg
->umax_value
+ off
, size
,
1533 verbose(env
, "R%d max value is outside of the array range\n",
1536 if (map_value_has_spin_lock(reg
->map_ptr
)) {
1537 u32 lock
= reg
->map_ptr
->spin_lock_off
;
1539 /* if any part of struct bpf_spin_lock can be touched by
1540 * load/store reject this program.
1541 * To check that [x1, x2) overlaps with [y1, y2)
1542 * it is sufficient to check x1 < y2 && y1 < x2.
1544 if (reg
->smin_value
+ off
< lock
+ sizeof(struct bpf_spin_lock
) &&
1545 lock
< reg
->umax_value
+ off
+ size
) {
1546 verbose(env
, "bpf_spin_lock cannot be accessed directly by load/store\n");
1553 #define MAX_PACKET_OFF 0xffff
1555 static bool may_access_direct_pkt_data(struct bpf_verifier_env
*env
,
1556 const struct bpf_call_arg_meta
*meta
,
1557 enum bpf_access_type t
)
1559 switch (env
->prog
->type
) {
1560 /* Program types only with direct read access go here! */
1561 case BPF_PROG_TYPE_LWT_IN
:
1562 case BPF_PROG_TYPE_LWT_OUT
:
1563 case BPF_PROG_TYPE_LWT_SEG6LOCAL
:
1564 case BPF_PROG_TYPE_SK_REUSEPORT
:
1565 case BPF_PROG_TYPE_FLOW_DISSECTOR
:
1566 case BPF_PROG_TYPE_CGROUP_SKB
:
1571 /* Program types with direct read + write access go here! */
1572 case BPF_PROG_TYPE_SCHED_CLS
:
1573 case BPF_PROG_TYPE_SCHED_ACT
:
1574 case BPF_PROG_TYPE_XDP
:
1575 case BPF_PROG_TYPE_LWT_XMIT
:
1576 case BPF_PROG_TYPE_SK_SKB
:
1577 case BPF_PROG_TYPE_SK_MSG
:
1579 return meta
->pkt_access
;
1581 env
->seen_direct_write
= true;
1588 static int __check_packet_access(struct bpf_verifier_env
*env
, u32 regno
,
1589 int off
, int size
, bool zero_size_allowed
)
1591 struct bpf_reg_state
*regs
= cur_regs(env
);
1592 struct bpf_reg_state
*reg
= ®s
[regno
];
1594 if (off
< 0 || size
< 0 || (size
== 0 && !zero_size_allowed
) ||
1595 (u64
)off
+ size
> reg
->range
) {
1596 verbose(env
, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1597 off
, size
, regno
, reg
->id
, reg
->off
, reg
->range
);
1603 static int check_packet_access(struct bpf_verifier_env
*env
, u32 regno
, int off
,
1604 int size
, bool zero_size_allowed
)
1606 struct bpf_reg_state
*regs
= cur_regs(env
);
1607 struct bpf_reg_state
*reg
= ®s
[regno
];
1610 /* We may have added a variable offset to the packet pointer; but any
1611 * reg->range we have comes after that. We are only checking the fixed
1615 /* We don't allow negative numbers, because we aren't tracking enough
1616 * detail to prove they're safe.
1618 if (reg
->smin_value
< 0) {
1619 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1623 err
= __check_packet_access(env
, regno
, off
, size
, zero_size_allowed
);
1625 verbose(env
, "R%d offset is outside of the packet\n", regno
);
1629 /* __check_packet_access has made sure "off + size - 1" is within u16.
1630 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
1631 * otherwise find_good_pkt_pointers would have refused to set range info
1632 * that __check_packet_access would have rejected this pkt access.
1633 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
1635 env
->prog
->aux
->max_pkt_offset
=
1636 max_t(u32
, env
->prog
->aux
->max_pkt_offset
,
1637 off
+ reg
->umax_value
+ size
- 1);
1642 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1643 static int check_ctx_access(struct bpf_verifier_env
*env
, int insn_idx
, int off
, int size
,
1644 enum bpf_access_type t
, enum bpf_reg_type
*reg_type
)
1646 struct bpf_insn_access_aux info
= {
1647 .reg_type
= *reg_type
,
1650 if (env
->ops
->is_valid_access
&&
1651 env
->ops
->is_valid_access(off
, size
, t
, env
->prog
, &info
)) {
1652 /* A non zero info.ctx_field_size indicates that this field is a
1653 * candidate for later verifier transformation to load the whole
1654 * field and then apply a mask when accessed with a narrower
1655 * access than actual ctx access size. A zero info.ctx_field_size
1656 * will only allow for whole field access and rejects any other
1657 * type of narrower access.
1659 *reg_type
= info
.reg_type
;
1661 env
->insn_aux_data
[insn_idx
].ctx_field_size
= info
.ctx_field_size
;
1662 /* remember the offset of last byte accessed in ctx */
1663 if (env
->prog
->aux
->max_ctx_offset
< off
+ size
)
1664 env
->prog
->aux
->max_ctx_offset
= off
+ size
;
1668 verbose(env
, "invalid bpf_context access off=%d size=%d\n", off
, size
);
1672 static int check_flow_keys_access(struct bpf_verifier_env
*env
, int off
,
1675 if (size
< 0 || off
< 0 ||
1676 (u64
)off
+ size
> sizeof(struct bpf_flow_keys
)) {
1677 verbose(env
, "invalid access to flow keys off=%d size=%d\n",
1684 static int check_sock_access(struct bpf_verifier_env
*env
, int insn_idx
,
1685 u32 regno
, int off
, int size
,
1686 enum bpf_access_type t
)
1688 struct bpf_reg_state
*regs
= cur_regs(env
);
1689 struct bpf_reg_state
*reg
= ®s
[regno
];
1690 struct bpf_insn_access_aux info
= {};
1693 if (reg
->smin_value
< 0) {
1694 verbose(env
, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1699 switch (reg
->type
) {
1700 case PTR_TO_SOCK_COMMON
:
1701 valid
= bpf_sock_common_is_valid_access(off
, size
, t
, &info
);
1704 valid
= bpf_sock_is_valid_access(off
, size
, t
, &info
);
1706 case PTR_TO_TCP_SOCK
:
1707 valid
= bpf_tcp_sock_is_valid_access(off
, size
, t
, &info
);
1715 env
->insn_aux_data
[insn_idx
].ctx_field_size
=
1716 info
.ctx_field_size
;
1720 verbose(env
, "R%d invalid %s access off=%d size=%d\n",
1721 regno
, reg_type_str
[reg
->type
], off
, size
);
1726 static bool __is_pointer_value(bool allow_ptr_leaks
,
1727 const struct bpf_reg_state
*reg
)
1729 if (allow_ptr_leaks
)
1732 return reg
->type
!= SCALAR_VALUE
;
1735 static struct bpf_reg_state
*reg_state(struct bpf_verifier_env
*env
, int regno
)
1737 return cur_regs(env
) + regno
;
1740 static bool is_pointer_value(struct bpf_verifier_env
*env
, int regno
)
1742 return __is_pointer_value(env
->allow_ptr_leaks
, reg_state(env
, regno
));
1745 static bool is_ctx_reg(struct bpf_verifier_env
*env
, int regno
)
1747 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
1749 return reg
->type
== PTR_TO_CTX
;
1752 static bool is_sk_reg(struct bpf_verifier_env
*env
, int regno
)
1754 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
1756 return type_is_sk_pointer(reg
->type
);
1759 static bool is_pkt_reg(struct bpf_verifier_env
*env
, int regno
)
1761 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
1763 return type_is_pkt_pointer(reg
->type
);
1766 static bool is_flow_key_reg(struct bpf_verifier_env
*env
, int regno
)
1768 const struct bpf_reg_state
*reg
= reg_state(env
, regno
);
1770 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
1771 return reg
->type
== PTR_TO_FLOW_KEYS
;
1774 static int check_pkt_ptr_alignment(struct bpf_verifier_env
*env
,
1775 const struct bpf_reg_state
*reg
,
1776 int off
, int size
, bool strict
)
1778 struct tnum reg_off
;
1781 /* Byte size accesses are always allowed. */
1782 if (!strict
|| size
== 1)
1785 /* For platforms that do not have a Kconfig enabling
1786 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1787 * NET_IP_ALIGN is universally set to '2'. And on platforms
1788 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1789 * to this code only in strict mode where we want to emulate
1790 * the NET_IP_ALIGN==2 checking. Therefore use an
1791 * unconditional IP align value of '2'.
1795 reg_off
= tnum_add(reg
->var_off
, tnum_const(ip_align
+ reg
->off
+ off
));
1796 if (!tnum_is_aligned(reg_off
, size
)) {
1799 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
1801 "misaligned packet access off %d+%s+%d+%d size %d\n",
1802 ip_align
, tn_buf
, reg
->off
, off
, size
);
1809 static int check_generic_ptr_alignment(struct bpf_verifier_env
*env
,
1810 const struct bpf_reg_state
*reg
,
1811 const char *pointer_desc
,
1812 int off
, int size
, bool strict
)
1814 struct tnum reg_off
;
1816 /* Byte size accesses are always allowed. */
1817 if (!strict
|| size
== 1)
1820 reg_off
= tnum_add(reg
->var_off
, tnum_const(reg
->off
+ off
));
1821 if (!tnum_is_aligned(reg_off
, size
)) {
1824 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
1825 verbose(env
, "misaligned %saccess off %s+%d+%d size %d\n",
1826 pointer_desc
, tn_buf
, reg
->off
, off
, size
);
1833 static int check_ptr_alignment(struct bpf_verifier_env
*env
,
1834 const struct bpf_reg_state
*reg
, int off
,
1835 int size
, bool strict_alignment_once
)
1837 bool strict
= env
->strict_alignment
|| strict_alignment_once
;
1838 const char *pointer_desc
= "";
1840 switch (reg
->type
) {
1842 case PTR_TO_PACKET_META
:
1843 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1844 * right in front, treat it the very same way.
1846 return check_pkt_ptr_alignment(env
, reg
, off
, size
, strict
);
1847 case PTR_TO_FLOW_KEYS
:
1848 pointer_desc
= "flow keys ";
1850 case PTR_TO_MAP_VALUE
:
1851 pointer_desc
= "value ";
1854 pointer_desc
= "context ";
1857 pointer_desc
= "stack ";
1858 /* The stack spill tracking logic in check_stack_write()
1859 * and check_stack_read() relies on stack accesses being
1865 pointer_desc
= "sock ";
1867 case PTR_TO_SOCK_COMMON
:
1868 pointer_desc
= "sock_common ";
1870 case PTR_TO_TCP_SOCK
:
1871 pointer_desc
= "tcp_sock ";
1876 return check_generic_ptr_alignment(env
, reg
, pointer_desc
, off
, size
,
1880 static int update_stack_depth(struct bpf_verifier_env
*env
,
1881 const struct bpf_func_state
*func
,
1884 u16 stack
= env
->subprog_info
[func
->subprogno
].stack_depth
;
1889 /* update known max for given subprogram */
1890 env
->subprog_info
[func
->subprogno
].stack_depth
= -off
;
1894 /* starting from main bpf function walk all instructions of the function
1895 * and recursively walk all callees that given function can call.
1896 * Ignore jump and exit insns.
1897 * Since recursion is prevented by check_cfg() this algorithm
1898 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1900 static int check_max_stack_depth(struct bpf_verifier_env
*env
)
1902 int depth
= 0, frame
= 0, idx
= 0, i
= 0, subprog_end
;
1903 struct bpf_subprog_info
*subprog
= env
->subprog_info
;
1904 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1905 int ret_insn
[MAX_CALL_FRAMES
];
1906 int ret_prog
[MAX_CALL_FRAMES
];
1909 /* round up to 32-bytes, since this is granularity
1910 * of interpreter stack size
1912 depth
+= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
1913 if (depth
> MAX_BPF_STACK
) {
1914 verbose(env
, "combined stack size of %d calls is %d. Too large\n",
1919 subprog_end
= subprog
[idx
+ 1].start
;
1920 for (; i
< subprog_end
; i
++) {
1921 if (insn
[i
].code
!= (BPF_JMP
| BPF_CALL
))
1923 if (insn
[i
].src_reg
!= BPF_PSEUDO_CALL
)
1925 /* remember insn and function to return to */
1926 ret_insn
[frame
] = i
+ 1;
1927 ret_prog
[frame
] = idx
;
1929 /* find the callee */
1930 i
= i
+ insn
[i
].imm
+ 1;
1931 idx
= find_subprog(env
, i
);
1933 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1938 if (frame
>= MAX_CALL_FRAMES
) {
1939 verbose(env
, "the call stack of %d frames is too deep !\n",
1945 /* end of for() loop means the last insn of the 'subprog'
1946 * was reached. Doesn't matter whether it was JA or EXIT
1950 depth
-= round_up(max_t(u32
, subprog
[idx
].stack_depth
, 1), 32);
1952 i
= ret_insn
[frame
];
1953 idx
= ret_prog
[frame
];
1957 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1958 static int get_callee_stack_depth(struct bpf_verifier_env
*env
,
1959 const struct bpf_insn
*insn
, int idx
)
1961 int start
= idx
+ insn
->imm
+ 1, subprog
;
1963 subprog
= find_subprog(env
, start
);
1965 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1969 return env
->subprog_info
[subprog
].stack_depth
;
1973 static int check_ctx_reg(struct bpf_verifier_env
*env
,
1974 const struct bpf_reg_state
*reg
, int regno
)
1976 /* Access to ctx or passing it to a helper is only allowed in
1977 * its original, unmodified form.
1981 verbose(env
, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1986 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
1989 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
1990 verbose(env
, "variable ctx access var_off=%s disallowed\n", tn_buf
);
1997 static int check_tp_buffer_access(struct bpf_verifier_env
*env
,
1998 const struct bpf_reg_state
*reg
,
1999 int regno
, int off
, int size
)
2003 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2007 if (!tnum_is_const(reg
->var_off
) || reg
->var_off
.value
) {
2010 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2012 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2013 regno
, off
, tn_buf
);
2016 if (off
+ size
> env
->prog
->aux
->max_tp_access
)
2017 env
->prog
->aux
->max_tp_access
= off
+ size
;
2023 /* truncate register to smaller size (in bytes)
2024 * must be called with size < BPF_REG_SIZE
2026 static void coerce_reg_to_size(struct bpf_reg_state
*reg
, int size
)
2030 /* clear high bits in bit representation */
2031 reg
->var_off
= tnum_cast(reg
->var_off
, size
);
2033 /* fix arithmetic bounds */
2034 mask
= ((u64
)1 << (size
* 8)) - 1;
2035 if ((reg
->umin_value
& ~mask
) == (reg
->umax_value
& ~mask
)) {
2036 reg
->umin_value
&= mask
;
2037 reg
->umax_value
&= mask
;
2039 reg
->umin_value
= 0;
2040 reg
->umax_value
= mask
;
2042 reg
->smin_value
= reg
->umin_value
;
2043 reg
->smax_value
= reg
->umax_value
;
2046 /* check whether memory at (regno + off) is accessible for t = (read | write)
2047 * if t==write, value_regno is a register which value is stored into memory
2048 * if t==read, value_regno is a register which will receive the value from memory
2049 * if t==write && value_regno==-1, some unknown value is stored into memory
2050 * if t==read && value_regno==-1, don't care what we read from memory
2052 static int check_mem_access(struct bpf_verifier_env
*env
, int insn_idx
, u32 regno
,
2053 int off
, int bpf_size
, enum bpf_access_type t
,
2054 int value_regno
, bool strict_alignment_once
)
2056 struct bpf_reg_state
*regs
= cur_regs(env
);
2057 struct bpf_reg_state
*reg
= regs
+ regno
;
2058 struct bpf_func_state
*state
;
2061 size
= bpf_size_to_bytes(bpf_size
);
2065 /* alignment checks will add in reg->off themselves */
2066 err
= check_ptr_alignment(env
, reg
, off
, size
, strict_alignment_once
);
2070 /* for access checks, reg->off is just part of off */
2073 if (reg
->type
== PTR_TO_MAP_VALUE
) {
2074 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
2075 is_pointer_value(env
, value_regno
)) {
2076 verbose(env
, "R%d leaks addr into map\n", value_regno
);
2079 err
= check_map_access_type(env
, regno
, off
, size
, t
);
2082 err
= check_map_access(env
, regno
, off
, size
, false);
2083 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
2084 mark_reg_unknown(env
, regs
, value_regno
);
2086 } else if (reg
->type
== PTR_TO_CTX
) {
2087 enum bpf_reg_type reg_type
= SCALAR_VALUE
;
2089 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
2090 is_pointer_value(env
, value_regno
)) {
2091 verbose(env
, "R%d leaks addr into ctx\n", value_regno
);
2095 err
= check_ctx_reg(env
, reg
, regno
);
2099 err
= check_ctx_access(env
, insn_idx
, off
, size
, t
, ®_type
);
2100 if (!err
&& t
== BPF_READ
&& value_regno
>= 0) {
2101 /* ctx access returns either a scalar, or a
2102 * PTR_TO_PACKET[_META,_END]. In the latter
2103 * case, we know the offset is zero.
2105 if (reg_type
== SCALAR_VALUE
) {
2106 mark_reg_unknown(env
, regs
, value_regno
);
2108 mark_reg_known_zero(env
, regs
,
2110 if (reg_type_may_be_null(reg_type
))
2111 regs
[value_regno
].id
= ++env
->id_gen
;
2113 regs
[value_regno
].type
= reg_type
;
2116 } else if (reg
->type
== PTR_TO_STACK
) {
2117 off
+= reg
->var_off
.value
;
2118 err
= check_stack_access(env
, reg
, off
, size
);
2122 state
= func(env
, reg
);
2123 err
= update_stack_depth(env
, state
, off
);
2128 err
= check_stack_write(env
, state
, off
, size
,
2129 value_regno
, insn_idx
);
2131 err
= check_stack_read(env
, state
, off
, size
,
2133 } else if (reg_is_pkt_pointer(reg
)) {
2134 if (t
== BPF_WRITE
&& !may_access_direct_pkt_data(env
, NULL
, t
)) {
2135 verbose(env
, "cannot write into packet\n");
2138 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
2139 is_pointer_value(env
, value_regno
)) {
2140 verbose(env
, "R%d leaks addr into packet\n",
2144 err
= check_packet_access(env
, regno
, off
, size
, false);
2145 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
2146 mark_reg_unknown(env
, regs
, value_regno
);
2147 } else if (reg
->type
== PTR_TO_FLOW_KEYS
) {
2148 if (t
== BPF_WRITE
&& value_regno
>= 0 &&
2149 is_pointer_value(env
, value_regno
)) {
2150 verbose(env
, "R%d leaks addr into flow keys\n",
2155 err
= check_flow_keys_access(env
, off
, size
);
2156 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
2157 mark_reg_unknown(env
, regs
, value_regno
);
2158 } else if (type_is_sk_pointer(reg
->type
)) {
2159 if (t
== BPF_WRITE
) {
2160 verbose(env
, "R%d cannot write into %s\n",
2161 regno
, reg_type_str
[reg
->type
]);
2164 err
= check_sock_access(env
, insn_idx
, regno
, off
, size
, t
);
2165 if (!err
&& value_regno
>= 0)
2166 mark_reg_unknown(env
, regs
, value_regno
);
2167 } else if (reg
->type
== PTR_TO_TP_BUFFER
) {
2168 err
= check_tp_buffer_access(env
, reg
, regno
, off
, size
);
2169 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
2170 mark_reg_unknown(env
, regs
, value_regno
);
2172 verbose(env
, "R%d invalid mem access '%s'\n", regno
,
2173 reg_type_str
[reg
->type
]);
2177 if (!err
&& size
< BPF_REG_SIZE
&& value_regno
>= 0 && t
== BPF_READ
&&
2178 regs
[value_regno
].type
== SCALAR_VALUE
) {
2179 /* b/h/w load zero-extends, mark upper bits as known 0 */
2180 coerce_reg_to_size(®s
[value_regno
], size
);
2185 static int check_xadd(struct bpf_verifier_env
*env
, int insn_idx
, struct bpf_insn
*insn
)
2189 if ((BPF_SIZE(insn
->code
) != BPF_W
&& BPF_SIZE(insn
->code
) != BPF_DW
) ||
2191 verbose(env
, "BPF_XADD uses reserved fields\n");
2195 /* check src1 operand */
2196 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
2200 /* check src2 operand */
2201 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
2205 if (is_pointer_value(env
, insn
->src_reg
)) {
2206 verbose(env
, "R%d leaks addr into mem\n", insn
->src_reg
);
2210 if (is_ctx_reg(env
, insn
->dst_reg
) ||
2211 is_pkt_reg(env
, insn
->dst_reg
) ||
2212 is_flow_key_reg(env
, insn
->dst_reg
) ||
2213 is_sk_reg(env
, insn
->dst_reg
)) {
2214 verbose(env
, "BPF_XADD stores into R%d %s is not allowed\n",
2216 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
2220 /* check whether atomic_add can read the memory */
2221 err
= check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
2222 BPF_SIZE(insn
->code
), BPF_READ
, -1, true);
2226 /* check whether atomic_add can write into the same memory */
2227 return check_mem_access(env
, insn_idx
, insn
->dst_reg
, insn
->off
,
2228 BPF_SIZE(insn
->code
), BPF_WRITE
, -1, true);
2231 static int __check_stack_boundary(struct bpf_verifier_env
*env
, u32 regno
,
2232 int off
, int access_size
,
2233 bool zero_size_allowed
)
2235 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2237 if (off
>= 0 || off
< -MAX_BPF_STACK
|| off
+ access_size
> 0 ||
2238 access_size
< 0 || (access_size
== 0 && !zero_size_allowed
)) {
2239 if (tnum_is_const(reg
->var_off
)) {
2240 verbose(env
, "invalid stack type R%d off=%d access_size=%d\n",
2241 regno
, off
, access_size
);
2245 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2246 verbose(env
, "invalid stack type R%d var_off=%s access_size=%d\n",
2247 regno
, tn_buf
, access_size
);
2254 /* when register 'regno' is passed into function that will read 'access_size'
2255 * bytes from that pointer, make sure that it's within stack boundary
2256 * and all elements of stack are initialized.
2257 * Unlike most pointer bounds-checking functions, this one doesn't take an
2258 * 'off' argument, so it has to add in reg->off itself.
2260 static int check_stack_boundary(struct bpf_verifier_env
*env
, int regno
,
2261 int access_size
, bool zero_size_allowed
,
2262 struct bpf_call_arg_meta
*meta
)
2264 struct bpf_reg_state
*reg
= reg_state(env
, regno
);
2265 struct bpf_func_state
*state
= func(env
, reg
);
2266 int err
, min_off
, max_off
, i
, slot
, spi
;
2268 if (reg
->type
!= PTR_TO_STACK
) {
2269 /* Allow zero-byte read from NULL, regardless of pointer type */
2270 if (zero_size_allowed
&& access_size
== 0 &&
2271 register_is_null(reg
))
2274 verbose(env
, "R%d type=%s expected=%s\n", regno
,
2275 reg_type_str
[reg
->type
],
2276 reg_type_str
[PTR_TO_STACK
]);
2280 if (tnum_is_const(reg
->var_off
)) {
2281 min_off
= max_off
= reg
->var_off
.value
+ reg
->off
;
2282 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
2287 /* Variable offset is prohibited for unprivileged mode for
2288 * simplicity since it requires corresponding support in
2289 * Spectre masking for stack ALU.
2290 * See also retrieve_ptr_limit().
2292 if (!env
->allow_ptr_leaks
) {
2295 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2296 verbose(env
, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
2300 /* Only initialized buffer on stack is allowed to be accessed
2301 * with variable offset. With uninitialized buffer it's hard to
2302 * guarantee that whole memory is marked as initialized on
2303 * helper return since specific bounds are unknown what may
2304 * cause uninitialized stack leaking.
2306 if (meta
&& meta
->raw_mode
)
2309 if (reg
->smax_value
>= BPF_MAX_VAR_OFF
||
2310 reg
->smax_value
<= -BPF_MAX_VAR_OFF
) {
2311 verbose(env
, "R%d unbounded indirect variable offset stack access\n",
2315 min_off
= reg
->smin_value
+ reg
->off
;
2316 max_off
= reg
->smax_value
+ reg
->off
;
2317 err
= __check_stack_boundary(env
, regno
, min_off
, access_size
,
2320 verbose(env
, "R%d min value is outside of stack bound\n",
2324 err
= __check_stack_boundary(env
, regno
, max_off
, access_size
,
2327 verbose(env
, "R%d max value is outside of stack bound\n",
2333 if (meta
&& meta
->raw_mode
) {
2334 meta
->access_size
= access_size
;
2335 meta
->regno
= regno
;
2339 for (i
= min_off
; i
< max_off
+ access_size
; i
++) {
2343 spi
= slot
/ BPF_REG_SIZE
;
2344 if (state
->allocated_stack
<= slot
)
2346 stype
= &state
->stack
[spi
].slot_type
[slot
% BPF_REG_SIZE
];
2347 if (*stype
== STACK_MISC
)
2349 if (*stype
== STACK_ZERO
) {
2350 /* helper can write anything into the stack */
2351 *stype
= STACK_MISC
;
2355 if (tnum_is_const(reg
->var_off
)) {
2356 verbose(env
, "invalid indirect read from stack off %d+%d size %d\n",
2357 min_off
, i
- min_off
, access_size
);
2361 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
2362 verbose(env
, "invalid indirect read from stack var_off %s+%d size %d\n",
2363 tn_buf
, i
- min_off
, access_size
);
2367 /* reading any byte out of 8-byte 'spill_slot' will cause
2368 * the whole slot to be marked as 'read'
2370 mark_reg_read(env
, &state
->stack
[spi
].spilled_ptr
,
2371 state
->stack
[spi
].spilled_ptr
.parent
);
2373 return update_stack_depth(env
, state
, min_off
);
2376 static int check_helper_mem_access(struct bpf_verifier_env
*env
, int regno
,
2377 int access_size
, bool zero_size_allowed
,
2378 struct bpf_call_arg_meta
*meta
)
2380 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
2382 switch (reg
->type
) {
2384 case PTR_TO_PACKET_META
:
2385 return check_packet_access(env
, regno
, reg
->off
, access_size
,
2387 case PTR_TO_MAP_VALUE
:
2388 if (check_map_access_type(env
, regno
, reg
->off
, access_size
,
2389 meta
&& meta
->raw_mode
? BPF_WRITE
:
2392 return check_map_access(env
, regno
, reg
->off
, access_size
,
2394 default: /* scalar_value|ptr_to_stack or invalid ptr */
2395 return check_stack_boundary(env
, regno
, access_size
,
2396 zero_size_allowed
, meta
);
2400 /* Implementation details:
2401 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
2402 * Two bpf_map_lookups (even with the same key) will have different reg->id.
2403 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
2404 * value_or_null->value transition, since the verifier only cares about
2405 * the range of access to valid map value pointer and doesn't care about actual
2406 * address of the map element.
2407 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
2408 * reg->id > 0 after value_or_null->value transition. By doing so
2409 * two bpf_map_lookups will be considered two different pointers that
2410 * point to different bpf_spin_locks.
2411 * The verifier allows taking only one bpf_spin_lock at a time to avoid
2413 * Since only one bpf_spin_lock is allowed the checks are simpler than
2414 * reg_is_refcounted() logic. The verifier needs to remember only
2415 * one spin_lock instead of array of acquired_refs.
2416 * cur_state->active_spin_lock remembers which map value element got locked
2417 * and clears it after bpf_spin_unlock.
2419 static int process_spin_lock(struct bpf_verifier_env
*env
, int regno
,
2422 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
2423 struct bpf_verifier_state
*cur
= env
->cur_state
;
2424 bool is_const
= tnum_is_const(reg
->var_off
);
2425 struct bpf_map
*map
= reg
->map_ptr
;
2426 u64 val
= reg
->var_off
.value
;
2428 if (reg
->type
!= PTR_TO_MAP_VALUE
) {
2429 verbose(env
, "R%d is not a pointer to map_value\n", regno
);
2434 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
2440 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
2444 if (!map_value_has_spin_lock(map
)) {
2445 if (map
->spin_lock_off
== -E2BIG
)
2447 "map '%s' has more than one 'struct bpf_spin_lock'\n",
2449 else if (map
->spin_lock_off
== -ENOENT
)
2451 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
2455 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
2459 if (map
->spin_lock_off
!= val
+ reg
->off
) {
2460 verbose(env
, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
2465 if (cur
->active_spin_lock
) {
2467 "Locking two bpf_spin_locks are not allowed\n");
2470 cur
->active_spin_lock
= reg
->id
;
2472 if (!cur
->active_spin_lock
) {
2473 verbose(env
, "bpf_spin_unlock without taking a lock\n");
2476 if (cur
->active_spin_lock
!= reg
->id
) {
2477 verbose(env
, "bpf_spin_unlock of different lock\n");
2480 cur
->active_spin_lock
= 0;
2485 static bool arg_type_is_mem_ptr(enum bpf_arg_type type
)
2487 return type
== ARG_PTR_TO_MEM
||
2488 type
== ARG_PTR_TO_MEM_OR_NULL
||
2489 type
== ARG_PTR_TO_UNINIT_MEM
;
2492 static bool arg_type_is_mem_size(enum bpf_arg_type type
)
2494 return type
== ARG_CONST_SIZE
||
2495 type
== ARG_CONST_SIZE_OR_ZERO
;
2498 static bool arg_type_is_int_ptr(enum bpf_arg_type type
)
2500 return type
== ARG_PTR_TO_INT
||
2501 type
== ARG_PTR_TO_LONG
;
2504 static int int_ptr_type_to_size(enum bpf_arg_type type
)
2506 if (type
== ARG_PTR_TO_INT
)
2508 else if (type
== ARG_PTR_TO_LONG
)
2514 static int check_func_arg(struct bpf_verifier_env
*env
, u32 regno
,
2515 enum bpf_arg_type arg_type
,
2516 struct bpf_call_arg_meta
*meta
)
2518 struct bpf_reg_state
*regs
= cur_regs(env
), *reg
= ®s
[regno
];
2519 enum bpf_reg_type expected_type
, type
= reg
->type
;
2522 if (arg_type
== ARG_DONTCARE
)
2525 err
= check_reg_arg(env
, regno
, SRC_OP
);
2529 if (arg_type
== ARG_ANYTHING
) {
2530 if (is_pointer_value(env
, regno
)) {
2531 verbose(env
, "R%d leaks addr into helper function\n",
2538 if (type_is_pkt_pointer(type
) &&
2539 !may_access_direct_pkt_data(env
, meta
, BPF_READ
)) {
2540 verbose(env
, "helper access to the packet is not allowed\n");
2544 if (arg_type
== ARG_PTR_TO_MAP_KEY
||
2545 arg_type
== ARG_PTR_TO_MAP_VALUE
||
2546 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
||
2547 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
) {
2548 expected_type
= PTR_TO_STACK
;
2549 if (register_is_null(reg
) &&
2550 arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
)
2551 /* final test in check_stack_boundary() */;
2552 else if (!type_is_pkt_pointer(type
) &&
2553 type
!= PTR_TO_MAP_VALUE
&&
2554 type
!= expected_type
)
2556 } else if (arg_type
== ARG_CONST_SIZE
||
2557 arg_type
== ARG_CONST_SIZE_OR_ZERO
) {
2558 expected_type
= SCALAR_VALUE
;
2559 if (type
!= expected_type
)
2561 } else if (arg_type
== ARG_CONST_MAP_PTR
) {
2562 expected_type
= CONST_PTR_TO_MAP
;
2563 if (type
!= expected_type
)
2565 } else if (arg_type
== ARG_PTR_TO_CTX
) {
2566 expected_type
= PTR_TO_CTX
;
2567 if (type
!= expected_type
)
2569 err
= check_ctx_reg(env
, reg
, regno
);
2572 } else if (arg_type
== ARG_PTR_TO_SOCK_COMMON
) {
2573 expected_type
= PTR_TO_SOCK_COMMON
;
2574 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
2575 if (!type_is_sk_pointer(type
))
2577 if (reg
->ref_obj_id
) {
2578 if (meta
->ref_obj_id
) {
2579 verbose(env
, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
2580 regno
, reg
->ref_obj_id
,
2584 meta
->ref_obj_id
= reg
->ref_obj_id
;
2586 } else if (arg_type
== ARG_PTR_TO_SOCKET
) {
2587 expected_type
= PTR_TO_SOCKET
;
2588 if (type
!= expected_type
)
2590 } else if (arg_type
== ARG_PTR_TO_SPIN_LOCK
) {
2591 if (meta
->func_id
== BPF_FUNC_spin_lock
) {
2592 if (process_spin_lock(env
, regno
, true))
2594 } else if (meta
->func_id
== BPF_FUNC_spin_unlock
) {
2595 if (process_spin_lock(env
, regno
, false))
2598 verbose(env
, "verifier internal error\n");
2601 } else if (arg_type_is_mem_ptr(arg_type
)) {
2602 expected_type
= PTR_TO_STACK
;
2603 /* One exception here. In case function allows for NULL to be
2604 * passed in as argument, it's a SCALAR_VALUE type. Final test
2605 * happens during stack boundary checking.
2607 if (register_is_null(reg
) &&
2608 arg_type
== ARG_PTR_TO_MEM_OR_NULL
)
2609 /* final test in check_stack_boundary() */;
2610 else if (!type_is_pkt_pointer(type
) &&
2611 type
!= PTR_TO_MAP_VALUE
&&
2612 type
!= expected_type
)
2614 meta
->raw_mode
= arg_type
== ARG_PTR_TO_UNINIT_MEM
;
2615 } else if (arg_type_is_int_ptr(arg_type
)) {
2616 expected_type
= PTR_TO_STACK
;
2617 if (!type_is_pkt_pointer(type
) &&
2618 type
!= PTR_TO_MAP_VALUE
&&
2619 type
!= expected_type
)
2622 verbose(env
, "unsupported arg_type %d\n", arg_type
);
2626 if (arg_type
== ARG_CONST_MAP_PTR
) {
2627 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
2628 meta
->map_ptr
= reg
->map_ptr
;
2629 } else if (arg_type
== ARG_PTR_TO_MAP_KEY
) {
2630 /* bpf_map_xxx(..., map_ptr, ..., key) call:
2631 * check that [key, key + map->key_size) are within
2632 * stack limits and initialized
2634 if (!meta
->map_ptr
) {
2635 /* in function declaration map_ptr must come before
2636 * map_key, so that it's verified and known before
2637 * we have to check map_key here. Otherwise it means
2638 * that kernel subsystem misconfigured verifier
2640 verbose(env
, "invalid map_ptr to access map->key\n");
2643 err
= check_helper_mem_access(env
, regno
,
2644 meta
->map_ptr
->key_size
, false,
2646 } else if (arg_type
== ARG_PTR_TO_MAP_VALUE
||
2647 (arg_type
== ARG_PTR_TO_MAP_VALUE_OR_NULL
&&
2648 !register_is_null(reg
)) ||
2649 arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
) {
2650 /* bpf_map_xxx(..., map_ptr, ..., value) call:
2651 * check [value, value + map->value_size) validity
2653 if (!meta
->map_ptr
) {
2654 /* kernel subsystem misconfigured verifier */
2655 verbose(env
, "invalid map_ptr to access map->value\n");
2658 meta
->raw_mode
= (arg_type
== ARG_PTR_TO_UNINIT_MAP_VALUE
);
2659 err
= check_helper_mem_access(env
, regno
,
2660 meta
->map_ptr
->value_size
, false,
2662 } else if (arg_type_is_mem_size(arg_type
)) {
2663 bool zero_size_allowed
= (arg_type
== ARG_CONST_SIZE_OR_ZERO
);
2665 /* remember the mem_size which may be used later
2666 * to refine return values.
2668 meta
->msize_smax_value
= reg
->smax_value
;
2669 meta
->msize_umax_value
= reg
->umax_value
;
2671 /* The register is SCALAR_VALUE; the access check
2672 * happens using its boundaries.
2674 if (!tnum_is_const(reg
->var_off
))
2675 /* For unprivileged variable accesses, disable raw
2676 * mode so that the program is required to
2677 * initialize all the memory that the helper could
2678 * just partially fill up.
2682 if (reg
->smin_value
< 0) {
2683 verbose(env
, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2688 if (reg
->umin_value
== 0) {
2689 err
= check_helper_mem_access(env
, regno
- 1, 0,
2696 if (reg
->umax_value
>= BPF_MAX_VAR_SIZ
) {
2697 verbose(env
, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2701 err
= check_helper_mem_access(env
, regno
- 1,
2703 zero_size_allowed
, meta
);
2704 } else if (arg_type_is_int_ptr(arg_type
)) {
2705 int size
= int_ptr_type_to_size(arg_type
);
2707 err
= check_helper_mem_access(env
, regno
, size
, false, meta
);
2710 err
= check_ptr_alignment(env
, reg
, 0, size
, true);
2715 verbose(env
, "R%d type=%s expected=%s\n", regno
,
2716 reg_type_str
[type
], reg_type_str
[expected_type
]);
2720 static int check_map_func_compatibility(struct bpf_verifier_env
*env
,
2721 struct bpf_map
*map
, int func_id
)
2726 /* We need a two way check, first is from map perspective ... */
2727 switch (map
->map_type
) {
2728 case BPF_MAP_TYPE_PROG_ARRAY
:
2729 if (func_id
!= BPF_FUNC_tail_call
)
2732 case BPF_MAP_TYPE_PERF_EVENT_ARRAY
:
2733 if (func_id
!= BPF_FUNC_perf_event_read
&&
2734 func_id
!= BPF_FUNC_perf_event_output
&&
2735 func_id
!= BPF_FUNC_perf_event_read_value
)
2738 case BPF_MAP_TYPE_STACK_TRACE
:
2739 if (func_id
!= BPF_FUNC_get_stackid
)
2742 case BPF_MAP_TYPE_CGROUP_ARRAY
:
2743 if (func_id
!= BPF_FUNC_skb_under_cgroup
&&
2744 func_id
!= BPF_FUNC_current_task_under_cgroup
)
2747 case BPF_MAP_TYPE_CGROUP_STORAGE
:
2748 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
:
2749 if (func_id
!= BPF_FUNC_get_local_storage
)
2752 /* devmap returns a pointer to a live net_device ifindex that we cannot
2753 * allow to be modified from bpf side. So do not allow lookup elements
2756 case BPF_MAP_TYPE_DEVMAP
:
2757 if (func_id
!= BPF_FUNC_redirect_map
)
2760 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2763 case BPF_MAP_TYPE_CPUMAP
:
2764 case BPF_MAP_TYPE_XSKMAP
:
2765 if (func_id
!= BPF_FUNC_redirect_map
)
2768 case BPF_MAP_TYPE_ARRAY_OF_MAPS
:
2769 case BPF_MAP_TYPE_HASH_OF_MAPS
:
2770 if (func_id
!= BPF_FUNC_map_lookup_elem
)
2773 case BPF_MAP_TYPE_SOCKMAP
:
2774 if (func_id
!= BPF_FUNC_sk_redirect_map
&&
2775 func_id
!= BPF_FUNC_sock_map_update
&&
2776 func_id
!= BPF_FUNC_map_delete_elem
&&
2777 func_id
!= BPF_FUNC_msg_redirect_map
)
2780 case BPF_MAP_TYPE_SOCKHASH
:
2781 if (func_id
!= BPF_FUNC_sk_redirect_hash
&&
2782 func_id
!= BPF_FUNC_sock_hash_update
&&
2783 func_id
!= BPF_FUNC_map_delete_elem
&&
2784 func_id
!= BPF_FUNC_msg_redirect_hash
)
2787 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
:
2788 if (func_id
!= BPF_FUNC_sk_select_reuseport
)
2791 case BPF_MAP_TYPE_QUEUE
:
2792 case BPF_MAP_TYPE_STACK
:
2793 if (func_id
!= BPF_FUNC_map_peek_elem
&&
2794 func_id
!= BPF_FUNC_map_pop_elem
&&
2795 func_id
!= BPF_FUNC_map_push_elem
)
2798 case BPF_MAP_TYPE_SK_STORAGE
:
2799 if (func_id
!= BPF_FUNC_sk_storage_get
&&
2800 func_id
!= BPF_FUNC_sk_storage_delete
)
2807 /* ... and second from the function itself. */
2809 case BPF_FUNC_tail_call
:
2810 if (map
->map_type
!= BPF_MAP_TYPE_PROG_ARRAY
)
2812 if (env
->subprog_cnt
> 1) {
2813 verbose(env
, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2817 case BPF_FUNC_perf_event_read
:
2818 case BPF_FUNC_perf_event_output
:
2819 case BPF_FUNC_perf_event_read_value
:
2820 if (map
->map_type
!= BPF_MAP_TYPE_PERF_EVENT_ARRAY
)
2823 case BPF_FUNC_get_stackid
:
2824 if (map
->map_type
!= BPF_MAP_TYPE_STACK_TRACE
)
2827 case BPF_FUNC_current_task_under_cgroup
:
2828 case BPF_FUNC_skb_under_cgroup
:
2829 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_ARRAY
)
2832 case BPF_FUNC_redirect_map
:
2833 if (map
->map_type
!= BPF_MAP_TYPE_DEVMAP
&&
2834 map
->map_type
!= BPF_MAP_TYPE_CPUMAP
&&
2835 map
->map_type
!= BPF_MAP_TYPE_XSKMAP
)
2838 case BPF_FUNC_sk_redirect_map
:
2839 case BPF_FUNC_msg_redirect_map
:
2840 case BPF_FUNC_sock_map_update
:
2841 if (map
->map_type
!= BPF_MAP_TYPE_SOCKMAP
)
2844 case BPF_FUNC_sk_redirect_hash
:
2845 case BPF_FUNC_msg_redirect_hash
:
2846 case BPF_FUNC_sock_hash_update
:
2847 if (map
->map_type
!= BPF_MAP_TYPE_SOCKHASH
)
2850 case BPF_FUNC_get_local_storage
:
2851 if (map
->map_type
!= BPF_MAP_TYPE_CGROUP_STORAGE
&&
2852 map
->map_type
!= BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
)
2855 case BPF_FUNC_sk_select_reuseport
:
2856 if (map
->map_type
!= BPF_MAP_TYPE_REUSEPORT_SOCKARRAY
)
2859 case BPF_FUNC_map_peek_elem
:
2860 case BPF_FUNC_map_pop_elem
:
2861 case BPF_FUNC_map_push_elem
:
2862 if (map
->map_type
!= BPF_MAP_TYPE_QUEUE
&&
2863 map
->map_type
!= BPF_MAP_TYPE_STACK
)
2866 case BPF_FUNC_sk_storage_get
:
2867 case BPF_FUNC_sk_storage_delete
:
2868 if (map
->map_type
!= BPF_MAP_TYPE_SK_STORAGE
)
2877 verbose(env
, "cannot pass map_type %d into func %s#%d\n",
2878 map
->map_type
, func_id_name(func_id
), func_id
);
2882 static bool check_raw_mode_ok(const struct bpf_func_proto
*fn
)
2886 if (fn
->arg1_type
== ARG_PTR_TO_UNINIT_MEM
)
2888 if (fn
->arg2_type
== ARG_PTR_TO_UNINIT_MEM
)
2890 if (fn
->arg3_type
== ARG_PTR_TO_UNINIT_MEM
)
2892 if (fn
->arg4_type
== ARG_PTR_TO_UNINIT_MEM
)
2894 if (fn
->arg5_type
== ARG_PTR_TO_UNINIT_MEM
)
2897 /* We only support one arg being in raw mode at the moment,
2898 * which is sufficient for the helper functions we have
2904 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr
,
2905 enum bpf_arg_type arg_next
)
2907 return (arg_type_is_mem_ptr(arg_curr
) &&
2908 !arg_type_is_mem_size(arg_next
)) ||
2909 (!arg_type_is_mem_ptr(arg_curr
) &&
2910 arg_type_is_mem_size(arg_next
));
2913 static bool check_arg_pair_ok(const struct bpf_func_proto
*fn
)
2915 /* bpf_xxx(..., buf, len) call will access 'len'
2916 * bytes from memory 'buf'. Both arg types need
2917 * to be paired, so make sure there's no buggy
2918 * helper function specification.
2920 if (arg_type_is_mem_size(fn
->arg1_type
) ||
2921 arg_type_is_mem_ptr(fn
->arg5_type
) ||
2922 check_args_pair_invalid(fn
->arg1_type
, fn
->arg2_type
) ||
2923 check_args_pair_invalid(fn
->arg2_type
, fn
->arg3_type
) ||
2924 check_args_pair_invalid(fn
->arg3_type
, fn
->arg4_type
) ||
2925 check_args_pair_invalid(fn
->arg4_type
, fn
->arg5_type
))
2931 static bool check_refcount_ok(const struct bpf_func_proto
*fn
, int func_id
)
2935 if (arg_type_may_be_refcounted(fn
->arg1_type
))
2937 if (arg_type_may_be_refcounted(fn
->arg2_type
))
2939 if (arg_type_may_be_refcounted(fn
->arg3_type
))
2941 if (arg_type_may_be_refcounted(fn
->arg4_type
))
2943 if (arg_type_may_be_refcounted(fn
->arg5_type
))
2946 /* A reference acquiring function cannot acquire
2947 * another refcounted ptr.
2949 if (is_acquire_function(func_id
) && count
)
2952 /* We only support one arg being unreferenced at the moment,
2953 * which is sufficient for the helper functions we have right now.
2958 static int check_func_proto(const struct bpf_func_proto
*fn
, int func_id
)
2960 return check_raw_mode_ok(fn
) &&
2961 check_arg_pair_ok(fn
) &&
2962 check_refcount_ok(fn
, func_id
) ? 0 : -EINVAL
;
2965 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2966 * are now invalid, so turn them into unknown SCALAR_VALUE.
2968 static void __clear_all_pkt_pointers(struct bpf_verifier_env
*env
,
2969 struct bpf_func_state
*state
)
2971 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
2974 for (i
= 0; i
< MAX_BPF_REG
; i
++)
2975 if (reg_is_pkt_pointer_any(®s
[i
]))
2976 mark_reg_unknown(env
, regs
, i
);
2978 bpf_for_each_spilled_reg(i
, state
, reg
) {
2981 if (reg_is_pkt_pointer_any(reg
))
2982 __mark_reg_unknown(reg
);
2986 static void clear_all_pkt_pointers(struct bpf_verifier_env
*env
)
2988 struct bpf_verifier_state
*vstate
= env
->cur_state
;
2991 for (i
= 0; i
<= vstate
->curframe
; i
++)
2992 __clear_all_pkt_pointers(env
, vstate
->frame
[i
]);
2995 static void release_reg_references(struct bpf_verifier_env
*env
,
2996 struct bpf_func_state
*state
,
2999 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
3002 for (i
= 0; i
< MAX_BPF_REG
; i
++)
3003 if (regs
[i
].ref_obj_id
== ref_obj_id
)
3004 mark_reg_unknown(env
, regs
, i
);
3006 bpf_for_each_spilled_reg(i
, state
, reg
) {
3009 if (reg
->ref_obj_id
== ref_obj_id
)
3010 __mark_reg_unknown(reg
);
3014 /* The pointer with the specified id has released its reference to kernel
3015 * resources. Identify all copies of the same pointer and clear the reference.
3017 static int release_reference(struct bpf_verifier_env
*env
,
3020 struct bpf_verifier_state
*vstate
= env
->cur_state
;
3024 err
= release_reference_state(cur_func(env
), ref_obj_id
);
3028 for (i
= 0; i
<= vstate
->curframe
; i
++)
3029 release_reg_references(env
, vstate
->frame
[i
], ref_obj_id
);
3034 static int check_func_call(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
,
3037 struct bpf_verifier_state
*state
= env
->cur_state
;
3038 struct bpf_func_state
*caller
, *callee
;
3039 int i
, err
, subprog
, target_insn
;
3041 if (state
->curframe
+ 1 >= MAX_CALL_FRAMES
) {
3042 verbose(env
, "the call stack of %d frames is too deep\n",
3043 state
->curframe
+ 2);
3047 target_insn
= *insn_idx
+ insn
->imm
;
3048 subprog
= find_subprog(env
, target_insn
+ 1);
3050 verbose(env
, "verifier bug. No program starts at insn %d\n",
3055 caller
= state
->frame
[state
->curframe
];
3056 if (state
->frame
[state
->curframe
+ 1]) {
3057 verbose(env
, "verifier bug. Frame %d already allocated\n",
3058 state
->curframe
+ 1);
3062 callee
= kzalloc(sizeof(*callee
), GFP_KERNEL
);
3065 state
->frame
[state
->curframe
+ 1] = callee
;
3067 /* callee cannot access r0, r6 - r9 for reading and has to write
3068 * into its own stack before reading from it.
3069 * callee can read/write into caller's stack
3071 init_func_state(env
, callee
,
3072 /* remember the callsite, it will be used by bpf_exit */
3073 *insn_idx
/* callsite */,
3074 state
->curframe
+ 1 /* frameno within this callchain */,
3075 subprog
/* subprog number within this prog */);
3077 /* Transfer references to the callee */
3078 err
= transfer_reference_state(callee
, caller
);
3082 /* copy r1 - r5 args that callee can access. The copy includes parent
3083 * pointers, which connects us up to the liveness chain
3085 for (i
= BPF_REG_1
; i
<= BPF_REG_5
; i
++)
3086 callee
->regs
[i
] = caller
->regs
[i
];
3088 /* after the call registers r0 - r5 were scratched */
3089 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
3090 mark_reg_not_init(env
, caller
->regs
, caller_saved
[i
]);
3091 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
3094 /* only increment it after check_reg_arg() finished */
3097 /* and go analyze first insn of the callee */
3098 *insn_idx
= target_insn
;
3100 if (env
->log
.level
& BPF_LOG_LEVEL
) {
3101 verbose(env
, "caller:\n");
3102 print_verifier_state(env
, caller
);
3103 verbose(env
, "callee:\n");
3104 print_verifier_state(env
, callee
);
3109 static int prepare_func_exit(struct bpf_verifier_env
*env
, int *insn_idx
)
3111 struct bpf_verifier_state
*state
= env
->cur_state
;
3112 struct bpf_func_state
*caller
, *callee
;
3113 struct bpf_reg_state
*r0
;
3116 callee
= state
->frame
[state
->curframe
];
3117 r0
= &callee
->regs
[BPF_REG_0
];
3118 if (r0
->type
== PTR_TO_STACK
) {
3119 /* technically it's ok to return caller's stack pointer
3120 * (or caller's caller's pointer) back to the caller,
3121 * since these pointers are valid. Only current stack
3122 * pointer will be invalid as soon as function exits,
3123 * but let's be conservative
3125 verbose(env
, "cannot return stack pointer to the caller\n");
3130 caller
= state
->frame
[state
->curframe
];
3131 /* return to the caller whatever r0 had in the callee */
3132 caller
->regs
[BPF_REG_0
] = *r0
;
3134 /* Transfer references to the caller */
3135 err
= transfer_reference_state(caller
, callee
);
3139 *insn_idx
= callee
->callsite
+ 1;
3140 if (env
->log
.level
& BPF_LOG_LEVEL
) {
3141 verbose(env
, "returning from callee:\n");
3142 print_verifier_state(env
, callee
);
3143 verbose(env
, "to caller at %d:\n", *insn_idx
);
3144 print_verifier_state(env
, caller
);
3146 /* clear everything in the callee */
3147 free_func_state(callee
);
3148 state
->frame
[state
->curframe
+ 1] = NULL
;
3152 static void do_refine_retval_range(struct bpf_reg_state
*regs
, int ret_type
,
3154 struct bpf_call_arg_meta
*meta
)
3156 struct bpf_reg_state
*ret_reg
= ®s
[BPF_REG_0
];
3158 if (ret_type
!= RET_INTEGER
||
3159 (func_id
!= BPF_FUNC_get_stack
&&
3160 func_id
!= BPF_FUNC_probe_read_str
))
3163 ret_reg
->smax_value
= meta
->msize_smax_value
;
3164 ret_reg
->umax_value
= meta
->msize_umax_value
;
3165 __reg_deduce_bounds(ret_reg
);
3166 __reg_bound_offset(ret_reg
);
3170 record_func_map(struct bpf_verifier_env
*env
, struct bpf_call_arg_meta
*meta
,
3171 int func_id
, int insn_idx
)
3173 struct bpf_insn_aux_data
*aux
= &env
->insn_aux_data
[insn_idx
];
3174 struct bpf_map
*map
= meta
->map_ptr
;
3176 if (func_id
!= BPF_FUNC_tail_call
&&
3177 func_id
!= BPF_FUNC_map_lookup_elem
&&
3178 func_id
!= BPF_FUNC_map_update_elem
&&
3179 func_id
!= BPF_FUNC_map_delete_elem
&&
3180 func_id
!= BPF_FUNC_map_push_elem
&&
3181 func_id
!= BPF_FUNC_map_pop_elem
&&
3182 func_id
!= BPF_FUNC_map_peek_elem
)
3186 verbose(env
, "kernel subsystem misconfigured verifier\n");
3190 /* In case of read-only, some additional restrictions
3191 * need to be applied in order to prevent altering the
3192 * state of the map from program side.
3194 if ((map
->map_flags
& BPF_F_RDONLY_PROG
) &&
3195 (func_id
== BPF_FUNC_map_delete_elem
||
3196 func_id
== BPF_FUNC_map_update_elem
||
3197 func_id
== BPF_FUNC_map_push_elem
||
3198 func_id
== BPF_FUNC_map_pop_elem
)) {
3199 verbose(env
, "write into map forbidden\n");
3203 if (!BPF_MAP_PTR(aux
->map_state
))
3204 bpf_map_ptr_store(aux
, meta
->map_ptr
,
3205 meta
->map_ptr
->unpriv_array
);
3206 else if (BPF_MAP_PTR(aux
->map_state
) != meta
->map_ptr
)
3207 bpf_map_ptr_store(aux
, BPF_MAP_PTR_POISON
,
3208 meta
->map_ptr
->unpriv_array
);
3212 static int check_reference_leak(struct bpf_verifier_env
*env
)
3214 struct bpf_func_state
*state
= cur_func(env
);
3217 for (i
= 0; i
< state
->acquired_refs
; i
++) {
3218 verbose(env
, "Unreleased reference id=%d alloc_insn=%d\n",
3219 state
->refs
[i
].id
, state
->refs
[i
].insn_idx
);
3221 return state
->acquired_refs
? -EINVAL
: 0;
3224 static int check_helper_call(struct bpf_verifier_env
*env
, int func_id
, int insn_idx
)
3226 const struct bpf_func_proto
*fn
= NULL
;
3227 struct bpf_reg_state
*regs
;
3228 struct bpf_call_arg_meta meta
;
3232 /* find function prototype */
3233 if (func_id
< 0 || func_id
>= __BPF_FUNC_MAX_ID
) {
3234 verbose(env
, "invalid func %s#%d\n", func_id_name(func_id
),
3239 if (env
->ops
->get_func_proto
)
3240 fn
= env
->ops
->get_func_proto(func_id
, env
->prog
);
3242 verbose(env
, "unknown func %s#%d\n", func_id_name(func_id
),
3247 /* eBPF programs must be GPL compatible to use GPL-ed functions */
3248 if (!env
->prog
->gpl_compatible
&& fn
->gpl_only
) {
3249 verbose(env
, "cannot call GPL-restricted function from non-GPL compatible program\n");
3253 /* With LD_ABS/IND some JITs save/restore skb from r1. */
3254 changes_data
= bpf_helper_changes_pkt_data(fn
->func
);
3255 if (changes_data
&& fn
->arg1_type
!= ARG_PTR_TO_CTX
) {
3256 verbose(env
, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
3257 func_id_name(func_id
), func_id
);
3261 memset(&meta
, 0, sizeof(meta
));
3262 meta
.pkt_access
= fn
->pkt_access
;
3264 err
= check_func_proto(fn
, func_id
);
3266 verbose(env
, "kernel subsystem misconfigured func %s#%d\n",
3267 func_id_name(func_id
), func_id
);
3271 meta
.func_id
= func_id
;
3273 err
= check_func_arg(env
, BPF_REG_1
, fn
->arg1_type
, &meta
);
3276 err
= check_func_arg(env
, BPF_REG_2
, fn
->arg2_type
, &meta
);
3279 err
= check_func_arg(env
, BPF_REG_3
, fn
->arg3_type
, &meta
);
3282 err
= check_func_arg(env
, BPF_REG_4
, fn
->arg4_type
, &meta
);
3285 err
= check_func_arg(env
, BPF_REG_5
, fn
->arg5_type
, &meta
);
3289 err
= record_func_map(env
, &meta
, func_id
, insn_idx
);
3293 /* Mark slots with STACK_MISC in case of raw mode, stack offset
3294 * is inferred from register state.
3296 for (i
= 0; i
< meta
.access_size
; i
++) {
3297 err
= check_mem_access(env
, insn_idx
, meta
.regno
, i
, BPF_B
,
3298 BPF_WRITE
, -1, false);
3303 if (func_id
== BPF_FUNC_tail_call
) {
3304 err
= check_reference_leak(env
);
3306 verbose(env
, "tail_call would lead to reference leak\n");
3309 } else if (is_release_function(func_id
)) {
3310 err
= release_reference(env
, meta
.ref_obj_id
);
3312 verbose(env
, "func %s#%d reference has not been acquired before\n",
3313 func_id_name(func_id
), func_id
);
3318 regs
= cur_regs(env
);
3320 /* check that flags argument in get_local_storage(map, flags) is 0,
3321 * this is required because get_local_storage() can't return an error.
3323 if (func_id
== BPF_FUNC_get_local_storage
&&
3324 !register_is_null(®s
[BPF_REG_2
])) {
3325 verbose(env
, "get_local_storage() doesn't support non-zero flags\n");
3329 /* reset caller saved regs */
3330 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
3331 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
3332 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
3335 /* update return register (already marked as written above) */
3336 if (fn
->ret_type
== RET_INTEGER
) {
3337 /* sets type to SCALAR_VALUE */
3338 mark_reg_unknown(env
, regs
, BPF_REG_0
);
3339 } else if (fn
->ret_type
== RET_VOID
) {
3340 regs
[BPF_REG_0
].type
= NOT_INIT
;
3341 } else if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE_OR_NULL
||
3342 fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
3343 /* There is no offset yet applied, variable or fixed */
3344 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
3345 /* remember map_ptr, so that check_map_access()
3346 * can check 'value_size' boundary of memory access
3347 * to map element returned from bpf_map_lookup_elem()
3349 if (meta
.map_ptr
== NULL
) {
3351 "kernel subsystem misconfigured verifier\n");
3354 regs
[BPF_REG_0
].map_ptr
= meta
.map_ptr
;
3355 if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE
) {
3356 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE
;
3357 if (map_value_has_spin_lock(meta
.map_ptr
))
3358 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
3360 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE_OR_NULL
;
3361 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
3363 } else if (fn
->ret_type
== RET_PTR_TO_SOCKET_OR_NULL
) {
3364 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
3365 regs
[BPF_REG_0
].type
= PTR_TO_SOCKET_OR_NULL
;
3366 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
3367 } else if (fn
->ret_type
== RET_PTR_TO_SOCK_COMMON_OR_NULL
) {
3368 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
3369 regs
[BPF_REG_0
].type
= PTR_TO_SOCK_COMMON_OR_NULL
;
3370 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
3371 } else if (fn
->ret_type
== RET_PTR_TO_TCP_SOCK_OR_NULL
) {
3372 mark_reg_known_zero(env
, regs
, BPF_REG_0
);
3373 regs
[BPF_REG_0
].type
= PTR_TO_TCP_SOCK_OR_NULL
;
3374 regs
[BPF_REG_0
].id
= ++env
->id_gen
;
3376 verbose(env
, "unknown return type %d of func %s#%d\n",
3377 fn
->ret_type
, func_id_name(func_id
), func_id
);
3381 if (is_ptr_cast_function(func_id
)) {
3382 /* For release_reference() */
3383 regs
[BPF_REG_0
].ref_obj_id
= meta
.ref_obj_id
;
3384 } else if (is_acquire_function(func_id
)) {
3385 int id
= acquire_reference_state(env
, insn_idx
);
3389 /* For mark_ptr_or_null_reg() */
3390 regs
[BPF_REG_0
].id
= id
;
3391 /* For release_reference() */
3392 regs
[BPF_REG_0
].ref_obj_id
= id
;
3395 do_refine_retval_range(regs
, fn
->ret_type
, func_id
, &meta
);
3397 err
= check_map_func_compatibility(env
, meta
.map_ptr
, func_id
);
3401 if (func_id
== BPF_FUNC_get_stack
&& !env
->prog
->has_callchain_buf
) {
3402 const char *err_str
;
3404 #ifdef CONFIG_PERF_EVENTS
3405 err
= get_callchain_buffers(sysctl_perf_event_max_stack
);
3406 err_str
= "cannot get callchain buffer for func %s#%d\n";
3409 err_str
= "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
3412 verbose(env
, err_str
, func_id_name(func_id
), func_id
);
3416 env
->prog
->has_callchain_buf
= true;
3420 clear_all_pkt_pointers(env
);
3424 static bool signed_add_overflows(s64 a
, s64 b
)
3426 /* Do the add in u64, where overflow is well-defined */
3427 s64 res
= (s64
)((u64
)a
+ (u64
)b
);
3434 static bool signed_sub_overflows(s64 a
, s64 b
)
3436 /* Do the sub in u64, where overflow is well-defined */
3437 s64 res
= (s64
)((u64
)a
- (u64
)b
);
3444 static bool check_reg_sane_offset(struct bpf_verifier_env
*env
,
3445 const struct bpf_reg_state
*reg
,
3446 enum bpf_reg_type type
)
3448 bool known
= tnum_is_const(reg
->var_off
);
3449 s64 val
= reg
->var_off
.value
;
3450 s64 smin
= reg
->smin_value
;
3452 if (known
&& (val
>= BPF_MAX_VAR_OFF
|| val
<= -BPF_MAX_VAR_OFF
)) {
3453 verbose(env
, "math between %s pointer and %lld is not allowed\n",
3454 reg_type_str
[type
], val
);
3458 if (reg
->off
>= BPF_MAX_VAR_OFF
|| reg
->off
<= -BPF_MAX_VAR_OFF
) {
3459 verbose(env
, "%s pointer offset %d is not allowed\n",
3460 reg_type_str
[type
], reg
->off
);
3464 if (smin
== S64_MIN
) {
3465 verbose(env
, "math between %s pointer and register with unbounded min value is not allowed\n",
3466 reg_type_str
[type
]);
3470 if (smin
>= BPF_MAX_VAR_OFF
|| smin
<= -BPF_MAX_VAR_OFF
) {
3471 verbose(env
, "value %lld makes %s pointer be out of bounds\n",
3472 smin
, reg_type_str
[type
]);
3479 static struct bpf_insn_aux_data
*cur_aux(struct bpf_verifier_env
*env
)
3481 return &env
->insn_aux_data
[env
->insn_idx
];
3484 static int retrieve_ptr_limit(const struct bpf_reg_state
*ptr_reg
,
3485 u32
*ptr_limit
, u8 opcode
, bool off_is_neg
)
3487 bool mask_to_left
= (opcode
== BPF_ADD
&& off_is_neg
) ||
3488 (opcode
== BPF_SUB
&& !off_is_neg
);
3491 switch (ptr_reg
->type
) {
3493 /* Indirect variable offset stack access is prohibited in
3494 * unprivileged mode so it's not handled here.
3496 off
= ptr_reg
->off
+ ptr_reg
->var_off
.value
;
3498 *ptr_limit
= MAX_BPF_STACK
+ off
;
3502 case PTR_TO_MAP_VALUE
:
3504 *ptr_limit
= ptr_reg
->umax_value
+ ptr_reg
->off
;
3506 off
= ptr_reg
->smin_value
+ ptr_reg
->off
;
3507 *ptr_limit
= ptr_reg
->map_ptr
->value_size
- off
;
3515 static bool can_skip_alu_sanitation(const struct bpf_verifier_env
*env
,
3516 const struct bpf_insn
*insn
)
3518 return env
->allow_ptr_leaks
|| BPF_SRC(insn
->code
) == BPF_K
;
3521 static int update_alu_sanitation_state(struct bpf_insn_aux_data
*aux
,
3522 u32 alu_state
, u32 alu_limit
)
3524 /* If we arrived here from different branches with different
3525 * state or limits to sanitize, then this won't work.
3527 if (aux
->alu_state
&&
3528 (aux
->alu_state
!= alu_state
||
3529 aux
->alu_limit
!= alu_limit
))
3532 /* Corresponding fixup done in fixup_bpf_calls(). */
3533 aux
->alu_state
= alu_state
;
3534 aux
->alu_limit
= alu_limit
;
3538 static int sanitize_val_alu(struct bpf_verifier_env
*env
,
3539 struct bpf_insn
*insn
)
3541 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
3543 if (can_skip_alu_sanitation(env
, insn
))
3546 return update_alu_sanitation_state(aux
, BPF_ALU_NON_POINTER
, 0);
3549 static int sanitize_ptr_alu(struct bpf_verifier_env
*env
,
3550 struct bpf_insn
*insn
,
3551 const struct bpf_reg_state
*ptr_reg
,
3552 struct bpf_reg_state
*dst_reg
,
3555 struct bpf_verifier_state
*vstate
= env
->cur_state
;
3556 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
3557 bool ptr_is_dst_reg
= ptr_reg
== dst_reg
;
3558 u8 opcode
= BPF_OP(insn
->code
);
3559 u32 alu_state
, alu_limit
;
3560 struct bpf_reg_state tmp
;
3563 if (can_skip_alu_sanitation(env
, insn
))
3566 /* We already marked aux for masking from non-speculative
3567 * paths, thus we got here in the first place. We only care
3568 * to explore bad access from here.
3570 if (vstate
->speculative
)
3573 alu_state
= off_is_neg
? BPF_ALU_NEG_VALUE
: 0;
3574 alu_state
|= ptr_is_dst_reg
?
3575 BPF_ALU_SANITIZE_SRC
: BPF_ALU_SANITIZE_DST
;
3577 if (retrieve_ptr_limit(ptr_reg
, &alu_limit
, opcode
, off_is_neg
))
3579 if (update_alu_sanitation_state(aux
, alu_state
, alu_limit
))
3582 /* Simulate and find potential out-of-bounds access under
3583 * speculative execution from truncation as a result of
3584 * masking when off was not within expected range. If off
3585 * sits in dst, then we temporarily need to move ptr there
3586 * to simulate dst (== 0) +/-= ptr. Needed, for example,
3587 * for cases where we use K-based arithmetic in one direction
3588 * and truncated reg-based in the other in order to explore
3591 if (!ptr_is_dst_reg
) {
3593 *dst_reg
= *ptr_reg
;
3595 ret
= push_stack(env
, env
->insn_idx
+ 1, env
->insn_idx
, true);
3596 if (!ptr_is_dst_reg
&& ret
)
3598 return !ret
? -EFAULT
: 0;
3601 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
3602 * Caller should also handle BPF_MOV case separately.
3603 * If we return -EACCES, caller may want to try again treating pointer as a
3604 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
3606 static int adjust_ptr_min_max_vals(struct bpf_verifier_env
*env
,
3607 struct bpf_insn
*insn
,
3608 const struct bpf_reg_state
*ptr_reg
,
3609 const struct bpf_reg_state
*off_reg
)
3611 struct bpf_verifier_state
*vstate
= env
->cur_state
;
3612 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
3613 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
;
3614 bool known
= tnum_is_const(off_reg
->var_off
);
3615 s64 smin_val
= off_reg
->smin_value
, smax_val
= off_reg
->smax_value
,
3616 smin_ptr
= ptr_reg
->smin_value
, smax_ptr
= ptr_reg
->smax_value
;
3617 u64 umin_val
= off_reg
->umin_value
, umax_val
= off_reg
->umax_value
,
3618 umin_ptr
= ptr_reg
->umin_value
, umax_ptr
= ptr_reg
->umax_value
;
3619 u32 dst
= insn
->dst_reg
, src
= insn
->src_reg
;
3620 u8 opcode
= BPF_OP(insn
->code
);
3623 dst_reg
= ®s
[dst
];
3625 if ((known
&& (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
3626 smin_val
> smax_val
|| umin_val
> umax_val
) {
3627 /* Taint dst register if offset had invalid bounds derived from
3628 * e.g. dead branches.
3630 __mark_reg_unknown(dst_reg
);
3634 if (BPF_CLASS(insn
->code
) != BPF_ALU64
) {
3635 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
3637 "R%d 32-bit pointer arithmetic prohibited\n",
3642 switch (ptr_reg
->type
) {
3643 case PTR_TO_MAP_VALUE_OR_NULL
:
3644 verbose(env
, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
3645 dst
, reg_type_str
[ptr_reg
->type
]);
3647 case CONST_PTR_TO_MAP
:
3648 case PTR_TO_PACKET_END
:
3650 case PTR_TO_SOCKET_OR_NULL
:
3651 case PTR_TO_SOCK_COMMON
:
3652 case PTR_TO_SOCK_COMMON_OR_NULL
:
3653 case PTR_TO_TCP_SOCK
:
3654 case PTR_TO_TCP_SOCK_OR_NULL
:
3655 verbose(env
, "R%d pointer arithmetic on %s prohibited\n",
3656 dst
, reg_type_str
[ptr_reg
->type
]);
3658 case PTR_TO_MAP_VALUE
:
3659 if (!env
->allow_ptr_leaks
&& !known
&& (smin_val
< 0) != (smax_val
< 0)) {
3660 verbose(env
, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
3661 off_reg
== dst_reg
? dst
: src
);
3669 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3670 * The id may be overwritten later if we create a new variable offset.
3672 dst_reg
->type
= ptr_reg
->type
;
3673 dst_reg
->id
= ptr_reg
->id
;
3675 if (!check_reg_sane_offset(env
, off_reg
, ptr_reg
->type
) ||
3676 !check_reg_sane_offset(env
, ptr_reg
, ptr_reg
->type
))
3681 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
3683 verbose(env
, "R%d tried to add from different maps or paths\n", dst
);
3686 /* We can take a fixed offset as long as it doesn't overflow
3687 * the s32 'off' field
3689 if (known
&& (ptr_reg
->off
+ smin_val
==
3690 (s64
)(s32
)(ptr_reg
->off
+ smin_val
))) {
3691 /* pointer += K. Accumulate it into fixed offset */
3692 dst_reg
->smin_value
= smin_ptr
;
3693 dst_reg
->smax_value
= smax_ptr
;
3694 dst_reg
->umin_value
= umin_ptr
;
3695 dst_reg
->umax_value
= umax_ptr
;
3696 dst_reg
->var_off
= ptr_reg
->var_off
;
3697 dst_reg
->off
= ptr_reg
->off
+ smin_val
;
3698 dst_reg
->raw
= ptr_reg
->raw
;
3701 /* A new variable offset is created. Note that off_reg->off
3702 * == 0, since it's a scalar.
3703 * dst_reg gets the pointer type and since some positive
3704 * integer value was added to the pointer, give it a new 'id'
3705 * if it's a PTR_TO_PACKET.
3706 * this creates a new 'base' pointer, off_reg (variable) gets
3707 * added into the variable offset, and we copy the fixed offset
3710 if (signed_add_overflows(smin_ptr
, smin_val
) ||
3711 signed_add_overflows(smax_ptr
, smax_val
)) {
3712 dst_reg
->smin_value
= S64_MIN
;
3713 dst_reg
->smax_value
= S64_MAX
;
3715 dst_reg
->smin_value
= smin_ptr
+ smin_val
;
3716 dst_reg
->smax_value
= smax_ptr
+ smax_val
;
3718 if (umin_ptr
+ umin_val
< umin_ptr
||
3719 umax_ptr
+ umax_val
< umax_ptr
) {
3720 dst_reg
->umin_value
= 0;
3721 dst_reg
->umax_value
= U64_MAX
;
3723 dst_reg
->umin_value
= umin_ptr
+ umin_val
;
3724 dst_reg
->umax_value
= umax_ptr
+ umax_val
;
3726 dst_reg
->var_off
= tnum_add(ptr_reg
->var_off
, off_reg
->var_off
);
3727 dst_reg
->off
= ptr_reg
->off
;
3728 dst_reg
->raw
= ptr_reg
->raw
;
3729 if (reg_is_pkt_pointer(ptr_reg
)) {
3730 dst_reg
->id
= ++env
->id_gen
;
3731 /* something was added to pkt_ptr, set range to zero */
3736 ret
= sanitize_ptr_alu(env
, insn
, ptr_reg
, dst_reg
, smin_val
< 0);
3738 verbose(env
, "R%d tried to sub from different maps or paths\n", dst
);
3741 if (dst_reg
== off_reg
) {
3742 /* scalar -= pointer. Creates an unknown scalar */
3743 verbose(env
, "R%d tried to subtract pointer from scalar\n",
3747 /* We don't allow subtraction from FP, because (according to
3748 * test_verifier.c test "invalid fp arithmetic", JITs might not
3749 * be able to deal with it.
3751 if (ptr_reg
->type
== PTR_TO_STACK
) {
3752 verbose(env
, "R%d subtraction from stack pointer prohibited\n",
3756 if (known
&& (ptr_reg
->off
- smin_val
==
3757 (s64
)(s32
)(ptr_reg
->off
- smin_val
))) {
3758 /* pointer -= K. Subtract it from fixed offset */
3759 dst_reg
->smin_value
= smin_ptr
;
3760 dst_reg
->smax_value
= smax_ptr
;
3761 dst_reg
->umin_value
= umin_ptr
;
3762 dst_reg
->umax_value
= umax_ptr
;
3763 dst_reg
->var_off
= ptr_reg
->var_off
;
3764 dst_reg
->id
= ptr_reg
->id
;
3765 dst_reg
->off
= ptr_reg
->off
- smin_val
;
3766 dst_reg
->raw
= ptr_reg
->raw
;
3769 /* A new variable offset is created. If the subtrahend is known
3770 * nonnegative, then any reg->range we had before is still good.
3772 if (signed_sub_overflows(smin_ptr
, smax_val
) ||
3773 signed_sub_overflows(smax_ptr
, smin_val
)) {
3774 /* Overflow possible, we know nothing */
3775 dst_reg
->smin_value
= S64_MIN
;
3776 dst_reg
->smax_value
= S64_MAX
;
3778 dst_reg
->smin_value
= smin_ptr
- smax_val
;
3779 dst_reg
->smax_value
= smax_ptr
- smin_val
;
3781 if (umin_ptr
< umax_val
) {
3782 /* Overflow possible, we know nothing */
3783 dst_reg
->umin_value
= 0;
3784 dst_reg
->umax_value
= U64_MAX
;
3786 /* Cannot overflow (as long as bounds are consistent) */
3787 dst_reg
->umin_value
= umin_ptr
- umax_val
;
3788 dst_reg
->umax_value
= umax_ptr
- umin_val
;
3790 dst_reg
->var_off
= tnum_sub(ptr_reg
->var_off
, off_reg
->var_off
);
3791 dst_reg
->off
= ptr_reg
->off
;
3792 dst_reg
->raw
= ptr_reg
->raw
;
3793 if (reg_is_pkt_pointer(ptr_reg
)) {
3794 dst_reg
->id
= ++env
->id_gen
;
3795 /* something was added to pkt_ptr, set range to zero */
3803 /* bitwise ops on pointers are troublesome, prohibit. */
3804 verbose(env
, "R%d bitwise operator %s on pointer prohibited\n",
3805 dst
, bpf_alu_string
[opcode
>> 4]);
3808 /* other operators (e.g. MUL,LSH) produce non-pointer results */
3809 verbose(env
, "R%d pointer arithmetic with %s operator prohibited\n",
3810 dst
, bpf_alu_string
[opcode
>> 4]);
3814 if (!check_reg_sane_offset(env
, dst_reg
, ptr_reg
->type
))
3817 __update_reg_bounds(dst_reg
);
3818 __reg_deduce_bounds(dst_reg
);
3819 __reg_bound_offset(dst_reg
);
3821 /* For unprivileged we require that resulting offset must be in bounds
3822 * in order to be able to sanitize access later on.
3824 if (!env
->allow_ptr_leaks
) {
3825 if (dst_reg
->type
== PTR_TO_MAP_VALUE
&&
3826 check_map_access(env
, dst
, dst_reg
->off
, 1, false)) {
3827 verbose(env
, "R%d pointer arithmetic of map value goes out of range, "
3828 "prohibited for !root\n", dst
);
3830 } else if (dst_reg
->type
== PTR_TO_STACK
&&
3831 check_stack_access(env
, dst_reg
, dst_reg
->off
+
3832 dst_reg
->var_off
.value
, 1)) {
3833 verbose(env
, "R%d stack pointer arithmetic goes out of range, "
3834 "prohibited for !root\n", dst
);
3842 /* WARNING: This function does calculations on 64-bit values, but the actual
3843 * execution may occur on 32-bit values. Therefore, things like bitshifts
3844 * need extra checks in the 32-bit case.
3846 static int adjust_scalar_min_max_vals(struct bpf_verifier_env
*env
,
3847 struct bpf_insn
*insn
,
3848 struct bpf_reg_state
*dst_reg
,
3849 struct bpf_reg_state src_reg
)
3851 struct bpf_reg_state
*regs
= cur_regs(env
);
3852 u8 opcode
= BPF_OP(insn
->code
);
3853 bool src_known
, dst_known
;
3854 s64 smin_val
, smax_val
;
3855 u64 umin_val
, umax_val
;
3856 u64 insn_bitness
= (BPF_CLASS(insn
->code
) == BPF_ALU64
) ? 64 : 32;
3857 u32 dst
= insn
->dst_reg
;
3860 if (insn_bitness
== 32) {
3861 /* Relevant for 32-bit RSH: Information can propagate towards
3862 * LSB, so it isn't sufficient to only truncate the output to
3865 coerce_reg_to_size(dst_reg
, 4);
3866 coerce_reg_to_size(&src_reg
, 4);
3869 smin_val
= src_reg
.smin_value
;
3870 smax_val
= src_reg
.smax_value
;
3871 umin_val
= src_reg
.umin_value
;
3872 umax_val
= src_reg
.umax_value
;
3873 src_known
= tnum_is_const(src_reg
.var_off
);
3874 dst_known
= tnum_is_const(dst_reg
->var_off
);
3876 if ((src_known
&& (smin_val
!= smax_val
|| umin_val
!= umax_val
)) ||
3877 smin_val
> smax_val
|| umin_val
> umax_val
) {
3878 /* Taint dst register if offset had invalid bounds derived from
3879 * e.g. dead branches.
3881 __mark_reg_unknown(dst_reg
);
3886 opcode
!= BPF_ADD
&& opcode
!= BPF_SUB
&& opcode
!= BPF_AND
) {
3887 __mark_reg_unknown(dst_reg
);
3893 ret
= sanitize_val_alu(env
, insn
);
3895 verbose(env
, "R%d tried to add from different pointers or scalars\n", dst
);
3898 if (signed_add_overflows(dst_reg
->smin_value
, smin_val
) ||
3899 signed_add_overflows(dst_reg
->smax_value
, smax_val
)) {
3900 dst_reg
->smin_value
= S64_MIN
;
3901 dst_reg
->smax_value
= S64_MAX
;
3903 dst_reg
->smin_value
+= smin_val
;
3904 dst_reg
->smax_value
+= smax_val
;
3906 if (dst_reg
->umin_value
+ umin_val
< umin_val
||
3907 dst_reg
->umax_value
+ umax_val
< umax_val
) {
3908 dst_reg
->umin_value
= 0;
3909 dst_reg
->umax_value
= U64_MAX
;
3911 dst_reg
->umin_value
+= umin_val
;
3912 dst_reg
->umax_value
+= umax_val
;
3914 dst_reg
->var_off
= tnum_add(dst_reg
->var_off
, src_reg
.var_off
);
3917 ret
= sanitize_val_alu(env
, insn
);
3919 verbose(env
, "R%d tried to sub from different pointers or scalars\n", dst
);
3922 if (signed_sub_overflows(dst_reg
->smin_value
, smax_val
) ||
3923 signed_sub_overflows(dst_reg
->smax_value
, smin_val
)) {
3924 /* Overflow possible, we know nothing */
3925 dst_reg
->smin_value
= S64_MIN
;
3926 dst_reg
->smax_value
= S64_MAX
;
3928 dst_reg
->smin_value
-= smax_val
;
3929 dst_reg
->smax_value
-= smin_val
;
3931 if (dst_reg
->umin_value
< umax_val
) {
3932 /* Overflow possible, we know nothing */
3933 dst_reg
->umin_value
= 0;
3934 dst_reg
->umax_value
= U64_MAX
;
3936 /* Cannot overflow (as long as bounds are consistent) */
3937 dst_reg
->umin_value
-= umax_val
;
3938 dst_reg
->umax_value
-= umin_val
;
3940 dst_reg
->var_off
= tnum_sub(dst_reg
->var_off
, src_reg
.var_off
);
3943 dst_reg
->var_off
= tnum_mul(dst_reg
->var_off
, src_reg
.var_off
);
3944 if (smin_val
< 0 || dst_reg
->smin_value
< 0) {
3945 /* Ain't nobody got time to multiply that sign */
3946 __mark_reg_unbounded(dst_reg
);
3947 __update_reg_bounds(dst_reg
);
3950 /* Both values are positive, so we can work with unsigned and
3951 * copy the result to signed (unless it exceeds S64_MAX).
3953 if (umax_val
> U32_MAX
|| dst_reg
->umax_value
> U32_MAX
) {
3954 /* Potential overflow, we know nothing */
3955 __mark_reg_unbounded(dst_reg
);
3956 /* (except what we can learn from the var_off) */
3957 __update_reg_bounds(dst_reg
);
3960 dst_reg
->umin_value
*= umin_val
;
3961 dst_reg
->umax_value
*= umax_val
;
3962 if (dst_reg
->umax_value
> S64_MAX
) {
3963 /* Overflow possible, we know nothing */
3964 dst_reg
->smin_value
= S64_MIN
;
3965 dst_reg
->smax_value
= S64_MAX
;
3967 dst_reg
->smin_value
= dst_reg
->umin_value
;
3968 dst_reg
->smax_value
= dst_reg
->umax_value
;
3972 if (src_known
&& dst_known
) {
3973 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
&
3974 src_reg
.var_off
.value
);
3977 /* We get our minimum from the var_off, since that's inherently
3978 * bitwise. Our maximum is the minimum of the operands' maxima.
3980 dst_reg
->var_off
= tnum_and(dst_reg
->var_off
, src_reg
.var_off
);
3981 dst_reg
->umin_value
= dst_reg
->var_off
.value
;
3982 dst_reg
->umax_value
= min(dst_reg
->umax_value
, umax_val
);
3983 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
3984 /* Lose signed bounds when ANDing negative numbers,
3985 * ain't nobody got time for that.
3987 dst_reg
->smin_value
= S64_MIN
;
3988 dst_reg
->smax_value
= S64_MAX
;
3990 /* ANDing two positives gives a positive, so safe to
3991 * cast result into s64.
3993 dst_reg
->smin_value
= dst_reg
->umin_value
;
3994 dst_reg
->smax_value
= dst_reg
->umax_value
;
3996 /* We may learn something more from the var_off */
3997 __update_reg_bounds(dst_reg
);
4000 if (src_known
&& dst_known
) {
4001 __mark_reg_known(dst_reg
, dst_reg
->var_off
.value
|
4002 src_reg
.var_off
.value
);
4005 /* We get our maximum from the var_off, and our minimum is the
4006 * maximum of the operands' minima
4008 dst_reg
->var_off
= tnum_or(dst_reg
->var_off
, src_reg
.var_off
);
4009 dst_reg
->umin_value
= max(dst_reg
->umin_value
, umin_val
);
4010 dst_reg
->umax_value
= dst_reg
->var_off
.value
|
4011 dst_reg
->var_off
.mask
;
4012 if (dst_reg
->smin_value
< 0 || smin_val
< 0) {
4013 /* Lose signed bounds when ORing negative numbers,
4014 * ain't nobody got time for that.
4016 dst_reg
->smin_value
= S64_MIN
;
4017 dst_reg
->smax_value
= S64_MAX
;
4019 /* ORing two positives gives a positive, so safe to
4020 * cast result into s64.
4022 dst_reg
->smin_value
= dst_reg
->umin_value
;
4023 dst_reg
->smax_value
= dst_reg
->umax_value
;
4025 /* We may learn something more from the var_off */
4026 __update_reg_bounds(dst_reg
);
4029 if (umax_val
>= insn_bitness
) {
4030 /* Shifts greater than 31 or 63 are undefined.
4031 * This includes shifts by a negative number.
4033 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
4036 /* We lose all sign bit information (except what we can pick
4039 dst_reg
->smin_value
= S64_MIN
;
4040 dst_reg
->smax_value
= S64_MAX
;
4041 /* If we might shift our top bit out, then we know nothing */
4042 if (dst_reg
->umax_value
> 1ULL << (63 - umax_val
)) {
4043 dst_reg
->umin_value
= 0;
4044 dst_reg
->umax_value
= U64_MAX
;
4046 dst_reg
->umin_value
<<= umin_val
;
4047 dst_reg
->umax_value
<<= umax_val
;
4049 dst_reg
->var_off
= tnum_lshift(dst_reg
->var_off
, umin_val
);
4050 /* We may learn something more from the var_off */
4051 __update_reg_bounds(dst_reg
);
4054 if (umax_val
>= insn_bitness
) {
4055 /* Shifts greater than 31 or 63 are undefined.
4056 * This includes shifts by a negative number.
4058 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
4061 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
4062 * be negative, then either:
4063 * 1) src_reg might be zero, so the sign bit of the result is
4064 * unknown, so we lose our signed bounds
4065 * 2) it's known negative, thus the unsigned bounds capture the
4067 * 3) the signed bounds cross zero, so they tell us nothing
4069 * If the value in dst_reg is known nonnegative, then again the
4070 * unsigned bounts capture the signed bounds.
4071 * Thus, in all cases it suffices to blow away our signed bounds
4072 * and rely on inferring new ones from the unsigned bounds and
4073 * var_off of the result.
4075 dst_reg
->smin_value
= S64_MIN
;
4076 dst_reg
->smax_value
= S64_MAX
;
4077 dst_reg
->var_off
= tnum_rshift(dst_reg
->var_off
, umin_val
);
4078 dst_reg
->umin_value
>>= umax_val
;
4079 dst_reg
->umax_value
>>= umin_val
;
4080 /* We may learn something more from the var_off */
4081 __update_reg_bounds(dst_reg
);
4084 if (umax_val
>= insn_bitness
) {
4085 /* Shifts greater than 31 or 63 are undefined.
4086 * This includes shifts by a negative number.
4088 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
4092 /* Upon reaching here, src_known is true and
4093 * umax_val is equal to umin_val.
4095 dst_reg
->smin_value
>>= umin_val
;
4096 dst_reg
->smax_value
>>= umin_val
;
4097 dst_reg
->var_off
= tnum_arshift(dst_reg
->var_off
, umin_val
);
4099 /* blow away the dst_reg umin_value/umax_value and rely on
4100 * dst_reg var_off to refine the result.
4102 dst_reg
->umin_value
= 0;
4103 dst_reg
->umax_value
= U64_MAX
;
4104 __update_reg_bounds(dst_reg
);
4107 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
4111 if (BPF_CLASS(insn
->code
) != BPF_ALU64
) {
4112 /* 32-bit ALU ops are (32,32)->32 */
4113 coerce_reg_to_size(dst_reg
, 4);
4116 __reg_deduce_bounds(dst_reg
);
4117 __reg_bound_offset(dst_reg
);
4121 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
4124 static int adjust_reg_min_max_vals(struct bpf_verifier_env
*env
,
4125 struct bpf_insn
*insn
)
4127 struct bpf_verifier_state
*vstate
= env
->cur_state
;
4128 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
4129 struct bpf_reg_state
*regs
= state
->regs
, *dst_reg
, *src_reg
;
4130 struct bpf_reg_state
*ptr_reg
= NULL
, off_reg
= {0};
4131 u8 opcode
= BPF_OP(insn
->code
);
4133 dst_reg
= ®s
[insn
->dst_reg
];
4135 if (dst_reg
->type
!= SCALAR_VALUE
)
4137 if (BPF_SRC(insn
->code
) == BPF_X
) {
4138 src_reg
= ®s
[insn
->src_reg
];
4139 if (src_reg
->type
!= SCALAR_VALUE
) {
4140 if (dst_reg
->type
!= SCALAR_VALUE
) {
4141 /* Combining two pointers by any ALU op yields
4142 * an arbitrary scalar. Disallow all math except
4143 * pointer subtraction
4145 if (opcode
== BPF_SUB
&& env
->allow_ptr_leaks
) {
4146 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
4149 verbose(env
, "R%d pointer %s pointer prohibited\n",
4151 bpf_alu_string
[opcode
>> 4]);
4154 /* scalar += pointer
4155 * This is legal, but we have to reverse our
4156 * src/dest handling in computing the range
4158 return adjust_ptr_min_max_vals(env
, insn
,
4161 } else if (ptr_reg
) {
4162 /* pointer += scalar */
4163 return adjust_ptr_min_max_vals(env
, insn
,
4167 /* Pretend the src is a reg with a known value, since we only
4168 * need to be able to read from this state.
4170 off_reg
.type
= SCALAR_VALUE
;
4171 __mark_reg_known(&off_reg
, insn
->imm
);
4173 if (ptr_reg
) /* pointer += K */
4174 return adjust_ptr_min_max_vals(env
, insn
,
4178 /* Got here implies adding two SCALAR_VALUEs */
4179 if (WARN_ON_ONCE(ptr_reg
)) {
4180 print_verifier_state(env
, state
);
4181 verbose(env
, "verifier internal error: unexpected ptr_reg\n");
4184 if (WARN_ON(!src_reg
)) {
4185 print_verifier_state(env
, state
);
4186 verbose(env
, "verifier internal error: no src_reg\n");
4189 return adjust_scalar_min_max_vals(env
, insn
, dst_reg
, *src_reg
);
4192 /* check validity of 32-bit and 64-bit arithmetic operations */
4193 static int check_alu_op(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
4195 struct bpf_reg_state
*regs
= cur_regs(env
);
4196 u8 opcode
= BPF_OP(insn
->code
);
4199 if (opcode
== BPF_END
|| opcode
== BPF_NEG
) {
4200 if (opcode
== BPF_NEG
) {
4201 if (BPF_SRC(insn
->code
) != 0 ||
4202 insn
->src_reg
!= BPF_REG_0
||
4203 insn
->off
!= 0 || insn
->imm
!= 0) {
4204 verbose(env
, "BPF_NEG uses reserved fields\n");
4208 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
4209 (insn
->imm
!= 16 && insn
->imm
!= 32 && insn
->imm
!= 64) ||
4210 BPF_CLASS(insn
->code
) == BPF_ALU64
) {
4211 verbose(env
, "BPF_END uses reserved fields\n");
4216 /* check src operand */
4217 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
4221 if (is_pointer_value(env
, insn
->dst_reg
)) {
4222 verbose(env
, "R%d pointer arithmetic prohibited\n",
4227 /* check dest operand */
4228 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
4232 } else if (opcode
== BPF_MOV
) {
4234 if (BPF_SRC(insn
->code
) == BPF_X
) {
4235 if (insn
->imm
!= 0 || insn
->off
!= 0) {
4236 verbose(env
, "BPF_MOV uses reserved fields\n");
4240 /* check src operand */
4241 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
4245 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
4246 verbose(env
, "BPF_MOV uses reserved fields\n");
4251 /* check dest operand, mark as required later */
4252 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
4256 if (BPF_SRC(insn
->code
) == BPF_X
) {
4257 struct bpf_reg_state
*src_reg
= regs
+ insn
->src_reg
;
4258 struct bpf_reg_state
*dst_reg
= regs
+ insn
->dst_reg
;
4260 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
4262 * copy register state to dest reg
4264 *dst_reg
= *src_reg
;
4265 dst_reg
->live
|= REG_LIVE_WRITTEN
;
4268 if (is_pointer_value(env
, insn
->src_reg
)) {
4270 "R%d partial copy of pointer\n",
4273 } else if (src_reg
->type
== SCALAR_VALUE
) {
4274 *dst_reg
= *src_reg
;
4275 dst_reg
->live
|= REG_LIVE_WRITTEN
;
4277 mark_reg_unknown(env
, regs
,
4280 coerce_reg_to_size(dst_reg
, 4);
4284 * remember the value we stored into this reg
4286 /* clear any state __mark_reg_known doesn't set */
4287 mark_reg_unknown(env
, regs
, insn
->dst_reg
);
4288 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
4289 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
4290 __mark_reg_known(regs
+ insn
->dst_reg
,
4293 __mark_reg_known(regs
+ insn
->dst_reg
,
4298 } else if (opcode
> BPF_END
) {
4299 verbose(env
, "invalid BPF_ALU opcode %x\n", opcode
);
4302 } else { /* all other ALU ops: and, sub, xor, add, ... */
4304 if (BPF_SRC(insn
->code
) == BPF_X
) {
4305 if (insn
->imm
!= 0 || insn
->off
!= 0) {
4306 verbose(env
, "BPF_ALU uses reserved fields\n");
4309 /* check src1 operand */
4310 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
4314 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
4315 verbose(env
, "BPF_ALU uses reserved fields\n");
4320 /* check src2 operand */
4321 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
4325 if ((opcode
== BPF_MOD
|| opcode
== BPF_DIV
) &&
4326 BPF_SRC(insn
->code
) == BPF_K
&& insn
->imm
== 0) {
4327 verbose(env
, "div by zero\n");
4331 if ((opcode
== BPF_LSH
|| opcode
== BPF_RSH
||
4332 opcode
== BPF_ARSH
) && BPF_SRC(insn
->code
) == BPF_K
) {
4333 int size
= BPF_CLASS(insn
->code
) == BPF_ALU64
? 64 : 32;
4335 if (insn
->imm
< 0 || insn
->imm
>= size
) {
4336 verbose(env
, "invalid shift %d\n", insn
->imm
);
4341 /* check dest operand */
4342 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
4346 return adjust_reg_min_max_vals(env
, insn
);
4352 static void find_good_pkt_pointers(struct bpf_verifier_state
*vstate
,
4353 struct bpf_reg_state
*dst_reg
,
4354 enum bpf_reg_type type
,
4355 bool range_right_open
)
4357 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
4358 struct bpf_reg_state
*regs
= state
->regs
, *reg
;
4362 if (dst_reg
->off
< 0 ||
4363 (dst_reg
->off
== 0 && range_right_open
))
4364 /* This doesn't give us any range */
4367 if (dst_reg
->umax_value
> MAX_PACKET_OFF
||
4368 dst_reg
->umax_value
+ dst_reg
->off
> MAX_PACKET_OFF
)
4369 /* Risk of overflow. For instance, ptr + (1<<63) may be less
4370 * than pkt_end, but that's because it's also less than pkt.
4374 new_range
= dst_reg
->off
;
4375 if (range_right_open
)
4378 /* Examples for register markings:
4380 * pkt_data in dst register:
4384 * if (r2 > pkt_end) goto <handle exception>
4389 * if (r2 < pkt_end) goto <access okay>
4390 * <handle exception>
4393 * r2 == dst_reg, pkt_end == src_reg
4394 * r2=pkt(id=n,off=8,r=0)
4395 * r3=pkt(id=n,off=0,r=0)
4397 * pkt_data in src register:
4401 * if (pkt_end >= r2) goto <access okay>
4402 * <handle exception>
4406 * if (pkt_end <= r2) goto <handle exception>
4410 * pkt_end == dst_reg, r2 == src_reg
4411 * r2=pkt(id=n,off=8,r=0)
4412 * r3=pkt(id=n,off=0,r=0)
4414 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
4415 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
4416 * and [r3, r3 + 8-1) respectively is safe to access depending on
4420 /* If our ids match, then we must have the same max_value. And we
4421 * don't care about the other reg's fixed offset, since if it's too big
4422 * the range won't allow anything.
4423 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
4425 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4426 if (regs
[i
].type
== type
&& regs
[i
].id
== dst_reg
->id
)
4427 /* keep the maximum range already checked */
4428 regs
[i
].range
= max(regs
[i
].range
, new_range
);
4430 for (j
= 0; j
<= vstate
->curframe
; j
++) {
4431 state
= vstate
->frame
[j
];
4432 bpf_for_each_spilled_reg(i
, state
, reg
) {
4435 if (reg
->type
== type
&& reg
->id
== dst_reg
->id
)
4436 reg
->range
= max(reg
->range
, new_range
);
4441 /* compute branch direction of the expression "if (reg opcode val) goto target;"
4443 * 1 - branch will be taken and "goto target" will be executed
4444 * 0 - branch will not be taken and fall-through to next insn
4445 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
4447 static int is_branch_taken(struct bpf_reg_state
*reg
, u64 val
, u8 opcode
,
4450 struct bpf_reg_state reg_lo
;
4453 if (__is_pointer_value(false, reg
))
4459 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
4460 * could truncate high bits and update umin/umax according to
4461 * information of low bits.
4463 coerce_reg_to_size(reg
, 4);
4464 /* smin/smax need special handling. For example, after coerce,
4465 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
4466 * used as operand to JMP32. It is a negative number from s32's
4467 * point of view, while it is a positive number when seen as
4468 * s64. The smin/smax are kept as s64, therefore, when used with
4469 * JMP32, they need to be transformed into s32, then sign
4470 * extended back to s64.
4472 * Also, smin/smax were copied from umin/umax. If umin/umax has
4473 * different sign bit, then min/max relationship doesn't
4474 * maintain after casting into s32, for this case, set smin/smax
4477 if ((reg
->umax_value
^ reg
->umin_value
) &
4479 reg
->smin_value
= S32_MIN
;
4480 reg
->smax_value
= S32_MAX
;
4482 reg
->smin_value
= (s64
)(s32
)reg
->smin_value
;
4483 reg
->smax_value
= (s64
)(s32
)reg
->smax_value
;
4486 sval
= (s64
)(s32
)val
;
4493 if (tnum_is_const(reg
->var_off
))
4494 return !!tnum_equals_const(reg
->var_off
, val
);
4497 if (tnum_is_const(reg
->var_off
))
4498 return !tnum_equals_const(reg
->var_off
, val
);
4501 if ((~reg
->var_off
.mask
& reg
->var_off
.value
) & val
)
4503 if (!((reg
->var_off
.mask
| reg
->var_off
.value
) & val
))
4507 if (reg
->umin_value
> val
)
4509 else if (reg
->umax_value
<= val
)
4513 if (reg
->smin_value
> sval
)
4515 else if (reg
->smax_value
< sval
)
4519 if (reg
->umax_value
< val
)
4521 else if (reg
->umin_value
>= val
)
4525 if (reg
->smax_value
< sval
)
4527 else if (reg
->smin_value
>= sval
)
4531 if (reg
->umin_value
>= val
)
4533 else if (reg
->umax_value
< val
)
4537 if (reg
->smin_value
>= sval
)
4539 else if (reg
->smax_value
< sval
)
4543 if (reg
->umax_value
<= val
)
4545 else if (reg
->umin_value
> val
)
4549 if (reg
->smax_value
<= sval
)
4551 else if (reg
->smin_value
> sval
)
4559 /* Generate min value of the high 32-bit from TNUM info. */
4560 static u64
gen_hi_min(struct tnum var
)
4562 return var
.value
& ~0xffffffffULL
;
4565 /* Generate max value of the high 32-bit from TNUM info. */
4566 static u64
gen_hi_max(struct tnum var
)
4568 return (var
.value
| var
.mask
) & ~0xffffffffULL
;
4571 /* Return true if VAL is compared with a s64 sign extended from s32, and they
4572 * are with the same signedness.
4574 static bool cmp_val_with_extended_s64(s64 sval
, struct bpf_reg_state
*reg
)
4576 return ((s32
)sval
>= 0 &&
4577 reg
->smin_value
>= 0 && reg
->smax_value
<= S32_MAX
) ||
4579 reg
->smax_value
<= 0 && reg
->smin_value
>= S32_MIN
);
4582 /* Adjusts the register min/max values in the case that the dst_reg is the
4583 * variable register that we are working on, and src_reg is a constant or we're
4584 * simply doing a BPF_K check.
4585 * In JEQ/JNE cases we also adjust the var_off values.
4587 static void reg_set_min_max(struct bpf_reg_state
*true_reg
,
4588 struct bpf_reg_state
*false_reg
, u64 val
,
4589 u8 opcode
, bool is_jmp32
)
4593 /* If the dst_reg is a pointer, we can't learn anything about its
4594 * variable offset from the compare (unless src_reg were a pointer into
4595 * the same object, but we don't bother with that.
4596 * Since false_reg and true_reg have the same type by construction, we
4597 * only need to check one of them for pointerness.
4599 if (__is_pointer_value(false, false_reg
))
4602 val
= is_jmp32
? (u32
)val
: val
;
4603 sval
= is_jmp32
? (s64
)(s32
)val
: (s64
)val
;
4609 struct bpf_reg_state
*reg
=
4610 opcode
== BPF_JEQ
? true_reg
: false_reg
;
4612 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
4613 * if it is true we know the value for sure. Likewise for
4617 u64 old_v
= reg
->var_off
.value
;
4618 u64 hi_mask
= ~0xffffffffULL
;
4620 reg
->var_off
.value
= (old_v
& hi_mask
) | val
;
4621 reg
->var_off
.mask
&= hi_mask
;
4623 __mark_reg_known(reg
, val
);
4628 false_reg
->var_off
= tnum_and(false_reg
->var_off
,
4630 if (is_power_of_2(val
))
4631 true_reg
->var_off
= tnum_or(true_reg
->var_off
,
4637 u64 false_umax
= opcode
== BPF_JGT
? val
: val
- 1;
4638 u64 true_umin
= opcode
== BPF_JGT
? val
+ 1 : val
;
4641 false_umax
+= gen_hi_max(false_reg
->var_off
);
4642 true_umin
+= gen_hi_min(true_reg
->var_off
);
4644 false_reg
->umax_value
= min(false_reg
->umax_value
, false_umax
);
4645 true_reg
->umin_value
= max(true_reg
->umin_value
, true_umin
);
4651 s64 false_smax
= opcode
== BPF_JSGT
? sval
: sval
- 1;
4652 s64 true_smin
= opcode
== BPF_JSGT
? sval
+ 1 : sval
;
4654 /* If the full s64 was not sign-extended from s32 then don't
4655 * deduct further info.
4657 if (is_jmp32
&& !cmp_val_with_extended_s64(sval
, false_reg
))
4659 false_reg
->smax_value
= min(false_reg
->smax_value
, false_smax
);
4660 true_reg
->smin_value
= max(true_reg
->smin_value
, true_smin
);
4666 u64 false_umin
= opcode
== BPF_JLT
? val
: val
+ 1;
4667 u64 true_umax
= opcode
== BPF_JLT
? val
- 1 : val
;
4670 false_umin
+= gen_hi_min(false_reg
->var_off
);
4671 true_umax
+= gen_hi_max(true_reg
->var_off
);
4673 false_reg
->umin_value
= max(false_reg
->umin_value
, false_umin
);
4674 true_reg
->umax_value
= min(true_reg
->umax_value
, true_umax
);
4680 s64 false_smin
= opcode
== BPF_JSLT
? sval
: sval
+ 1;
4681 s64 true_smax
= opcode
== BPF_JSLT
? sval
- 1 : sval
;
4683 if (is_jmp32
&& !cmp_val_with_extended_s64(sval
, false_reg
))
4685 false_reg
->smin_value
= max(false_reg
->smin_value
, false_smin
);
4686 true_reg
->smax_value
= min(true_reg
->smax_value
, true_smax
);
4693 __reg_deduce_bounds(false_reg
);
4694 __reg_deduce_bounds(true_reg
);
4695 /* We might have learned some bits from the bounds. */
4696 __reg_bound_offset(false_reg
);
4697 __reg_bound_offset(true_reg
);
4698 /* Intersecting with the old var_off might have improved our bounds
4699 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4700 * then new var_off is (0; 0x7f...fc) which improves our umax.
4702 __update_reg_bounds(false_reg
);
4703 __update_reg_bounds(true_reg
);
4706 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
4709 static void reg_set_min_max_inv(struct bpf_reg_state
*true_reg
,
4710 struct bpf_reg_state
*false_reg
, u64 val
,
4711 u8 opcode
, bool is_jmp32
)
4715 if (__is_pointer_value(false, false_reg
))
4718 val
= is_jmp32
? (u32
)val
: val
;
4719 sval
= is_jmp32
? (s64
)(s32
)val
: (s64
)val
;
4725 struct bpf_reg_state
*reg
=
4726 opcode
== BPF_JEQ
? true_reg
: false_reg
;
4729 u64 old_v
= reg
->var_off
.value
;
4730 u64 hi_mask
= ~0xffffffffULL
;
4732 reg
->var_off
.value
= (old_v
& hi_mask
) | val
;
4733 reg
->var_off
.mask
&= hi_mask
;
4735 __mark_reg_known(reg
, val
);
4740 false_reg
->var_off
= tnum_and(false_reg
->var_off
,
4742 if (is_power_of_2(val
))
4743 true_reg
->var_off
= tnum_or(true_reg
->var_off
,
4749 u64 false_umin
= opcode
== BPF_JGT
? val
: val
+ 1;
4750 u64 true_umax
= opcode
== BPF_JGT
? val
- 1 : val
;
4753 false_umin
+= gen_hi_min(false_reg
->var_off
);
4754 true_umax
+= gen_hi_max(true_reg
->var_off
);
4756 false_reg
->umin_value
= max(false_reg
->umin_value
, false_umin
);
4757 true_reg
->umax_value
= min(true_reg
->umax_value
, true_umax
);
4763 s64 false_smin
= opcode
== BPF_JSGT
? sval
: sval
+ 1;
4764 s64 true_smax
= opcode
== BPF_JSGT
? sval
- 1 : sval
;
4766 if (is_jmp32
&& !cmp_val_with_extended_s64(sval
, false_reg
))
4768 false_reg
->smin_value
= max(false_reg
->smin_value
, false_smin
);
4769 true_reg
->smax_value
= min(true_reg
->smax_value
, true_smax
);
4775 u64 false_umax
= opcode
== BPF_JLT
? val
: val
- 1;
4776 u64 true_umin
= opcode
== BPF_JLT
? val
+ 1 : val
;
4779 false_umax
+= gen_hi_max(false_reg
->var_off
);
4780 true_umin
+= gen_hi_min(true_reg
->var_off
);
4782 false_reg
->umax_value
= min(false_reg
->umax_value
, false_umax
);
4783 true_reg
->umin_value
= max(true_reg
->umin_value
, true_umin
);
4789 s64 false_smax
= opcode
== BPF_JSLT
? sval
: sval
- 1;
4790 s64 true_smin
= opcode
== BPF_JSLT
? sval
+ 1 : sval
;
4792 if (is_jmp32
&& !cmp_val_with_extended_s64(sval
, false_reg
))
4794 false_reg
->smax_value
= min(false_reg
->smax_value
, false_smax
);
4795 true_reg
->smin_value
= max(true_reg
->smin_value
, true_smin
);
4802 __reg_deduce_bounds(false_reg
);
4803 __reg_deduce_bounds(true_reg
);
4804 /* We might have learned some bits from the bounds. */
4805 __reg_bound_offset(false_reg
);
4806 __reg_bound_offset(true_reg
);
4807 /* Intersecting with the old var_off might have improved our bounds
4808 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4809 * then new var_off is (0; 0x7f...fc) which improves our umax.
4811 __update_reg_bounds(false_reg
);
4812 __update_reg_bounds(true_reg
);
4815 /* Regs are known to be equal, so intersect their min/max/var_off */
4816 static void __reg_combine_min_max(struct bpf_reg_state
*src_reg
,
4817 struct bpf_reg_state
*dst_reg
)
4819 src_reg
->umin_value
= dst_reg
->umin_value
= max(src_reg
->umin_value
,
4820 dst_reg
->umin_value
);
4821 src_reg
->umax_value
= dst_reg
->umax_value
= min(src_reg
->umax_value
,
4822 dst_reg
->umax_value
);
4823 src_reg
->smin_value
= dst_reg
->smin_value
= max(src_reg
->smin_value
,
4824 dst_reg
->smin_value
);
4825 src_reg
->smax_value
= dst_reg
->smax_value
= min(src_reg
->smax_value
,
4826 dst_reg
->smax_value
);
4827 src_reg
->var_off
= dst_reg
->var_off
= tnum_intersect(src_reg
->var_off
,
4829 /* We might have learned new bounds from the var_off. */
4830 __update_reg_bounds(src_reg
);
4831 __update_reg_bounds(dst_reg
);
4832 /* We might have learned something about the sign bit. */
4833 __reg_deduce_bounds(src_reg
);
4834 __reg_deduce_bounds(dst_reg
);
4835 /* We might have learned some bits from the bounds. */
4836 __reg_bound_offset(src_reg
);
4837 __reg_bound_offset(dst_reg
);
4838 /* Intersecting with the old var_off might have improved our bounds
4839 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4840 * then new var_off is (0; 0x7f...fc) which improves our umax.
4842 __update_reg_bounds(src_reg
);
4843 __update_reg_bounds(dst_reg
);
4846 static void reg_combine_min_max(struct bpf_reg_state
*true_src
,
4847 struct bpf_reg_state
*true_dst
,
4848 struct bpf_reg_state
*false_src
,
4849 struct bpf_reg_state
*false_dst
,
4854 __reg_combine_min_max(true_src
, true_dst
);
4857 __reg_combine_min_max(false_src
, false_dst
);
4862 static void mark_ptr_or_null_reg(struct bpf_func_state
*state
,
4863 struct bpf_reg_state
*reg
, u32 id
,
4866 if (reg_type_may_be_null(reg
->type
) && reg
->id
== id
) {
4867 /* Old offset (both fixed and variable parts) should
4868 * have been known-zero, because we don't allow pointer
4869 * arithmetic on pointers that might be NULL.
4871 if (WARN_ON_ONCE(reg
->smin_value
|| reg
->smax_value
||
4872 !tnum_equals_const(reg
->var_off
, 0) ||
4874 __mark_reg_known_zero(reg
);
4878 reg
->type
= SCALAR_VALUE
;
4879 } else if (reg
->type
== PTR_TO_MAP_VALUE_OR_NULL
) {
4880 if (reg
->map_ptr
->inner_map_meta
) {
4881 reg
->type
= CONST_PTR_TO_MAP
;
4882 reg
->map_ptr
= reg
->map_ptr
->inner_map_meta
;
4884 reg
->type
= PTR_TO_MAP_VALUE
;
4886 } else if (reg
->type
== PTR_TO_SOCKET_OR_NULL
) {
4887 reg
->type
= PTR_TO_SOCKET
;
4888 } else if (reg
->type
== PTR_TO_SOCK_COMMON_OR_NULL
) {
4889 reg
->type
= PTR_TO_SOCK_COMMON
;
4890 } else if (reg
->type
== PTR_TO_TCP_SOCK_OR_NULL
) {
4891 reg
->type
= PTR_TO_TCP_SOCK
;
4894 /* We don't need id and ref_obj_id from this point
4895 * onwards anymore, thus we should better reset it,
4896 * so that state pruning has chances to take effect.
4899 reg
->ref_obj_id
= 0;
4900 } else if (!reg_may_point_to_spin_lock(reg
)) {
4901 /* For not-NULL ptr, reg->ref_obj_id will be reset
4902 * in release_reg_references().
4904 * reg->id is still used by spin_lock ptr. Other
4905 * than spin_lock ptr type, reg->id can be reset.
4912 /* The logic is similar to find_good_pkt_pointers(), both could eventually
4913 * be folded together at some point.
4915 static void mark_ptr_or_null_regs(struct bpf_verifier_state
*vstate
, u32 regno
,
4918 struct bpf_func_state
*state
= vstate
->frame
[vstate
->curframe
];
4919 struct bpf_reg_state
*reg
, *regs
= state
->regs
;
4920 u32 ref_obj_id
= regs
[regno
].ref_obj_id
;
4921 u32 id
= regs
[regno
].id
;
4924 if (ref_obj_id
&& ref_obj_id
== id
&& is_null
)
4925 /* regs[regno] is in the " == NULL" branch.
4926 * No one could have freed the reference state before
4927 * doing the NULL check.
4929 WARN_ON_ONCE(release_reference_state(state
, id
));
4931 for (i
= 0; i
< MAX_BPF_REG
; i
++)
4932 mark_ptr_or_null_reg(state
, ®s
[i
], id
, is_null
);
4934 for (j
= 0; j
<= vstate
->curframe
; j
++) {
4935 state
= vstate
->frame
[j
];
4936 bpf_for_each_spilled_reg(i
, state
, reg
) {
4939 mark_ptr_or_null_reg(state
, reg
, id
, is_null
);
4944 static bool try_match_pkt_pointers(const struct bpf_insn
*insn
,
4945 struct bpf_reg_state
*dst_reg
,
4946 struct bpf_reg_state
*src_reg
,
4947 struct bpf_verifier_state
*this_branch
,
4948 struct bpf_verifier_state
*other_branch
)
4950 if (BPF_SRC(insn
->code
) != BPF_X
)
4953 /* Pointers are always 64-bit. */
4954 if (BPF_CLASS(insn
->code
) == BPF_JMP32
)
4957 switch (BPF_OP(insn
->code
)) {
4959 if ((dst_reg
->type
== PTR_TO_PACKET
&&
4960 src_reg
->type
== PTR_TO_PACKET_END
) ||
4961 (dst_reg
->type
== PTR_TO_PACKET_META
&&
4962 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
4963 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4964 find_good_pkt_pointers(this_branch
, dst_reg
,
4965 dst_reg
->type
, false);
4966 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
4967 src_reg
->type
== PTR_TO_PACKET
) ||
4968 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
4969 src_reg
->type
== PTR_TO_PACKET_META
)) {
4970 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4971 find_good_pkt_pointers(other_branch
, src_reg
,
4972 src_reg
->type
, true);
4978 if ((dst_reg
->type
== PTR_TO_PACKET
&&
4979 src_reg
->type
== PTR_TO_PACKET_END
) ||
4980 (dst_reg
->type
== PTR_TO_PACKET_META
&&
4981 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
4982 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4983 find_good_pkt_pointers(other_branch
, dst_reg
,
4984 dst_reg
->type
, true);
4985 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
4986 src_reg
->type
== PTR_TO_PACKET
) ||
4987 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
4988 src_reg
->type
== PTR_TO_PACKET_META
)) {
4989 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
4990 find_good_pkt_pointers(this_branch
, src_reg
,
4991 src_reg
->type
, false);
4997 if ((dst_reg
->type
== PTR_TO_PACKET
&&
4998 src_reg
->type
== PTR_TO_PACKET_END
) ||
4999 (dst_reg
->type
== PTR_TO_PACKET_META
&&
5000 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
5001 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
5002 find_good_pkt_pointers(this_branch
, dst_reg
,
5003 dst_reg
->type
, true);
5004 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
5005 src_reg
->type
== PTR_TO_PACKET
) ||
5006 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
5007 src_reg
->type
== PTR_TO_PACKET_META
)) {
5008 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
5009 find_good_pkt_pointers(other_branch
, src_reg
,
5010 src_reg
->type
, false);
5016 if ((dst_reg
->type
== PTR_TO_PACKET
&&
5017 src_reg
->type
== PTR_TO_PACKET_END
) ||
5018 (dst_reg
->type
== PTR_TO_PACKET_META
&&
5019 reg_is_init_pkt_pointer(src_reg
, PTR_TO_PACKET
))) {
5020 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
5021 find_good_pkt_pointers(other_branch
, dst_reg
,
5022 dst_reg
->type
, false);
5023 } else if ((dst_reg
->type
== PTR_TO_PACKET_END
&&
5024 src_reg
->type
== PTR_TO_PACKET
) ||
5025 (reg_is_init_pkt_pointer(dst_reg
, PTR_TO_PACKET
) &&
5026 src_reg
->type
== PTR_TO_PACKET_META
)) {
5027 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
5028 find_good_pkt_pointers(this_branch
, src_reg
,
5029 src_reg
->type
, true);
5041 static int check_cond_jmp_op(struct bpf_verifier_env
*env
,
5042 struct bpf_insn
*insn
, int *insn_idx
)
5044 struct bpf_verifier_state
*this_branch
= env
->cur_state
;
5045 struct bpf_verifier_state
*other_branch
;
5046 struct bpf_reg_state
*regs
= this_branch
->frame
[this_branch
->curframe
]->regs
;
5047 struct bpf_reg_state
*dst_reg
, *other_branch_regs
;
5048 u8 opcode
= BPF_OP(insn
->code
);
5052 /* Only conditional jumps are expected to reach here. */
5053 if (opcode
== BPF_JA
|| opcode
> BPF_JSLE
) {
5054 verbose(env
, "invalid BPF_JMP/JMP32 opcode %x\n", opcode
);
5058 if (BPF_SRC(insn
->code
) == BPF_X
) {
5059 if (insn
->imm
!= 0) {
5060 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
5064 /* check src1 operand */
5065 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
5069 if (is_pointer_value(env
, insn
->src_reg
)) {
5070 verbose(env
, "R%d pointer comparison prohibited\n",
5075 if (insn
->src_reg
!= BPF_REG_0
) {
5076 verbose(env
, "BPF_JMP/JMP32 uses reserved fields\n");
5081 /* check src2 operand */
5082 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
5086 dst_reg
= ®s
[insn
->dst_reg
];
5087 is_jmp32
= BPF_CLASS(insn
->code
) == BPF_JMP32
;
5089 if (BPF_SRC(insn
->code
) == BPF_K
) {
5090 int pred
= is_branch_taken(dst_reg
, insn
->imm
, opcode
,
5094 /* only follow the goto, ignore fall-through */
5095 *insn_idx
+= insn
->off
;
5097 } else if (pred
== 0) {
5098 /* only follow fall-through branch, since
5099 * that's where the program will go
5105 other_branch
= push_stack(env
, *insn_idx
+ insn
->off
+ 1, *insn_idx
,
5109 other_branch_regs
= other_branch
->frame
[other_branch
->curframe
]->regs
;
5111 /* detect if we are comparing against a constant value so we can adjust
5112 * our min/max values for our dst register.
5113 * this is only legit if both are scalars (or pointers to the same
5114 * object, I suppose, but we don't support that right now), because
5115 * otherwise the different base pointers mean the offsets aren't
5118 if (BPF_SRC(insn
->code
) == BPF_X
) {
5119 struct bpf_reg_state
*src_reg
= ®s
[insn
->src_reg
];
5120 struct bpf_reg_state lo_reg0
= *dst_reg
;
5121 struct bpf_reg_state lo_reg1
= *src_reg
;
5122 struct bpf_reg_state
*src_lo
, *dst_lo
;
5126 coerce_reg_to_size(dst_lo
, 4);
5127 coerce_reg_to_size(src_lo
, 4);
5129 if (dst_reg
->type
== SCALAR_VALUE
&&
5130 src_reg
->type
== SCALAR_VALUE
) {
5131 if (tnum_is_const(src_reg
->var_off
) ||
5132 (is_jmp32
&& tnum_is_const(src_lo
->var_off
)))
5133 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
5136 ? src_lo
->var_off
.value
5137 : src_reg
->var_off
.value
,
5139 else if (tnum_is_const(dst_reg
->var_off
) ||
5140 (is_jmp32
&& tnum_is_const(dst_lo
->var_off
)))
5141 reg_set_min_max_inv(&other_branch_regs
[insn
->src_reg
],
5144 ? dst_lo
->var_off
.value
5145 : dst_reg
->var_off
.value
,
5147 else if (!is_jmp32
&&
5148 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
))
5149 /* Comparing for equality, we can combine knowledge */
5150 reg_combine_min_max(&other_branch_regs
[insn
->src_reg
],
5151 &other_branch_regs
[insn
->dst_reg
],
5152 src_reg
, dst_reg
, opcode
);
5154 } else if (dst_reg
->type
== SCALAR_VALUE
) {
5155 reg_set_min_max(&other_branch_regs
[insn
->dst_reg
],
5156 dst_reg
, insn
->imm
, opcode
, is_jmp32
);
5159 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
5160 * NOTE: these optimizations below are related with pointer comparison
5161 * which will never be JMP32.
5163 if (!is_jmp32
&& BPF_SRC(insn
->code
) == BPF_K
&&
5164 insn
->imm
== 0 && (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
) &&
5165 reg_type_may_be_null(dst_reg
->type
)) {
5166 /* Mark all identical registers in each branch as either
5167 * safe or unknown depending R == 0 or R != 0 conditional.
5169 mark_ptr_or_null_regs(this_branch
, insn
->dst_reg
,
5171 mark_ptr_or_null_regs(other_branch
, insn
->dst_reg
,
5173 } else if (!try_match_pkt_pointers(insn
, dst_reg
, ®s
[insn
->src_reg
],
5174 this_branch
, other_branch
) &&
5175 is_pointer_value(env
, insn
->dst_reg
)) {
5176 verbose(env
, "R%d pointer comparison prohibited\n",
5180 if (env
->log
.level
& BPF_LOG_LEVEL
)
5181 print_verifier_state(env
, this_branch
->frame
[this_branch
->curframe
]);
5185 /* verify BPF_LD_IMM64 instruction */
5186 static int check_ld_imm(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
5188 struct bpf_insn_aux_data
*aux
= cur_aux(env
);
5189 struct bpf_reg_state
*regs
= cur_regs(env
);
5190 struct bpf_map
*map
;
5193 if (BPF_SIZE(insn
->code
) != BPF_DW
) {
5194 verbose(env
, "invalid BPF_LD_IMM insn\n");
5197 if (insn
->off
!= 0) {
5198 verbose(env
, "BPF_LD_IMM64 uses reserved fields\n");
5202 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP
);
5206 if (insn
->src_reg
== 0) {
5207 u64 imm
= ((u64
)(insn
+ 1)->imm
<< 32) | (u32
)insn
->imm
;
5209 regs
[insn
->dst_reg
].type
= SCALAR_VALUE
;
5210 __mark_reg_known(®s
[insn
->dst_reg
], imm
);
5214 map
= env
->used_maps
[aux
->map_index
];
5215 mark_reg_known_zero(env
, regs
, insn
->dst_reg
);
5216 regs
[insn
->dst_reg
].map_ptr
= map
;
5218 if (insn
->src_reg
== BPF_PSEUDO_MAP_VALUE
) {
5219 regs
[insn
->dst_reg
].type
= PTR_TO_MAP_VALUE
;
5220 regs
[insn
->dst_reg
].off
= aux
->map_off
;
5221 if (map_value_has_spin_lock(map
))
5222 regs
[insn
->dst_reg
].id
= ++env
->id_gen
;
5223 } else if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
5224 regs
[insn
->dst_reg
].type
= CONST_PTR_TO_MAP
;
5226 verbose(env
, "bpf verifier is misconfigured\n");
5233 static bool may_access_skb(enum bpf_prog_type type
)
5236 case BPF_PROG_TYPE_SOCKET_FILTER
:
5237 case BPF_PROG_TYPE_SCHED_CLS
:
5238 case BPF_PROG_TYPE_SCHED_ACT
:
5245 /* verify safety of LD_ABS|LD_IND instructions:
5246 * - they can only appear in the programs where ctx == skb
5247 * - since they are wrappers of function calls, they scratch R1-R5 registers,
5248 * preserve R6-R9, and store return value into R0
5251 * ctx == skb == R6 == CTX
5254 * SRC == any register
5255 * IMM == 32-bit immediate
5258 * R0 - 8/16/32-bit skb data converted to cpu endianness
5260 static int check_ld_abs(struct bpf_verifier_env
*env
, struct bpf_insn
*insn
)
5262 struct bpf_reg_state
*regs
= cur_regs(env
);
5263 u8 mode
= BPF_MODE(insn
->code
);
5266 if (!may_access_skb(env
->prog
->type
)) {
5267 verbose(env
, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
5271 if (!env
->ops
->gen_ld_abs
) {
5272 verbose(env
, "bpf verifier is misconfigured\n");
5276 if (env
->subprog_cnt
> 1) {
5277 /* when program has LD_ABS insn JITs and interpreter assume
5278 * that r1 == ctx == skb which is not the case for callees
5279 * that can have arbitrary arguments. It's problematic
5280 * for main prog as well since JITs would need to analyze
5281 * all functions in order to make proper register save/restore
5282 * decisions in the main prog. Hence disallow LD_ABS with calls
5284 verbose(env
, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
5288 if (insn
->dst_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
5289 BPF_SIZE(insn
->code
) == BPF_DW
||
5290 (mode
== BPF_ABS
&& insn
->src_reg
!= BPF_REG_0
)) {
5291 verbose(env
, "BPF_LD_[ABS|IND] uses reserved fields\n");
5295 /* check whether implicit source operand (register R6) is readable */
5296 err
= check_reg_arg(env
, BPF_REG_6
, SRC_OP
);
5300 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
5301 * gen_ld_abs() may terminate the program at runtime, leading to
5304 err
= check_reference_leak(env
);
5306 verbose(env
, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
5310 if (env
->cur_state
->active_spin_lock
) {
5311 verbose(env
, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
5315 if (regs
[BPF_REG_6
].type
!= PTR_TO_CTX
) {
5317 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
5321 if (mode
== BPF_IND
) {
5322 /* check explicit source operand */
5323 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
5328 /* reset caller saved regs to unreadable */
5329 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
5330 mark_reg_not_init(env
, regs
, caller_saved
[i
]);
5331 check_reg_arg(env
, caller_saved
[i
], DST_OP_NO_MARK
);
5334 /* mark destination R0 register as readable, since it contains
5335 * the value fetched from the packet.
5336 * Already marked as written above.
5338 mark_reg_unknown(env
, regs
, BPF_REG_0
);
5342 static int check_return_code(struct bpf_verifier_env
*env
)
5344 struct bpf_reg_state
*reg
;
5345 struct tnum range
= tnum_range(0, 1);
5347 switch (env
->prog
->type
) {
5348 case BPF_PROG_TYPE_CGROUP_SKB
:
5349 case BPF_PROG_TYPE_CGROUP_SOCK
:
5350 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR
:
5351 case BPF_PROG_TYPE_SOCK_OPS
:
5352 case BPF_PROG_TYPE_CGROUP_DEVICE
:
5353 case BPF_PROG_TYPE_CGROUP_SYSCTL
:
5359 reg
= cur_regs(env
) + BPF_REG_0
;
5360 if (reg
->type
!= SCALAR_VALUE
) {
5361 verbose(env
, "At program exit the register R0 is not a known value (%s)\n",
5362 reg_type_str
[reg
->type
]);
5366 if (!tnum_in(range
, reg
->var_off
)) {
5367 verbose(env
, "At program exit the register R0 ");
5368 if (!tnum_is_unknown(reg
->var_off
)) {
5371 tnum_strn(tn_buf
, sizeof(tn_buf
), reg
->var_off
);
5372 verbose(env
, "has value %s", tn_buf
);
5374 verbose(env
, "has unknown scalar value");
5376 verbose(env
, " should have been 0 or 1\n");
5382 /* non-recursive DFS pseudo code
5383 * 1 procedure DFS-iterative(G,v):
5384 * 2 label v as discovered
5385 * 3 let S be a stack
5387 * 5 while S is not empty
5389 * 7 if t is what we're looking for:
5391 * 9 for all edges e in G.adjacentEdges(t) do
5392 * 10 if edge e is already labelled
5393 * 11 continue with the next edge
5394 * 12 w <- G.adjacentVertex(t,e)
5395 * 13 if vertex w is not discovered and not explored
5396 * 14 label e as tree-edge
5397 * 15 label w as discovered
5400 * 18 else if vertex w is discovered
5401 * 19 label e as back-edge
5403 * 21 // vertex w is explored
5404 * 22 label e as forward- or cross-edge
5405 * 23 label t as explored
5410 * 0x11 - discovered and fall-through edge labelled
5411 * 0x12 - discovered and fall-through and branch edges labelled
5422 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
5424 /* t, w, e - match pseudo-code above:
5425 * t - index of current instruction
5426 * w - next instruction
5429 static int push_insn(int t
, int w
, int e
, struct bpf_verifier_env
*env
)
5431 int *insn_stack
= env
->cfg
.insn_stack
;
5432 int *insn_state
= env
->cfg
.insn_state
;
5434 if (e
== FALLTHROUGH
&& insn_state
[t
] >= (DISCOVERED
| FALLTHROUGH
))
5437 if (e
== BRANCH
&& insn_state
[t
] >= (DISCOVERED
| BRANCH
))
5440 if (w
< 0 || w
>= env
->prog
->len
) {
5441 verbose_linfo(env
, t
, "%d: ", t
);
5442 verbose(env
, "jump out of range from insn %d to %d\n", t
, w
);
5447 /* mark branch target for state pruning */
5448 env
->explored_states
[w
] = STATE_LIST_MARK
;
5450 if (insn_state
[w
] == 0) {
5452 insn_state
[t
] = DISCOVERED
| e
;
5453 insn_state
[w
] = DISCOVERED
;
5454 if (env
->cfg
.cur_stack
>= env
->prog
->len
)
5456 insn_stack
[env
->cfg
.cur_stack
++] = w
;
5458 } else if ((insn_state
[w
] & 0xF0) == DISCOVERED
) {
5459 verbose_linfo(env
, t
, "%d: ", t
);
5460 verbose_linfo(env
, w
, "%d: ", w
);
5461 verbose(env
, "back-edge from insn %d to %d\n", t
, w
);
5463 } else if (insn_state
[w
] == EXPLORED
) {
5464 /* forward- or cross-edge */
5465 insn_state
[t
] = DISCOVERED
| e
;
5467 verbose(env
, "insn state internal bug\n");
5473 /* non-recursive depth-first-search to detect loops in BPF program
5474 * loop == back-edge in directed graph
5476 static int check_cfg(struct bpf_verifier_env
*env
)
5478 struct bpf_insn
*insns
= env
->prog
->insnsi
;
5479 int insn_cnt
= env
->prog
->len
;
5480 int *insn_stack
, *insn_state
;
5484 insn_state
= env
->cfg
.insn_state
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
5488 insn_stack
= env
->cfg
.insn_stack
= kvcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
5494 insn_state
[0] = DISCOVERED
; /* mark 1st insn as discovered */
5495 insn_stack
[0] = 0; /* 0 is the first instruction */
5496 env
->cfg
.cur_stack
= 1;
5499 if (env
->cfg
.cur_stack
== 0)
5501 t
= insn_stack
[env
->cfg
.cur_stack
- 1];
5503 if (BPF_CLASS(insns
[t
].code
) == BPF_JMP
||
5504 BPF_CLASS(insns
[t
].code
) == BPF_JMP32
) {
5505 u8 opcode
= BPF_OP(insns
[t
].code
);
5507 if (opcode
== BPF_EXIT
) {
5509 } else if (opcode
== BPF_CALL
) {
5510 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
);
5515 if (t
+ 1 < insn_cnt
)
5516 env
->explored_states
[t
+ 1] = STATE_LIST_MARK
;
5517 if (insns
[t
].src_reg
== BPF_PSEUDO_CALL
) {
5518 env
->explored_states
[t
] = STATE_LIST_MARK
;
5519 ret
= push_insn(t
, t
+ insns
[t
].imm
+ 1, BRANCH
, env
);
5525 } else if (opcode
== BPF_JA
) {
5526 if (BPF_SRC(insns
[t
].code
) != BPF_K
) {
5530 /* unconditional jump with single edge */
5531 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1,
5537 /* tell verifier to check for equivalent states
5538 * after every call and jump
5540 if (t
+ 1 < insn_cnt
)
5541 env
->explored_states
[t
+ 1] = STATE_LIST_MARK
;
5543 /* conditional jump with two edges */
5544 env
->explored_states
[t
] = STATE_LIST_MARK
;
5545 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
);
5551 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1, BRANCH
, env
);
5558 /* all other non-branch instructions with single
5561 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
);
5569 insn_state
[t
] = EXPLORED
;
5570 if (env
->cfg
.cur_stack
-- <= 0) {
5571 verbose(env
, "pop stack internal bug\n");
5578 for (i
= 0; i
< insn_cnt
; i
++) {
5579 if (insn_state
[i
] != EXPLORED
) {
5580 verbose(env
, "unreachable insn %d\n", i
);
5585 ret
= 0; /* cfg looks good */
5590 env
->cfg
.insn_state
= env
->cfg
.insn_stack
= NULL
;
5594 /* The minimum supported BTF func info size */
5595 #define MIN_BPF_FUNCINFO_SIZE 8
5596 #define MAX_FUNCINFO_REC_SIZE 252
5598 static int check_btf_func(struct bpf_verifier_env
*env
,
5599 const union bpf_attr
*attr
,
5600 union bpf_attr __user
*uattr
)
5602 u32 i
, nfuncs
, urec_size
, min_size
;
5603 u32 krec_size
= sizeof(struct bpf_func_info
);
5604 struct bpf_func_info
*krecord
;
5605 const struct btf_type
*type
;
5606 struct bpf_prog
*prog
;
5607 const struct btf
*btf
;
5608 void __user
*urecord
;
5609 u32 prev_offset
= 0;
5612 nfuncs
= attr
->func_info_cnt
;
5616 if (nfuncs
!= env
->subprog_cnt
) {
5617 verbose(env
, "number of funcs in func_info doesn't match number of subprogs\n");
5621 urec_size
= attr
->func_info_rec_size
;
5622 if (urec_size
< MIN_BPF_FUNCINFO_SIZE
||
5623 urec_size
> MAX_FUNCINFO_REC_SIZE
||
5624 urec_size
% sizeof(u32
)) {
5625 verbose(env
, "invalid func info rec size %u\n", urec_size
);
5630 btf
= prog
->aux
->btf
;
5632 urecord
= u64_to_user_ptr(attr
->func_info
);
5633 min_size
= min_t(u32
, krec_size
, urec_size
);
5635 krecord
= kvcalloc(nfuncs
, krec_size
, GFP_KERNEL
| __GFP_NOWARN
);
5639 for (i
= 0; i
< nfuncs
; i
++) {
5640 ret
= bpf_check_uarg_tail_zero(urecord
, krec_size
, urec_size
);
5642 if (ret
== -E2BIG
) {
5643 verbose(env
, "nonzero tailing record in func info");
5644 /* set the size kernel expects so loader can zero
5645 * out the rest of the record.
5647 if (put_user(min_size
, &uattr
->func_info_rec_size
))
5653 if (copy_from_user(&krecord
[i
], urecord
, min_size
)) {
5658 /* check insn_off */
5660 if (krecord
[i
].insn_off
) {
5662 "nonzero insn_off %u for the first func info record",
5663 krecord
[i
].insn_off
);
5667 } else if (krecord
[i
].insn_off
<= prev_offset
) {
5669 "same or smaller insn offset (%u) than previous func info record (%u)",
5670 krecord
[i
].insn_off
, prev_offset
);
5675 if (env
->subprog_info
[i
].start
!= krecord
[i
].insn_off
) {
5676 verbose(env
, "func_info BTF section doesn't match subprog layout in BPF program\n");
5682 type
= btf_type_by_id(btf
, krecord
[i
].type_id
);
5683 if (!type
|| BTF_INFO_KIND(type
->info
) != BTF_KIND_FUNC
) {
5684 verbose(env
, "invalid type id %d in func info",
5685 krecord
[i
].type_id
);
5690 prev_offset
= krecord
[i
].insn_off
;
5691 urecord
+= urec_size
;
5694 prog
->aux
->func_info
= krecord
;
5695 prog
->aux
->func_info_cnt
= nfuncs
;
5703 static void adjust_btf_func(struct bpf_verifier_env
*env
)
5707 if (!env
->prog
->aux
->func_info
)
5710 for (i
= 0; i
< env
->subprog_cnt
; i
++)
5711 env
->prog
->aux
->func_info
[i
].insn_off
= env
->subprog_info
[i
].start
;
5714 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
5715 sizeof(((struct bpf_line_info *)(0))->line_col))
5716 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
5718 static int check_btf_line(struct bpf_verifier_env
*env
,
5719 const union bpf_attr
*attr
,
5720 union bpf_attr __user
*uattr
)
5722 u32 i
, s
, nr_linfo
, ncopy
, expected_size
, rec_size
, prev_offset
= 0;
5723 struct bpf_subprog_info
*sub
;
5724 struct bpf_line_info
*linfo
;
5725 struct bpf_prog
*prog
;
5726 const struct btf
*btf
;
5727 void __user
*ulinfo
;
5730 nr_linfo
= attr
->line_info_cnt
;
5734 rec_size
= attr
->line_info_rec_size
;
5735 if (rec_size
< MIN_BPF_LINEINFO_SIZE
||
5736 rec_size
> MAX_LINEINFO_REC_SIZE
||
5737 rec_size
& (sizeof(u32
) - 1))
5740 /* Need to zero it in case the userspace may
5741 * pass in a smaller bpf_line_info object.
5743 linfo
= kvcalloc(nr_linfo
, sizeof(struct bpf_line_info
),
5744 GFP_KERNEL
| __GFP_NOWARN
);
5749 btf
= prog
->aux
->btf
;
5752 sub
= env
->subprog_info
;
5753 ulinfo
= u64_to_user_ptr(attr
->line_info
);
5754 expected_size
= sizeof(struct bpf_line_info
);
5755 ncopy
= min_t(u32
, expected_size
, rec_size
);
5756 for (i
= 0; i
< nr_linfo
; i
++) {
5757 err
= bpf_check_uarg_tail_zero(ulinfo
, expected_size
, rec_size
);
5759 if (err
== -E2BIG
) {
5760 verbose(env
, "nonzero tailing record in line_info");
5761 if (put_user(expected_size
,
5762 &uattr
->line_info_rec_size
))
5768 if (copy_from_user(&linfo
[i
], ulinfo
, ncopy
)) {
5774 * Check insn_off to ensure
5775 * 1) strictly increasing AND
5776 * 2) bounded by prog->len
5778 * The linfo[0].insn_off == 0 check logically falls into
5779 * the later "missing bpf_line_info for func..." case
5780 * because the first linfo[0].insn_off must be the
5781 * first sub also and the first sub must have
5782 * subprog_info[0].start == 0.
5784 if ((i
&& linfo
[i
].insn_off
<= prev_offset
) ||
5785 linfo
[i
].insn_off
>= prog
->len
) {
5786 verbose(env
, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
5787 i
, linfo
[i
].insn_off
, prev_offset
,
5793 if (!prog
->insnsi
[linfo
[i
].insn_off
].code
) {
5795 "Invalid insn code at line_info[%u].insn_off\n",
5801 if (!btf_name_by_offset(btf
, linfo
[i
].line_off
) ||
5802 !btf_name_by_offset(btf
, linfo
[i
].file_name_off
)) {
5803 verbose(env
, "Invalid line_info[%u].line_off or .file_name_off\n", i
);
5808 if (s
!= env
->subprog_cnt
) {
5809 if (linfo
[i
].insn_off
== sub
[s
].start
) {
5810 sub
[s
].linfo_idx
= i
;
5812 } else if (sub
[s
].start
< linfo
[i
].insn_off
) {
5813 verbose(env
, "missing bpf_line_info for func#%u\n", s
);
5819 prev_offset
= linfo
[i
].insn_off
;
5823 if (s
!= env
->subprog_cnt
) {
5824 verbose(env
, "missing bpf_line_info for %u funcs starting from func#%u\n",
5825 env
->subprog_cnt
- s
, s
);
5830 prog
->aux
->linfo
= linfo
;
5831 prog
->aux
->nr_linfo
= nr_linfo
;
5840 static int check_btf_info(struct bpf_verifier_env
*env
,
5841 const union bpf_attr
*attr
,
5842 union bpf_attr __user
*uattr
)
5847 if (!attr
->func_info_cnt
&& !attr
->line_info_cnt
)
5850 btf
= btf_get_by_fd(attr
->prog_btf_fd
);
5852 return PTR_ERR(btf
);
5853 env
->prog
->aux
->btf
= btf
;
5855 err
= check_btf_func(env
, attr
, uattr
);
5859 err
= check_btf_line(env
, attr
, uattr
);
5866 /* check %cur's range satisfies %old's */
5867 static bool range_within(struct bpf_reg_state
*old
,
5868 struct bpf_reg_state
*cur
)
5870 return old
->umin_value
<= cur
->umin_value
&&
5871 old
->umax_value
>= cur
->umax_value
&&
5872 old
->smin_value
<= cur
->smin_value
&&
5873 old
->smax_value
>= cur
->smax_value
;
5876 /* Maximum number of register states that can exist at once */
5877 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
5883 /* If in the old state two registers had the same id, then they need to have
5884 * the same id in the new state as well. But that id could be different from
5885 * the old state, so we need to track the mapping from old to new ids.
5886 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
5887 * regs with old id 5 must also have new id 9 for the new state to be safe. But
5888 * regs with a different old id could still have new id 9, we don't care about
5890 * So we look through our idmap to see if this old id has been seen before. If
5891 * so, we require the new id to match; otherwise, we add the id pair to the map.
5893 static bool check_ids(u32 old_id
, u32 cur_id
, struct idpair
*idmap
)
5897 for (i
= 0; i
< ID_MAP_SIZE
; i
++) {
5898 if (!idmap
[i
].old
) {
5899 /* Reached an empty slot; haven't seen this id before */
5900 idmap
[i
].old
= old_id
;
5901 idmap
[i
].cur
= cur_id
;
5904 if (idmap
[i
].old
== old_id
)
5905 return idmap
[i
].cur
== cur_id
;
5907 /* We ran out of idmap slots, which should be impossible */
5912 static void clean_func_state(struct bpf_verifier_env
*env
,
5913 struct bpf_func_state
*st
)
5915 enum bpf_reg_liveness live
;
5918 for (i
= 0; i
< BPF_REG_FP
; i
++) {
5919 live
= st
->regs
[i
].live
;
5920 /* liveness must not touch this register anymore */
5921 st
->regs
[i
].live
|= REG_LIVE_DONE
;
5922 if (!(live
& REG_LIVE_READ
))
5923 /* since the register is unused, clear its state
5924 * to make further comparison simpler
5926 __mark_reg_not_init(&st
->regs
[i
]);
5929 for (i
= 0; i
< st
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
5930 live
= st
->stack
[i
].spilled_ptr
.live
;
5931 /* liveness must not touch this stack slot anymore */
5932 st
->stack
[i
].spilled_ptr
.live
|= REG_LIVE_DONE
;
5933 if (!(live
& REG_LIVE_READ
)) {
5934 __mark_reg_not_init(&st
->stack
[i
].spilled_ptr
);
5935 for (j
= 0; j
< BPF_REG_SIZE
; j
++)
5936 st
->stack
[i
].slot_type
[j
] = STACK_INVALID
;
5941 static void clean_verifier_state(struct bpf_verifier_env
*env
,
5942 struct bpf_verifier_state
*st
)
5946 if (st
->frame
[0]->regs
[0].live
& REG_LIVE_DONE
)
5947 /* all regs in this state in all frames were already marked */
5950 for (i
= 0; i
<= st
->curframe
; i
++)
5951 clean_func_state(env
, st
->frame
[i
]);
5954 /* the parentage chains form a tree.
5955 * the verifier states are added to state lists at given insn and
5956 * pushed into state stack for future exploration.
5957 * when the verifier reaches bpf_exit insn some of the verifer states
5958 * stored in the state lists have their final liveness state already,
5959 * but a lot of states will get revised from liveness point of view when
5960 * the verifier explores other branches.
5963 * 2: if r1 == 100 goto pc+1
5966 * when the verifier reaches exit insn the register r0 in the state list of
5967 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
5968 * of insn 2 and goes exploring further. At the insn 4 it will walk the
5969 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
5971 * Since the verifier pushes the branch states as it sees them while exploring
5972 * the program the condition of walking the branch instruction for the second
5973 * time means that all states below this branch were already explored and
5974 * their final liveness markes are already propagated.
5975 * Hence when the verifier completes the search of state list in is_state_visited()
5976 * we can call this clean_live_states() function to mark all liveness states
5977 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
5979 * This function also clears the registers and stack for states that !READ
5980 * to simplify state merging.
5982 * Important note here that walking the same branch instruction in the callee
5983 * doesn't meant that the states are DONE. The verifier has to compare
5986 static void clean_live_states(struct bpf_verifier_env
*env
, int insn
,
5987 struct bpf_verifier_state
*cur
)
5989 struct bpf_verifier_state_list
*sl
;
5992 sl
= env
->explored_states
[insn
];
5996 while (sl
!= STATE_LIST_MARK
) {
5997 if (sl
->state
.curframe
!= cur
->curframe
)
5999 for (i
= 0; i
<= cur
->curframe
; i
++)
6000 if (sl
->state
.frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
6002 clean_verifier_state(env
, &sl
->state
);
6008 /* Returns true if (rold safe implies rcur safe) */
6009 static bool regsafe(struct bpf_reg_state
*rold
, struct bpf_reg_state
*rcur
,
6010 struct idpair
*idmap
)
6014 if (!(rold
->live
& REG_LIVE_READ
))
6015 /* explored state didn't use this */
6018 equal
= memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, parent
)) == 0;
6020 if (rold
->type
== PTR_TO_STACK
)
6021 /* two stack pointers are equal only if they're pointing to
6022 * the same stack frame, since fp-8 in foo != fp-8 in bar
6024 return equal
&& rold
->frameno
== rcur
->frameno
;
6029 if (rold
->type
== NOT_INIT
)
6030 /* explored state can't have used this */
6032 if (rcur
->type
== NOT_INIT
)
6034 switch (rold
->type
) {
6036 if (rcur
->type
== SCALAR_VALUE
) {
6037 /* new val must satisfy old val knowledge */
6038 return range_within(rold
, rcur
) &&
6039 tnum_in(rold
->var_off
, rcur
->var_off
);
6041 /* We're trying to use a pointer in place of a scalar.
6042 * Even if the scalar was unbounded, this could lead to
6043 * pointer leaks because scalars are allowed to leak
6044 * while pointers are not. We could make this safe in
6045 * special cases if root is calling us, but it's
6046 * probably not worth the hassle.
6050 case PTR_TO_MAP_VALUE
:
6051 /* If the new min/max/var_off satisfy the old ones and
6052 * everything else matches, we are OK.
6053 * 'id' is not compared, since it's only used for maps with
6054 * bpf_spin_lock inside map element and in such cases if
6055 * the rest of the prog is valid for one map element then
6056 * it's valid for all map elements regardless of the key
6057 * used in bpf_map_lookup()
6059 return memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)) == 0 &&
6060 range_within(rold
, rcur
) &&
6061 tnum_in(rold
->var_off
, rcur
->var_off
);
6062 case PTR_TO_MAP_VALUE_OR_NULL
:
6063 /* a PTR_TO_MAP_VALUE could be safe to use as a
6064 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
6065 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
6066 * checked, doing so could have affected others with the same
6067 * id, and we can't check for that because we lost the id when
6068 * we converted to a PTR_TO_MAP_VALUE.
6070 if (rcur
->type
!= PTR_TO_MAP_VALUE_OR_NULL
)
6072 if (memcmp(rold
, rcur
, offsetof(struct bpf_reg_state
, id
)))
6074 /* Check our ids match any regs they're supposed to */
6075 return check_ids(rold
->id
, rcur
->id
, idmap
);
6076 case PTR_TO_PACKET_META
:
6078 if (rcur
->type
!= rold
->type
)
6080 /* We must have at least as much range as the old ptr
6081 * did, so that any accesses which were safe before are
6082 * still safe. This is true even if old range < old off,
6083 * since someone could have accessed through (ptr - k), or
6084 * even done ptr -= k in a register, to get a safe access.
6086 if (rold
->range
> rcur
->range
)
6088 /* If the offsets don't match, we can't trust our alignment;
6089 * nor can we be sure that we won't fall out of range.
6091 if (rold
->off
!= rcur
->off
)
6093 /* id relations must be preserved */
6094 if (rold
->id
&& !check_ids(rold
->id
, rcur
->id
, idmap
))
6096 /* new val must satisfy old val knowledge */
6097 return range_within(rold
, rcur
) &&
6098 tnum_in(rold
->var_off
, rcur
->var_off
);
6100 case CONST_PTR_TO_MAP
:
6101 case PTR_TO_PACKET_END
:
6102 case PTR_TO_FLOW_KEYS
:
6104 case PTR_TO_SOCKET_OR_NULL
:
6105 case PTR_TO_SOCK_COMMON
:
6106 case PTR_TO_SOCK_COMMON_OR_NULL
:
6107 case PTR_TO_TCP_SOCK
:
6108 case PTR_TO_TCP_SOCK_OR_NULL
:
6109 /* Only valid matches are exact, which memcmp() above
6110 * would have accepted
6113 /* Don't know what's going on, just say it's not safe */
6117 /* Shouldn't get here; if we do, say it's not safe */
6122 static bool stacksafe(struct bpf_func_state
*old
,
6123 struct bpf_func_state
*cur
,
6124 struct idpair
*idmap
)
6128 /* walk slots of the explored stack and ignore any additional
6129 * slots in the current stack, since explored(safe) state
6132 for (i
= 0; i
< old
->allocated_stack
; i
++) {
6133 spi
= i
/ BPF_REG_SIZE
;
6135 if (!(old
->stack
[spi
].spilled_ptr
.live
& REG_LIVE_READ
)) {
6136 i
+= BPF_REG_SIZE
- 1;
6137 /* explored state didn't use this */
6141 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_INVALID
)
6144 /* explored stack has more populated slots than current stack
6145 * and these slots were used
6147 if (i
>= cur
->allocated_stack
)
6150 /* if old state was safe with misc data in the stack
6151 * it will be safe with zero-initialized stack.
6152 * The opposite is not true
6154 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_MISC
&&
6155 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] == STACK_ZERO
)
6157 if (old
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
] !=
6158 cur
->stack
[spi
].slot_type
[i
% BPF_REG_SIZE
])
6159 /* Ex: old explored (safe) state has STACK_SPILL in
6160 * this stack slot, but current has has STACK_MISC ->
6161 * this verifier states are not equivalent,
6162 * return false to continue verification of this path
6165 if (i
% BPF_REG_SIZE
)
6167 if (old
->stack
[spi
].slot_type
[0] != STACK_SPILL
)
6169 if (!regsafe(&old
->stack
[spi
].spilled_ptr
,
6170 &cur
->stack
[spi
].spilled_ptr
,
6172 /* when explored and current stack slot are both storing
6173 * spilled registers, check that stored pointers types
6174 * are the same as well.
6175 * Ex: explored safe path could have stored
6176 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
6177 * but current path has stored:
6178 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
6179 * such verifier states are not equivalent.
6180 * return false to continue verification of this path
6187 static bool refsafe(struct bpf_func_state
*old
, struct bpf_func_state
*cur
)
6189 if (old
->acquired_refs
!= cur
->acquired_refs
)
6191 return !memcmp(old
->refs
, cur
->refs
,
6192 sizeof(*old
->refs
) * old
->acquired_refs
);
6195 /* compare two verifier states
6197 * all states stored in state_list are known to be valid, since
6198 * verifier reached 'bpf_exit' instruction through them
6200 * this function is called when verifier exploring different branches of
6201 * execution popped from the state stack. If it sees an old state that has
6202 * more strict register state and more strict stack state then this execution
6203 * branch doesn't need to be explored further, since verifier already
6204 * concluded that more strict state leads to valid finish.
6206 * Therefore two states are equivalent if register state is more conservative
6207 * and explored stack state is more conservative than the current one.
6210 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
6211 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
6213 * In other words if current stack state (one being explored) has more
6214 * valid slots than old one that already passed validation, it means
6215 * the verifier can stop exploring and conclude that current state is valid too
6217 * Similarly with registers. If explored state has register type as invalid
6218 * whereas register type in current state is meaningful, it means that
6219 * the current state will reach 'bpf_exit' instruction safely
6221 static bool func_states_equal(struct bpf_func_state
*old
,
6222 struct bpf_func_state
*cur
)
6224 struct idpair
*idmap
;
6228 idmap
= kcalloc(ID_MAP_SIZE
, sizeof(struct idpair
), GFP_KERNEL
);
6229 /* If we failed to allocate the idmap, just say it's not safe */
6233 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
6234 if (!regsafe(&old
->regs
[i
], &cur
->regs
[i
], idmap
))
6238 if (!stacksafe(old
, cur
, idmap
))
6241 if (!refsafe(old
, cur
))
6249 static bool states_equal(struct bpf_verifier_env
*env
,
6250 struct bpf_verifier_state
*old
,
6251 struct bpf_verifier_state
*cur
)
6255 if (old
->curframe
!= cur
->curframe
)
6258 /* Verification state from speculative execution simulation
6259 * must never prune a non-speculative execution one.
6261 if (old
->speculative
&& !cur
->speculative
)
6264 if (old
->active_spin_lock
!= cur
->active_spin_lock
)
6267 /* for states to be equal callsites have to be the same
6268 * and all frame states need to be equivalent
6270 for (i
= 0; i
<= old
->curframe
; i
++) {
6271 if (old
->frame
[i
]->callsite
!= cur
->frame
[i
]->callsite
)
6273 if (!func_states_equal(old
->frame
[i
], cur
->frame
[i
]))
6279 static int propagate_liveness_reg(struct bpf_verifier_env
*env
,
6280 struct bpf_reg_state
*reg
,
6281 struct bpf_reg_state
*parent_reg
)
6285 if (parent_reg
->live
& REG_LIVE_READ
|| !(reg
->live
& REG_LIVE_READ
))
6288 err
= mark_reg_read(env
, reg
, parent_reg
);
6295 /* A write screens off any subsequent reads; but write marks come from the
6296 * straight-line code between a state and its parent. When we arrive at an
6297 * equivalent state (jump target or such) we didn't arrive by the straight-line
6298 * code, so read marks in the state must propagate to the parent regardless
6299 * of the state's write marks. That's what 'parent == state->parent' comparison
6300 * in mark_reg_read() is for.
6302 static int propagate_liveness(struct bpf_verifier_env
*env
,
6303 const struct bpf_verifier_state
*vstate
,
6304 struct bpf_verifier_state
*vparent
)
6306 struct bpf_reg_state
*state_reg
, *parent_reg
;
6307 struct bpf_func_state
*state
, *parent
;
6308 int i
, frame
, err
= 0;
6310 if (vparent
->curframe
!= vstate
->curframe
) {
6311 WARN(1, "propagate_live: parent frame %d current frame %d\n",
6312 vparent
->curframe
, vstate
->curframe
);
6315 /* Propagate read liveness of registers... */
6316 BUILD_BUG_ON(BPF_REG_FP
+ 1 != MAX_BPF_REG
);
6317 for (frame
= 0; frame
<= vstate
->curframe
; frame
++) {
6318 parent
= vparent
->frame
[frame
];
6319 state
= vstate
->frame
[frame
];
6320 parent_reg
= parent
->regs
;
6321 state_reg
= state
->regs
;
6322 /* We don't need to worry about FP liveness, it's read-only */
6323 for (i
= frame
< vstate
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++) {
6324 err
= propagate_liveness_reg(env
, &state_reg
[i
],
6330 /* Propagate stack slots. */
6331 for (i
= 0; i
< state
->allocated_stack
/ BPF_REG_SIZE
&&
6332 i
< parent
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
6333 parent_reg
= &parent
->stack
[i
].spilled_ptr
;
6334 state_reg
= &state
->stack
[i
].spilled_ptr
;
6335 err
= propagate_liveness_reg(env
, state_reg
,
6344 static int is_state_visited(struct bpf_verifier_env
*env
, int insn_idx
)
6346 struct bpf_verifier_state_list
*new_sl
;
6347 struct bpf_verifier_state_list
*sl
, **pprev
;
6348 struct bpf_verifier_state
*cur
= env
->cur_state
, *new;
6349 int i
, j
, err
, states_cnt
= 0;
6351 pprev
= &env
->explored_states
[insn_idx
];
6355 /* this 'insn_idx' instruction wasn't marked, so we will not
6356 * be doing state search here
6360 clean_live_states(env
, insn_idx
, cur
);
6362 while (sl
!= STATE_LIST_MARK
) {
6363 if (states_equal(env
, &sl
->state
, cur
)) {
6365 /* reached equivalent register/stack state,
6367 * Registers read by the continuation are read by us.
6368 * If we have any write marks in env->cur_state, they
6369 * will prevent corresponding reads in the continuation
6370 * from reaching our parent (an explored_state). Our
6371 * own state will get the read marks recorded, but
6372 * they'll be immediately forgotten as we're pruning
6373 * this state and will pop a new one.
6375 err
= propagate_liveness(env
, &sl
->state
, cur
);
6382 /* heuristic to determine whether this state is beneficial
6383 * to keep checking from state equivalence point of view.
6384 * Higher numbers increase max_states_per_insn and verification time,
6385 * but do not meaningfully decrease insn_processed.
6387 if (sl
->miss_cnt
> sl
->hit_cnt
* 3 + 3) {
6388 /* the state is unlikely to be useful. Remove it to
6389 * speed up verification
6392 if (sl
->state
.frame
[0]->regs
[0].live
& REG_LIVE_DONE
) {
6393 free_verifier_state(&sl
->state
, false);
6397 /* cannot free this state, since parentage chain may
6398 * walk it later. Add it for free_list instead to
6399 * be freed at the end of verification
6401 sl
->next
= env
->free_list
;
6402 env
->free_list
= sl
;
6411 if (env
->max_states_per_insn
< states_cnt
)
6412 env
->max_states_per_insn
= states_cnt
;
6414 if (!env
->allow_ptr_leaks
&& states_cnt
> BPF_COMPLEXITY_LIMIT_STATES
)
6417 /* there were no equivalent states, remember current one.
6418 * technically the current state is not proven to be safe yet,
6419 * but it will either reach outer most bpf_exit (which means it's safe)
6420 * or it will be rejected. Since there are no loops, we won't be
6421 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
6422 * again on the way to bpf_exit
6424 new_sl
= kzalloc(sizeof(struct bpf_verifier_state_list
), GFP_KERNEL
);
6427 env
->total_states
++;
6430 /* add new state to the head of linked list */
6431 new = &new_sl
->state
;
6432 err
= copy_verifier_state(new, cur
);
6434 free_verifier_state(new, false);
6438 new_sl
->next
= env
->explored_states
[insn_idx
];
6439 env
->explored_states
[insn_idx
] = new_sl
;
6440 /* connect new state to parentage chain. Current frame needs all
6441 * registers connected. Only r6 - r9 of the callers are alive (pushed
6442 * to the stack implicitly by JITs) so in callers' frames connect just
6443 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
6444 * the state of the call instruction (with WRITTEN set), and r0 comes
6445 * from callee with its full parentage chain, anyway.
6447 for (j
= 0; j
<= cur
->curframe
; j
++)
6448 for (i
= j
< cur
->curframe
? BPF_REG_6
: 0; i
< BPF_REG_FP
; i
++)
6449 cur
->frame
[j
]->regs
[i
].parent
= &new->frame
[j
]->regs
[i
];
6450 /* clear write marks in current state: the writes we did are not writes
6451 * our child did, so they don't screen off its reads from us.
6452 * (There are no read marks in current state, because reads always mark
6453 * their parent and current state never has children yet. Only
6454 * explored_states can get read marks.)
6456 for (i
= 0; i
< BPF_REG_FP
; i
++)
6457 cur
->frame
[cur
->curframe
]->regs
[i
].live
= REG_LIVE_NONE
;
6459 /* all stack frames are accessible from callee, clear them all */
6460 for (j
= 0; j
<= cur
->curframe
; j
++) {
6461 struct bpf_func_state
*frame
= cur
->frame
[j
];
6462 struct bpf_func_state
*newframe
= new->frame
[j
];
6464 for (i
= 0; i
< frame
->allocated_stack
/ BPF_REG_SIZE
; i
++) {
6465 frame
->stack
[i
].spilled_ptr
.live
= REG_LIVE_NONE
;
6466 frame
->stack
[i
].spilled_ptr
.parent
=
6467 &newframe
->stack
[i
].spilled_ptr
;
6473 /* Return true if it's OK to have the same insn return a different type. */
6474 static bool reg_type_mismatch_ok(enum bpf_reg_type type
)
6479 case PTR_TO_SOCKET_OR_NULL
:
6480 case PTR_TO_SOCK_COMMON
:
6481 case PTR_TO_SOCK_COMMON_OR_NULL
:
6482 case PTR_TO_TCP_SOCK
:
6483 case PTR_TO_TCP_SOCK_OR_NULL
:
6490 /* If an instruction was previously used with particular pointer types, then we
6491 * need to be careful to avoid cases such as the below, where it may be ok
6492 * for one branch accessing the pointer, but not ok for the other branch:
6497 * R1 = some_other_valid_ptr;
6500 * R2 = *(u32 *)(R1 + 0);
6502 static bool reg_type_mismatch(enum bpf_reg_type src
, enum bpf_reg_type prev
)
6504 return src
!= prev
&& (!reg_type_mismatch_ok(src
) ||
6505 !reg_type_mismatch_ok(prev
));
6508 static int do_check(struct bpf_verifier_env
*env
)
6510 struct bpf_verifier_state
*state
;
6511 struct bpf_insn
*insns
= env
->prog
->insnsi
;
6512 struct bpf_reg_state
*regs
;
6513 int insn_cnt
= env
->prog
->len
;
6514 bool do_print_state
= false;
6516 env
->prev_linfo
= NULL
;
6518 state
= kzalloc(sizeof(struct bpf_verifier_state
), GFP_KERNEL
);
6521 state
->curframe
= 0;
6522 state
->speculative
= false;
6523 state
->frame
[0] = kzalloc(sizeof(struct bpf_func_state
), GFP_KERNEL
);
6524 if (!state
->frame
[0]) {
6528 env
->cur_state
= state
;
6529 init_func_state(env
, state
->frame
[0],
6530 BPF_MAIN_FUNC
/* callsite */,
6532 0 /* subprogno, zero == main subprog */);
6535 struct bpf_insn
*insn
;
6539 if (env
->insn_idx
>= insn_cnt
) {
6540 verbose(env
, "invalid insn idx %d insn_cnt %d\n",
6541 env
->insn_idx
, insn_cnt
);
6545 insn
= &insns
[env
->insn_idx
];
6546 class = BPF_CLASS(insn
->code
);
6548 if (++env
->insn_processed
> BPF_COMPLEXITY_LIMIT_INSNS
) {
6550 "BPF program is too large. Processed %d insn\n",
6551 env
->insn_processed
);
6555 err
= is_state_visited(env
, env
->insn_idx
);
6559 /* found equivalent state, can prune the search */
6560 if (env
->log
.level
& BPF_LOG_LEVEL
) {
6562 verbose(env
, "\nfrom %d to %d%s: safe\n",
6563 env
->prev_insn_idx
, env
->insn_idx
,
6564 env
->cur_state
->speculative
?
6565 " (speculative execution)" : "");
6567 verbose(env
, "%d: safe\n", env
->insn_idx
);
6569 goto process_bpf_exit
;
6572 if (signal_pending(current
))
6578 if (env
->log
.level
& BPF_LOG_LEVEL2
||
6579 (env
->log
.level
& BPF_LOG_LEVEL
&& do_print_state
)) {
6580 if (env
->log
.level
& BPF_LOG_LEVEL2
)
6581 verbose(env
, "%d:", env
->insn_idx
);
6583 verbose(env
, "\nfrom %d to %d%s:",
6584 env
->prev_insn_idx
, env
->insn_idx
,
6585 env
->cur_state
->speculative
?
6586 " (speculative execution)" : "");
6587 print_verifier_state(env
, state
->frame
[state
->curframe
]);
6588 do_print_state
= false;
6591 if (env
->log
.level
& BPF_LOG_LEVEL
) {
6592 const struct bpf_insn_cbs cbs
= {
6593 .cb_print
= verbose
,
6594 .private_data
= env
,
6597 verbose_linfo(env
, env
->insn_idx
, "; ");
6598 verbose(env
, "%d: ", env
->insn_idx
);
6599 print_bpf_insn(&cbs
, insn
, env
->allow_ptr_leaks
);
6602 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
6603 err
= bpf_prog_offload_verify_insn(env
, env
->insn_idx
,
6604 env
->prev_insn_idx
);
6609 regs
= cur_regs(env
);
6610 env
->insn_aux_data
[env
->insn_idx
].seen
= true;
6612 if (class == BPF_ALU
|| class == BPF_ALU64
) {
6613 err
= check_alu_op(env
, insn
);
6617 } else if (class == BPF_LDX
) {
6618 enum bpf_reg_type
*prev_src_type
, src_reg_type
;
6620 /* check for reserved fields is already done */
6622 /* check src operand */
6623 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6627 err
= check_reg_arg(env
, insn
->dst_reg
, DST_OP_NO_MARK
);
6631 src_reg_type
= regs
[insn
->src_reg
].type
;
6633 /* check that memory (src_reg + off) is readable,
6634 * the state of dst_reg will be updated by this func
6636 err
= check_mem_access(env
, env
->insn_idx
, insn
->src_reg
,
6637 insn
->off
, BPF_SIZE(insn
->code
),
6638 BPF_READ
, insn
->dst_reg
, false);
6642 prev_src_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
6644 if (*prev_src_type
== NOT_INIT
) {
6646 * dst_reg = *(u32 *)(src_reg + off)
6647 * save type to validate intersecting paths
6649 *prev_src_type
= src_reg_type
;
6651 } else if (reg_type_mismatch(src_reg_type
, *prev_src_type
)) {
6652 /* ABuser program is trying to use the same insn
6653 * dst_reg = *(u32*) (src_reg + off)
6654 * with different pointer types:
6655 * src_reg == ctx in one branch and
6656 * src_reg == stack|map in some other branch.
6659 verbose(env
, "same insn cannot be used with different pointers\n");
6663 } else if (class == BPF_STX
) {
6664 enum bpf_reg_type
*prev_dst_type
, dst_reg_type
;
6666 if (BPF_MODE(insn
->code
) == BPF_XADD
) {
6667 err
= check_xadd(env
, env
->insn_idx
, insn
);
6674 /* check src1 operand */
6675 err
= check_reg_arg(env
, insn
->src_reg
, SRC_OP
);
6678 /* check src2 operand */
6679 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6683 dst_reg_type
= regs
[insn
->dst_reg
].type
;
6685 /* check that memory (dst_reg + off) is writeable */
6686 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
6687 insn
->off
, BPF_SIZE(insn
->code
),
6688 BPF_WRITE
, insn
->src_reg
, false);
6692 prev_dst_type
= &env
->insn_aux_data
[env
->insn_idx
].ptr_type
;
6694 if (*prev_dst_type
== NOT_INIT
) {
6695 *prev_dst_type
= dst_reg_type
;
6696 } else if (reg_type_mismatch(dst_reg_type
, *prev_dst_type
)) {
6697 verbose(env
, "same insn cannot be used with different pointers\n");
6701 } else if (class == BPF_ST
) {
6702 if (BPF_MODE(insn
->code
) != BPF_MEM
||
6703 insn
->src_reg
!= BPF_REG_0
) {
6704 verbose(env
, "BPF_ST uses reserved fields\n");
6707 /* check src operand */
6708 err
= check_reg_arg(env
, insn
->dst_reg
, SRC_OP
);
6712 if (is_ctx_reg(env
, insn
->dst_reg
)) {
6713 verbose(env
, "BPF_ST stores into R%d %s is not allowed\n",
6715 reg_type_str
[reg_state(env
, insn
->dst_reg
)->type
]);
6719 /* check that memory (dst_reg + off) is writeable */
6720 err
= check_mem_access(env
, env
->insn_idx
, insn
->dst_reg
,
6721 insn
->off
, BPF_SIZE(insn
->code
),
6722 BPF_WRITE
, -1, false);
6726 } else if (class == BPF_JMP
|| class == BPF_JMP32
) {
6727 u8 opcode
= BPF_OP(insn
->code
);
6729 if (opcode
== BPF_CALL
) {
6730 if (BPF_SRC(insn
->code
) != BPF_K
||
6732 (insn
->src_reg
!= BPF_REG_0
&&
6733 insn
->src_reg
!= BPF_PSEUDO_CALL
) ||
6734 insn
->dst_reg
!= BPF_REG_0
||
6735 class == BPF_JMP32
) {
6736 verbose(env
, "BPF_CALL uses reserved fields\n");
6740 if (env
->cur_state
->active_spin_lock
&&
6741 (insn
->src_reg
== BPF_PSEUDO_CALL
||
6742 insn
->imm
!= BPF_FUNC_spin_unlock
)) {
6743 verbose(env
, "function calls are not allowed while holding a lock\n");
6746 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
6747 err
= check_func_call(env
, insn
, &env
->insn_idx
);
6749 err
= check_helper_call(env
, insn
->imm
, env
->insn_idx
);
6753 } else if (opcode
== BPF_JA
) {
6754 if (BPF_SRC(insn
->code
) != BPF_K
||
6756 insn
->src_reg
!= BPF_REG_0
||
6757 insn
->dst_reg
!= BPF_REG_0
||
6758 class == BPF_JMP32
) {
6759 verbose(env
, "BPF_JA uses reserved fields\n");
6763 env
->insn_idx
+= insn
->off
+ 1;
6766 } else if (opcode
== BPF_EXIT
) {
6767 if (BPF_SRC(insn
->code
) != BPF_K
||
6769 insn
->src_reg
!= BPF_REG_0
||
6770 insn
->dst_reg
!= BPF_REG_0
||
6771 class == BPF_JMP32
) {
6772 verbose(env
, "BPF_EXIT uses reserved fields\n");
6776 if (env
->cur_state
->active_spin_lock
) {
6777 verbose(env
, "bpf_spin_unlock is missing\n");
6781 if (state
->curframe
) {
6782 /* exit from nested function */
6783 env
->prev_insn_idx
= env
->insn_idx
;
6784 err
= prepare_func_exit(env
, &env
->insn_idx
);
6787 do_print_state
= true;
6791 err
= check_reference_leak(env
);
6795 /* eBPF calling convetion is such that R0 is used
6796 * to return the value from eBPF program.
6797 * Make sure that it's readable at this time
6798 * of bpf_exit, which means that program wrote
6799 * something into it earlier
6801 err
= check_reg_arg(env
, BPF_REG_0
, SRC_OP
);
6805 if (is_pointer_value(env
, BPF_REG_0
)) {
6806 verbose(env
, "R0 leaks addr as return value\n");
6810 err
= check_return_code(env
);
6814 err
= pop_stack(env
, &env
->prev_insn_idx
,
6821 do_print_state
= true;
6825 err
= check_cond_jmp_op(env
, insn
, &env
->insn_idx
);
6829 } else if (class == BPF_LD
) {
6830 u8 mode
= BPF_MODE(insn
->code
);
6832 if (mode
== BPF_ABS
|| mode
== BPF_IND
) {
6833 err
= check_ld_abs(env
, insn
);
6837 } else if (mode
== BPF_IMM
) {
6838 err
= check_ld_imm(env
, insn
);
6843 env
->insn_aux_data
[env
->insn_idx
].seen
= true;
6845 verbose(env
, "invalid BPF_LD mode\n");
6849 verbose(env
, "unknown insn class %d\n", class);
6856 env
->prog
->aux
->stack_depth
= env
->subprog_info
[0].stack_depth
;
6860 static int check_map_prealloc(struct bpf_map
*map
)
6862 return (map
->map_type
!= BPF_MAP_TYPE_HASH
&&
6863 map
->map_type
!= BPF_MAP_TYPE_PERCPU_HASH
&&
6864 map
->map_type
!= BPF_MAP_TYPE_HASH_OF_MAPS
) ||
6865 !(map
->map_flags
& BPF_F_NO_PREALLOC
);
6868 static bool is_tracing_prog_type(enum bpf_prog_type type
)
6871 case BPF_PROG_TYPE_KPROBE
:
6872 case BPF_PROG_TYPE_TRACEPOINT
:
6873 case BPF_PROG_TYPE_PERF_EVENT
:
6874 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
6881 static int check_map_prog_compatibility(struct bpf_verifier_env
*env
,
6882 struct bpf_map
*map
,
6883 struct bpf_prog
*prog
)
6886 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
6887 * preallocated hash maps, since doing memory allocation
6888 * in overflow_handler can crash depending on where nmi got
6891 if (prog
->type
== BPF_PROG_TYPE_PERF_EVENT
) {
6892 if (!check_map_prealloc(map
)) {
6893 verbose(env
, "perf_event programs can only use preallocated hash map\n");
6896 if (map
->inner_map_meta
&&
6897 !check_map_prealloc(map
->inner_map_meta
)) {
6898 verbose(env
, "perf_event programs can only use preallocated inner hash map\n");
6903 if ((is_tracing_prog_type(prog
->type
) ||
6904 prog
->type
== BPF_PROG_TYPE_SOCKET_FILTER
) &&
6905 map_value_has_spin_lock(map
)) {
6906 verbose(env
, "tracing progs cannot use bpf_spin_lock yet\n");
6910 if ((bpf_prog_is_dev_bound(prog
->aux
) || bpf_map_is_dev_bound(map
)) &&
6911 !bpf_offload_prog_map_match(prog
, map
)) {
6912 verbose(env
, "offload device mismatch between prog and map\n");
6919 static bool bpf_map_is_cgroup_storage(struct bpf_map
*map
)
6921 return (map
->map_type
== BPF_MAP_TYPE_CGROUP_STORAGE
||
6922 map
->map_type
== BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE
);
6925 /* look for pseudo eBPF instructions that access map FDs and
6926 * replace them with actual map pointers
6928 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env
*env
)
6930 struct bpf_insn
*insn
= env
->prog
->insnsi
;
6931 int insn_cnt
= env
->prog
->len
;
6934 err
= bpf_prog_calc_tag(env
->prog
);
6938 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
6939 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
6940 (BPF_MODE(insn
->code
) != BPF_MEM
|| insn
->imm
!= 0)) {
6941 verbose(env
, "BPF_LDX uses reserved fields\n");
6945 if (BPF_CLASS(insn
->code
) == BPF_STX
&&
6946 ((BPF_MODE(insn
->code
) != BPF_MEM
&&
6947 BPF_MODE(insn
->code
) != BPF_XADD
) || insn
->imm
!= 0)) {
6948 verbose(env
, "BPF_STX uses reserved fields\n");
6952 if (insn
[0].code
== (BPF_LD
| BPF_IMM
| BPF_DW
)) {
6953 struct bpf_insn_aux_data
*aux
;
6954 struct bpf_map
*map
;
6958 if (i
== insn_cnt
- 1 || insn
[1].code
!= 0 ||
6959 insn
[1].dst_reg
!= 0 || insn
[1].src_reg
!= 0 ||
6961 verbose(env
, "invalid bpf_ld_imm64 insn\n");
6965 if (insn
[0].src_reg
== 0)
6966 /* valid generic load 64-bit imm */
6969 /* In final convert_pseudo_ld_imm64() step, this is
6970 * converted into regular 64-bit imm load insn.
6972 if ((insn
[0].src_reg
!= BPF_PSEUDO_MAP_FD
&&
6973 insn
[0].src_reg
!= BPF_PSEUDO_MAP_VALUE
) ||
6974 (insn
[0].src_reg
== BPF_PSEUDO_MAP_FD
&&
6975 insn
[1].imm
!= 0)) {
6977 "unrecognized bpf_ld_imm64 insn\n");
6981 f
= fdget(insn
[0].imm
);
6982 map
= __bpf_map_get(f
);
6984 verbose(env
, "fd %d is not pointing to valid bpf_map\n",
6986 return PTR_ERR(map
);
6989 err
= check_map_prog_compatibility(env
, map
, env
->prog
);
6995 aux
= &env
->insn_aux_data
[i
];
6996 if (insn
->src_reg
== BPF_PSEUDO_MAP_FD
) {
6997 addr
= (unsigned long)map
;
6999 u32 off
= insn
[1].imm
;
7001 if (off
>= BPF_MAX_VAR_OFF
) {
7002 verbose(env
, "direct value offset of %u is not allowed\n", off
);
7007 if (!map
->ops
->map_direct_value_addr
) {
7008 verbose(env
, "no direct value access support for this map type\n");
7013 err
= map
->ops
->map_direct_value_addr(map
, &addr
, off
);
7015 verbose(env
, "invalid access to map value pointer, value_size=%u off=%u\n",
7016 map
->value_size
, off
);
7025 insn
[0].imm
= (u32
)addr
;
7026 insn
[1].imm
= addr
>> 32;
7028 /* check whether we recorded this map already */
7029 for (j
= 0; j
< env
->used_map_cnt
; j
++) {
7030 if (env
->used_maps
[j
] == map
) {
7037 if (env
->used_map_cnt
>= MAX_USED_MAPS
) {
7042 /* hold the map. If the program is rejected by verifier,
7043 * the map will be released by release_maps() or it
7044 * will be used by the valid program until it's unloaded
7045 * and all maps are released in free_used_maps()
7047 map
= bpf_map_inc(map
, false);
7050 return PTR_ERR(map
);
7053 aux
->map_index
= env
->used_map_cnt
;
7054 env
->used_maps
[env
->used_map_cnt
++] = map
;
7056 if (bpf_map_is_cgroup_storage(map
) &&
7057 bpf_cgroup_storage_assign(env
->prog
, map
)) {
7058 verbose(env
, "only one cgroup storage of each type is allowed\n");
7070 /* Basic sanity check before we invest more work here. */
7071 if (!bpf_opcode_in_insntable(insn
->code
)) {
7072 verbose(env
, "unknown opcode %02x\n", insn
->code
);
7077 /* now all pseudo BPF_LD_IMM64 instructions load valid
7078 * 'struct bpf_map *' into a register instead of user map_fd.
7079 * These pointers will be used later by verifier to validate map access.
7084 /* drop refcnt of maps used by the rejected program */
7085 static void release_maps(struct bpf_verifier_env
*env
)
7087 enum bpf_cgroup_storage_type stype
;
7090 for_each_cgroup_storage_type(stype
) {
7091 if (!env
->prog
->aux
->cgroup_storage
[stype
])
7093 bpf_cgroup_storage_release(env
->prog
,
7094 env
->prog
->aux
->cgroup_storage
[stype
]);
7097 for (i
= 0; i
< env
->used_map_cnt
; i
++)
7098 bpf_map_put(env
->used_maps
[i
]);
7101 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
7102 static void convert_pseudo_ld_imm64(struct bpf_verifier_env
*env
)
7104 struct bpf_insn
*insn
= env
->prog
->insnsi
;
7105 int insn_cnt
= env
->prog
->len
;
7108 for (i
= 0; i
< insn_cnt
; i
++, insn
++)
7109 if (insn
->code
== (BPF_LD
| BPF_IMM
| BPF_DW
))
7113 /* single env->prog->insni[off] instruction was replaced with the range
7114 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
7115 * [0, off) and [off, end) to new locations, so the patched range stays zero
7117 static int adjust_insn_aux_data(struct bpf_verifier_env
*env
, u32 prog_len
,
7120 struct bpf_insn_aux_data
*new_data
, *old_data
= env
->insn_aux_data
;
7125 new_data
= vzalloc(array_size(prog_len
,
7126 sizeof(struct bpf_insn_aux_data
)));
7129 memcpy(new_data
, old_data
, sizeof(struct bpf_insn_aux_data
) * off
);
7130 memcpy(new_data
+ off
+ cnt
- 1, old_data
+ off
,
7131 sizeof(struct bpf_insn_aux_data
) * (prog_len
- off
- cnt
+ 1));
7132 for (i
= off
; i
< off
+ cnt
- 1; i
++)
7133 new_data
[i
].seen
= true;
7134 env
->insn_aux_data
= new_data
;
7139 static void adjust_subprog_starts(struct bpf_verifier_env
*env
, u32 off
, u32 len
)
7145 /* NOTE: fake 'exit' subprog should be updated as well. */
7146 for (i
= 0; i
<= env
->subprog_cnt
; i
++) {
7147 if (env
->subprog_info
[i
].start
<= off
)
7149 env
->subprog_info
[i
].start
+= len
- 1;
7153 static struct bpf_prog
*bpf_patch_insn_data(struct bpf_verifier_env
*env
, u32 off
,
7154 const struct bpf_insn
*patch
, u32 len
)
7156 struct bpf_prog
*new_prog
;
7158 new_prog
= bpf_patch_insn_single(env
->prog
, off
, patch
, len
);
7159 if (IS_ERR(new_prog
)) {
7160 if (PTR_ERR(new_prog
) == -ERANGE
)
7162 "insn %d cannot be patched due to 16-bit range\n",
7163 env
->insn_aux_data
[off
].orig_idx
);
7166 if (adjust_insn_aux_data(env
, new_prog
->len
, off
, len
))
7168 adjust_subprog_starts(env
, off
, len
);
7172 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env
*env
,
7177 /* find first prog starting at or after off (first to remove) */
7178 for (i
= 0; i
< env
->subprog_cnt
; i
++)
7179 if (env
->subprog_info
[i
].start
>= off
)
7181 /* find first prog starting at or after off + cnt (first to stay) */
7182 for (j
= i
; j
< env
->subprog_cnt
; j
++)
7183 if (env
->subprog_info
[j
].start
>= off
+ cnt
)
7185 /* if j doesn't start exactly at off + cnt, we are just removing
7186 * the front of previous prog
7188 if (env
->subprog_info
[j
].start
!= off
+ cnt
)
7192 struct bpf_prog_aux
*aux
= env
->prog
->aux
;
7195 /* move fake 'exit' subprog as well */
7196 move
= env
->subprog_cnt
+ 1 - j
;
7198 memmove(env
->subprog_info
+ i
,
7199 env
->subprog_info
+ j
,
7200 sizeof(*env
->subprog_info
) * move
);
7201 env
->subprog_cnt
-= j
- i
;
7203 /* remove func_info */
7204 if (aux
->func_info
) {
7205 move
= aux
->func_info_cnt
- j
;
7207 memmove(aux
->func_info
+ i
,
7209 sizeof(*aux
->func_info
) * move
);
7210 aux
->func_info_cnt
-= j
- i
;
7211 /* func_info->insn_off is set after all code rewrites,
7212 * in adjust_btf_func() - no need to adjust
7216 /* convert i from "first prog to remove" to "first to adjust" */
7217 if (env
->subprog_info
[i
].start
== off
)
7221 /* update fake 'exit' subprog as well */
7222 for (; i
<= env
->subprog_cnt
; i
++)
7223 env
->subprog_info
[i
].start
-= cnt
;
7228 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env
*env
, u32 off
,
7231 struct bpf_prog
*prog
= env
->prog
;
7232 u32 i
, l_off
, l_cnt
, nr_linfo
;
7233 struct bpf_line_info
*linfo
;
7235 nr_linfo
= prog
->aux
->nr_linfo
;
7239 linfo
= prog
->aux
->linfo
;
7241 /* find first line info to remove, count lines to be removed */
7242 for (i
= 0; i
< nr_linfo
; i
++)
7243 if (linfo
[i
].insn_off
>= off
)
7248 for (; i
< nr_linfo
; i
++)
7249 if (linfo
[i
].insn_off
< off
+ cnt
)
7254 /* First live insn doesn't match first live linfo, it needs to "inherit"
7255 * last removed linfo. prog is already modified, so prog->len == off
7256 * means no live instructions after (tail of the program was removed).
7258 if (prog
->len
!= off
&& l_cnt
&&
7259 (i
== nr_linfo
|| linfo
[i
].insn_off
!= off
+ cnt
)) {
7261 linfo
[--i
].insn_off
= off
+ cnt
;
7264 /* remove the line info which refer to the removed instructions */
7266 memmove(linfo
+ l_off
, linfo
+ i
,
7267 sizeof(*linfo
) * (nr_linfo
- i
));
7269 prog
->aux
->nr_linfo
-= l_cnt
;
7270 nr_linfo
= prog
->aux
->nr_linfo
;
7273 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
7274 for (i
= l_off
; i
< nr_linfo
; i
++)
7275 linfo
[i
].insn_off
-= cnt
;
7277 /* fix up all subprogs (incl. 'exit') which start >= off */
7278 for (i
= 0; i
<= env
->subprog_cnt
; i
++)
7279 if (env
->subprog_info
[i
].linfo_idx
> l_off
) {
7280 /* program may have started in the removed region but
7281 * may not be fully removed
7283 if (env
->subprog_info
[i
].linfo_idx
>= l_off
+ l_cnt
)
7284 env
->subprog_info
[i
].linfo_idx
-= l_cnt
;
7286 env
->subprog_info
[i
].linfo_idx
= l_off
;
7292 static int verifier_remove_insns(struct bpf_verifier_env
*env
, u32 off
, u32 cnt
)
7294 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
7295 unsigned int orig_prog_len
= env
->prog
->len
;
7298 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
7299 bpf_prog_offload_remove_insns(env
, off
, cnt
);
7301 err
= bpf_remove_insns(env
->prog
, off
, cnt
);
7305 err
= adjust_subprog_starts_after_remove(env
, off
, cnt
);
7309 err
= bpf_adj_linfo_after_remove(env
, off
, cnt
);
7313 memmove(aux_data
+ off
, aux_data
+ off
+ cnt
,
7314 sizeof(*aux_data
) * (orig_prog_len
- off
- cnt
));
7319 /* The verifier does more data flow analysis than llvm and will not
7320 * explore branches that are dead at run time. Malicious programs can
7321 * have dead code too. Therefore replace all dead at-run-time code
7324 * Just nops are not optimal, e.g. if they would sit at the end of the
7325 * program and through another bug we would manage to jump there, then
7326 * we'd execute beyond program memory otherwise. Returning exception
7327 * code also wouldn't work since we can have subprogs where the dead
7328 * code could be located.
7330 static void sanitize_dead_code(struct bpf_verifier_env
*env
)
7332 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
7333 struct bpf_insn trap
= BPF_JMP_IMM(BPF_JA
, 0, 0, -1);
7334 struct bpf_insn
*insn
= env
->prog
->insnsi
;
7335 const int insn_cnt
= env
->prog
->len
;
7338 for (i
= 0; i
< insn_cnt
; i
++) {
7339 if (aux_data
[i
].seen
)
7341 memcpy(insn
+ i
, &trap
, sizeof(trap
));
7345 static bool insn_is_cond_jump(u8 code
)
7349 if (BPF_CLASS(code
) == BPF_JMP32
)
7352 if (BPF_CLASS(code
) != BPF_JMP
)
7356 return op
!= BPF_JA
&& op
!= BPF_EXIT
&& op
!= BPF_CALL
;
7359 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env
*env
)
7361 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
7362 struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
7363 struct bpf_insn
*insn
= env
->prog
->insnsi
;
7364 const int insn_cnt
= env
->prog
->len
;
7367 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
7368 if (!insn_is_cond_jump(insn
->code
))
7371 if (!aux_data
[i
+ 1].seen
)
7373 else if (!aux_data
[i
+ 1 + insn
->off
].seen
)
7378 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
7379 bpf_prog_offload_replace_insn(env
, i
, &ja
);
7381 memcpy(insn
, &ja
, sizeof(ja
));
7385 static int opt_remove_dead_code(struct bpf_verifier_env
*env
)
7387 struct bpf_insn_aux_data
*aux_data
= env
->insn_aux_data
;
7388 int insn_cnt
= env
->prog
->len
;
7391 for (i
= 0; i
< insn_cnt
; i
++) {
7395 while (i
+ j
< insn_cnt
&& !aux_data
[i
+ j
].seen
)
7400 err
= verifier_remove_insns(env
, i
, j
);
7403 insn_cnt
= env
->prog
->len
;
7409 static int opt_remove_nops(struct bpf_verifier_env
*env
)
7411 const struct bpf_insn ja
= BPF_JMP_IMM(BPF_JA
, 0, 0, 0);
7412 struct bpf_insn
*insn
= env
->prog
->insnsi
;
7413 int insn_cnt
= env
->prog
->len
;
7416 for (i
= 0; i
< insn_cnt
; i
++) {
7417 if (memcmp(&insn
[i
], &ja
, sizeof(ja
)))
7420 err
= verifier_remove_insns(env
, i
, 1);
7430 /* convert load instructions that access fields of a context type into a
7431 * sequence of instructions that access fields of the underlying structure:
7432 * struct __sk_buff -> struct sk_buff
7433 * struct bpf_sock_ops -> struct sock
7435 static int convert_ctx_accesses(struct bpf_verifier_env
*env
)
7437 const struct bpf_verifier_ops
*ops
= env
->ops
;
7438 int i
, cnt
, size
, ctx_field_size
, delta
= 0;
7439 const int insn_cnt
= env
->prog
->len
;
7440 struct bpf_insn insn_buf
[16], *insn
;
7441 u32 target_size
, size_default
, off
;
7442 struct bpf_prog
*new_prog
;
7443 enum bpf_access_type type
;
7444 bool is_narrower_load
;
7446 if (ops
->gen_prologue
|| env
->seen_direct_write
) {
7447 if (!ops
->gen_prologue
) {
7448 verbose(env
, "bpf verifier is misconfigured\n");
7451 cnt
= ops
->gen_prologue(insn_buf
, env
->seen_direct_write
,
7453 if (cnt
>= ARRAY_SIZE(insn_buf
)) {
7454 verbose(env
, "bpf verifier is misconfigured\n");
7457 new_prog
= bpf_patch_insn_data(env
, 0, insn_buf
, cnt
);
7461 env
->prog
= new_prog
;
7466 if (bpf_prog_is_dev_bound(env
->prog
->aux
))
7469 insn
= env
->prog
->insnsi
+ delta
;
7471 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
7472 bpf_convert_ctx_access_t convert_ctx_access
;
7474 if (insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_B
) ||
7475 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_H
) ||
7476 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_W
) ||
7477 insn
->code
== (BPF_LDX
| BPF_MEM
| BPF_DW
))
7479 else if (insn
->code
== (BPF_STX
| BPF_MEM
| BPF_B
) ||
7480 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_H
) ||
7481 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_W
) ||
7482 insn
->code
== (BPF_STX
| BPF_MEM
| BPF_DW
))
7487 if (type
== BPF_WRITE
&&
7488 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
) {
7489 struct bpf_insn patch
[] = {
7490 /* Sanitize suspicious stack slot with zero.
7491 * There are no memory dependencies for this store,
7492 * since it's only using frame pointer and immediate
7495 BPF_ST_MEM(BPF_DW
, BPF_REG_FP
,
7496 env
->insn_aux_data
[i
+ delta
].sanitize_stack_off
,
7498 /* the original STX instruction will immediately
7499 * overwrite the same stack slot with appropriate value
7504 cnt
= ARRAY_SIZE(patch
);
7505 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patch
, cnt
);
7510 env
->prog
= new_prog
;
7511 insn
= new_prog
->insnsi
+ i
+ delta
;
7515 switch (env
->insn_aux_data
[i
+ delta
].ptr_type
) {
7517 if (!ops
->convert_ctx_access
)
7519 convert_ctx_access
= ops
->convert_ctx_access
;
7522 case PTR_TO_SOCK_COMMON
:
7523 convert_ctx_access
= bpf_sock_convert_ctx_access
;
7525 case PTR_TO_TCP_SOCK
:
7526 convert_ctx_access
= bpf_tcp_sock_convert_ctx_access
;
7532 ctx_field_size
= env
->insn_aux_data
[i
+ delta
].ctx_field_size
;
7533 size
= BPF_LDST_BYTES(insn
);
7535 /* If the read access is a narrower load of the field,
7536 * convert to a 4/8-byte load, to minimum program type specific
7537 * convert_ctx_access changes. If conversion is successful,
7538 * we will apply proper mask to the result.
7540 is_narrower_load
= size
< ctx_field_size
;
7541 size_default
= bpf_ctx_off_adjust_machine(ctx_field_size
);
7543 if (is_narrower_load
) {
7546 if (type
== BPF_WRITE
) {
7547 verbose(env
, "bpf verifier narrow ctx access misconfigured\n");
7552 if (ctx_field_size
== 4)
7554 else if (ctx_field_size
== 8)
7557 insn
->off
= off
& ~(size_default
- 1);
7558 insn
->code
= BPF_LDX
| BPF_MEM
| size_code
;
7562 cnt
= convert_ctx_access(type
, insn
, insn_buf
, env
->prog
,
7564 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
) ||
7565 (ctx_field_size
&& !target_size
)) {
7566 verbose(env
, "bpf verifier is misconfigured\n");
7570 if (is_narrower_load
&& size
< target_size
) {
7571 u8 shift
= (off
& (size_default
- 1)) * 8;
7573 if (ctx_field_size
<= 4) {
7575 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_RSH
,
7578 insn_buf
[cnt
++] = BPF_ALU32_IMM(BPF_AND
, insn
->dst_reg
,
7579 (1 << size
* 8) - 1);
7582 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_RSH
,
7585 insn_buf
[cnt
++] = BPF_ALU64_IMM(BPF_AND
, insn
->dst_reg
,
7586 (1 << size
* 8) - 1);
7590 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
7596 /* keep walking new program and skip insns we just inserted */
7597 env
->prog
= new_prog
;
7598 insn
= new_prog
->insnsi
+ i
+ delta
;
7604 static int jit_subprogs(struct bpf_verifier_env
*env
)
7606 struct bpf_prog
*prog
= env
->prog
, **func
, *tmp
;
7607 int i
, j
, subprog_start
, subprog_end
= 0, len
, subprog
;
7608 struct bpf_insn
*insn
;
7612 if (env
->subprog_cnt
<= 1)
7615 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
7616 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
7617 insn
->src_reg
!= BPF_PSEUDO_CALL
)
7619 /* Upon error here we cannot fall back to interpreter but
7620 * need a hard reject of the program. Thus -EFAULT is
7621 * propagated in any case.
7623 subprog
= find_subprog(env
, i
+ insn
->imm
+ 1);
7625 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
7629 /* temporarily remember subprog id inside insn instead of
7630 * aux_data, since next loop will split up all insns into funcs
7632 insn
->off
= subprog
;
7633 /* remember original imm in case JIT fails and fallback
7634 * to interpreter will be needed
7636 env
->insn_aux_data
[i
].call_imm
= insn
->imm
;
7637 /* point imm to __bpf_call_base+1 from JITs point of view */
7641 err
= bpf_prog_alloc_jited_linfo(prog
);
7646 func
= kcalloc(env
->subprog_cnt
, sizeof(prog
), GFP_KERNEL
);
7650 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
7651 subprog_start
= subprog_end
;
7652 subprog_end
= env
->subprog_info
[i
+ 1].start
;
7654 len
= subprog_end
- subprog_start
;
7655 /* BPF_PROG_RUN doesn't call subprogs directly,
7656 * hence main prog stats include the runtime of subprogs.
7657 * subprogs don't have IDs and not reachable via prog_get_next_id
7658 * func[i]->aux->stats will never be accessed and stays NULL
7660 func
[i
] = bpf_prog_alloc_no_stats(bpf_prog_size(len
), GFP_USER
);
7663 memcpy(func
[i
]->insnsi
, &prog
->insnsi
[subprog_start
],
7664 len
* sizeof(struct bpf_insn
));
7665 func
[i
]->type
= prog
->type
;
7667 if (bpf_prog_calc_tag(func
[i
]))
7669 func
[i
]->is_func
= 1;
7670 func
[i
]->aux
->func_idx
= i
;
7671 /* the btf and func_info will be freed only at prog->aux */
7672 func
[i
]->aux
->btf
= prog
->aux
->btf
;
7673 func
[i
]->aux
->func_info
= prog
->aux
->func_info
;
7675 /* Use bpf_prog_F_tag to indicate functions in stack traces.
7676 * Long term would need debug info to populate names
7678 func
[i
]->aux
->name
[0] = 'F';
7679 func
[i
]->aux
->stack_depth
= env
->subprog_info
[i
].stack_depth
;
7680 func
[i
]->jit_requested
= 1;
7681 func
[i
]->aux
->linfo
= prog
->aux
->linfo
;
7682 func
[i
]->aux
->nr_linfo
= prog
->aux
->nr_linfo
;
7683 func
[i
]->aux
->jited_linfo
= prog
->aux
->jited_linfo
;
7684 func
[i
]->aux
->linfo_idx
= env
->subprog_info
[i
].linfo_idx
;
7685 func
[i
] = bpf_int_jit_compile(func
[i
]);
7686 if (!func
[i
]->jited
) {
7692 /* at this point all bpf functions were successfully JITed
7693 * now populate all bpf_calls with correct addresses and
7694 * run last pass of JIT
7696 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
7697 insn
= func
[i
]->insnsi
;
7698 for (j
= 0; j
< func
[i
]->len
; j
++, insn
++) {
7699 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
7700 insn
->src_reg
!= BPF_PSEUDO_CALL
)
7702 subprog
= insn
->off
;
7703 insn
->imm
= BPF_CAST_CALL(func
[subprog
]->bpf_func
) -
7707 /* we use the aux data to keep a list of the start addresses
7708 * of the JITed images for each function in the program
7710 * for some architectures, such as powerpc64, the imm field
7711 * might not be large enough to hold the offset of the start
7712 * address of the callee's JITed image from __bpf_call_base
7714 * in such cases, we can lookup the start address of a callee
7715 * by using its subprog id, available from the off field of
7716 * the call instruction, as an index for this list
7718 func
[i
]->aux
->func
= func
;
7719 func
[i
]->aux
->func_cnt
= env
->subprog_cnt
;
7721 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
7722 old_bpf_func
= func
[i
]->bpf_func
;
7723 tmp
= bpf_int_jit_compile(func
[i
]);
7724 if (tmp
!= func
[i
] || func
[i
]->bpf_func
!= old_bpf_func
) {
7725 verbose(env
, "JIT doesn't support bpf-to-bpf calls\n");
7732 /* finally lock prog and jit images for all functions and
7735 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
7736 bpf_prog_lock_ro(func
[i
]);
7737 bpf_prog_kallsyms_add(func
[i
]);
7740 /* Last step: make now unused interpreter insns from main
7741 * prog consistent for later dump requests, so they can
7742 * later look the same as if they were interpreted only.
7744 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
7745 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
7746 insn
->src_reg
!= BPF_PSEUDO_CALL
)
7748 insn
->off
= env
->insn_aux_data
[i
].call_imm
;
7749 subprog
= find_subprog(env
, i
+ insn
->off
+ 1);
7750 insn
->imm
= subprog
;
7754 prog
->bpf_func
= func
[0]->bpf_func
;
7755 prog
->aux
->func
= func
;
7756 prog
->aux
->func_cnt
= env
->subprog_cnt
;
7757 bpf_prog_free_unused_jited_linfo(prog
);
7760 for (i
= 0; i
< env
->subprog_cnt
; i
++)
7762 bpf_jit_free(func
[i
]);
7765 /* cleanup main prog to be interpreted */
7766 prog
->jit_requested
= 0;
7767 for (i
= 0, insn
= prog
->insnsi
; i
< prog
->len
; i
++, insn
++) {
7768 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
7769 insn
->src_reg
!= BPF_PSEUDO_CALL
)
7772 insn
->imm
= env
->insn_aux_data
[i
].call_imm
;
7774 bpf_prog_free_jited_linfo(prog
);
7778 static int fixup_call_args(struct bpf_verifier_env
*env
)
7780 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
7781 struct bpf_prog
*prog
= env
->prog
;
7782 struct bpf_insn
*insn
= prog
->insnsi
;
7787 if (env
->prog
->jit_requested
&&
7788 !bpf_prog_is_dev_bound(env
->prog
->aux
)) {
7789 err
= jit_subprogs(env
);
7795 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
7796 for (i
= 0; i
< prog
->len
; i
++, insn
++) {
7797 if (insn
->code
!= (BPF_JMP
| BPF_CALL
) ||
7798 insn
->src_reg
!= BPF_PSEUDO_CALL
)
7800 depth
= get_callee_stack_depth(env
, insn
, i
);
7803 bpf_patch_call_args(insn
, depth
);
7810 /* fixup insn->imm field of bpf_call instructions
7811 * and inline eligible helpers as explicit sequence of BPF instructions
7813 * this function is called after eBPF program passed verification
7815 static int fixup_bpf_calls(struct bpf_verifier_env
*env
)
7817 struct bpf_prog
*prog
= env
->prog
;
7818 struct bpf_insn
*insn
= prog
->insnsi
;
7819 const struct bpf_func_proto
*fn
;
7820 const int insn_cnt
= prog
->len
;
7821 const struct bpf_map_ops
*ops
;
7822 struct bpf_insn_aux_data
*aux
;
7823 struct bpf_insn insn_buf
[16];
7824 struct bpf_prog
*new_prog
;
7825 struct bpf_map
*map_ptr
;
7826 int i
, cnt
, delta
= 0;
7828 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
7829 if (insn
->code
== (BPF_ALU64
| BPF_MOD
| BPF_X
) ||
7830 insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
7831 insn
->code
== (BPF_ALU
| BPF_MOD
| BPF_X
) ||
7832 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
7833 bool is64
= BPF_CLASS(insn
->code
) == BPF_ALU64
;
7834 struct bpf_insn mask_and_div
[] = {
7835 BPF_MOV32_REG(insn
->src_reg
, insn
->src_reg
),
7837 BPF_JMP_IMM(BPF_JNE
, insn
->src_reg
, 0, 2),
7838 BPF_ALU32_REG(BPF_XOR
, insn
->dst_reg
, insn
->dst_reg
),
7839 BPF_JMP_IMM(BPF_JA
, 0, 0, 1),
7842 struct bpf_insn mask_and_mod
[] = {
7843 BPF_MOV32_REG(insn
->src_reg
, insn
->src_reg
),
7844 /* Rx mod 0 -> Rx */
7845 BPF_JMP_IMM(BPF_JEQ
, insn
->src_reg
, 0, 1),
7848 struct bpf_insn
*patchlet
;
7850 if (insn
->code
== (BPF_ALU64
| BPF_DIV
| BPF_X
) ||
7851 insn
->code
== (BPF_ALU
| BPF_DIV
| BPF_X
)) {
7852 patchlet
= mask_and_div
+ (is64
? 1 : 0);
7853 cnt
= ARRAY_SIZE(mask_and_div
) - (is64
? 1 : 0);
7855 patchlet
= mask_and_mod
+ (is64
? 1 : 0);
7856 cnt
= ARRAY_SIZE(mask_and_mod
) - (is64
? 1 : 0);
7859 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, patchlet
, cnt
);
7864 env
->prog
= prog
= new_prog
;
7865 insn
= new_prog
->insnsi
+ i
+ delta
;
7869 if (BPF_CLASS(insn
->code
) == BPF_LD
&&
7870 (BPF_MODE(insn
->code
) == BPF_ABS
||
7871 BPF_MODE(insn
->code
) == BPF_IND
)) {
7872 cnt
= env
->ops
->gen_ld_abs(insn
, insn_buf
);
7873 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
7874 verbose(env
, "bpf verifier is misconfigured\n");
7878 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
7883 env
->prog
= prog
= new_prog
;
7884 insn
= new_prog
->insnsi
+ i
+ delta
;
7888 if (insn
->code
== (BPF_ALU64
| BPF_ADD
| BPF_X
) ||
7889 insn
->code
== (BPF_ALU64
| BPF_SUB
| BPF_X
)) {
7890 const u8 code_add
= BPF_ALU64
| BPF_ADD
| BPF_X
;
7891 const u8 code_sub
= BPF_ALU64
| BPF_SUB
| BPF_X
;
7892 struct bpf_insn insn_buf
[16];
7893 struct bpf_insn
*patch
= &insn_buf
[0];
7897 aux
= &env
->insn_aux_data
[i
+ delta
];
7898 if (!aux
->alu_state
||
7899 aux
->alu_state
== BPF_ALU_NON_POINTER
)
7902 isneg
= aux
->alu_state
& BPF_ALU_NEG_VALUE
;
7903 issrc
= (aux
->alu_state
& BPF_ALU_SANITIZE
) ==
7904 BPF_ALU_SANITIZE_SRC
;
7906 off_reg
= issrc
? insn
->src_reg
: insn
->dst_reg
;
7908 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
7909 *patch
++ = BPF_MOV32_IMM(BPF_REG_AX
, aux
->alu_limit
- 1);
7910 *patch
++ = BPF_ALU64_REG(BPF_SUB
, BPF_REG_AX
, off_reg
);
7911 *patch
++ = BPF_ALU64_REG(BPF_OR
, BPF_REG_AX
, off_reg
);
7912 *patch
++ = BPF_ALU64_IMM(BPF_NEG
, BPF_REG_AX
, 0);
7913 *patch
++ = BPF_ALU64_IMM(BPF_ARSH
, BPF_REG_AX
, 63);
7915 *patch
++ = BPF_ALU64_REG(BPF_AND
, BPF_REG_AX
,
7917 insn
->src_reg
= BPF_REG_AX
;
7919 *patch
++ = BPF_ALU64_REG(BPF_AND
, off_reg
,
7923 insn
->code
= insn
->code
== code_add
?
7924 code_sub
: code_add
;
7927 *patch
++ = BPF_ALU64_IMM(BPF_MUL
, off_reg
, -1);
7928 cnt
= patch
- insn_buf
;
7930 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
7935 env
->prog
= prog
= new_prog
;
7936 insn
= new_prog
->insnsi
+ i
+ delta
;
7940 if (insn
->code
!= (BPF_JMP
| BPF_CALL
))
7942 if (insn
->src_reg
== BPF_PSEUDO_CALL
)
7945 if (insn
->imm
== BPF_FUNC_get_route_realm
)
7946 prog
->dst_needed
= 1;
7947 if (insn
->imm
== BPF_FUNC_get_prandom_u32
)
7948 bpf_user_rnd_init_once();
7949 if (insn
->imm
== BPF_FUNC_override_return
)
7950 prog
->kprobe_override
= 1;
7951 if (insn
->imm
== BPF_FUNC_tail_call
) {
7952 /* If we tail call into other programs, we
7953 * cannot make any assumptions since they can
7954 * be replaced dynamically during runtime in
7955 * the program array.
7957 prog
->cb_access
= 1;
7958 env
->prog
->aux
->stack_depth
= MAX_BPF_STACK
;
7959 env
->prog
->aux
->max_pkt_offset
= MAX_PACKET_OFF
;
7961 /* mark bpf_tail_call as different opcode to avoid
7962 * conditional branch in the interpeter for every normal
7963 * call and to prevent accidental JITing by JIT compiler
7964 * that doesn't support bpf_tail_call yet
7967 insn
->code
= BPF_JMP
| BPF_TAIL_CALL
;
7969 aux
= &env
->insn_aux_data
[i
+ delta
];
7970 if (!bpf_map_ptr_unpriv(aux
))
7973 /* instead of changing every JIT dealing with tail_call
7974 * emit two extra insns:
7975 * if (index >= max_entries) goto out;
7976 * index &= array->index_mask;
7977 * to avoid out-of-bounds cpu speculation
7979 if (bpf_map_ptr_poisoned(aux
)) {
7980 verbose(env
, "tail_call abusing map_ptr\n");
7984 map_ptr
= BPF_MAP_PTR(aux
->map_state
);
7985 insn_buf
[0] = BPF_JMP_IMM(BPF_JGE
, BPF_REG_3
,
7986 map_ptr
->max_entries
, 2);
7987 insn_buf
[1] = BPF_ALU32_IMM(BPF_AND
, BPF_REG_3
,
7988 container_of(map_ptr
,
7991 insn_buf
[2] = *insn
;
7993 new_prog
= bpf_patch_insn_data(env
, i
+ delta
, insn_buf
, cnt
);
7998 env
->prog
= prog
= new_prog
;
7999 insn
= new_prog
->insnsi
+ i
+ delta
;
8003 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
8004 * and other inlining handlers are currently limited to 64 bit
8007 if (prog
->jit_requested
&& BITS_PER_LONG
== 64 &&
8008 (insn
->imm
== BPF_FUNC_map_lookup_elem
||
8009 insn
->imm
== BPF_FUNC_map_update_elem
||
8010 insn
->imm
== BPF_FUNC_map_delete_elem
||
8011 insn
->imm
== BPF_FUNC_map_push_elem
||
8012 insn
->imm
== BPF_FUNC_map_pop_elem
||
8013 insn
->imm
== BPF_FUNC_map_peek_elem
)) {
8014 aux
= &env
->insn_aux_data
[i
+ delta
];
8015 if (bpf_map_ptr_poisoned(aux
))
8016 goto patch_call_imm
;
8018 map_ptr
= BPF_MAP_PTR(aux
->map_state
);
8020 if (insn
->imm
== BPF_FUNC_map_lookup_elem
&&
8021 ops
->map_gen_lookup
) {
8022 cnt
= ops
->map_gen_lookup(map_ptr
, insn_buf
);
8023 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
8024 verbose(env
, "bpf verifier is misconfigured\n");
8028 new_prog
= bpf_patch_insn_data(env
, i
+ delta
,
8034 env
->prog
= prog
= new_prog
;
8035 insn
= new_prog
->insnsi
+ i
+ delta
;
8039 BUILD_BUG_ON(!__same_type(ops
->map_lookup_elem
,
8040 (void *(*)(struct bpf_map
*map
, void *key
))NULL
));
8041 BUILD_BUG_ON(!__same_type(ops
->map_delete_elem
,
8042 (int (*)(struct bpf_map
*map
, void *key
))NULL
));
8043 BUILD_BUG_ON(!__same_type(ops
->map_update_elem
,
8044 (int (*)(struct bpf_map
*map
, void *key
, void *value
,
8046 BUILD_BUG_ON(!__same_type(ops
->map_push_elem
,
8047 (int (*)(struct bpf_map
*map
, void *value
,
8049 BUILD_BUG_ON(!__same_type(ops
->map_pop_elem
,
8050 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
8051 BUILD_BUG_ON(!__same_type(ops
->map_peek_elem
,
8052 (int (*)(struct bpf_map
*map
, void *value
))NULL
));
8054 switch (insn
->imm
) {
8055 case BPF_FUNC_map_lookup_elem
:
8056 insn
->imm
= BPF_CAST_CALL(ops
->map_lookup_elem
) -
8059 case BPF_FUNC_map_update_elem
:
8060 insn
->imm
= BPF_CAST_CALL(ops
->map_update_elem
) -
8063 case BPF_FUNC_map_delete_elem
:
8064 insn
->imm
= BPF_CAST_CALL(ops
->map_delete_elem
) -
8067 case BPF_FUNC_map_push_elem
:
8068 insn
->imm
= BPF_CAST_CALL(ops
->map_push_elem
) -
8071 case BPF_FUNC_map_pop_elem
:
8072 insn
->imm
= BPF_CAST_CALL(ops
->map_pop_elem
) -
8075 case BPF_FUNC_map_peek_elem
:
8076 insn
->imm
= BPF_CAST_CALL(ops
->map_peek_elem
) -
8081 goto patch_call_imm
;
8085 fn
= env
->ops
->get_func_proto(insn
->imm
, env
->prog
);
8086 /* all functions that have prototype and verifier allowed
8087 * programs to call them, must be real in-kernel functions
8091 "kernel subsystem misconfigured func %s#%d\n",
8092 func_id_name(insn
->imm
), insn
->imm
);
8095 insn
->imm
= fn
->func
- __bpf_call_base
;
8101 static void free_states(struct bpf_verifier_env
*env
)
8103 struct bpf_verifier_state_list
*sl
, *sln
;
8106 sl
= env
->free_list
;
8109 free_verifier_state(&sl
->state
, false);
8114 if (!env
->explored_states
)
8117 for (i
= 0; i
< env
->prog
->len
; i
++) {
8118 sl
= env
->explored_states
[i
];
8121 while (sl
!= STATE_LIST_MARK
) {
8123 free_verifier_state(&sl
->state
, false);
8129 kvfree(env
->explored_states
);
8132 static void print_verification_stats(struct bpf_verifier_env
*env
)
8136 if (env
->log
.level
& BPF_LOG_STATS
) {
8137 verbose(env
, "verification time %lld usec\n",
8138 div_u64(env
->verification_time
, 1000));
8139 verbose(env
, "stack depth ");
8140 for (i
= 0; i
< env
->subprog_cnt
; i
++) {
8141 u32 depth
= env
->subprog_info
[i
].stack_depth
;
8143 verbose(env
, "%d", depth
);
8144 if (i
+ 1 < env
->subprog_cnt
)
8149 verbose(env
, "processed %d insns (limit %d) max_states_per_insn %d "
8150 "total_states %d peak_states %d mark_read %d\n",
8151 env
->insn_processed
, BPF_COMPLEXITY_LIMIT_INSNS
,
8152 env
->max_states_per_insn
, env
->total_states
,
8153 env
->peak_states
, env
->longest_mark_read_walk
);
8156 int bpf_check(struct bpf_prog
**prog
, union bpf_attr
*attr
,
8157 union bpf_attr __user
*uattr
)
8159 u64 start_time
= ktime_get_ns();
8160 struct bpf_verifier_env
*env
;
8161 struct bpf_verifier_log
*log
;
8162 int i
, len
, ret
= -EINVAL
;
8165 /* no program is valid */
8166 if (ARRAY_SIZE(bpf_verifier_ops
) == 0)
8169 /* 'struct bpf_verifier_env' can be global, but since it's not small,
8170 * allocate/free it every time bpf_check() is called
8172 env
= kzalloc(sizeof(struct bpf_verifier_env
), GFP_KERNEL
);
8178 env
->insn_aux_data
=
8179 vzalloc(array_size(sizeof(struct bpf_insn_aux_data
), len
));
8181 if (!env
->insn_aux_data
)
8183 for (i
= 0; i
< len
; i
++)
8184 env
->insn_aux_data
[i
].orig_idx
= i
;
8186 env
->ops
= bpf_verifier_ops
[env
->prog
->type
];
8187 is_priv
= capable(CAP_SYS_ADMIN
);
8189 /* grab the mutex to protect few globals used by verifier */
8191 mutex_lock(&bpf_verifier_lock
);
8193 if (attr
->log_level
|| attr
->log_buf
|| attr
->log_size
) {
8194 /* user requested verbose verifier output
8195 * and supplied buffer to store the verification trace
8197 log
->level
= attr
->log_level
;
8198 log
->ubuf
= (char __user
*) (unsigned long) attr
->log_buf
;
8199 log
->len_total
= attr
->log_size
;
8202 /* log attributes have to be sane */
8203 if (log
->len_total
< 128 || log
->len_total
> UINT_MAX
>> 2 ||
8204 !log
->level
|| !log
->ubuf
|| log
->level
& ~BPF_LOG_MASK
)
8208 env
->strict_alignment
= !!(attr
->prog_flags
& BPF_F_STRICT_ALIGNMENT
);
8209 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
))
8210 env
->strict_alignment
= true;
8211 if (attr
->prog_flags
& BPF_F_ANY_ALIGNMENT
)
8212 env
->strict_alignment
= false;
8214 env
->allow_ptr_leaks
= is_priv
;
8216 ret
= replace_map_fd_with_map_ptr(env
);
8218 goto skip_full_check
;
8220 if (bpf_prog_is_dev_bound(env
->prog
->aux
)) {
8221 ret
= bpf_prog_offload_verifier_prep(env
->prog
);
8223 goto skip_full_check
;
8226 env
->explored_states
= kvcalloc(env
->prog
->len
,
8227 sizeof(struct bpf_verifier_state_list
*),
8230 if (!env
->explored_states
)
8231 goto skip_full_check
;
8233 ret
= check_subprogs(env
);
8235 goto skip_full_check
;
8237 ret
= check_btf_info(env
, attr
, uattr
);
8239 goto skip_full_check
;
8241 ret
= check_cfg(env
);
8243 goto skip_full_check
;
8245 ret
= do_check(env
);
8246 if (env
->cur_state
) {
8247 free_verifier_state(env
->cur_state
, true);
8248 env
->cur_state
= NULL
;
8251 if (ret
== 0 && bpf_prog_is_dev_bound(env
->prog
->aux
))
8252 ret
= bpf_prog_offload_finalize(env
);
8255 while (!pop_stack(env
, NULL
, NULL
));
8259 ret
= check_max_stack_depth(env
);
8261 /* instruction rewrites happen after this point */
8264 opt_hard_wire_dead_code_branches(env
);
8266 ret
= opt_remove_dead_code(env
);
8268 ret
= opt_remove_nops(env
);
8271 sanitize_dead_code(env
);
8275 /* program is valid, convert *(u32*)(ctx + off) accesses */
8276 ret
= convert_ctx_accesses(env
);
8279 ret
= fixup_bpf_calls(env
);
8282 ret
= fixup_call_args(env
);
8284 env
->verification_time
= ktime_get_ns() - start_time
;
8285 print_verification_stats(env
);
8287 if (log
->level
&& bpf_verifier_log_full(log
))
8289 if (log
->level
&& !log
->ubuf
) {
8291 goto err_release_maps
;
8294 if (ret
== 0 && env
->used_map_cnt
) {
8295 /* if program passed verifier, update used_maps in bpf_prog_info */
8296 env
->prog
->aux
->used_maps
= kmalloc_array(env
->used_map_cnt
,
8297 sizeof(env
->used_maps
[0]),
8300 if (!env
->prog
->aux
->used_maps
) {
8302 goto err_release_maps
;
8305 memcpy(env
->prog
->aux
->used_maps
, env
->used_maps
,
8306 sizeof(env
->used_maps
[0]) * env
->used_map_cnt
);
8307 env
->prog
->aux
->used_map_cnt
= env
->used_map_cnt
;
8309 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
8310 * bpf_ld_imm64 instructions
8312 convert_pseudo_ld_imm64(env
);
8316 adjust_btf_func(env
);
8319 if (!env
->prog
->aux
->used_maps
)
8320 /* if we didn't copy map pointers into bpf_prog_info, release
8321 * them now. Otherwise free_used_maps() will release them.
8327 mutex_unlock(&bpf_verifier_lock
);
8328 vfree(env
->insn_aux_data
);