1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5 */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <linux/bpf_mem_alloc.h>
30 #include <net/xdp.h>
31 #include <linux/trace_events.h>
32 #include <linux/kallsyms.h>
33
34 #include "disasm.h"
35
36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
38 [_id] = & _name ## _verifier_ops,
39 #define BPF_MAP_TYPE(_id, _ops)
40 #define BPF_LINK_TYPE(_id, _name)
41 #include <linux/bpf_types.h>
42 #undef BPF_PROG_TYPE
43 #undef BPF_MAP_TYPE
44 #undef BPF_LINK_TYPE
45 };
46
47 enum bpf_features {
48 BPF_FEAT_RDONLY_CAST_TO_VOID = 0,
49 BPF_FEAT_STREAMS = 1,
50 __MAX_BPF_FEAT,
51 };
52
53 struct bpf_mem_alloc bpf_global_percpu_ma;
54 static bool bpf_global_percpu_ma_set;
55
56 /* bpf_check() is a static code analyzer that walks eBPF program
57 * instruction by instruction and updates register/stack state.
58 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
59 *
60 * The first pass is depth-first-search to check that the program is a DAG.
61 * It rejects the following programs:
62 * - larger than BPF_MAXINSNS insns
63 * - if loop is present (detected via back-edge)
64 * - unreachable insns exist (shouldn't be a forest. program = one function)
65 * - out of bounds or malformed jumps
66 * The second pass is all possible path descent from the 1st insn.
67 * Since it's analyzing all paths through the program, the length of the
68 * analysis is limited to 64k insn, which may be hit even if total number of
69 * insn is less then 4K, but there are too many branches that change stack/regs.
70 * Number of 'branches to be analyzed' is limited to 1k
71 *
72 * On entry to each instruction, each register has a type, and the instruction
73 * changes the types of the registers depending on instruction semantics.
74 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
75 * copied to R1.
76 *
77 * All registers are 64-bit.
78 * R0 - return register
79 * R1-R5 argument passing registers
80 * R6-R9 callee saved registers
81 * R10 - frame pointer read-only
82 *
83 * At the start of BPF program the register R1 contains a pointer to bpf_context
84 * and has type PTR_TO_CTX.
85 *
86 * Verifier tracks arithmetic operations on pointers in case:
87 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
88 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
89 * 1st insn copies R10 (which has FRAME_PTR) type into R1
90 * and 2nd arithmetic instruction is pattern matched to recognize
91 * that it wants to construct a pointer to some element within stack.
92 * So after 2nd insn, the register R1 has type PTR_TO_STACK
93 * (and -20 constant is saved for further stack bounds checking).
94 * Meaning that this reg is a pointer to stack plus known immediate constant.
95 *
96 * Most of the time the registers have SCALAR_VALUE type, which
97 * means the register has some value, but it's not a valid pointer.
98 * (like pointer plus pointer becomes SCALAR_VALUE type)
99 *
100 * When verifier sees load or store instructions the type of base register
101 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
102 * four pointer types recognized by check_mem_access() function.
103 *
104 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
105 * and the range of [ptr, ptr + map's value_size) is accessible.
106 *
107 * registers used to pass values to function calls are checked against
108 * function argument constraints.
109 *
110 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
111 * It means that the register type passed to this function must be
112 * PTR_TO_STACK and it will be used inside the function as
113 * 'pointer to map element key'
114 *
115 * For example the argument constraints for bpf_map_lookup_elem():
116 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
117 * .arg1_type = ARG_CONST_MAP_PTR,
118 * .arg2_type = ARG_PTR_TO_MAP_KEY,
119 *
120 * ret_type says that this function returns 'pointer to map elem value or null'
121 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
122 * 2nd argument should be a pointer to stack, which will be used inside
123 * the helper function as a pointer to map element key.
124 *
125 * On the kernel side the helper function looks like:
126 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
127 * {
128 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
129 * void *key = (void *) (unsigned long) r2;
130 * void *value;
131 *
132 * here kernel can access 'key' and 'map' pointers safely, knowing that
133 * [key, key + map->key_size) bytes are valid and were initialized on
134 * the stack of eBPF program.
135 * }
136 *
137 * Corresponding eBPF program may look like:
138 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
139 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
140 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
141 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
142 * here verifier looks at prototype of map_lookup_elem() and sees:
143 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
144 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
145 *
146 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
147 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
148 * and were initialized prior to this call.
149 * If it's ok, then verifier allows this BPF_CALL insn and looks at
150 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
151 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
152 * returns either pointer to map value or NULL.
153 *
154 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
155 * insn, the register holding that pointer in the true branch changes state to
156 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
157 * branch. See check_cond_jmp_op().
158 *
159 * After the call R0 is set to return type of the function and registers R1-R5
160 * are set to NOT_INIT to indicate that they are no longer readable.
161 *
162 * The following reference types represent a potential reference to a kernel
163 * resource which, after first being allocated, must be checked and freed by
164 * the BPF program:
165 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
166 *
167 * When the verifier sees a helper call return a reference type, it allocates a
168 * pointer id for the reference and stores it in the current function state.
169 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
170 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
171 * passes through a NULL-check conditional. For the branch wherein the state is
172 * changed to CONST_IMM, the verifier releases the reference.
173 *
174 * For each helper function that allocates a reference, such as
175 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
176 * bpf_sk_release(). When a reference type passes into the release function,
177 * the verifier also releases the reference. If any unchecked or unreleased
178 * reference remains at the end of the program, the verifier rejects it.
179 */
180
181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
182 struct bpf_verifier_stack_elem {
183 /* verifier state is 'st'
184 * before processing instruction 'insn_idx'
185 * and after processing instruction 'prev_insn_idx'
186 */
187 struct bpf_verifier_state st;
188 int insn_idx;
189 int prev_insn_idx;
190 struct bpf_verifier_stack_elem *next;
191 /* length of verifier log at the time this state was pushed on stack */
192 u32 log_pos;
193 };
194
195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
196 #define BPF_COMPLEXITY_LIMIT_STATES 64
197
198 #define BPF_MAP_KEY_POISON (1ULL << 63)
199 #define BPF_MAP_KEY_SEEN (1ULL << 62)
200
201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512
202
203 #define BPF_PRIV_STACK_MIN_SIZE 64
204
205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx);
206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id);
207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
210 static int ref_set_non_owning(struct bpf_verifier_env *env,
211 struct bpf_reg_state *reg);
212 static bool is_trusted_reg(const struct bpf_reg_state *reg);
213
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)214 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
215 {
216 return aux->map_ptr_state.poison;
217 }
218
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)219 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
220 {
221 return aux->map_ptr_state.unpriv;
222 }
223
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,struct bpf_map * map,bool unpriv,bool poison)224 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
225 struct bpf_map *map,
226 bool unpriv, bool poison)
227 {
228 unpriv |= bpf_map_ptr_unpriv(aux);
229 aux->map_ptr_state.unpriv = unpriv;
230 aux->map_ptr_state.poison = poison;
231 aux->map_ptr_state.map_ptr = map;
232 }
233
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)234 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
235 {
236 return aux->map_key_state & BPF_MAP_KEY_POISON;
237 }
238
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)239 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
240 {
241 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
242 }
243
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)244 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
245 {
246 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
247 }
248
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)249 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
250 {
251 bool poisoned = bpf_map_key_poisoned(aux);
252
253 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
254 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
255 }
256
bpf_helper_call(const struct bpf_insn * insn)257 static bool bpf_helper_call(const struct bpf_insn *insn)
258 {
259 return insn->code == (BPF_JMP | BPF_CALL) &&
260 insn->src_reg == 0;
261 }
262
bpf_pseudo_call(const struct bpf_insn * insn)263 static bool bpf_pseudo_call(const struct bpf_insn *insn)
264 {
265 return insn->code == (BPF_JMP | BPF_CALL) &&
266 insn->src_reg == BPF_PSEUDO_CALL;
267 }
268
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)269 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
270 {
271 return insn->code == (BPF_JMP | BPF_CALL) &&
272 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
273 }
274
275 struct bpf_call_arg_meta {
276 struct bpf_map *map_ptr;
277 bool raw_mode;
278 bool pkt_access;
279 u8 release_regno;
280 int regno;
281 int access_size;
282 int mem_size;
283 u64 msize_max_value;
284 int ref_obj_id;
285 int dynptr_id;
286 int map_uid;
287 int func_id;
288 struct btf *btf;
289 u32 btf_id;
290 struct btf *ret_btf;
291 u32 ret_btf_id;
292 u32 subprogno;
293 struct btf_field *kptr_field;
294 s64 const_map_key;
295 };
296
297 struct bpf_kfunc_call_arg_meta {
298 /* In parameters */
299 struct btf *btf;
300 u32 func_id;
301 u32 kfunc_flags;
302 const struct btf_type *func_proto;
303 const char *func_name;
304 /* Out parameters */
305 u32 ref_obj_id;
306 u8 release_regno;
307 bool r0_rdonly;
308 u32 ret_btf_id;
309 u64 r0_size;
310 u32 subprogno;
311 struct {
312 u64 value;
313 bool found;
314 } arg_constant;
315
316 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
317 * generally to pass info about user-defined local kptr types to later
318 * verification logic
319 * bpf_obj_drop/bpf_percpu_obj_drop
320 * Record the local kptr type to be drop'd
321 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
322 * Record the local kptr type to be refcount_incr'd and use
323 * arg_owning_ref to determine whether refcount_acquire should be
324 * fallible
325 */
326 struct btf *arg_btf;
327 u32 arg_btf_id;
328 bool arg_owning_ref;
329 bool arg_prog;
330
331 struct {
332 struct btf_field *field;
333 } arg_list_head;
334 struct {
335 struct btf_field *field;
336 } arg_rbtree_root;
337 struct {
338 enum bpf_dynptr_type type;
339 u32 id;
340 u32 ref_obj_id;
341 } initialized_dynptr;
342 struct {
343 u8 spi;
344 u8 frameno;
345 } iter;
346 struct {
347 struct bpf_map *ptr;
348 int uid;
349 } map;
350 u64 mem_size;
351 };
352
353 struct btf *btf_vmlinux;
354
btf_type_name(const struct btf * btf,u32 id)355 static const char *btf_type_name(const struct btf *btf, u32 id)
356 {
357 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
358 }
359
360 static DEFINE_MUTEX(bpf_verifier_lock);
361 static DEFINE_MUTEX(bpf_percpu_ma_lock);
362
verbose(void * private_data,const char * fmt,...)363 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
364 {
365 struct bpf_verifier_env *env = private_data;
366 va_list args;
367
368 if (!bpf_verifier_log_needed(&env->log))
369 return;
370
371 va_start(args, fmt);
372 bpf_verifier_vlog(&env->log, fmt, args);
373 va_end(args);
374 }
375
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_retval_range range,const char * ctx,const char * reg_name)376 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
377 struct bpf_reg_state *reg,
378 struct bpf_retval_range range, const char *ctx,
379 const char *reg_name)
380 {
381 bool unknown = true;
382
383 verbose(env, "%s the register %s has", ctx, reg_name);
384 if (reg->smin_value > S64_MIN) {
385 verbose(env, " smin=%lld", reg->smin_value);
386 unknown = false;
387 }
388 if (reg->smax_value < S64_MAX) {
389 verbose(env, " smax=%lld", reg->smax_value);
390 unknown = false;
391 }
392 if (unknown)
393 verbose(env, " unknown scalar value");
394 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval);
395 }
396
reg_not_null(const struct bpf_reg_state * reg)397 static bool reg_not_null(const struct bpf_reg_state *reg)
398 {
399 enum bpf_reg_type type;
400
401 type = reg->type;
402 if (type_may_be_null(type))
403 return false;
404
405 type = base_type(type);
406 return type == PTR_TO_SOCKET ||
407 type == PTR_TO_TCP_SOCK ||
408 type == PTR_TO_MAP_VALUE ||
409 type == PTR_TO_MAP_KEY ||
410 type == PTR_TO_SOCK_COMMON ||
411 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
412 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) ||
413 type == CONST_PTR_TO_MAP;
414 }
415
reg_btf_record(const struct bpf_reg_state * reg)416 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
417 {
418 struct btf_record *rec = NULL;
419 struct btf_struct_meta *meta;
420
421 if (reg->type == PTR_TO_MAP_VALUE) {
422 rec = reg->map_ptr->record;
423 } else if (type_is_ptr_alloc_obj(reg->type)) {
424 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
425 if (meta)
426 rec = meta->record;
427 }
428 return rec;
429 }
430
subprog_is_global(const struct bpf_verifier_env * env,int subprog)431 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
432 {
433 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
434
435 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
436 }
437
subprog_name(const struct bpf_verifier_env * env,int subprog)438 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
439 {
440 struct bpf_func_info *info;
441
442 if (!env->prog->aux->func_info)
443 return "";
444
445 info = &env->prog->aux->func_info[subprog];
446 return btf_type_name(env->prog->aux->btf, info->type_id);
447 }
448
mark_subprog_exc_cb(struct bpf_verifier_env * env,int subprog)449 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
450 {
451 struct bpf_subprog_info *info = subprog_info(env, subprog);
452
453 info->is_cb = true;
454 info->is_async_cb = true;
455 info->is_exception_cb = true;
456 }
457
subprog_is_exc_cb(struct bpf_verifier_env * env,int subprog)458 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
459 {
460 return subprog_info(env, subprog)->is_exception_cb;
461 }
462
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)463 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
464 {
465 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK);
466 }
467
type_is_rdonly_mem(u32 type)468 static bool type_is_rdonly_mem(u32 type)
469 {
470 return type & MEM_RDONLY;
471 }
472
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)473 static bool is_acquire_function(enum bpf_func_id func_id,
474 const struct bpf_map *map)
475 {
476 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
477
478 if (func_id == BPF_FUNC_sk_lookup_tcp ||
479 func_id == BPF_FUNC_sk_lookup_udp ||
480 func_id == BPF_FUNC_skc_lookup_tcp ||
481 func_id == BPF_FUNC_ringbuf_reserve ||
482 func_id == BPF_FUNC_kptr_xchg)
483 return true;
484
485 if (func_id == BPF_FUNC_map_lookup_elem &&
486 (map_type == BPF_MAP_TYPE_SOCKMAP ||
487 map_type == BPF_MAP_TYPE_SOCKHASH))
488 return true;
489
490 return false;
491 }
492
is_ptr_cast_function(enum bpf_func_id func_id)493 static bool is_ptr_cast_function(enum bpf_func_id func_id)
494 {
495 return func_id == BPF_FUNC_tcp_sock ||
496 func_id == BPF_FUNC_sk_fullsock ||
497 func_id == BPF_FUNC_skc_to_tcp_sock ||
498 func_id == BPF_FUNC_skc_to_tcp6_sock ||
499 func_id == BPF_FUNC_skc_to_udp6_sock ||
500 func_id == BPF_FUNC_skc_to_mptcp_sock ||
501 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
502 func_id == BPF_FUNC_skc_to_tcp_request_sock;
503 }
504
is_dynptr_ref_function(enum bpf_func_id func_id)505 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
506 {
507 return func_id == BPF_FUNC_dynptr_data;
508 }
509
510 static bool is_sync_callback_calling_kfunc(u32 btf_id);
511 static bool is_async_callback_calling_kfunc(u32 btf_id);
512 static bool is_callback_calling_kfunc(u32 btf_id);
513 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
514
515 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id);
516 static bool is_task_work_add_kfunc(u32 func_id);
517
is_sync_callback_calling_function(enum bpf_func_id func_id)518 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
519 {
520 return func_id == BPF_FUNC_for_each_map_elem ||
521 func_id == BPF_FUNC_find_vma ||
522 func_id == BPF_FUNC_loop ||
523 func_id == BPF_FUNC_user_ringbuf_drain;
524 }
525
is_async_callback_calling_function(enum bpf_func_id func_id)526 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
527 {
528 return func_id == BPF_FUNC_timer_set_callback;
529 }
530
is_callback_calling_function(enum bpf_func_id func_id)531 static bool is_callback_calling_function(enum bpf_func_id func_id)
532 {
533 return is_sync_callback_calling_function(func_id) ||
534 is_async_callback_calling_function(func_id);
535 }
536
is_sync_callback_calling_insn(struct bpf_insn * insn)537 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
538 {
539 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
540 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
541 }
542
is_async_callback_calling_insn(struct bpf_insn * insn)543 static bool is_async_callback_calling_insn(struct bpf_insn *insn)
544 {
545 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) ||
546 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
547 }
548
is_async_cb_sleepable(struct bpf_verifier_env * env,struct bpf_insn * insn)549 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn)
550 {
551 /* bpf_timer callbacks are never sleepable. */
552 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback)
553 return false;
554
555 /* bpf_wq and bpf_task_work callbacks are always sleepable. */
556 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
557 (is_bpf_wq_set_callback_impl_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm)))
558 return true;
559
560 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable");
561 return false;
562 }
563
is_may_goto_insn(struct bpf_insn * insn)564 static bool is_may_goto_insn(struct bpf_insn *insn)
565 {
566 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
567 }
568
is_may_goto_insn_at(struct bpf_verifier_env * env,int insn_idx)569 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx)
570 {
571 return is_may_goto_insn(&env->prog->insnsi[insn_idx]);
572 }
573
is_storage_get_function(enum bpf_func_id func_id)574 static bool is_storage_get_function(enum bpf_func_id func_id)
575 {
576 return func_id == BPF_FUNC_sk_storage_get ||
577 func_id == BPF_FUNC_inode_storage_get ||
578 func_id == BPF_FUNC_task_storage_get ||
579 func_id == BPF_FUNC_cgrp_storage_get;
580 }
581
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)582 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
583 const struct bpf_map *map)
584 {
585 int ref_obj_uses = 0;
586
587 if (is_ptr_cast_function(func_id))
588 ref_obj_uses++;
589 if (is_acquire_function(func_id, map))
590 ref_obj_uses++;
591 if (is_dynptr_ref_function(func_id))
592 ref_obj_uses++;
593
594 return ref_obj_uses > 1;
595 }
596
is_cmpxchg_insn(const struct bpf_insn * insn)597 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
598 {
599 return BPF_CLASS(insn->code) == BPF_STX &&
600 BPF_MODE(insn->code) == BPF_ATOMIC &&
601 insn->imm == BPF_CMPXCHG;
602 }
603
is_atomic_load_insn(const struct bpf_insn * insn)604 static bool is_atomic_load_insn(const struct bpf_insn *insn)
605 {
606 return BPF_CLASS(insn->code) == BPF_STX &&
607 BPF_MODE(insn->code) == BPF_ATOMIC &&
608 insn->imm == BPF_LOAD_ACQ;
609 }
610
__get_spi(s32 off)611 static int __get_spi(s32 off)
612 {
613 return (-off - 1) / BPF_REG_SIZE;
614 }
615
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)616 static struct bpf_func_state *func(struct bpf_verifier_env *env,
617 const struct bpf_reg_state *reg)
618 {
619 struct bpf_verifier_state *cur = env->cur_state;
620
621 return cur->frame[reg->frameno];
622 }
623
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)624 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
625 {
626 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
627
628 /* We need to check that slots between [spi - nr_slots + 1, spi] are
629 * within [0, allocated_stack).
630 *
631 * Please note that the spi grows downwards. For example, a dynptr
632 * takes the size of two stack slots; the first slot will be at
633 * spi and the second slot will be at spi - 1.
634 */
635 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
636 }
637
stack_slot_obj_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * obj_kind,int nr_slots)638 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
639 const char *obj_kind, int nr_slots)
640 {
641 int off, spi;
642
643 if (!tnum_is_const(reg->var_off)) {
644 verbose(env, "%s has to be at a constant offset\n", obj_kind);
645 return -EINVAL;
646 }
647
648 off = reg->off + reg->var_off.value;
649 if (off % BPF_REG_SIZE) {
650 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
651 return -EINVAL;
652 }
653
654 spi = __get_spi(off);
655 if (spi + 1 < nr_slots) {
656 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
657 return -EINVAL;
658 }
659
660 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
661 return -ERANGE;
662 return spi;
663 }
664
dynptr_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)665 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
666 {
667 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
668 }
669
iter_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)670 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
671 {
672 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
673 }
674
irq_flag_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)675 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
676 {
677 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1);
678 }
679
arg_to_dynptr_type(enum bpf_arg_type arg_type)680 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
681 {
682 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
683 case DYNPTR_TYPE_LOCAL:
684 return BPF_DYNPTR_TYPE_LOCAL;
685 case DYNPTR_TYPE_RINGBUF:
686 return BPF_DYNPTR_TYPE_RINGBUF;
687 case DYNPTR_TYPE_SKB:
688 return BPF_DYNPTR_TYPE_SKB;
689 case DYNPTR_TYPE_XDP:
690 return BPF_DYNPTR_TYPE_XDP;
691 case DYNPTR_TYPE_SKB_META:
692 return BPF_DYNPTR_TYPE_SKB_META;
693 case DYNPTR_TYPE_FILE:
694 return BPF_DYNPTR_TYPE_FILE;
695 default:
696 return BPF_DYNPTR_TYPE_INVALID;
697 }
698 }
699
get_dynptr_type_flag(enum bpf_dynptr_type type)700 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
701 {
702 switch (type) {
703 case BPF_DYNPTR_TYPE_LOCAL:
704 return DYNPTR_TYPE_LOCAL;
705 case BPF_DYNPTR_TYPE_RINGBUF:
706 return DYNPTR_TYPE_RINGBUF;
707 case BPF_DYNPTR_TYPE_SKB:
708 return DYNPTR_TYPE_SKB;
709 case BPF_DYNPTR_TYPE_XDP:
710 return DYNPTR_TYPE_XDP;
711 case BPF_DYNPTR_TYPE_SKB_META:
712 return DYNPTR_TYPE_SKB_META;
713 case BPF_DYNPTR_TYPE_FILE:
714 return DYNPTR_TYPE_FILE;
715 default:
716 return 0;
717 }
718 }
719
dynptr_type_refcounted(enum bpf_dynptr_type type)720 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
721 {
722 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
723 }
724
725 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
726 enum bpf_dynptr_type type,
727 bool first_slot, int dynptr_id);
728
729 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
730 struct bpf_reg_state *reg);
731
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)732 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
733 struct bpf_reg_state *sreg1,
734 struct bpf_reg_state *sreg2,
735 enum bpf_dynptr_type type)
736 {
737 int id = ++env->id_gen;
738
739 __mark_dynptr_reg(sreg1, type, true, id);
740 __mark_dynptr_reg(sreg2, type, false, id);
741 }
742
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)743 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
744 struct bpf_reg_state *reg,
745 enum bpf_dynptr_type type)
746 {
747 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
748 }
749
750 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
751 struct bpf_func_state *state, int spi);
752
mark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type,int insn_idx,int clone_ref_obj_id)753 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
754 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
755 {
756 struct bpf_func_state *state = func(env, reg);
757 enum bpf_dynptr_type type;
758 int spi, i, err;
759
760 spi = dynptr_get_spi(env, reg);
761 if (spi < 0)
762 return spi;
763
764 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
765 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
766 * to ensure that for the following example:
767 * [d1][d1][d2][d2]
768 * spi 3 2 1 0
769 * So marking spi = 2 should lead to destruction of both d1 and d2. In
770 * case they do belong to same dynptr, second call won't see slot_type
771 * as STACK_DYNPTR and will simply skip destruction.
772 */
773 err = destroy_if_dynptr_stack_slot(env, state, spi);
774 if (err)
775 return err;
776 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
777 if (err)
778 return err;
779
780 for (i = 0; i < BPF_REG_SIZE; i++) {
781 state->stack[spi].slot_type[i] = STACK_DYNPTR;
782 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
783 }
784
785 type = arg_to_dynptr_type(arg_type);
786 if (type == BPF_DYNPTR_TYPE_INVALID)
787 return -EINVAL;
788
789 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
790 &state->stack[spi - 1].spilled_ptr, type);
791
792 if (dynptr_type_refcounted(type)) {
793 /* The id is used to track proper releasing */
794 int id;
795
796 if (clone_ref_obj_id)
797 id = clone_ref_obj_id;
798 else
799 id = acquire_reference(env, insn_idx);
800
801 if (id < 0)
802 return id;
803
804 state->stack[spi].spilled_ptr.ref_obj_id = id;
805 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
806 }
807
808 bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
809
810 return 0;
811 }
812
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)813 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
814 {
815 int i;
816
817 for (i = 0; i < BPF_REG_SIZE; i++) {
818 state->stack[spi].slot_type[i] = STACK_INVALID;
819 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
820 }
821
822 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
823 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
824
825 bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
826 }
827
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)828 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
829 {
830 struct bpf_func_state *state = func(env, reg);
831 int spi, ref_obj_id, i;
832
833 /*
834 * This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
835 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
836 * is safe to do directly.
837 */
838 if (reg->type == CONST_PTR_TO_DYNPTR) {
839 verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
840 return -EFAULT;
841 }
842 spi = dynptr_get_spi(env, reg);
843 if (spi < 0)
844 return spi;
845
846 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
847 invalidate_dynptr(env, state, spi);
848 return 0;
849 }
850
851 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
852
853 /* If the dynptr has a ref_obj_id, then we need to invalidate
854 * two things:
855 *
856 * 1) Any dynptrs with a matching ref_obj_id (clones)
857 * 2) Any slices derived from this dynptr.
858 */
859
860 /* Invalidate any slices associated with this dynptr */
861 WARN_ON_ONCE(release_reference(env, ref_obj_id));
862
863 /* Invalidate any dynptr clones */
864 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
865 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
866 continue;
867
868 /* it should always be the case that if the ref obj id
869 * matches then the stack slot also belongs to a
870 * dynptr
871 */
872 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
873 verifier_bug(env, "misconfigured ref_obj_id");
874 return -EFAULT;
875 }
876 if (state->stack[i].spilled_ptr.dynptr.first_slot)
877 invalidate_dynptr(env, state, i);
878 }
879
880 return 0;
881 }
882
883 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
884 struct bpf_reg_state *reg);
885
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)886 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
887 {
888 if (!env->allow_ptr_leaks)
889 __mark_reg_not_init(env, reg);
890 else
891 __mark_reg_unknown(env, reg);
892 }
893
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)894 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
895 struct bpf_func_state *state, int spi)
896 {
897 struct bpf_func_state *fstate;
898 struct bpf_reg_state *dreg;
899 int i, dynptr_id;
900
901 /* We always ensure that STACK_DYNPTR is never set partially,
902 * hence just checking for slot_type[0] is enough. This is
903 * different for STACK_SPILL, where it may be only set for
904 * 1 byte, so code has to use is_spilled_reg.
905 */
906 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
907 return 0;
908
909 /* Reposition spi to first slot */
910 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
911 spi = spi + 1;
912
913 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
914 verbose(env, "cannot overwrite referenced dynptr\n");
915 return -EINVAL;
916 }
917
918 mark_stack_slot_scratched(env, spi);
919 mark_stack_slot_scratched(env, spi - 1);
920
921 /* Writing partially to one dynptr stack slot destroys both. */
922 for (i = 0; i < BPF_REG_SIZE; i++) {
923 state->stack[spi].slot_type[i] = STACK_INVALID;
924 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
925 }
926
927 dynptr_id = state->stack[spi].spilled_ptr.id;
928 /* Invalidate any slices associated with this dynptr */
929 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
930 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
931 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
932 continue;
933 if (dreg->dynptr_id == dynptr_id)
934 mark_reg_invalid(env, dreg);
935 }));
936
937 /* Do not release reference state, we are destroying dynptr on stack,
938 * not using some helper to release it. Just reset register.
939 */
940 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
941 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
942
943 bpf_mark_stack_write(env, state->frameno, BIT(spi - 1) | BIT(spi));
944
945 return 0;
946 }
947
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)948 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
949 {
950 int spi;
951
952 if (reg->type == CONST_PTR_TO_DYNPTR)
953 return false;
954
955 spi = dynptr_get_spi(env, reg);
956
957 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
958 * error because this just means the stack state hasn't been updated yet.
959 * We will do check_mem_access to check and update stack bounds later.
960 */
961 if (spi < 0 && spi != -ERANGE)
962 return false;
963
964 /* We don't need to check if the stack slots are marked by previous
965 * dynptr initializations because we allow overwriting existing unreferenced
966 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
967 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
968 * touching are completely destructed before we reinitialize them for a new
969 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
970 * instead of delaying it until the end where the user will get "Unreleased
971 * reference" error.
972 */
973 return true;
974 }
975
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)976 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
977 {
978 struct bpf_func_state *state = func(env, reg);
979 int i, spi;
980
981 /* This already represents first slot of initialized bpf_dynptr.
982 *
983 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
984 * check_func_arg_reg_off's logic, so we don't need to check its
985 * offset and alignment.
986 */
987 if (reg->type == CONST_PTR_TO_DYNPTR)
988 return true;
989
990 spi = dynptr_get_spi(env, reg);
991 if (spi < 0)
992 return false;
993 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
994 return false;
995
996 for (i = 0; i < BPF_REG_SIZE; i++) {
997 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
998 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
999 return false;
1000 }
1001
1002 return true;
1003 }
1004
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)1005 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1006 enum bpf_arg_type arg_type)
1007 {
1008 struct bpf_func_state *state = func(env, reg);
1009 enum bpf_dynptr_type dynptr_type;
1010 int spi;
1011
1012 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1013 if (arg_type == ARG_PTR_TO_DYNPTR)
1014 return true;
1015
1016 dynptr_type = arg_to_dynptr_type(arg_type);
1017 if (reg->type == CONST_PTR_TO_DYNPTR) {
1018 return reg->dynptr.type == dynptr_type;
1019 } else {
1020 spi = dynptr_get_spi(env, reg);
1021 if (spi < 0)
1022 return false;
1023 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1024 }
1025 }
1026
1027 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1028
1029 static bool in_rcu_cs(struct bpf_verifier_env *env);
1030
1031 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1032
mark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,struct bpf_reg_state * reg,int insn_idx,struct btf * btf,u32 btf_id,int nr_slots)1033 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1034 struct bpf_kfunc_call_arg_meta *meta,
1035 struct bpf_reg_state *reg, int insn_idx,
1036 struct btf *btf, u32 btf_id, int nr_slots)
1037 {
1038 struct bpf_func_state *state = func(env, reg);
1039 int spi, i, j, id;
1040
1041 spi = iter_get_spi(env, reg, nr_slots);
1042 if (spi < 0)
1043 return spi;
1044
1045 id = acquire_reference(env, insn_idx);
1046 if (id < 0)
1047 return id;
1048
1049 for (i = 0; i < nr_slots; i++) {
1050 struct bpf_stack_state *slot = &state->stack[spi - i];
1051 struct bpf_reg_state *st = &slot->spilled_ptr;
1052
1053 __mark_reg_known_zero(st);
1054 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1055 if (is_kfunc_rcu_protected(meta)) {
1056 if (in_rcu_cs(env))
1057 st->type |= MEM_RCU;
1058 else
1059 st->type |= PTR_UNTRUSTED;
1060 }
1061 st->ref_obj_id = i == 0 ? id : 0;
1062 st->iter.btf = btf;
1063 st->iter.btf_id = btf_id;
1064 st->iter.state = BPF_ITER_STATE_ACTIVE;
1065 st->iter.depth = 0;
1066
1067 for (j = 0; j < BPF_REG_SIZE; j++)
1068 slot->slot_type[j] = STACK_ITER;
1069
1070 bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1071 mark_stack_slot_scratched(env, spi - i);
1072 }
1073
1074 return 0;
1075 }
1076
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1077 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1078 struct bpf_reg_state *reg, int nr_slots)
1079 {
1080 struct bpf_func_state *state = func(env, reg);
1081 int spi, i, j;
1082
1083 spi = iter_get_spi(env, reg, nr_slots);
1084 if (spi < 0)
1085 return spi;
1086
1087 for (i = 0; i < nr_slots; i++) {
1088 struct bpf_stack_state *slot = &state->stack[spi - i];
1089 struct bpf_reg_state *st = &slot->spilled_ptr;
1090
1091 if (i == 0)
1092 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1093
1094 __mark_reg_not_init(env, st);
1095
1096 for (j = 0; j < BPF_REG_SIZE; j++)
1097 slot->slot_type[j] = STACK_INVALID;
1098
1099 bpf_mark_stack_write(env, state->frameno, BIT(spi - i));
1100 mark_stack_slot_scratched(env, spi - i);
1101 }
1102
1103 return 0;
1104 }
1105
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1106 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1107 struct bpf_reg_state *reg, int nr_slots)
1108 {
1109 struct bpf_func_state *state = func(env, reg);
1110 int spi, i, j;
1111
1112 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1113 * will do check_mem_access to check and update stack bounds later, so
1114 * return true for that case.
1115 */
1116 spi = iter_get_spi(env, reg, nr_slots);
1117 if (spi == -ERANGE)
1118 return true;
1119 if (spi < 0)
1120 return false;
1121
1122 for (i = 0; i < nr_slots; i++) {
1123 struct bpf_stack_state *slot = &state->stack[spi - i];
1124
1125 for (j = 0; j < BPF_REG_SIZE; j++)
1126 if (slot->slot_type[j] == STACK_ITER)
1127 return false;
1128 }
1129
1130 return true;
1131 }
1132
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1133 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1134 struct btf *btf, u32 btf_id, int nr_slots)
1135 {
1136 struct bpf_func_state *state = func(env, reg);
1137 int spi, i, j;
1138
1139 spi = iter_get_spi(env, reg, nr_slots);
1140 if (spi < 0)
1141 return -EINVAL;
1142
1143 for (i = 0; i < nr_slots; i++) {
1144 struct bpf_stack_state *slot = &state->stack[spi - i];
1145 struct bpf_reg_state *st = &slot->spilled_ptr;
1146
1147 if (st->type & PTR_UNTRUSTED)
1148 return -EPROTO;
1149 /* only main (first) slot has ref_obj_id set */
1150 if (i == 0 && !st->ref_obj_id)
1151 return -EINVAL;
1152 if (i != 0 && st->ref_obj_id)
1153 return -EINVAL;
1154 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1155 return -EINVAL;
1156
1157 for (j = 0; j < BPF_REG_SIZE; j++)
1158 if (slot->slot_type[j] != STACK_ITER)
1159 return -EINVAL;
1160 }
1161
1162 return 0;
1163 }
1164
1165 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
1166 static int release_irq_state(struct bpf_verifier_state *state, int id);
1167
mark_stack_slot_irq_flag(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,struct bpf_reg_state * reg,int insn_idx,int kfunc_class)1168 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
1169 struct bpf_kfunc_call_arg_meta *meta,
1170 struct bpf_reg_state *reg, int insn_idx,
1171 int kfunc_class)
1172 {
1173 struct bpf_func_state *state = func(env, reg);
1174 struct bpf_stack_state *slot;
1175 struct bpf_reg_state *st;
1176 int spi, i, id;
1177
1178 spi = irq_flag_get_spi(env, reg);
1179 if (spi < 0)
1180 return spi;
1181
1182 id = acquire_irq_state(env, insn_idx);
1183 if (id < 0)
1184 return id;
1185
1186 slot = &state->stack[spi];
1187 st = &slot->spilled_ptr;
1188
1189 bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1190 __mark_reg_known_zero(st);
1191 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1192 st->ref_obj_id = id;
1193 st->irq.kfunc_class = kfunc_class;
1194
1195 for (i = 0; i < BPF_REG_SIZE; i++)
1196 slot->slot_type[i] = STACK_IRQ_FLAG;
1197
1198 mark_stack_slot_scratched(env, spi);
1199 return 0;
1200 }
1201
unmark_stack_slot_irq_flag(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int kfunc_class)1202 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1203 int kfunc_class)
1204 {
1205 struct bpf_func_state *state = func(env, reg);
1206 struct bpf_stack_state *slot;
1207 struct bpf_reg_state *st;
1208 int spi, i, err;
1209
1210 spi = irq_flag_get_spi(env, reg);
1211 if (spi < 0)
1212 return spi;
1213
1214 slot = &state->stack[spi];
1215 st = &slot->spilled_ptr;
1216
1217 if (st->irq.kfunc_class != kfunc_class) {
1218 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1219 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock";
1220
1221 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n",
1222 flag_kfunc, used_kfunc);
1223 return -EINVAL;
1224 }
1225
1226 err = release_irq_state(env->cur_state, st->ref_obj_id);
1227 WARN_ON_ONCE(err && err != -EACCES);
1228 if (err) {
1229 int insn_idx = 0;
1230
1231 for (int i = 0; i < env->cur_state->acquired_refs; i++) {
1232 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) {
1233 insn_idx = env->cur_state->refs[i].insn_idx;
1234 break;
1235 }
1236 }
1237
1238 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n",
1239 env->cur_state->active_irq_id, insn_idx);
1240 return err;
1241 }
1242
1243 __mark_reg_not_init(env, st);
1244
1245 bpf_mark_stack_write(env, reg->frameno, BIT(spi));
1246
1247 for (i = 0; i < BPF_REG_SIZE; i++)
1248 slot->slot_type[i] = STACK_INVALID;
1249
1250 mark_stack_slot_scratched(env, spi);
1251 return 0;
1252 }
1253
is_irq_flag_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1254 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1255 {
1256 struct bpf_func_state *state = func(env, reg);
1257 struct bpf_stack_state *slot;
1258 int spi, i;
1259
1260 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 * will do check_mem_access to check and update stack bounds later, so
1262 * return true for that case.
1263 */
1264 spi = irq_flag_get_spi(env, reg);
1265 if (spi == -ERANGE)
1266 return true;
1267 if (spi < 0)
1268 return false;
1269
1270 slot = &state->stack[spi];
1271
1272 for (i = 0; i < BPF_REG_SIZE; i++)
1273 if (slot->slot_type[i] == STACK_IRQ_FLAG)
1274 return false;
1275 return true;
1276 }
1277
is_irq_flag_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1278 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1279 {
1280 struct bpf_func_state *state = func(env, reg);
1281 struct bpf_stack_state *slot;
1282 struct bpf_reg_state *st;
1283 int spi, i;
1284
1285 spi = irq_flag_get_spi(env, reg);
1286 if (spi < 0)
1287 return -EINVAL;
1288
1289 slot = &state->stack[spi];
1290 st = &slot->spilled_ptr;
1291
1292 if (!st->ref_obj_id)
1293 return -EINVAL;
1294
1295 for (i = 0; i < BPF_REG_SIZE; i++)
1296 if (slot->slot_type[i] != STACK_IRQ_FLAG)
1297 return -EINVAL;
1298 return 0;
1299 }
1300
1301 /* Check if given stack slot is "special":
1302 * - spilled register state (STACK_SPILL);
1303 * - dynptr state (STACK_DYNPTR);
1304 * - iter state (STACK_ITER).
1305 * - irq flag state (STACK_IRQ_FLAG)
1306 */
is_stack_slot_special(const struct bpf_stack_state * stack)1307 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1308 {
1309 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1310
1311 switch (type) {
1312 case STACK_SPILL:
1313 case STACK_DYNPTR:
1314 case STACK_ITER:
1315 case STACK_IRQ_FLAG:
1316 return true;
1317 case STACK_INVALID:
1318 case STACK_MISC:
1319 case STACK_ZERO:
1320 return false;
1321 default:
1322 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1323 return true;
1324 }
1325 }
1326
1327 /* The reg state of a pointer or a bounded scalar was saved when
1328 * it was spilled to the stack.
1329 */
is_spilled_reg(const struct bpf_stack_state * stack)1330 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1331 {
1332 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1333 }
1334
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1335 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1336 {
1337 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1338 stack->spilled_ptr.type == SCALAR_VALUE;
1339 }
1340
is_spilled_scalar_reg64(const struct bpf_stack_state * stack)1341 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack)
1342 {
1343 return stack->slot_type[0] == STACK_SPILL &&
1344 stack->spilled_ptr.type == SCALAR_VALUE;
1345 }
1346
1347 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which
1348 * case they are equivalent, or it's STACK_ZERO, in which case we preserve
1349 * more precise STACK_ZERO.
1350 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged
1351 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is
1352 * unnecessary as both are considered equivalent when loading data and pruning,
1353 * in case of unprivileged mode it will be incorrect to allow reads of invalid
1354 * slots.
1355 */
mark_stack_slot_misc(struct bpf_verifier_env * env,u8 * stype)1356 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype)
1357 {
1358 if (*stype == STACK_ZERO)
1359 return;
1360 if (*stype == STACK_INVALID)
1361 return;
1362 *stype = STACK_MISC;
1363 }
1364
scrub_spilled_slot(u8 * stype)1365 static void scrub_spilled_slot(u8 *stype)
1366 {
1367 if (*stype != STACK_INVALID)
1368 *stype = STACK_MISC;
1369 }
1370
1371 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1372 * small to hold src. This is different from krealloc since we don't want to preserve
1373 * the contents of dst.
1374 *
1375 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1376 * not be allocated.
1377 */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1378 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1379 {
1380 size_t alloc_bytes;
1381 void *orig = dst;
1382 size_t bytes;
1383
1384 if (ZERO_OR_NULL_PTR(src))
1385 goto out;
1386
1387 if (unlikely(check_mul_overflow(n, size, &bytes)))
1388 return NULL;
1389
1390 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1391 dst = krealloc(orig, alloc_bytes, flags);
1392 if (!dst) {
1393 kfree(orig);
1394 return NULL;
1395 }
1396
1397 memcpy(dst, src, bytes);
1398 out:
1399 return dst ? dst : ZERO_SIZE_PTR;
1400 }
1401
1402 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1403 * small to hold new_n items. new items are zeroed out if the array grows.
1404 *
1405 * Contrary to krealloc_array, does not free arr if new_n is zero.
1406 */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1407 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1408 {
1409 size_t alloc_size;
1410 void *new_arr;
1411
1412 if (!new_n || old_n == new_n)
1413 goto out;
1414
1415 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1416 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT);
1417 if (!new_arr) {
1418 kfree(arr);
1419 return NULL;
1420 }
1421 arr = new_arr;
1422
1423 if (new_n > old_n)
1424 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1425
1426 out:
1427 return arr ? arr : ZERO_SIZE_PTR;
1428 }
1429
copy_reference_state(struct bpf_verifier_state * dst,const struct bpf_verifier_state * src)1430 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src)
1431 {
1432 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1433 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT);
1434 if (!dst->refs)
1435 return -ENOMEM;
1436
1437 dst->acquired_refs = src->acquired_refs;
1438 dst->active_locks = src->active_locks;
1439 dst->active_preempt_locks = src->active_preempt_locks;
1440 dst->active_rcu_locks = src->active_rcu_locks;
1441 dst->active_irq_id = src->active_irq_id;
1442 dst->active_lock_id = src->active_lock_id;
1443 dst->active_lock_ptr = src->active_lock_ptr;
1444 return 0;
1445 }
1446
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1447 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1448 {
1449 size_t n = src->allocated_stack / BPF_REG_SIZE;
1450
1451 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1452 GFP_KERNEL_ACCOUNT);
1453 if (!dst->stack)
1454 return -ENOMEM;
1455
1456 dst->allocated_stack = src->allocated_stack;
1457 return 0;
1458 }
1459
resize_reference_state(struct bpf_verifier_state * state,size_t n)1460 static int resize_reference_state(struct bpf_verifier_state *state, size_t n)
1461 {
1462 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1463 sizeof(struct bpf_reference_state));
1464 if (!state->refs)
1465 return -ENOMEM;
1466
1467 state->acquired_refs = n;
1468 return 0;
1469 }
1470
1471 /* Possibly update state->allocated_stack to be at least size bytes. Also
1472 * possibly update the function's high-water mark in its bpf_subprog_info.
1473 */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1474 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1475 {
1476 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n;
1477
1478 /* The stack size is always a multiple of BPF_REG_SIZE. */
1479 size = round_up(size, BPF_REG_SIZE);
1480 n = size / BPF_REG_SIZE;
1481
1482 if (old_n >= n)
1483 return 0;
1484
1485 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1486 if (!state->stack)
1487 return -ENOMEM;
1488
1489 state->allocated_stack = size;
1490
1491 /* update known max for given subprogram */
1492 if (env->subprog_info[state->subprogno].stack_depth < size)
1493 env->subprog_info[state->subprogno].stack_depth = size;
1494
1495 return 0;
1496 }
1497
1498 /* Acquire a pointer id from the env and update the state->refs to include
1499 * this new pointer reference.
1500 * On success, returns a valid pointer id to associate with the register
1501 * On failure, returns a negative errno.
1502 */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1503 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1504 {
1505 struct bpf_verifier_state *state = env->cur_state;
1506 int new_ofs = state->acquired_refs;
1507 int err;
1508
1509 err = resize_reference_state(state, state->acquired_refs + 1);
1510 if (err)
1511 return NULL;
1512 state->refs[new_ofs].insn_idx = insn_idx;
1513
1514 return &state->refs[new_ofs];
1515 }
1516
acquire_reference(struct bpf_verifier_env * env,int insn_idx)1517 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx)
1518 {
1519 struct bpf_reference_state *s;
1520
1521 s = acquire_reference_state(env, insn_idx);
1522 if (!s)
1523 return -ENOMEM;
1524 s->type = REF_TYPE_PTR;
1525 s->id = ++env->id_gen;
1526 return s->id;
1527 }
1528
acquire_lock_state(struct bpf_verifier_env * env,int insn_idx,enum ref_state_type type,int id,void * ptr)1529 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type,
1530 int id, void *ptr)
1531 {
1532 struct bpf_verifier_state *state = env->cur_state;
1533 struct bpf_reference_state *s;
1534
1535 s = acquire_reference_state(env, insn_idx);
1536 if (!s)
1537 return -ENOMEM;
1538 s->type = type;
1539 s->id = id;
1540 s->ptr = ptr;
1541
1542 state->active_locks++;
1543 state->active_lock_id = id;
1544 state->active_lock_ptr = ptr;
1545 return 0;
1546 }
1547
acquire_irq_state(struct bpf_verifier_env * env,int insn_idx)1548 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
1549 {
1550 struct bpf_verifier_state *state = env->cur_state;
1551 struct bpf_reference_state *s;
1552
1553 s = acquire_reference_state(env, insn_idx);
1554 if (!s)
1555 return -ENOMEM;
1556 s->type = REF_TYPE_IRQ;
1557 s->id = ++env->id_gen;
1558
1559 state->active_irq_id = s->id;
1560 return s->id;
1561 }
1562
release_reference_state(struct bpf_verifier_state * state,int idx)1563 static void release_reference_state(struct bpf_verifier_state *state, int idx)
1564 {
1565 int last_idx;
1566 size_t rem;
1567
1568 /* IRQ state requires the relative ordering of elements remaining the
1569 * same, since it relies on the refs array to behave as a stack, so that
1570 * it can detect out-of-order IRQ restore. Hence use memmove to shift
1571 * the array instead of swapping the final element into the deleted idx.
1572 */
1573 last_idx = state->acquired_refs - 1;
1574 rem = state->acquired_refs - idx - 1;
1575 if (last_idx && idx != last_idx)
1576 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem);
1577 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1578 state->acquired_refs--;
1579 return;
1580 }
1581
find_reference_state(struct bpf_verifier_state * state,int ptr_id)1582 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id)
1583 {
1584 int i;
1585
1586 for (i = 0; i < state->acquired_refs; i++)
1587 if (state->refs[i].id == ptr_id)
1588 return true;
1589
1590 return false;
1591 }
1592
release_lock_state(struct bpf_verifier_state * state,int type,int id,void * ptr)1593 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
1594 {
1595 void *prev_ptr = NULL;
1596 u32 prev_id = 0;
1597 int i;
1598
1599 for (i = 0; i < state->acquired_refs; i++) {
1600 if (state->refs[i].type == type && state->refs[i].id == id &&
1601 state->refs[i].ptr == ptr) {
1602 release_reference_state(state, i);
1603 state->active_locks--;
1604 /* Reassign active lock (id, ptr). */
1605 state->active_lock_id = prev_id;
1606 state->active_lock_ptr = prev_ptr;
1607 return 0;
1608 }
1609 if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
1610 prev_id = state->refs[i].id;
1611 prev_ptr = state->refs[i].ptr;
1612 }
1613 }
1614 return -EINVAL;
1615 }
1616
release_irq_state(struct bpf_verifier_state * state,int id)1617 static int release_irq_state(struct bpf_verifier_state *state, int id)
1618 {
1619 u32 prev_id = 0;
1620 int i;
1621
1622 if (id != state->active_irq_id)
1623 return -EACCES;
1624
1625 for (i = 0; i < state->acquired_refs; i++) {
1626 if (state->refs[i].type != REF_TYPE_IRQ)
1627 continue;
1628 if (state->refs[i].id == id) {
1629 release_reference_state(state, i);
1630 state->active_irq_id = prev_id;
1631 return 0;
1632 } else {
1633 prev_id = state->refs[i].id;
1634 }
1635 }
1636 return -EINVAL;
1637 }
1638
find_lock_state(struct bpf_verifier_state * state,enum ref_state_type type,int id,void * ptr)1639 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type,
1640 int id, void *ptr)
1641 {
1642 int i;
1643
1644 for (i = 0; i < state->acquired_refs; i++) {
1645 struct bpf_reference_state *s = &state->refs[i];
1646
1647 if (!(s->type & type))
1648 continue;
1649
1650 if (s->id == id && s->ptr == ptr)
1651 return s;
1652 }
1653 return NULL;
1654 }
1655
update_peak_states(struct bpf_verifier_env * env)1656 static void update_peak_states(struct bpf_verifier_env *env)
1657 {
1658 u32 cur_states;
1659
1660 cur_states = env->explored_states_size + env->free_list_size + env->num_backedges;
1661 env->peak_states = max(env->peak_states, cur_states);
1662 }
1663
free_func_state(struct bpf_func_state * state)1664 static void free_func_state(struct bpf_func_state *state)
1665 {
1666 if (!state)
1667 return;
1668 kfree(state->stack);
1669 kfree(state);
1670 }
1671
clear_jmp_history(struct bpf_verifier_state * state)1672 static void clear_jmp_history(struct bpf_verifier_state *state)
1673 {
1674 kfree(state->jmp_history);
1675 state->jmp_history = NULL;
1676 state->jmp_history_cnt = 0;
1677 }
1678
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1679 static void free_verifier_state(struct bpf_verifier_state *state,
1680 bool free_self)
1681 {
1682 int i;
1683
1684 for (i = 0; i <= state->curframe; i++) {
1685 free_func_state(state->frame[i]);
1686 state->frame[i] = NULL;
1687 }
1688 kfree(state->refs);
1689 clear_jmp_history(state);
1690 if (free_self)
1691 kfree(state);
1692 }
1693
1694 /* struct bpf_verifier_state->parent refers to states
1695 * that are in either of env->{expored_states,free_list}.
1696 * In both cases the state is contained in struct bpf_verifier_state_list.
1697 */
state_parent_as_list(struct bpf_verifier_state * st)1698 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st)
1699 {
1700 if (st->parent)
1701 return container_of(st->parent, struct bpf_verifier_state_list, state);
1702 return NULL;
1703 }
1704
1705 static bool incomplete_read_marks(struct bpf_verifier_env *env,
1706 struct bpf_verifier_state *st);
1707
1708 /* A state can be freed if it is no longer referenced:
1709 * - is in the env->free_list;
1710 * - has no children states;
1711 */
maybe_free_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state_list * sl)1712 static void maybe_free_verifier_state(struct bpf_verifier_env *env,
1713 struct bpf_verifier_state_list *sl)
1714 {
1715 if (!sl->in_free_list
1716 || sl->state.branches != 0
1717 || incomplete_read_marks(env, &sl->state))
1718 return;
1719 list_del(&sl->node);
1720 free_verifier_state(&sl->state, false);
1721 kfree(sl);
1722 env->free_list_size--;
1723 }
1724
1725 /* copy verifier state from src to dst growing dst stack space
1726 * when necessary to accommodate larger src stack
1727 */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1728 static int copy_func_state(struct bpf_func_state *dst,
1729 const struct bpf_func_state *src)
1730 {
1731 memcpy(dst, src, offsetof(struct bpf_func_state, stack));
1732 return copy_stack_state(dst, src);
1733 }
1734
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1735 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1736 const struct bpf_verifier_state *src)
1737 {
1738 struct bpf_func_state *dst;
1739 int i, err;
1740
1741 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1742 src->jmp_history_cnt, sizeof(*dst_state->jmp_history),
1743 GFP_KERNEL_ACCOUNT);
1744 if (!dst_state->jmp_history)
1745 return -ENOMEM;
1746 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1747
1748 /* if dst has more stack frames then src frame, free them, this is also
1749 * necessary in case of exceptional exits using bpf_throw.
1750 */
1751 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752 free_func_state(dst_state->frame[i]);
1753 dst_state->frame[i] = NULL;
1754 }
1755 err = copy_reference_state(dst_state, src);
1756 if (err)
1757 return err;
1758 dst_state->speculative = src->speculative;
1759 dst_state->in_sleepable = src->in_sleepable;
1760 dst_state->cleaned = src->cleaned;
1761 dst_state->curframe = src->curframe;
1762 dst_state->branches = src->branches;
1763 dst_state->parent = src->parent;
1764 dst_state->first_insn_idx = src->first_insn_idx;
1765 dst_state->last_insn_idx = src->last_insn_idx;
1766 dst_state->dfs_depth = src->dfs_depth;
1767 dst_state->callback_unroll_depth = src->callback_unroll_depth;
1768 dst_state->may_goto_depth = src->may_goto_depth;
1769 dst_state->equal_state = src->equal_state;
1770 for (i = 0; i <= src->curframe; i++) {
1771 dst = dst_state->frame[i];
1772 if (!dst) {
1773 dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT);
1774 if (!dst)
1775 return -ENOMEM;
1776 dst_state->frame[i] = dst;
1777 }
1778 err = copy_func_state(dst, src->frame[i]);
1779 if (err)
1780 return err;
1781 }
1782 return 0;
1783 }
1784
state_htab_size(struct bpf_verifier_env * env)1785 static u32 state_htab_size(struct bpf_verifier_env *env)
1786 {
1787 return env->prog->len;
1788 }
1789
explored_state(struct bpf_verifier_env * env,int idx)1790 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx)
1791 {
1792 struct bpf_verifier_state *cur = env->cur_state;
1793 struct bpf_func_state *state = cur->frame[cur->curframe];
1794
1795 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1796 }
1797
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1798 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1799 {
1800 int fr;
1801
1802 if (a->curframe != b->curframe)
1803 return false;
1804
1805 for (fr = a->curframe; fr >= 0; fr--)
1806 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1807 return false;
1808
1809 return true;
1810 }
1811
1812 /* Return IP for a given frame in a call stack */
frame_insn_idx(struct bpf_verifier_state * st,u32 frame)1813 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
1814 {
1815 return frame == st->curframe
1816 ? st->insn_idx
1817 : st->frame[frame + 1]->callsite;
1818 }
1819
1820 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC,
1821 * if such frame exists form a corresponding @callchain as an array of
1822 * call sites leading to this frame and SCC id.
1823 * E.g.:
1824 *
1825 * void foo() { A: loop {... SCC#1 ...}; }
1826 * void bar() { B: loop { C: foo(); ... SCC#2 ... }
1827 * D: loop { E: foo(); ... SCC#3 ... } }
1828 * void main() { F: bar(); }
1829 *
1830 * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending
1831 * on @st frame call sites being (F,C,A) or (F,E,A).
1832 */
compute_scc_callchain(struct bpf_verifier_env * env,struct bpf_verifier_state * st,struct bpf_scc_callchain * callchain)1833 static bool compute_scc_callchain(struct bpf_verifier_env *env,
1834 struct bpf_verifier_state *st,
1835 struct bpf_scc_callchain *callchain)
1836 {
1837 u32 i, scc, insn_idx;
1838
1839 memset(callchain, 0, sizeof(*callchain));
1840 for (i = 0; i <= st->curframe; i++) {
1841 insn_idx = frame_insn_idx(st, i);
1842 scc = env->insn_aux_data[insn_idx].scc;
1843 if (scc) {
1844 callchain->scc = scc;
1845 break;
1846 } else if (i < st->curframe) {
1847 callchain->callsites[i] = insn_idx;
1848 } else {
1849 return false;
1850 }
1851 }
1852 return true;
1853 }
1854
1855 /* Check if bpf_scc_visit instance for @callchain exists. */
scc_visit_lookup(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1856 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env,
1857 struct bpf_scc_callchain *callchain)
1858 {
1859 struct bpf_scc_info *info = env->scc_info[callchain->scc];
1860 struct bpf_scc_visit *visits = info->visits;
1861 u32 i;
1862
1863 if (!info)
1864 return NULL;
1865 for (i = 0; i < info->num_visits; i++)
1866 if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0)
1867 return &visits[i];
1868 return NULL;
1869 }
1870
1871 /* Allocate a new bpf_scc_visit instance corresponding to @callchain.
1872 * Allocated instances are alive for a duration of the do_check_common()
1873 * call and are freed by free_states().
1874 */
scc_visit_alloc(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1875 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env,
1876 struct bpf_scc_callchain *callchain)
1877 {
1878 struct bpf_scc_visit *visit;
1879 struct bpf_scc_info *info;
1880 u32 scc, num_visits;
1881 u64 new_sz;
1882
1883 scc = callchain->scc;
1884 info = env->scc_info[scc];
1885 num_visits = info ? info->num_visits : 0;
1886 new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1);
1887 info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT);
1888 if (!info)
1889 return NULL;
1890 env->scc_info[scc] = info;
1891 info->num_visits = num_visits + 1;
1892 visit = &info->visits[num_visits];
1893 memset(visit, 0, sizeof(*visit));
1894 memcpy(&visit->callchain, callchain, sizeof(*callchain));
1895 return visit;
1896 }
1897
1898 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */
format_callchain(struct bpf_verifier_env * env,struct bpf_scc_callchain * callchain)1899 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain)
1900 {
1901 char *buf = env->tmp_str_buf;
1902 int i, delta = 0;
1903
1904 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "(");
1905 for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) {
1906 if (!callchain->callsites[i])
1907 break;
1908 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,",
1909 callchain->callsites[i]);
1910 }
1911 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc);
1912 return env->tmp_str_buf;
1913 }
1914
1915 /* If callchain for @st exists (@st is in some SCC), ensure that
1916 * bpf_scc_visit instance for this callchain exists.
1917 * If instance does not exist or is empty, assign visit->entry_state to @st.
1918 */
maybe_enter_scc(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1919 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1920 {
1921 struct bpf_scc_callchain *callchain = &env->callchain_buf;
1922 struct bpf_scc_visit *visit;
1923
1924 if (!compute_scc_callchain(env, st, callchain))
1925 return 0;
1926 visit = scc_visit_lookup(env, callchain);
1927 visit = visit ?: scc_visit_alloc(env, callchain);
1928 if (!visit)
1929 return -ENOMEM;
1930 if (!visit->entry_state) {
1931 visit->entry_state = st;
1932 if (env->log.level & BPF_LOG_LEVEL2)
1933 verbose(env, "SCC enter %s\n", format_callchain(env, callchain));
1934 }
1935 return 0;
1936 }
1937
1938 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit);
1939
1940 /* If callchain for @st exists (@st is in some SCC), make it empty:
1941 * - set visit->entry_state to NULL;
1942 * - flush accumulated backedges.
1943 */
maybe_exit_scc(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1944 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1945 {
1946 struct bpf_scc_callchain *callchain = &env->callchain_buf;
1947 struct bpf_scc_visit *visit;
1948
1949 if (!compute_scc_callchain(env, st, callchain))
1950 return 0;
1951 visit = scc_visit_lookup(env, callchain);
1952 if (!visit) {
1953 /*
1954 * If path traversal stops inside an SCC, corresponding bpf_scc_visit
1955 * must exist for non-speculative paths. For non-speculative paths
1956 * traversal stops when:
1957 * a. Verification error is found, maybe_exit_scc() is not called.
1958 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member
1959 * of any SCC.
1960 * c. A checkpoint is reached and matched. Checkpoints are created by
1961 * is_state_visited(), which calls maybe_enter_scc(), which allocates
1962 * bpf_scc_visit instances for checkpoints within SCCs.
1963 * (c) is the only case that can reach this point.
1964 */
1965 if (!st->speculative) {
1966 verifier_bug(env, "scc exit: no visit info for call chain %s",
1967 format_callchain(env, callchain));
1968 return -EFAULT;
1969 }
1970 return 0;
1971 }
1972 if (visit->entry_state != st)
1973 return 0;
1974 if (env->log.level & BPF_LOG_LEVEL2)
1975 verbose(env, "SCC exit %s\n", format_callchain(env, callchain));
1976 visit->entry_state = NULL;
1977 env->num_backedges -= visit->num_backedges;
1978 visit->num_backedges = 0;
1979 update_peak_states(env);
1980 return propagate_backedges(env, visit);
1981 }
1982
1983 /* Lookup an bpf_scc_visit instance corresponding to @st callchain
1984 * and add @backedge to visit->backedges. @st callchain must exist.
1985 */
add_scc_backedge(struct bpf_verifier_env * env,struct bpf_verifier_state * st,struct bpf_scc_backedge * backedge)1986 static int add_scc_backedge(struct bpf_verifier_env *env,
1987 struct bpf_verifier_state *st,
1988 struct bpf_scc_backedge *backedge)
1989 {
1990 struct bpf_scc_callchain *callchain = &env->callchain_buf;
1991 struct bpf_scc_visit *visit;
1992
1993 if (!compute_scc_callchain(env, st, callchain)) {
1994 verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d",
1995 st->insn_idx);
1996 return -EFAULT;
1997 }
1998 visit = scc_visit_lookup(env, callchain);
1999 if (!visit) {
2000 verifier_bug(env, "add backedge: no visit info for call chain %s",
2001 format_callchain(env, callchain));
2002 return -EFAULT;
2003 }
2004 if (env->log.level & BPF_LOG_LEVEL2)
2005 verbose(env, "SCC backedge %s\n", format_callchain(env, callchain));
2006 backedge->next = visit->backedges;
2007 visit->backedges = backedge;
2008 visit->num_backedges++;
2009 env->num_backedges++;
2010 update_peak_states(env);
2011 return 0;
2012 }
2013
2014 /* bpf_reg_state->live marks for registers in a state @st are incomplete,
2015 * if state @st is in some SCC and not all execution paths starting at this
2016 * SCC are fully explored.
2017 */
incomplete_read_marks(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2018 static bool incomplete_read_marks(struct bpf_verifier_env *env,
2019 struct bpf_verifier_state *st)
2020 {
2021 struct bpf_scc_callchain *callchain = &env->callchain_buf;
2022 struct bpf_scc_visit *visit;
2023
2024 if (!compute_scc_callchain(env, st, callchain))
2025 return false;
2026 visit = scc_visit_lookup(env, callchain);
2027 if (!visit)
2028 return false;
2029 return !!visit->backedges;
2030 }
2031
free_backedges(struct bpf_scc_visit * visit)2032 static void free_backedges(struct bpf_scc_visit *visit)
2033 {
2034 struct bpf_scc_backedge *backedge, *next;
2035
2036 for (backedge = visit->backedges; backedge; backedge = next) {
2037 free_verifier_state(&backedge->state, false);
2038 next = backedge->next;
2039 kfree(backedge);
2040 }
2041 visit->backedges = NULL;
2042 }
2043
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2044 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2045 {
2046 struct bpf_verifier_state_list *sl = NULL, *parent_sl;
2047 struct bpf_verifier_state *parent;
2048 int err;
2049
2050 while (st) {
2051 u32 br = --st->branches;
2052
2053 /* verifier_bug_if(br > 1, ...) technically makes sense here,
2054 * but see comment in push_stack(), hence:
2055 */
2056 verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br);
2057 if (br)
2058 break;
2059 err = maybe_exit_scc(env, st);
2060 if (err)
2061 return err;
2062 parent = st->parent;
2063 parent_sl = state_parent_as_list(st);
2064 if (sl)
2065 maybe_free_verifier_state(env, sl);
2066 st = parent;
2067 sl = parent_sl;
2068 }
2069 return 0;
2070 }
2071
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)2072 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2073 int *insn_idx, bool pop_log)
2074 {
2075 struct bpf_verifier_state *cur = env->cur_state;
2076 struct bpf_verifier_stack_elem *elem, *head = env->head;
2077 int err;
2078
2079 if (env->head == NULL)
2080 return -ENOENT;
2081
2082 if (cur) {
2083 err = copy_verifier_state(cur, &head->st);
2084 if (err)
2085 return err;
2086 }
2087 if (pop_log)
2088 bpf_vlog_reset(&env->log, head->log_pos);
2089 if (insn_idx)
2090 *insn_idx = head->insn_idx;
2091 if (prev_insn_idx)
2092 *prev_insn_idx = head->prev_insn_idx;
2093 elem = head->next;
2094 free_verifier_state(&head->st, false);
2095 kfree(head);
2096 env->head = elem;
2097 env->stack_size--;
2098 return 0;
2099 }
2100
error_recoverable_with_nospec(int err)2101 static bool error_recoverable_with_nospec(int err)
2102 {
2103 /* Should only return true for non-fatal errors that are allowed to
2104 * occur during speculative verification. For these we can insert a
2105 * nospec and the program might still be accepted. Do not include
2106 * something like ENOMEM because it is likely to re-occur for the next
2107 * architectural path once it has been recovered-from in all speculative
2108 * paths.
2109 */
2110 return err == -EPERM || err == -EACCES || err == -EINVAL;
2111 }
2112
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)2113 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2114 int insn_idx, int prev_insn_idx,
2115 bool speculative)
2116 {
2117 struct bpf_verifier_state *cur = env->cur_state;
2118 struct bpf_verifier_stack_elem *elem;
2119 int err;
2120
2121 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2122 if (!elem)
2123 return ERR_PTR(-ENOMEM);
2124
2125 elem->insn_idx = insn_idx;
2126 elem->prev_insn_idx = prev_insn_idx;
2127 elem->next = env->head;
2128 elem->log_pos = env->log.end_pos;
2129 env->head = elem;
2130 env->stack_size++;
2131 err = copy_verifier_state(&elem->st, cur);
2132 if (err)
2133 return ERR_PTR(-ENOMEM);
2134 elem->st.speculative |= speculative;
2135 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2136 verbose(env, "The sequence of %d jumps is too complex.\n",
2137 env->stack_size);
2138 return ERR_PTR(-E2BIG);
2139 }
2140 if (elem->st.parent) {
2141 ++elem->st.parent->branches;
2142 /* WARN_ON(branches > 2) technically makes sense here,
2143 * but
2144 * 1. speculative states will bump 'branches' for non-branch
2145 * instructions
2146 * 2. is_state_visited() heuristics may decide not to create
2147 * a new state for a sequence of branches and all such current
2148 * and cloned states will be pointing to a single parent state
2149 * which might have large 'branches' count.
2150 */
2151 }
2152 return &elem->st;
2153 }
2154
2155 #define CALLER_SAVED_REGS 6
2156 static const int caller_saved[CALLER_SAVED_REGS] = {
2157 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2158 };
2159
2160 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)2161 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2162 {
2163 reg->var_off = tnum_const(imm);
2164 reg->smin_value = (s64)imm;
2165 reg->smax_value = (s64)imm;
2166 reg->umin_value = imm;
2167 reg->umax_value = imm;
2168
2169 reg->s32_min_value = (s32)imm;
2170 reg->s32_max_value = (s32)imm;
2171 reg->u32_min_value = (u32)imm;
2172 reg->u32_max_value = (u32)imm;
2173 }
2174
2175 /* Mark the unknown part of a register (variable offset or scalar value) as
2176 * known to have the value @imm.
2177 */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)2178 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2179 {
2180 /* Clear off and union(map_ptr, range) */
2181 memset(((u8 *)reg) + sizeof(reg->type), 0,
2182 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2183 reg->id = 0;
2184 reg->ref_obj_id = 0;
2185 ___mark_reg_known(reg, imm);
2186 }
2187
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)2188 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2189 {
2190 reg->var_off = tnum_const_subreg(reg->var_off, imm);
2191 reg->s32_min_value = (s32)imm;
2192 reg->s32_max_value = (s32)imm;
2193 reg->u32_min_value = (u32)imm;
2194 reg->u32_max_value = (u32)imm;
2195 }
2196
2197 /* Mark the 'variable offset' part of a register as zero. This should be
2198 * used only on registers holding a pointer type.
2199 */
__mark_reg_known_zero(struct bpf_reg_state * reg)2200 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2201 {
2202 __mark_reg_known(reg, 0);
2203 }
2204
__mark_reg_const_zero(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2205 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2206 {
2207 __mark_reg_known(reg, 0);
2208 reg->type = SCALAR_VALUE;
2209 /* all scalars are assumed imprecise initially (unless unprivileged,
2210 * in which case everything is forced to be precise)
2211 */
2212 reg->precise = !env->bpf_capable;
2213 }
2214
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2215 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2216 struct bpf_reg_state *regs, u32 regno)
2217 {
2218 if (WARN_ON(regno >= MAX_BPF_REG)) {
2219 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2220 /* Something bad happened, let's kill all regs */
2221 for (regno = 0; regno < MAX_BPF_REG; regno++)
2222 __mark_reg_not_init(env, regs + regno);
2223 return;
2224 }
2225 __mark_reg_known_zero(regs + regno);
2226 }
2227
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)2228 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2229 bool first_slot, int dynptr_id)
2230 {
2231 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2232 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2233 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2234 */
2235 __mark_reg_known_zero(reg);
2236 reg->type = CONST_PTR_TO_DYNPTR;
2237 /* Give each dynptr a unique id to uniquely associate slices to it. */
2238 reg->id = dynptr_id;
2239 reg->dynptr.type = type;
2240 reg->dynptr.first_slot = first_slot;
2241 }
2242
mark_ptr_not_null_reg(struct bpf_reg_state * reg)2243 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2244 {
2245 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2246 const struct bpf_map *map = reg->map_ptr;
2247
2248 if (map->inner_map_meta) {
2249 reg->type = CONST_PTR_TO_MAP;
2250 reg->map_ptr = map->inner_map_meta;
2251 /* transfer reg's id which is unique for every map_lookup_elem
2252 * as UID of the inner map.
2253 */
2254 if (btf_record_has_field(map->inner_map_meta->record,
2255 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) {
2256 reg->map_uid = reg->id;
2257 }
2258 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2259 reg->type = PTR_TO_XDP_SOCK;
2260 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2261 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2262 reg->type = PTR_TO_SOCKET;
2263 } else {
2264 reg->type = PTR_TO_MAP_VALUE;
2265 }
2266 return;
2267 }
2268
2269 reg->type &= ~PTR_MAYBE_NULL;
2270 }
2271
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)2272 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2273 struct btf_field_graph_root *ds_head)
2274 {
2275 __mark_reg_known_zero(®s[regno]);
2276 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2277 regs[regno].btf = ds_head->btf;
2278 regs[regno].btf_id = ds_head->value_btf_id;
2279 regs[regno].off = ds_head->node_offset;
2280 }
2281
reg_is_pkt_pointer(const struct bpf_reg_state * reg)2282 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2283 {
2284 return type_is_pkt_pointer(reg->type);
2285 }
2286
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)2287 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2288 {
2289 return reg_is_pkt_pointer(reg) ||
2290 reg->type == PTR_TO_PACKET_END;
2291 }
2292
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)2293 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2294 {
2295 return base_type(reg->type) == PTR_TO_MEM &&
2296 (reg->type &
2297 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META));
2298 }
2299
2300 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
reg_is_init_pkt_pointer(const struct bpf_reg_state * reg,enum bpf_reg_type which)2301 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2302 enum bpf_reg_type which)
2303 {
2304 /* The register can already have a range from prior markings.
2305 * This is fine as long as it hasn't been advanced from its
2306 * origin.
2307 */
2308 return reg->type == which &&
2309 reg->id == 0 &&
2310 reg->off == 0 &&
2311 tnum_equals_const(reg->var_off, 0);
2312 }
2313
2314 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)2315 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2316 {
2317 reg->smin_value = S64_MIN;
2318 reg->smax_value = S64_MAX;
2319 reg->umin_value = 0;
2320 reg->umax_value = U64_MAX;
2321
2322 reg->s32_min_value = S32_MIN;
2323 reg->s32_max_value = S32_MAX;
2324 reg->u32_min_value = 0;
2325 reg->u32_max_value = U32_MAX;
2326 }
2327
__mark_reg64_unbounded(struct bpf_reg_state * reg)2328 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2329 {
2330 reg->smin_value = S64_MIN;
2331 reg->smax_value = S64_MAX;
2332 reg->umin_value = 0;
2333 reg->umax_value = U64_MAX;
2334 }
2335
__mark_reg32_unbounded(struct bpf_reg_state * reg)2336 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2337 {
2338 reg->s32_min_value = S32_MIN;
2339 reg->s32_max_value = S32_MAX;
2340 reg->u32_min_value = 0;
2341 reg->u32_max_value = U32_MAX;
2342 }
2343
__update_reg32_bounds(struct bpf_reg_state * reg)2344 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2345 {
2346 struct tnum var32_off = tnum_subreg(reg->var_off);
2347
2348 /* min signed is max(sign bit) | min(other bits) */
2349 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2350 var32_off.value | (var32_off.mask & S32_MIN));
2351 /* max signed is min(sign bit) | max(other bits) */
2352 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2353 var32_off.value | (var32_off.mask & S32_MAX));
2354 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2355 reg->u32_max_value = min(reg->u32_max_value,
2356 (u32)(var32_off.value | var32_off.mask));
2357 }
2358
__update_reg64_bounds(struct bpf_reg_state * reg)2359 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2360 {
2361 /* min signed is max(sign bit) | min(other bits) */
2362 reg->smin_value = max_t(s64, reg->smin_value,
2363 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2364 /* max signed is min(sign bit) | max(other bits) */
2365 reg->smax_value = min_t(s64, reg->smax_value,
2366 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2367 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2368 reg->umax_value = min(reg->umax_value,
2369 reg->var_off.value | reg->var_off.mask);
2370 }
2371
__update_reg_bounds(struct bpf_reg_state * reg)2372 static void __update_reg_bounds(struct bpf_reg_state *reg)
2373 {
2374 __update_reg32_bounds(reg);
2375 __update_reg64_bounds(reg);
2376 }
2377
2378 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)2379 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2380 {
2381 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32
2382 * bits to improve our u32/s32 boundaries.
2383 *
2384 * E.g., the case where we have upper 32 bits as zero ([10, 20] in
2385 * u64) is pretty trivial, it's obvious that in u32 we'll also have
2386 * [10, 20] range. But this property holds for any 64-bit range as
2387 * long as upper 32 bits in that entire range of values stay the same.
2388 *
2389 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311]
2390 * in decimal) has the same upper 32 bits throughout all the values in
2391 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15])
2392 * range.
2393 *
2394 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32,
2395 * following the rules outlined below about u64/s64 correspondence
2396 * (which equally applies to u32 vs s32 correspondence). In general it
2397 * depends on actual hexadecimal values of 32-bit range. They can form
2398 * only valid u32, or only valid s32 ranges in some cases.
2399 *
2400 * So we use all these insights to derive bounds for subregisters here.
2401 */
2402 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) {
2403 /* u64 to u32 casting preserves validity of low 32 bits as
2404 * a range, if upper 32 bits are the same
2405 */
2406 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value);
2407 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value);
2408
2409 if ((s32)reg->umin_value <= (s32)reg->umax_value) {
2410 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2411 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2412 }
2413 }
2414 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) {
2415 /* low 32 bits should form a proper u32 range */
2416 if ((u32)reg->smin_value <= (u32)reg->smax_value) {
2417 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value);
2418 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value);
2419 }
2420 /* low 32 bits should form a proper s32 range */
2421 if ((s32)reg->smin_value <= (s32)reg->smax_value) {
2422 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2423 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2424 }
2425 }
2426 /* Special case where upper bits form a small sequence of two
2427 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to
2428 * 0x00000000 is also valid), while lower bits form a proper s32 range
2429 * going from negative numbers to positive numbers. E.g., let's say we
2430 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]).
2431 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff,
2432 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits,
2433 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]).
2434 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in
2435 * upper 32 bits. As a random example, s64 range
2436 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range
2437 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister.
2438 */
2439 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) &&
2440 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) {
2441 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value);
2442 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value);
2443 }
2444 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) &&
2445 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) {
2446 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value);
2447 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value);
2448 }
2449 /* if u32 range forms a valid s32 range (due to matching sign bit),
2450 * try to learn from that
2451 */
2452 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) {
2453 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value);
2454 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value);
2455 }
2456 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2457 * are the same, so combine. This works even in the negative case, e.g.
2458 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2459 */
2460 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) {
2461 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value);
2462 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value);
2463 }
2464 }
2465
__reg64_deduce_bounds(struct bpf_reg_state * reg)2466 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2467 {
2468 /* If u64 range forms a valid s64 range (due to matching sign bit),
2469 * try to learn from that. Let's do a bit of ASCII art to see when
2470 * this is happening. Let's take u64 range first:
2471 *
2472 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2473 * |-------------------------------|--------------------------------|
2474 *
2475 * Valid u64 range is formed when umin and umax are anywhere in the
2476 * range [0, U64_MAX], and umin <= umax. u64 case is simple and
2477 * straightforward. Let's see how s64 range maps onto the same range
2478 * of values, annotated below the line for comparison:
2479 *
2480 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2481 * |-------------------------------|--------------------------------|
2482 * 0 S64_MAX S64_MIN -1
2483 *
2484 * So s64 values basically start in the middle and they are logically
2485 * contiguous to the right of it, wrapping around from -1 to 0, and
2486 * then finishing as S64_MAX (0x7fffffffffffffff) right before
2487 * S64_MIN. We can try drawing the continuity of u64 vs s64 values
2488 * more visually as mapped to sign-agnostic range of hex values.
2489 *
2490 * u64 start u64 end
2491 * _______________________________________________________________
2492 * / \
2493 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX
2494 * |-------------------------------|--------------------------------|
2495 * 0 S64_MAX S64_MIN -1
2496 * / \
2497 * >------------------------------ ------------------------------->
2498 * s64 continues... s64 end s64 start s64 "midpoint"
2499 *
2500 * What this means is that, in general, we can't always derive
2501 * something new about u64 from any random s64 range, and vice versa.
2502 *
2503 * But we can do that in two particular cases. One is when entire
2504 * u64/s64 range is *entirely* contained within left half of the above
2505 * diagram or when it is *entirely* contained in the right half. I.e.:
2506 *
2507 * |-------------------------------|--------------------------------|
2508 * ^ ^ ^ ^
2509 * A B C D
2510 *
2511 * [A, B] and [C, D] are contained entirely in their respective halves
2512 * and form valid contiguous ranges as both u64 and s64 values. [A, B]
2513 * will be non-negative both as u64 and s64 (and in fact it will be
2514 * identical ranges no matter the signedness). [C, D] treated as s64
2515 * will be a range of negative values, while in u64 it will be
2516 * non-negative range of values larger than 0x8000000000000000.
2517 *
2518 * Now, any other range here can't be represented in both u64 and s64
2519 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid
2520 * contiguous u64 ranges, but they are discontinuous in s64. [B, C]
2521 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX],
2522 * for example. Similarly, valid s64 range [D, A] (going from negative
2523 * to positive values), would be two separate [D, U64_MAX] and [0, A]
2524 * ranges as u64. Currently reg_state can't represent two segments per
2525 * numeric domain, so in such situations we can only derive maximal
2526 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64).
2527 *
2528 * So we use these facts to derive umin/umax from smin/smax and vice
2529 * versa only if they stay within the same "half". This is equivalent
2530 * to checking sign bit: lower half will have sign bit as zero, upper
2531 * half have sign bit 1. Below in code we simplify this by just
2532 * casting umin/umax as smin/smax and checking if they form valid
2533 * range, and vice versa. Those are equivalent checks.
2534 */
2535 if ((s64)reg->umin_value <= (s64)reg->umax_value) {
2536 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value);
2537 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value);
2538 }
2539 /* If we cannot cross the sign boundary, then signed and unsigned bounds
2540 * are the same, so combine. This works even in the negative case, e.g.
2541 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2542 */
2543 if ((u64)reg->smin_value <= (u64)reg->smax_value) {
2544 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value);
2545 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value);
2546 } else {
2547 /* If the s64 range crosses the sign boundary, then it's split
2548 * between the beginning and end of the U64 domain. In that
2549 * case, we can derive new bounds if the u64 range overlaps
2550 * with only one end of the s64 range.
2551 *
2552 * In the following example, the u64 range overlaps only with
2553 * positive portion of the s64 range.
2554 *
2555 * 0 U64_MAX
2556 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] |
2557 * |----------------------------|----------------------------|
2558 * |xxxxx s64 range xxxxxxxxx] [xxxxxxx|
2559 * 0 S64_MAX S64_MIN -1
2560 *
2561 * We can thus derive the following new s64 and u64 ranges.
2562 *
2563 * 0 U64_MAX
2564 * | [xxxxxx u64 range xxxxx] |
2565 * |----------------------------|----------------------------|
2566 * | [xxxxxx s64 range xxxxx] |
2567 * 0 S64_MAX S64_MIN -1
2568 *
2569 * If they overlap in two places, we can't derive anything
2570 * because reg_state can't represent two ranges per numeric
2571 * domain.
2572 *
2573 * 0 U64_MAX
2574 * | [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx] |
2575 * |----------------------------|----------------------------|
2576 * |xxxxx s64 range xxxxxxxxx] [xxxxxxxxxx|
2577 * 0 S64_MAX S64_MIN -1
2578 *
2579 * The first condition below corresponds to the first diagram
2580 * above.
2581 */
2582 if (reg->umax_value < (u64)reg->smin_value) {
2583 reg->smin_value = (s64)reg->umin_value;
2584 reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value);
2585 } else if ((u64)reg->smax_value < reg->umin_value) {
2586 /* This second condition considers the case where the u64 range
2587 * overlaps with the negative portion of the s64 range:
2588 *
2589 * 0 U64_MAX
2590 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] |
2591 * |----------------------------|----------------------------|
2592 * |xxxxxxxxx] [xxxxxxxxxxxx s64 range |
2593 * 0 S64_MAX S64_MIN -1
2594 */
2595 reg->smax_value = (s64)reg->umax_value;
2596 reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value);
2597 }
2598 }
2599 }
2600
__reg_deduce_mixed_bounds(struct bpf_reg_state * reg)2601 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg)
2602 {
2603 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit
2604 * values on both sides of 64-bit range in hope to have tighter range.
2605 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from
2606 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff].
2607 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound
2608 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of
2609 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a
2610 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff].
2611 * We just need to make sure that derived bounds we are intersecting
2612 * with are well-formed ranges in respective s64 or u64 domain, just
2613 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments.
2614 */
2615 __u64 new_umin, new_umax;
2616 __s64 new_smin, new_smax;
2617
2618 /* u32 -> u64 tightening, it's always well-formed */
2619 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value;
2620 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value;
2621 reg->umin_value = max_t(u64, reg->umin_value, new_umin);
2622 reg->umax_value = min_t(u64, reg->umax_value, new_umax);
2623 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */
2624 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value;
2625 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value;
2626 reg->smin_value = max_t(s64, reg->smin_value, new_smin);
2627 reg->smax_value = min_t(s64, reg->smax_value, new_smax);
2628
2629 /* Here we would like to handle a special case after sign extending load,
2630 * when upper bits for a 64-bit range are all 1s or all 0s.
2631 *
2632 * Upper bits are all 1s when register is in a range:
2633 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff]
2634 * Upper bits are all 0s when register is in a range:
2635 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff]
2636 * Together this forms are continuous range:
2637 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff]
2638 *
2639 * Now, suppose that register range is in fact tighter:
2640 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R)
2641 * Also suppose that it's 32-bit range is positive,
2642 * meaning that lower 32-bits of the full 64-bit register
2643 * are in the range:
2644 * [0x0000_0000, 0x7fff_ffff] (W)
2645 *
2646 * If this happens, then any value in a range:
2647 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff]
2648 * is smaller than a lowest bound of the range (R):
2649 * 0xffff_ffff_8000_0000
2650 * which means that upper bits of the full 64-bit register
2651 * can't be all 1s, when lower bits are in range (W).
2652 *
2653 * Note that:
2654 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN
2655 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX
2656 * These relations are used in the conditions below.
2657 */
2658 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) {
2659 reg->smin_value = reg->s32_min_value;
2660 reg->smax_value = reg->s32_max_value;
2661 reg->umin_value = reg->s32_min_value;
2662 reg->umax_value = reg->s32_max_value;
2663 reg->var_off = tnum_intersect(reg->var_off,
2664 tnum_range(reg->smin_value, reg->smax_value));
2665 }
2666 }
2667
__reg_deduce_bounds(struct bpf_reg_state * reg)2668 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2669 {
2670 __reg32_deduce_bounds(reg);
2671 __reg64_deduce_bounds(reg);
2672 __reg_deduce_mixed_bounds(reg);
2673 }
2674
2675 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2676 static void __reg_bound_offset(struct bpf_reg_state *reg)
2677 {
2678 struct tnum var64_off = tnum_intersect(reg->var_off,
2679 tnum_range(reg->umin_value,
2680 reg->umax_value));
2681 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2682 tnum_range(reg->u32_min_value,
2683 reg->u32_max_value));
2684
2685 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2686 }
2687
reg_bounds_sync(struct bpf_reg_state * reg)2688 static void reg_bounds_sync(struct bpf_reg_state *reg)
2689 {
2690 /* We might have learned new bounds from the var_off. */
2691 __update_reg_bounds(reg);
2692 /* We might have learned something about the sign bit. */
2693 __reg_deduce_bounds(reg);
2694 __reg_deduce_bounds(reg);
2695 __reg_deduce_bounds(reg);
2696 /* We might have learned some bits from the bounds. */
2697 __reg_bound_offset(reg);
2698 /* Intersecting with the old var_off might have improved our bounds
2699 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2700 * then new var_off is (0; 0x7f...fc) which improves our umax.
2701 */
2702 __update_reg_bounds(reg);
2703 }
2704
reg_bounds_sanity_check(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * ctx)2705 static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
2706 struct bpf_reg_state *reg, const char *ctx)
2707 {
2708 const char *msg;
2709
2710 if (reg->umin_value > reg->umax_value ||
2711 reg->smin_value > reg->smax_value ||
2712 reg->u32_min_value > reg->u32_max_value ||
2713 reg->s32_min_value > reg->s32_max_value) {
2714 msg = "range bounds violation";
2715 goto out;
2716 }
2717
2718 if (tnum_is_const(reg->var_off)) {
2719 u64 uval = reg->var_off.value;
2720 s64 sval = (s64)uval;
2721
2722 if (reg->umin_value != uval || reg->umax_value != uval ||
2723 reg->smin_value != sval || reg->smax_value != sval) {
2724 msg = "const tnum out of sync with range bounds";
2725 goto out;
2726 }
2727 }
2728
2729 if (tnum_subreg_is_const(reg->var_off)) {
2730 u32 uval32 = tnum_subreg(reg->var_off).value;
2731 s32 sval32 = (s32)uval32;
2732
2733 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 ||
2734 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) {
2735 msg = "const subreg tnum out of sync with range bounds";
2736 goto out;
2737 }
2738 }
2739
2740 return 0;
2741 out:
2742 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] "
2743 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)",
2744 ctx, msg, reg->umin_value, reg->umax_value,
2745 reg->smin_value, reg->smax_value,
2746 reg->u32_min_value, reg->u32_max_value,
2747 reg->s32_min_value, reg->s32_max_value,
2748 reg->var_off.value, reg->var_off.mask);
2749 if (env->test_reg_invariants)
2750 return -EFAULT;
2751 __mark_reg_unbounded(reg);
2752 return 0;
2753 }
2754
__reg32_bound_s64(s32 a)2755 static bool __reg32_bound_s64(s32 a)
2756 {
2757 return a >= 0 && a <= S32_MAX;
2758 }
2759
__reg_assign_32_into_64(struct bpf_reg_state * reg)2760 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2761 {
2762 reg->umin_value = reg->u32_min_value;
2763 reg->umax_value = reg->u32_max_value;
2764
2765 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2766 * be positive otherwise set to worse case bounds and refine later
2767 * from tnum.
2768 */
2769 if (__reg32_bound_s64(reg->s32_min_value) &&
2770 __reg32_bound_s64(reg->s32_max_value)) {
2771 reg->smin_value = reg->s32_min_value;
2772 reg->smax_value = reg->s32_max_value;
2773 } else {
2774 reg->smin_value = 0;
2775 reg->smax_value = U32_MAX;
2776 }
2777 }
2778
2779 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown_imprecise(struct bpf_reg_state * reg)2780 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg)
2781 {
2782 /*
2783 * Clear type, off, and union(map_ptr, range) and
2784 * padding between 'type' and union
2785 */
2786 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2787 reg->type = SCALAR_VALUE;
2788 reg->id = 0;
2789 reg->ref_obj_id = 0;
2790 reg->var_off = tnum_unknown;
2791 reg->frameno = 0;
2792 reg->precise = false;
2793 __mark_reg_unbounded(reg);
2794 }
2795
2796 /* Mark a register as having a completely unknown (scalar) value,
2797 * initialize .precise as true when not bpf capable.
2798 */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2799 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2800 struct bpf_reg_state *reg)
2801 {
2802 __mark_reg_unknown_imprecise(reg);
2803 reg->precise = !env->bpf_capable;
2804 }
2805
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2806 static void mark_reg_unknown(struct bpf_verifier_env *env,
2807 struct bpf_reg_state *regs, u32 regno)
2808 {
2809 if (WARN_ON(regno >= MAX_BPF_REG)) {
2810 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2811 /* Something bad happened, let's kill all regs except FP */
2812 for (regno = 0; regno < BPF_REG_FP; regno++)
2813 __mark_reg_not_init(env, regs + regno);
2814 return;
2815 }
2816 __mark_reg_unknown(env, regs + regno);
2817 }
2818
__mark_reg_s32_range(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,s32 s32_min,s32 s32_max)2819 static int __mark_reg_s32_range(struct bpf_verifier_env *env,
2820 struct bpf_reg_state *regs,
2821 u32 regno,
2822 s32 s32_min,
2823 s32 s32_max)
2824 {
2825 struct bpf_reg_state *reg = regs + regno;
2826
2827 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min);
2828 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max);
2829
2830 reg->smin_value = max_t(s64, reg->smin_value, s32_min);
2831 reg->smax_value = min_t(s64, reg->smax_value, s32_max);
2832
2833 reg_bounds_sync(reg);
2834
2835 return reg_bounds_sanity_check(env, reg, "s32_range");
2836 }
2837
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2838 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2839 struct bpf_reg_state *reg)
2840 {
2841 __mark_reg_unknown(env, reg);
2842 reg->type = NOT_INIT;
2843 }
2844
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2845 static void mark_reg_not_init(struct bpf_verifier_env *env,
2846 struct bpf_reg_state *regs, u32 regno)
2847 {
2848 if (WARN_ON(regno >= MAX_BPF_REG)) {
2849 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2850 /* Something bad happened, let's kill all regs except FP */
2851 for (regno = 0; regno < BPF_REG_FP; regno++)
2852 __mark_reg_not_init(env, regs + regno);
2853 return;
2854 }
2855 __mark_reg_not_init(env, regs + regno);
2856 }
2857
mark_btf_ld_reg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum bpf_reg_type reg_type,struct btf * btf,u32 btf_id,enum bpf_type_flag flag)2858 static int mark_btf_ld_reg(struct bpf_verifier_env *env,
2859 struct bpf_reg_state *regs, u32 regno,
2860 enum bpf_reg_type reg_type,
2861 struct btf *btf, u32 btf_id,
2862 enum bpf_type_flag flag)
2863 {
2864 switch (reg_type) {
2865 case SCALAR_VALUE:
2866 mark_reg_unknown(env, regs, regno);
2867 return 0;
2868 case PTR_TO_BTF_ID:
2869 mark_reg_known_zero(env, regs, regno);
2870 regs[regno].type = PTR_TO_BTF_ID | flag;
2871 regs[regno].btf = btf;
2872 regs[regno].btf_id = btf_id;
2873 if (type_may_be_null(flag))
2874 regs[regno].id = ++env->id_gen;
2875 return 0;
2876 case PTR_TO_MEM:
2877 mark_reg_known_zero(env, regs, regno);
2878 regs[regno].type = PTR_TO_MEM | flag;
2879 regs[regno].mem_size = 0;
2880 return 0;
2881 default:
2882 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__);
2883 return -EFAULT;
2884 }
2885 }
2886
2887 #define DEF_NOT_SUBREG (0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2888 static void init_reg_state(struct bpf_verifier_env *env,
2889 struct bpf_func_state *state)
2890 {
2891 struct bpf_reg_state *regs = state->regs;
2892 int i;
2893
2894 for (i = 0; i < MAX_BPF_REG; i++) {
2895 mark_reg_not_init(env, regs, i);
2896 regs[i].subreg_def = DEF_NOT_SUBREG;
2897 }
2898
2899 /* frame pointer */
2900 regs[BPF_REG_FP].type = PTR_TO_STACK;
2901 mark_reg_known_zero(env, regs, BPF_REG_FP);
2902 regs[BPF_REG_FP].frameno = state->frameno;
2903 }
2904
retval_range(s32 minval,s32 maxval)2905 static struct bpf_retval_range retval_range(s32 minval, s32 maxval)
2906 {
2907 return (struct bpf_retval_range){ minval, maxval };
2908 }
2909
2910 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2911 static void init_func_state(struct bpf_verifier_env *env,
2912 struct bpf_func_state *state,
2913 int callsite, int frameno, int subprogno)
2914 {
2915 state->callsite = callsite;
2916 state->frameno = frameno;
2917 state->subprogno = subprogno;
2918 state->callback_ret_range = retval_range(0, 0);
2919 init_reg_state(env, state);
2920 mark_verifier_state_scratched(env);
2921 }
2922
2923 /* Similar to push_stack(), but for async callbacks */
push_async_cb(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,int subprog,bool is_sleepable)2924 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2925 int insn_idx, int prev_insn_idx,
2926 int subprog, bool is_sleepable)
2927 {
2928 struct bpf_verifier_stack_elem *elem;
2929 struct bpf_func_state *frame;
2930
2931 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT);
2932 if (!elem)
2933 return ERR_PTR(-ENOMEM);
2934
2935 elem->insn_idx = insn_idx;
2936 elem->prev_insn_idx = prev_insn_idx;
2937 elem->next = env->head;
2938 elem->log_pos = env->log.end_pos;
2939 env->head = elem;
2940 env->stack_size++;
2941 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2942 verbose(env,
2943 "The sequence of %d jumps is too complex for async cb.\n",
2944 env->stack_size);
2945 return ERR_PTR(-E2BIG);
2946 }
2947 /* Unlike push_stack() do not copy_verifier_state().
2948 * The caller state doesn't matter.
2949 * This is async callback. It starts in a fresh stack.
2950 * Initialize it similar to do_check_common().
2951 */
2952 elem->st.branches = 1;
2953 elem->st.in_sleepable = is_sleepable;
2954 frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT);
2955 if (!frame)
2956 return ERR_PTR(-ENOMEM);
2957 init_func_state(env, frame,
2958 BPF_MAIN_FUNC /* callsite */,
2959 0 /* frameno within this callchain */,
2960 subprog /* subprog number within this prog */);
2961 elem->st.frame[0] = frame;
2962 return &elem->st;
2963 }
2964
2965
2966 enum reg_arg_type {
2967 SRC_OP, /* register is used as source operand */
2968 DST_OP, /* register is used as destination operand */
2969 DST_OP_NO_MARK /* same as above, check only, don't mark */
2970 };
2971
cmp_subprogs(const void * a,const void * b)2972 static int cmp_subprogs(const void *a, const void *b)
2973 {
2974 return ((struct bpf_subprog_info *)a)->start -
2975 ((struct bpf_subprog_info *)b)->start;
2976 }
2977
2978 /* Find subprogram that contains instruction at 'off' */
bpf_find_containing_subprog(struct bpf_verifier_env * env,int off)2979 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off)
2980 {
2981 struct bpf_subprog_info *vals = env->subprog_info;
2982 int l, r, m;
2983
2984 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0)
2985 return NULL;
2986
2987 l = 0;
2988 r = env->subprog_cnt - 1;
2989 while (l < r) {
2990 m = l + (r - l + 1) / 2;
2991 if (vals[m].start <= off)
2992 l = m;
2993 else
2994 r = m - 1;
2995 }
2996 return &vals[l];
2997 }
2998
2999 /* Find subprogram that starts exactly at 'off' */
find_subprog(struct bpf_verifier_env * env,int off)3000 static int find_subprog(struct bpf_verifier_env *env, int off)
3001 {
3002 struct bpf_subprog_info *p;
3003
3004 p = bpf_find_containing_subprog(env, off);
3005 if (!p || p->start != off)
3006 return -ENOENT;
3007 return p - env->subprog_info;
3008 }
3009
add_subprog(struct bpf_verifier_env * env,int off)3010 static int add_subprog(struct bpf_verifier_env *env, int off)
3011 {
3012 int insn_cnt = env->prog->len;
3013 int ret;
3014
3015 if (off >= insn_cnt || off < 0) {
3016 verbose(env, "call to invalid destination\n");
3017 return -EINVAL;
3018 }
3019 ret = find_subprog(env, off);
3020 if (ret >= 0)
3021 return ret;
3022 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
3023 verbose(env, "too many subprograms\n");
3024 return -E2BIG;
3025 }
3026 /* determine subprog starts. The end is one before the next starts */
3027 env->subprog_info[env->subprog_cnt++].start = off;
3028 sort(env->subprog_info, env->subprog_cnt,
3029 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
3030 return env->subprog_cnt - 1;
3031 }
3032
bpf_find_exception_callback_insn_off(struct bpf_verifier_env * env)3033 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
3034 {
3035 struct bpf_prog_aux *aux = env->prog->aux;
3036 struct btf *btf = aux->btf;
3037 const struct btf_type *t;
3038 u32 main_btf_id, id;
3039 const char *name;
3040 int ret, i;
3041
3042 /* Non-zero func_info_cnt implies valid btf */
3043 if (!aux->func_info_cnt)
3044 return 0;
3045 main_btf_id = aux->func_info[0].type_id;
3046
3047 t = btf_type_by_id(btf, main_btf_id);
3048 if (!t) {
3049 verbose(env, "invalid btf id for main subprog in func_info\n");
3050 return -EINVAL;
3051 }
3052
3053 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
3054 if (IS_ERR(name)) {
3055 ret = PTR_ERR(name);
3056 /* If there is no tag present, there is no exception callback */
3057 if (ret == -ENOENT)
3058 ret = 0;
3059 else if (ret == -EEXIST)
3060 verbose(env, "multiple exception callback tags for main subprog\n");
3061 return ret;
3062 }
3063
3064 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
3065 if (ret < 0) {
3066 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
3067 return ret;
3068 }
3069 id = ret;
3070 t = btf_type_by_id(btf, id);
3071 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
3072 verbose(env, "exception callback '%s' must have global linkage\n", name);
3073 return -EINVAL;
3074 }
3075 ret = 0;
3076 for (i = 0; i < aux->func_info_cnt; i++) {
3077 if (aux->func_info[i].type_id != id)
3078 continue;
3079 ret = aux->func_info[i].insn_off;
3080 /* Further func_info and subprog checks will also happen
3081 * later, so assume this is the right insn_off for now.
3082 */
3083 if (!ret) {
3084 verbose(env, "invalid exception callback insn_off in func_info: 0\n");
3085 ret = -EINVAL;
3086 }
3087 }
3088 if (!ret) {
3089 verbose(env, "exception callback type id not found in func_info\n");
3090 ret = -EINVAL;
3091 }
3092 return ret;
3093 }
3094
3095 #define MAX_KFUNC_DESCS 256
3096 #define MAX_KFUNC_BTFS 256
3097
3098 struct bpf_kfunc_desc {
3099 struct btf_func_model func_model;
3100 u32 func_id;
3101 s32 imm;
3102 u16 offset;
3103 unsigned long addr;
3104 };
3105
3106 struct bpf_kfunc_btf {
3107 struct btf *btf;
3108 struct module *module;
3109 u16 offset;
3110 };
3111
3112 struct bpf_kfunc_desc_tab {
3113 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
3114 * verification. JITs do lookups by bpf_insn, where func_id may not be
3115 * available, therefore at the end of verification do_misc_fixups()
3116 * sorts this by imm and offset.
3117 */
3118 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
3119 u32 nr_descs;
3120 };
3121
3122 struct bpf_kfunc_btf_tab {
3123 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
3124 u32 nr_descs;
3125 };
3126
3127 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
3128 int insn_idx);
3129
kfunc_desc_cmp_by_id_off(const void * a,const void * b)3130 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
3131 {
3132 const struct bpf_kfunc_desc *d0 = a;
3133 const struct bpf_kfunc_desc *d1 = b;
3134
3135 /* func_id is not greater than BTF_MAX_TYPE */
3136 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
3137 }
3138
kfunc_btf_cmp_by_off(const void * a,const void * b)3139 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
3140 {
3141 const struct bpf_kfunc_btf *d0 = a;
3142 const struct bpf_kfunc_btf *d1 = b;
3143
3144 return d0->offset - d1->offset;
3145 }
3146
3147 static struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)3148 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
3149 {
3150 struct bpf_kfunc_desc desc = {
3151 .func_id = func_id,
3152 .offset = offset,
3153 };
3154 struct bpf_kfunc_desc_tab *tab;
3155
3156 tab = prog->aux->kfunc_tab;
3157 return bsearch(&desc, tab->descs, tab->nr_descs,
3158 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
3159 }
3160
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)3161 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3162 u16 btf_fd_idx, u8 **func_addr)
3163 {
3164 const struct bpf_kfunc_desc *desc;
3165
3166 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
3167 if (!desc)
3168 return -EFAULT;
3169
3170 *func_addr = (u8 *)desc->addr;
3171 return 0;
3172 }
3173
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)3174 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
3175 s16 offset)
3176 {
3177 struct bpf_kfunc_btf kf_btf = { .offset = offset };
3178 struct bpf_kfunc_btf_tab *tab;
3179 struct bpf_kfunc_btf *b;
3180 struct module *mod;
3181 struct btf *btf;
3182 int btf_fd;
3183
3184 tab = env->prog->aux->kfunc_btf_tab;
3185 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
3186 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
3187 if (!b) {
3188 if (tab->nr_descs == MAX_KFUNC_BTFS) {
3189 verbose(env, "too many different module BTFs\n");
3190 return ERR_PTR(-E2BIG);
3191 }
3192
3193 if (bpfptr_is_null(env->fd_array)) {
3194 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
3195 return ERR_PTR(-EPROTO);
3196 }
3197
3198 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
3199 offset * sizeof(btf_fd),
3200 sizeof(btf_fd)))
3201 return ERR_PTR(-EFAULT);
3202
3203 btf = btf_get_by_fd(btf_fd);
3204 if (IS_ERR(btf)) {
3205 verbose(env, "invalid module BTF fd specified\n");
3206 return btf;
3207 }
3208
3209 if (!btf_is_module(btf)) {
3210 verbose(env, "BTF fd for kfunc is not a module BTF\n");
3211 btf_put(btf);
3212 return ERR_PTR(-EINVAL);
3213 }
3214
3215 mod = btf_try_get_module(btf);
3216 if (!mod) {
3217 btf_put(btf);
3218 return ERR_PTR(-ENXIO);
3219 }
3220
3221 b = &tab->descs[tab->nr_descs++];
3222 b->btf = btf;
3223 b->module = mod;
3224 b->offset = offset;
3225
3226 /* sort() reorders entries by value, so b may no longer point
3227 * to the right entry after this
3228 */
3229 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3230 kfunc_btf_cmp_by_off, NULL);
3231 } else {
3232 btf = b->btf;
3233 }
3234
3235 return btf;
3236 }
3237
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)3238 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
3239 {
3240 if (!tab)
3241 return;
3242
3243 while (tab->nr_descs--) {
3244 module_put(tab->descs[tab->nr_descs].module);
3245 btf_put(tab->descs[tab->nr_descs].btf);
3246 }
3247 kfree(tab);
3248 }
3249
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)3250 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
3251 {
3252 if (offset) {
3253 if (offset < 0) {
3254 /* In the future, this can be allowed to increase limit
3255 * of fd index into fd_array, interpreted as u16.
3256 */
3257 verbose(env, "negative offset disallowed for kernel module function call\n");
3258 return ERR_PTR(-EINVAL);
3259 }
3260
3261 return __find_kfunc_desc_btf(env, offset);
3262 }
3263 return btf_vmlinux ?: ERR_PTR(-ENOENT);
3264 }
3265
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)3266 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
3267 {
3268 const struct btf_type *func, *func_proto;
3269 struct bpf_kfunc_btf_tab *btf_tab;
3270 struct btf_func_model func_model;
3271 struct bpf_kfunc_desc_tab *tab;
3272 struct bpf_prog_aux *prog_aux;
3273 struct bpf_kfunc_desc *desc;
3274 const char *func_name;
3275 struct btf *desc_btf;
3276 unsigned long addr;
3277 int err;
3278
3279 prog_aux = env->prog->aux;
3280 tab = prog_aux->kfunc_tab;
3281 btf_tab = prog_aux->kfunc_btf_tab;
3282 if (!tab) {
3283 if (!btf_vmlinux) {
3284 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
3285 return -ENOTSUPP;
3286 }
3287
3288 if (!env->prog->jit_requested) {
3289 verbose(env, "JIT is required for calling kernel function\n");
3290 return -ENOTSUPP;
3291 }
3292
3293 if (!bpf_jit_supports_kfunc_call()) {
3294 verbose(env, "JIT does not support calling kernel function\n");
3295 return -ENOTSUPP;
3296 }
3297
3298 if (!env->prog->gpl_compatible) {
3299 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
3300 return -EINVAL;
3301 }
3302
3303 tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT);
3304 if (!tab)
3305 return -ENOMEM;
3306 prog_aux->kfunc_tab = tab;
3307 }
3308
3309 /* func_id == 0 is always invalid, but instead of returning an error, be
3310 * conservative and wait until the code elimination pass before returning
3311 * error, so that invalid calls that get pruned out can be in BPF programs
3312 * loaded from userspace. It is also required that offset be untouched
3313 * for such calls.
3314 */
3315 if (!func_id && !offset)
3316 return 0;
3317
3318 if (!btf_tab && offset) {
3319 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT);
3320 if (!btf_tab)
3321 return -ENOMEM;
3322 prog_aux->kfunc_btf_tab = btf_tab;
3323 }
3324
3325 desc_btf = find_kfunc_desc_btf(env, offset);
3326 if (IS_ERR(desc_btf)) {
3327 verbose(env, "failed to find BTF for kernel function\n");
3328 return PTR_ERR(desc_btf);
3329 }
3330
3331 if (find_kfunc_desc(env->prog, func_id, offset))
3332 return 0;
3333
3334 if (tab->nr_descs == MAX_KFUNC_DESCS) {
3335 verbose(env, "too many different kernel function calls\n");
3336 return -E2BIG;
3337 }
3338
3339 func = btf_type_by_id(desc_btf, func_id);
3340 if (!func || !btf_type_is_func(func)) {
3341 verbose(env, "kernel btf_id %u is not a function\n",
3342 func_id);
3343 return -EINVAL;
3344 }
3345 func_proto = btf_type_by_id(desc_btf, func->type);
3346 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
3347 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
3348 func_id);
3349 return -EINVAL;
3350 }
3351
3352 func_name = btf_name_by_offset(desc_btf, func->name_off);
3353 addr = kallsyms_lookup_name(func_name);
3354 if (!addr) {
3355 verbose(env, "cannot find address for kernel function %s\n",
3356 func_name);
3357 return -EINVAL;
3358 }
3359
3360 if (bpf_dev_bound_kfunc_id(func_id)) {
3361 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3362 if (err)
3363 return err;
3364 }
3365
3366 err = btf_distill_func_proto(&env->log, desc_btf,
3367 func_proto, func_name,
3368 &func_model);
3369 if (err)
3370 return err;
3371
3372 desc = &tab->descs[tab->nr_descs++];
3373 desc->func_id = func_id;
3374 desc->offset = offset;
3375 desc->addr = addr;
3376 desc->func_model = func_model;
3377 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3378 kfunc_desc_cmp_by_id_off, NULL);
3379 return 0;
3380 }
3381
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)3382 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3383 {
3384 const struct bpf_kfunc_desc *d0 = a;
3385 const struct bpf_kfunc_desc *d1 = b;
3386
3387 if (d0->imm != d1->imm)
3388 return d0->imm < d1->imm ? -1 : 1;
3389 if (d0->offset != d1->offset)
3390 return d0->offset < d1->offset ? -1 : 1;
3391 return 0;
3392 }
3393
set_kfunc_desc_imm(struct bpf_verifier_env * env,struct bpf_kfunc_desc * desc)3394 static int set_kfunc_desc_imm(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
3395 {
3396 unsigned long call_imm;
3397
3398 if (bpf_jit_supports_far_kfunc_call()) {
3399 call_imm = desc->func_id;
3400 } else {
3401 call_imm = BPF_CALL_IMM(desc->addr);
3402 /* Check whether the relative offset overflows desc->imm */
3403 if ((unsigned long)(s32)call_imm != call_imm) {
3404 verbose(env, "address of kernel func_id %u is out of range\n",
3405 desc->func_id);
3406 return -EINVAL;
3407 }
3408 }
3409 desc->imm = call_imm;
3410 return 0;
3411 }
3412
sort_kfunc_descs_by_imm_off(struct bpf_verifier_env * env)3413 static int sort_kfunc_descs_by_imm_off(struct bpf_verifier_env *env)
3414 {
3415 struct bpf_kfunc_desc_tab *tab;
3416 int i, err;
3417
3418 tab = env->prog->aux->kfunc_tab;
3419 if (!tab)
3420 return 0;
3421
3422 for (i = 0; i < tab->nr_descs; i++) {
3423 err = set_kfunc_desc_imm(env, &tab->descs[i]);
3424 if (err)
3425 return err;
3426 }
3427
3428 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3429 kfunc_desc_cmp_by_imm_off, NULL);
3430 return 0;
3431 }
3432
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)3433 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3434 {
3435 return !!prog->aux->kfunc_tab;
3436 }
3437
3438 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)3439 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3440 const struct bpf_insn *insn)
3441 {
3442 const struct bpf_kfunc_desc desc = {
3443 .imm = insn->imm,
3444 .offset = insn->off,
3445 };
3446 const struct bpf_kfunc_desc *res;
3447 struct bpf_kfunc_desc_tab *tab;
3448
3449 tab = prog->aux->kfunc_tab;
3450 res = bsearch(&desc, tab->descs, tab->nr_descs,
3451 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3452
3453 return res ? &res->func_model : NULL;
3454 }
3455
add_kfunc_in_insns(struct bpf_verifier_env * env,struct bpf_insn * insn,int cnt)3456 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
3457 struct bpf_insn *insn, int cnt)
3458 {
3459 int i, ret;
3460
3461 for (i = 0; i < cnt; i++, insn++) {
3462 if (bpf_pseudo_kfunc_call(insn)) {
3463 ret = add_kfunc_call(env, insn->imm, insn->off);
3464 if (ret < 0)
3465 return ret;
3466 }
3467 }
3468 return 0;
3469 }
3470
add_subprog_and_kfunc(struct bpf_verifier_env * env)3471 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3472 {
3473 struct bpf_subprog_info *subprog = env->subprog_info;
3474 int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3475 struct bpf_insn *insn = env->prog->insnsi;
3476
3477 /* Add entry function. */
3478 ret = add_subprog(env, 0);
3479 if (ret)
3480 return ret;
3481
3482 for (i = 0; i < insn_cnt; i++, insn++) {
3483 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3484 !bpf_pseudo_kfunc_call(insn))
3485 continue;
3486
3487 if (!env->bpf_capable) {
3488 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3489 return -EPERM;
3490 }
3491
3492 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3493 ret = add_subprog(env, i + insn->imm + 1);
3494 else
3495 ret = add_kfunc_call(env, insn->imm, insn->off);
3496
3497 if (ret < 0)
3498 return ret;
3499 }
3500
3501 ret = bpf_find_exception_callback_insn_off(env);
3502 if (ret < 0)
3503 return ret;
3504 ex_cb_insn = ret;
3505
3506 /* If ex_cb_insn > 0, this means that the main program has a subprog
3507 * marked using BTF decl tag to serve as the exception callback.
3508 */
3509 if (ex_cb_insn) {
3510 ret = add_subprog(env, ex_cb_insn);
3511 if (ret < 0)
3512 return ret;
3513 for (i = 1; i < env->subprog_cnt; i++) {
3514 if (env->subprog_info[i].start != ex_cb_insn)
3515 continue;
3516 env->exception_callback_subprog = i;
3517 mark_subprog_exc_cb(env, i);
3518 break;
3519 }
3520 }
3521
3522 /* Add a fake 'exit' subprog which could simplify subprog iteration
3523 * logic. 'subprog_cnt' should not be increased.
3524 */
3525 subprog[env->subprog_cnt].start = insn_cnt;
3526
3527 if (env->log.level & BPF_LOG_LEVEL2)
3528 for (i = 0; i < env->subprog_cnt; i++)
3529 verbose(env, "func#%d @%d\n", i, subprog[i].start);
3530
3531 return 0;
3532 }
3533
check_subprogs(struct bpf_verifier_env * env)3534 static int check_subprogs(struct bpf_verifier_env *env)
3535 {
3536 int i, subprog_start, subprog_end, off, cur_subprog = 0;
3537 struct bpf_subprog_info *subprog = env->subprog_info;
3538 struct bpf_insn *insn = env->prog->insnsi;
3539 int insn_cnt = env->prog->len;
3540
3541 /* now check that all jumps are within the same subprog */
3542 subprog_start = subprog[cur_subprog].start;
3543 subprog_end = subprog[cur_subprog + 1].start;
3544 for (i = 0; i < insn_cnt; i++) {
3545 u8 code = insn[i].code;
3546
3547 if (code == (BPF_JMP | BPF_CALL) &&
3548 insn[i].src_reg == 0 &&
3549 insn[i].imm == BPF_FUNC_tail_call) {
3550 subprog[cur_subprog].has_tail_call = true;
3551 subprog[cur_subprog].tail_call_reachable = true;
3552 }
3553 if (BPF_CLASS(code) == BPF_LD &&
3554 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3555 subprog[cur_subprog].has_ld_abs = true;
3556 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3557 goto next;
3558 if (BPF_OP(code) == BPF_CALL)
3559 goto next;
3560 if (BPF_OP(code) == BPF_EXIT) {
3561 subprog[cur_subprog].exit_idx = i;
3562 goto next;
3563 }
3564 off = i + bpf_jmp_offset(&insn[i]) + 1;
3565 if (off < subprog_start || off >= subprog_end) {
3566 verbose(env, "jump out of range from insn %d to %d\n", i, off);
3567 return -EINVAL;
3568 }
3569 next:
3570 if (i == subprog_end - 1) {
3571 /* to avoid fall-through from one subprog into another
3572 * the last insn of the subprog should be either exit
3573 * or unconditional jump back or bpf_throw call
3574 */
3575 if (code != (BPF_JMP | BPF_EXIT) &&
3576 code != (BPF_JMP32 | BPF_JA) &&
3577 code != (BPF_JMP | BPF_JA)) {
3578 verbose(env, "last insn is not an exit or jmp\n");
3579 return -EINVAL;
3580 }
3581 subprog_start = subprog_end;
3582 cur_subprog++;
3583 if (cur_subprog < env->subprog_cnt)
3584 subprog_end = subprog[cur_subprog + 1].start;
3585 }
3586 }
3587 return 0;
3588 }
3589
mark_stack_slot_obj_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3590 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3591 int spi, int nr_slots)
3592 {
3593 int err, i;
3594
3595 for (i = 0; i < nr_slots; i++) {
3596 err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi - i));
3597 if (err)
3598 return err;
3599 mark_stack_slot_scratched(env, spi - i);
3600 }
3601 return 0;
3602 }
3603
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3604 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3605 {
3606 int spi;
3607
3608 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3609 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3610 * check_kfunc_call.
3611 */
3612 if (reg->type == CONST_PTR_TO_DYNPTR)
3613 return 0;
3614 spi = dynptr_get_spi(env, reg);
3615 if (spi < 0)
3616 return spi;
3617 /* Caller ensures dynptr is valid and initialized, which means spi is in
3618 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3619 * read.
3620 */
3621 return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS);
3622 }
3623
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3624 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3625 int spi, int nr_slots)
3626 {
3627 return mark_stack_slot_obj_read(env, reg, spi, nr_slots);
3628 }
3629
mark_irq_flag_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3630 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3631 {
3632 int spi;
3633
3634 spi = irq_flag_get_spi(env, reg);
3635 if (spi < 0)
3636 return spi;
3637 return mark_stack_slot_obj_read(env, reg, spi, 1);
3638 }
3639
3640 /* This function is supposed to be used by the following 32-bit optimization
3641 * code only. It returns TRUE if the source or destination register operates
3642 * on 64-bit, otherwise return FALSE.
3643 */
is_reg64(struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3644 static bool is_reg64(struct bpf_insn *insn,
3645 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3646 {
3647 u8 code, class, op;
3648
3649 code = insn->code;
3650 class = BPF_CLASS(code);
3651 op = BPF_OP(code);
3652 if (class == BPF_JMP) {
3653 /* BPF_EXIT for "main" will reach here. Return TRUE
3654 * conservatively.
3655 */
3656 if (op == BPF_EXIT)
3657 return true;
3658 if (op == BPF_CALL) {
3659 /* BPF to BPF call will reach here because of marking
3660 * caller saved clobber with DST_OP_NO_MARK for which we
3661 * don't care the register def because they are anyway
3662 * marked as NOT_INIT already.
3663 */
3664 if (insn->src_reg == BPF_PSEUDO_CALL)
3665 return false;
3666 /* Helper call will reach here because of arg type
3667 * check, conservatively return TRUE.
3668 */
3669 if (t == SRC_OP)
3670 return true;
3671
3672 return false;
3673 }
3674 }
3675
3676 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3677 return false;
3678
3679 if (class == BPF_ALU64 || class == BPF_JMP ||
3680 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3681 return true;
3682
3683 if (class == BPF_ALU || class == BPF_JMP32)
3684 return false;
3685
3686 if (class == BPF_LDX) {
3687 if (t != SRC_OP)
3688 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3689 /* LDX source must be ptr. */
3690 return true;
3691 }
3692
3693 if (class == BPF_STX) {
3694 /* BPF_STX (including atomic variants) has one or more source
3695 * operands, one of which is a ptr. Check whether the caller is
3696 * asking about it.
3697 */
3698 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3699 return true;
3700 return BPF_SIZE(code) == BPF_DW;
3701 }
3702
3703 if (class == BPF_LD) {
3704 u8 mode = BPF_MODE(code);
3705
3706 /* LD_IMM64 */
3707 if (mode == BPF_IMM)
3708 return true;
3709
3710 /* Both LD_IND and LD_ABS return 32-bit data. */
3711 if (t != SRC_OP)
3712 return false;
3713
3714 /* Implicit ctx ptr. */
3715 if (regno == BPF_REG_6)
3716 return true;
3717
3718 /* Explicit source could be any width. */
3719 return true;
3720 }
3721
3722 if (class == BPF_ST)
3723 /* The only source register for BPF_ST is a ptr. */
3724 return true;
3725
3726 /* Conservatively return true at default. */
3727 return true;
3728 }
3729
3730 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3731 static int insn_def_regno(const struct bpf_insn *insn)
3732 {
3733 switch (BPF_CLASS(insn->code)) {
3734 case BPF_JMP:
3735 case BPF_JMP32:
3736 case BPF_ST:
3737 return -1;
3738 case BPF_STX:
3739 if (BPF_MODE(insn->code) == BPF_ATOMIC ||
3740 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) {
3741 if (insn->imm == BPF_CMPXCHG)
3742 return BPF_REG_0;
3743 else if (insn->imm == BPF_LOAD_ACQ)
3744 return insn->dst_reg;
3745 else if (insn->imm & BPF_FETCH)
3746 return insn->src_reg;
3747 }
3748 return -1;
3749 default:
3750 return insn->dst_reg;
3751 }
3752 }
3753
3754 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_insn * insn)3755 static bool insn_has_def32(struct bpf_insn *insn)
3756 {
3757 int dst_reg = insn_def_regno(insn);
3758
3759 if (dst_reg == -1)
3760 return false;
3761
3762 return !is_reg64(insn, dst_reg, NULL, DST_OP);
3763 }
3764
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3765 static void mark_insn_zext(struct bpf_verifier_env *env,
3766 struct bpf_reg_state *reg)
3767 {
3768 s32 def_idx = reg->subreg_def;
3769
3770 if (def_idx == DEF_NOT_SUBREG)
3771 return;
3772
3773 env->insn_aux_data[def_idx - 1].zext_dst = true;
3774 /* The dst will be zero extended, so won't be sub-register anymore. */
3775 reg->subreg_def = DEF_NOT_SUBREG;
3776 }
3777
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3778 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3779 enum reg_arg_type t)
3780 {
3781 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3782 struct bpf_reg_state *reg;
3783 bool rw64;
3784
3785 if (regno >= MAX_BPF_REG) {
3786 verbose(env, "R%d is invalid\n", regno);
3787 return -EINVAL;
3788 }
3789
3790 mark_reg_scratched(env, regno);
3791
3792 reg = ®s[regno];
3793 rw64 = is_reg64(insn, regno, reg, t);
3794 if (t == SRC_OP) {
3795 /* check whether register used as source operand can be read */
3796 if (reg->type == NOT_INIT) {
3797 verbose(env, "R%d !read_ok\n", regno);
3798 return -EACCES;
3799 }
3800 /* We don't need to worry about FP liveness because it's read-only */
3801 if (regno == BPF_REG_FP)
3802 return 0;
3803
3804 if (rw64)
3805 mark_insn_zext(env, reg);
3806
3807 return 0;
3808 } else {
3809 /* check whether register used as dest operand can be written to */
3810 if (regno == BPF_REG_FP) {
3811 verbose(env, "frame pointer is read only\n");
3812 return -EACCES;
3813 }
3814 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3815 if (t == DST_OP)
3816 mark_reg_unknown(env, regs, regno);
3817 }
3818 return 0;
3819 }
3820
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3821 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3822 enum reg_arg_type t)
3823 {
3824 struct bpf_verifier_state *vstate = env->cur_state;
3825 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3826
3827 return __check_reg_arg(env, state->regs, regno, t);
3828 }
3829
insn_stack_access_flags(int frameno,int spi)3830 static int insn_stack_access_flags(int frameno, int spi)
3831 {
3832 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno;
3833 }
3834
insn_stack_access_spi(int insn_flags)3835 static int insn_stack_access_spi(int insn_flags)
3836 {
3837 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK;
3838 }
3839
insn_stack_access_frameno(int insn_flags)3840 static int insn_stack_access_frameno(int insn_flags)
3841 {
3842 return insn_flags & INSN_F_FRAMENO_MASK;
3843 }
3844
mark_jmp_point(struct bpf_verifier_env * env,int idx)3845 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3846 {
3847 env->insn_aux_data[idx].jmp_point = true;
3848 }
3849
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3850 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3851 {
3852 return env->insn_aux_data[insn_idx].jmp_point;
3853 }
3854
3855 #define LR_FRAMENO_BITS 3
3856 #define LR_SPI_BITS 6
3857 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1)
3858 #define LR_SIZE_BITS 4
3859 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1)
3860 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1)
3861 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1)
3862 #define LR_SPI_OFF LR_FRAMENO_BITS
3863 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS)
3864 #define LINKED_REGS_MAX 6
3865
3866 struct linked_reg {
3867 u8 frameno;
3868 union {
3869 u8 spi;
3870 u8 regno;
3871 };
3872 bool is_reg;
3873 };
3874
3875 struct linked_regs {
3876 int cnt;
3877 struct linked_reg entries[LINKED_REGS_MAX];
3878 };
3879
linked_regs_push(struct linked_regs * s)3880 static struct linked_reg *linked_regs_push(struct linked_regs *s)
3881 {
3882 if (s->cnt < LINKED_REGS_MAX)
3883 return &s->entries[s->cnt++];
3884
3885 return NULL;
3886 }
3887
3888 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track
3889 * number of elements currently in stack.
3890 * Pack one history entry for linked registers as 10 bits in the following format:
3891 * - 3-bits frameno
3892 * - 6-bits spi_or_reg
3893 * - 1-bit is_reg
3894 */
linked_regs_pack(struct linked_regs * s)3895 static u64 linked_regs_pack(struct linked_regs *s)
3896 {
3897 u64 val = 0;
3898 int i;
3899
3900 for (i = 0; i < s->cnt; ++i) {
3901 struct linked_reg *e = &s->entries[i];
3902 u64 tmp = 0;
3903
3904 tmp |= e->frameno;
3905 tmp |= e->spi << LR_SPI_OFF;
3906 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF;
3907
3908 val <<= LR_ENTRY_BITS;
3909 val |= tmp;
3910 }
3911 val <<= LR_SIZE_BITS;
3912 val |= s->cnt;
3913 return val;
3914 }
3915
linked_regs_unpack(u64 val,struct linked_regs * s)3916 static void linked_regs_unpack(u64 val, struct linked_regs *s)
3917 {
3918 int i;
3919
3920 s->cnt = val & LR_SIZE_MASK;
3921 val >>= LR_SIZE_BITS;
3922
3923 for (i = 0; i < s->cnt; ++i) {
3924 struct linked_reg *e = &s->entries[i];
3925
3926 e->frameno = val & LR_FRAMENO_MASK;
3927 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK;
3928 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1;
3929 val >>= LR_ENTRY_BITS;
3930 }
3931 }
3932
3933 /* for any branch, call, exit record the history of jmps in the given state */
push_jmp_history(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_flags,u64 linked_regs)3934 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur,
3935 int insn_flags, u64 linked_regs)
3936 {
3937 u32 cnt = cur->jmp_history_cnt;
3938 struct bpf_jmp_history_entry *p;
3939 size_t alloc_size;
3940
3941 /* combine instruction flags if we already recorded this instruction */
3942 if (env->cur_hist_ent) {
3943 /* atomic instructions push insn_flags twice, for READ and
3944 * WRITE sides, but they should agree on stack slot
3945 */
3946 verifier_bug_if((env->cur_hist_ent->flags & insn_flags) &&
3947 (env->cur_hist_ent->flags & insn_flags) != insn_flags,
3948 env, "insn history: insn_idx %d cur flags %x new flags %x",
3949 env->insn_idx, env->cur_hist_ent->flags, insn_flags);
3950 env->cur_hist_ent->flags |= insn_flags;
3951 verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env,
3952 "insn history: insn_idx %d linked_regs: %#llx",
3953 env->insn_idx, env->cur_hist_ent->linked_regs);
3954 env->cur_hist_ent->linked_regs = linked_regs;
3955 return 0;
3956 }
3957
3958 cnt++;
3959 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3960 p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT);
3961 if (!p)
3962 return -ENOMEM;
3963 cur->jmp_history = p;
3964
3965 p = &cur->jmp_history[cnt - 1];
3966 p->idx = env->insn_idx;
3967 p->prev_idx = env->prev_insn_idx;
3968 p->flags = insn_flags;
3969 p->linked_regs = linked_regs;
3970 cur->jmp_history_cnt = cnt;
3971 env->cur_hist_ent = p;
3972
3973 return 0;
3974 }
3975
get_jmp_hist_entry(struct bpf_verifier_state * st,u32 hist_end,int insn_idx)3976 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st,
3977 u32 hist_end, int insn_idx)
3978 {
3979 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx)
3980 return &st->jmp_history[hist_end - 1];
3981 return NULL;
3982 }
3983
3984 /* Backtrack one insn at a time. If idx is not at the top of recorded
3985 * history then previous instruction came from straight line execution.
3986 * Return -ENOENT if we exhausted all instructions within given state.
3987 *
3988 * It's legal to have a bit of a looping with the same starting and ending
3989 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3990 * instruction index is the same as state's first_idx doesn't mean we are
3991 * done. If there is still some jump history left, we should keep going. We
3992 * need to take into account that we might have a jump history between given
3993 * state's parent and itself, due to checkpointing. In this case, we'll have
3994 * history entry recording a jump from last instruction of parent state and
3995 * first instruction of given state.
3996 */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)3997 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3998 u32 *history)
3999 {
4000 u32 cnt = *history;
4001
4002 if (i == st->first_insn_idx) {
4003 if (cnt == 0)
4004 return -ENOENT;
4005 if (cnt == 1 && st->jmp_history[0].idx == i)
4006 return -ENOENT;
4007 }
4008
4009 if (cnt && st->jmp_history[cnt - 1].idx == i) {
4010 i = st->jmp_history[cnt - 1].prev_idx;
4011 (*history)--;
4012 } else {
4013 i--;
4014 }
4015 return i;
4016 }
4017
disasm_kfunc_name(void * data,const struct bpf_insn * insn)4018 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
4019 {
4020 const struct btf_type *func;
4021 struct btf *desc_btf;
4022
4023 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
4024 return NULL;
4025
4026 desc_btf = find_kfunc_desc_btf(data, insn->off);
4027 if (IS_ERR(desc_btf))
4028 return "<error>";
4029
4030 func = btf_type_by_id(desc_btf, insn->imm);
4031 return btf_name_by_offset(desc_btf, func->name_off);
4032 }
4033
verbose_insn(struct bpf_verifier_env * env,struct bpf_insn * insn)4034 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
4035 {
4036 const struct bpf_insn_cbs cbs = {
4037 .cb_call = disasm_kfunc_name,
4038 .cb_print = verbose,
4039 .private_data = env,
4040 };
4041
4042 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4043 }
4044
bt_init(struct backtrack_state * bt,u32 frame)4045 static inline void bt_init(struct backtrack_state *bt, u32 frame)
4046 {
4047 bt->frame = frame;
4048 }
4049
bt_reset(struct backtrack_state * bt)4050 static inline void bt_reset(struct backtrack_state *bt)
4051 {
4052 struct bpf_verifier_env *env = bt->env;
4053
4054 memset(bt, 0, sizeof(*bt));
4055 bt->env = env;
4056 }
4057
bt_empty(struct backtrack_state * bt)4058 static inline u32 bt_empty(struct backtrack_state *bt)
4059 {
4060 u64 mask = 0;
4061 int i;
4062
4063 for (i = 0; i <= bt->frame; i++)
4064 mask |= bt->reg_masks[i] | bt->stack_masks[i];
4065
4066 return mask == 0;
4067 }
4068
bt_subprog_enter(struct backtrack_state * bt)4069 static inline int bt_subprog_enter(struct backtrack_state *bt)
4070 {
4071 if (bt->frame == MAX_CALL_FRAMES - 1) {
4072 verifier_bug(bt->env, "subprog enter from frame %d", bt->frame);
4073 return -EFAULT;
4074 }
4075 bt->frame++;
4076 return 0;
4077 }
4078
bt_subprog_exit(struct backtrack_state * bt)4079 static inline int bt_subprog_exit(struct backtrack_state *bt)
4080 {
4081 if (bt->frame == 0) {
4082 verifier_bug(bt->env, "subprog exit from frame 0");
4083 return -EFAULT;
4084 }
4085 bt->frame--;
4086 return 0;
4087 }
4088
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)4089 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4090 {
4091 bt->reg_masks[frame] |= 1 << reg;
4092 }
4093
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)4094 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
4095 {
4096 bt->reg_masks[frame] &= ~(1 << reg);
4097 }
4098
bt_set_reg(struct backtrack_state * bt,u32 reg)4099 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
4100 {
4101 bt_set_frame_reg(bt, bt->frame, reg);
4102 }
4103
bt_clear_reg(struct backtrack_state * bt,u32 reg)4104 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
4105 {
4106 bt_clear_frame_reg(bt, bt->frame, reg);
4107 }
4108
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)4109 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4110 {
4111 bt->stack_masks[frame] |= 1ull << slot;
4112 }
4113
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)4114 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
4115 {
4116 bt->stack_masks[frame] &= ~(1ull << slot);
4117 }
4118
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)4119 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
4120 {
4121 return bt->reg_masks[frame];
4122 }
4123
bt_reg_mask(struct backtrack_state * bt)4124 static inline u32 bt_reg_mask(struct backtrack_state *bt)
4125 {
4126 return bt->reg_masks[bt->frame];
4127 }
4128
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)4129 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
4130 {
4131 return bt->stack_masks[frame];
4132 }
4133
bt_stack_mask(struct backtrack_state * bt)4134 static inline u64 bt_stack_mask(struct backtrack_state *bt)
4135 {
4136 return bt->stack_masks[bt->frame];
4137 }
4138
bt_is_reg_set(struct backtrack_state * bt,u32 reg)4139 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
4140 {
4141 return bt->reg_masks[bt->frame] & (1 << reg);
4142 }
4143
bt_is_frame_reg_set(struct backtrack_state * bt,u32 frame,u32 reg)4144 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg)
4145 {
4146 return bt->reg_masks[frame] & (1 << reg);
4147 }
4148
bt_is_frame_slot_set(struct backtrack_state * bt,u32 frame,u32 slot)4149 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot)
4150 {
4151 return bt->stack_masks[frame] & (1ull << slot);
4152 }
4153
4154 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)4155 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
4156 {
4157 DECLARE_BITMAP(mask, 64);
4158 bool first = true;
4159 int i, n;
4160
4161 buf[0] = '\0';
4162
4163 bitmap_from_u64(mask, reg_mask);
4164 for_each_set_bit(i, mask, 32) {
4165 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
4166 first = false;
4167 buf += n;
4168 buf_sz -= n;
4169 if (buf_sz < 0)
4170 break;
4171 }
4172 }
4173 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
bpf_fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)4174 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
4175 {
4176 DECLARE_BITMAP(mask, 64);
4177 bool first = true;
4178 int i, n;
4179
4180 buf[0] = '\0';
4181
4182 bitmap_from_u64(mask, stack_mask);
4183 for_each_set_bit(i, mask, 64) {
4184 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
4185 first = false;
4186 buf += n;
4187 buf_sz -= n;
4188 if (buf_sz < 0)
4189 break;
4190 }
4191 }
4192
4193 /* If any register R in hist->linked_regs is marked as precise in bt,
4194 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs.
4195 */
bt_sync_linked_regs(struct backtrack_state * bt,struct bpf_jmp_history_entry * hist)4196 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist)
4197 {
4198 struct linked_regs linked_regs;
4199 bool some_precise = false;
4200 int i;
4201
4202 if (!hist || hist->linked_regs == 0)
4203 return;
4204
4205 linked_regs_unpack(hist->linked_regs, &linked_regs);
4206 for (i = 0; i < linked_regs.cnt; ++i) {
4207 struct linked_reg *e = &linked_regs.entries[i];
4208
4209 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) ||
4210 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) {
4211 some_precise = true;
4212 break;
4213 }
4214 }
4215
4216 if (!some_precise)
4217 return;
4218
4219 for (i = 0; i < linked_regs.cnt; ++i) {
4220 struct linked_reg *e = &linked_regs.entries[i];
4221
4222 if (e->is_reg)
4223 bt_set_frame_reg(bt, e->frameno, e->regno);
4224 else
4225 bt_set_frame_slot(bt, e->frameno, e->spi);
4226 }
4227 }
4228
4229 /* For given verifier state backtrack_insn() is called from the last insn to
4230 * the first insn. Its purpose is to compute a bitmask of registers and
4231 * stack slots that needs precision in the parent verifier state.
4232 *
4233 * @idx is an index of the instruction we are currently processing;
4234 * @subseq_idx is an index of the subsequent instruction that:
4235 * - *would be* executed next, if jump history is viewed in forward order;
4236 * - *was* processed previously during backtracking.
4237 */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct bpf_jmp_history_entry * hist,struct backtrack_state * bt)4238 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
4239 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt)
4240 {
4241 struct bpf_insn *insn = env->prog->insnsi + idx;
4242 u8 class = BPF_CLASS(insn->code);
4243 u8 opcode = BPF_OP(insn->code);
4244 u8 mode = BPF_MODE(insn->code);
4245 u32 dreg = insn->dst_reg;
4246 u32 sreg = insn->src_reg;
4247 u32 spi, i, fr;
4248
4249 if (insn->code == 0)
4250 return 0;
4251 if (env->log.level & BPF_LOG_LEVEL2) {
4252 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
4253 verbose(env, "mark_precise: frame%d: regs=%s ",
4254 bt->frame, env->tmp_str_buf);
4255 bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
4256 verbose(env, "stack=%s before ", env->tmp_str_buf);
4257 verbose(env, "%d: ", idx);
4258 verbose_insn(env, insn);
4259 }
4260
4261 /* If there is a history record that some registers gained range at this insn,
4262 * propagate precision marks to those registers, so that bt_is_reg_set()
4263 * accounts for these registers.
4264 */
4265 bt_sync_linked_regs(bt, hist);
4266
4267 if (class == BPF_ALU || class == BPF_ALU64) {
4268 if (!bt_is_reg_set(bt, dreg))
4269 return 0;
4270 if (opcode == BPF_END || opcode == BPF_NEG) {
4271 /* sreg is reserved and unused
4272 * dreg still need precision before this insn
4273 */
4274 return 0;
4275 } else if (opcode == BPF_MOV) {
4276 if (BPF_SRC(insn->code) == BPF_X) {
4277 /* dreg = sreg or dreg = (s8, s16, s32)sreg
4278 * dreg needs precision after this insn
4279 * sreg needs precision before this insn
4280 */
4281 bt_clear_reg(bt, dreg);
4282 if (sreg != BPF_REG_FP)
4283 bt_set_reg(bt, sreg);
4284 } else {
4285 /* dreg = K
4286 * dreg needs precision after this insn.
4287 * Corresponding register is already marked
4288 * as precise=true in this verifier state.
4289 * No further markings in parent are necessary
4290 */
4291 bt_clear_reg(bt, dreg);
4292 }
4293 } else {
4294 if (BPF_SRC(insn->code) == BPF_X) {
4295 /* dreg += sreg
4296 * both dreg and sreg need precision
4297 * before this insn
4298 */
4299 if (sreg != BPF_REG_FP)
4300 bt_set_reg(bt, sreg);
4301 } /* else dreg += K
4302 * dreg still needs precision before this insn
4303 */
4304 }
4305 } else if (class == BPF_LDX || is_atomic_load_insn(insn)) {
4306 if (!bt_is_reg_set(bt, dreg))
4307 return 0;
4308 bt_clear_reg(bt, dreg);
4309
4310 /* scalars can only be spilled into stack w/o losing precision.
4311 * Load from any other memory can be zero extended.
4312 * The desire to keep that precision is already indicated
4313 * by 'precise' mark in corresponding register of this state.
4314 * No further tracking necessary.
4315 */
4316 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4317 return 0;
4318 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
4319 * that [fp - off] slot contains scalar that needs to be
4320 * tracked with precision
4321 */
4322 spi = insn_stack_access_spi(hist->flags);
4323 fr = insn_stack_access_frameno(hist->flags);
4324 bt_set_frame_slot(bt, fr, spi);
4325 } else if (class == BPF_STX || class == BPF_ST) {
4326 if (bt_is_reg_set(bt, dreg))
4327 /* stx & st shouldn't be using _scalar_ dst_reg
4328 * to access memory. It means backtracking
4329 * encountered a case of pointer subtraction.
4330 */
4331 return -ENOTSUPP;
4332 /* scalars can only be spilled into stack */
4333 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS))
4334 return 0;
4335 spi = insn_stack_access_spi(hist->flags);
4336 fr = insn_stack_access_frameno(hist->flags);
4337 if (!bt_is_frame_slot_set(bt, fr, spi))
4338 return 0;
4339 bt_clear_frame_slot(bt, fr, spi);
4340 if (class == BPF_STX)
4341 bt_set_reg(bt, sreg);
4342 } else if (class == BPF_JMP || class == BPF_JMP32) {
4343 if (bpf_pseudo_call(insn)) {
4344 int subprog_insn_idx, subprog;
4345
4346 subprog_insn_idx = idx + insn->imm + 1;
4347 subprog = find_subprog(env, subprog_insn_idx);
4348 if (subprog < 0)
4349 return -EFAULT;
4350
4351 if (subprog_is_global(env, subprog)) {
4352 /* check that jump history doesn't have any
4353 * extra instructions from subprog; the next
4354 * instruction after call to global subprog
4355 * should be literally next instruction in
4356 * caller program
4357 */
4358 verifier_bug_if(idx + 1 != subseq_idx, env,
4359 "extra insn from subprog");
4360 /* r1-r5 are invalidated after subprog call,
4361 * so for global func call it shouldn't be set
4362 * anymore
4363 */
4364 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4365 verifier_bug(env, "global subprog unexpected regs %x",
4366 bt_reg_mask(bt));
4367 return -EFAULT;
4368 }
4369 /* global subprog always sets R0 */
4370 bt_clear_reg(bt, BPF_REG_0);
4371 return 0;
4372 } else {
4373 /* static subprog call instruction, which
4374 * means that we are exiting current subprog,
4375 * so only r1-r5 could be still requested as
4376 * precise, r0 and r6-r10 or any stack slot in
4377 * the current frame should be zero by now
4378 */
4379 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4380 verifier_bug(env, "static subprog unexpected regs %x",
4381 bt_reg_mask(bt));
4382 return -EFAULT;
4383 }
4384 /* we are now tracking register spills correctly,
4385 * so any instance of leftover slots is a bug
4386 */
4387 if (bt_stack_mask(bt) != 0) {
4388 verifier_bug(env,
4389 "static subprog leftover stack slots %llx",
4390 bt_stack_mask(bt));
4391 return -EFAULT;
4392 }
4393 /* propagate r1-r5 to the caller */
4394 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
4395 if (bt_is_reg_set(bt, i)) {
4396 bt_clear_reg(bt, i);
4397 bt_set_frame_reg(bt, bt->frame - 1, i);
4398 }
4399 }
4400 if (bt_subprog_exit(bt))
4401 return -EFAULT;
4402 return 0;
4403 }
4404 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
4405 /* exit from callback subprog to callback-calling helper or
4406 * kfunc call. Use idx/subseq_idx check to discern it from
4407 * straight line code backtracking.
4408 * Unlike the subprog call handling above, we shouldn't
4409 * propagate precision of r1-r5 (if any requested), as they are
4410 * not actually arguments passed directly to callback subprogs
4411 */
4412 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
4413 verifier_bug(env, "callback unexpected regs %x",
4414 bt_reg_mask(bt));
4415 return -EFAULT;
4416 }
4417 if (bt_stack_mask(bt) != 0) {
4418 verifier_bug(env, "callback leftover stack slots %llx",
4419 bt_stack_mask(bt));
4420 return -EFAULT;
4421 }
4422 /* clear r1-r5 in callback subprog's mask */
4423 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4424 bt_clear_reg(bt, i);
4425 if (bt_subprog_exit(bt))
4426 return -EFAULT;
4427 return 0;
4428 } else if (opcode == BPF_CALL) {
4429 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
4430 * catch this error later. Make backtracking conservative
4431 * with ENOTSUPP.
4432 */
4433 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
4434 return -ENOTSUPP;
4435 /* regular helper call sets R0 */
4436 bt_clear_reg(bt, BPF_REG_0);
4437 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4438 /* if backtracking was looking for registers R1-R5
4439 * they should have been found already.
4440 */
4441 verifier_bug(env, "backtracking call unexpected regs %x",
4442 bt_reg_mask(bt));
4443 return -EFAULT;
4444 }
4445 if (insn->src_reg == BPF_REG_0 && insn->imm == BPF_FUNC_tail_call
4446 && subseq_idx - idx != 1) {
4447 if (bt_subprog_enter(bt))
4448 return -EFAULT;
4449 }
4450 } else if (opcode == BPF_EXIT) {
4451 bool r0_precise;
4452
4453 /* Backtracking to a nested function call, 'idx' is a part of
4454 * the inner frame 'subseq_idx' is a part of the outer frame.
4455 * In case of a regular function call, instructions giving
4456 * precision to registers R1-R5 should have been found already.
4457 * In case of a callback, it is ok to have R1-R5 marked for
4458 * backtracking, as these registers are set by the function
4459 * invoking callback.
4460 */
4461 if (subseq_idx >= 0 && bpf_calls_callback(env, subseq_idx))
4462 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
4463 bt_clear_reg(bt, i);
4464 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
4465 verifier_bug(env, "backtracking exit unexpected regs %x",
4466 bt_reg_mask(bt));
4467 return -EFAULT;
4468 }
4469
4470 /* BPF_EXIT in subprog or callback always returns
4471 * right after the call instruction, so by checking
4472 * whether the instruction at subseq_idx-1 is subprog
4473 * call or not we can distinguish actual exit from
4474 * *subprog* from exit from *callback*. In the former
4475 * case, we need to propagate r0 precision, if
4476 * necessary. In the former we never do that.
4477 */
4478 r0_precise = subseq_idx - 1 >= 0 &&
4479 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
4480 bt_is_reg_set(bt, BPF_REG_0);
4481
4482 bt_clear_reg(bt, BPF_REG_0);
4483 if (bt_subprog_enter(bt))
4484 return -EFAULT;
4485
4486 if (r0_precise)
4487 bt_set_reg(bt, BPF_REG_0);
4488 /* r6-r9 and stack slots will stay set in caller frame
4489 * bitmasks until we return back from callee(s)
4490 */
4491 return 0;
4492 } else if (BPF_SRC(insn->code) == BPF_X) {
4493 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
4494 return 0;
4495 /* dreg <cond> sreg
4496 * Both dreg and sreg need precision before
4497 * this insn. If only sreg was marked precise
4498 * before it would be equally necessary to
4499 * propagate it to dreg.
4500 */
4501 if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK))
4502 bt_set_reg(bt, sreg);
4503 if (!hist || !(hist->flags & INSN_F_DST_REG_STACK))
4504 bt_set_reg(bt, dreg);
4505 } else if (BPF_SRC(insn->code) == BPF_K) {
4506 /* dreg <cond> K
4507 * Only dreg still needs precision before
4508 * this insn, so for the K-based conditional
4509 * there is nothing new to be marked.
4510 */
4511 }
4512 } else if (class == BPF_LD) {
4513 if (!bt_is_reg_set(bt, dreg))
4514 return 0;
4515 bt_clear_reg(bt, dreg);
4516 /* It's ld_imm64 or ld_abs or ld_ind.
4517 * For ld_imm64 no further tracking of precision
4518 * into parent is necessary
4519 */
4520 if (mode == BPF_IND || mode == BPF_ABS)
4521 /* to be analyzed */
4522 return -ENOTSUPP;
4523 }
4524 /* Propagate precision marks to linked registers, to account for
4525 * registers marked as precise in this function.
4526 */
4527 bt_sync_linked_regs(bt, hist);
4528 return 0;
4529 }
4530
4531 /* the scalar precision tracking algorithm:
4532 * . at the start all registers have precise=false.
4533 * . scalar ranges are tracked as normal through alu and jmp insns.
4534 * . once precise value of the scalar register is used in:
4535 * . ptr + scalar alu
4536 * . if (scalar cond K|scalar)
4537 * . helper_call(.., scalar, ...) where ARG_CONST is expected
4538 * backtrack through the verifier states and mark all registers and
4539 * stack slots with spilled constants that these scalar registers
4540 * should be precise.
4541 * . during state pruning two registers (or spilled stack slots)
4542 * are equivalent if both are not precise.
4543 *
4544 * Note the verifier cannot simply walk register parentage chain,
4545 * since many different registers and stack slots could have been
4546 * used to compute single precise scalar.
4547 *
4548 * The approach of starting with precise=true for all registers and then
4549 * backtrack to mark a register as not precise when the verifier detects
4550 * that program doesn't care about specific value (e.g., when helper
4551 * takes register as ARG_ANYTHING parameter) is not safe.
4552 *
4553 * It's ok to walk single parentage chain of the verifier states.
4554 * It's possible that this backtracking will go all the way till 1st insn.
4555 * All other branches will be explored for needing precision later.
4556 *
4557 * The backtracking needs to deal with cases like:
4558 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
4559 * r9 -= r8
4560 * r5 = r9
4561 * if r5 > 0x79f goto pc+7
4562 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4563 * r5 += 1
4564 * ...
4565 * call bpf_perf_event_output#25
4566 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4567 *
4568 * and this case:
4569 * r6 = 1
4570 * call foo // uses callee's r6 inside to compute r0
4571 * r0 += r6
4572 * if r0 == 0 goto
4573 *
4574 * to track above reg_mask/stack_mask needs to be independent for each frame.
4575 *
4576 * Also if parent's curframe > frame where backtracking started,
4577 * the verifier need to mark registers in both frames, otherwise callees
4578 * may incorrectly prune callers. This is similar to
4579 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4580 *
4581 * For now backtracking falls back into conservative marking.
4582 */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4583 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4584 struct bpf_verifier_state *st)
4585 {
4586 struct bpf_func_state *func;
4587 struct bpf_reg_state *reg;
4588 int i, j;
4589
4590 if (env->log.level & BPF_LOG_LEVEL2) {
4591 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4592 st->curframe);
4593 }
4594
4595 /* big hammer: mark all scalars precise in this path.
4596 * pop_stack may still get !precise scalars.
4597 * We also skip current state and go straight to first parent state,
4598 * because precision markings in current non-checkpointed state are
4599 * not needed. See why in the comment in __mark_chain_precision below.
4600 */
4601 for (st = st->parent; st; st = st->parent) {
4602 for (i = 0; i <= st->curframe; i++) {
4603 func = st->frame[i];
4604 for (j = 0; j < BPF_REG_FP; j++) {
4605 reg = &func->regs[j];
4606 if (reg->type != SCALAR_VALUE || reg->precise)
4607 continue;
4608 reg->precise = true;
4609 if (env->log.level & BPF_LOG_LEVEL2) {
4610 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4611 i, j);
4612 }
4613 }
4614 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4615 if (!is_spilled_reg(&func->stack[j]))
4616 continue;
4617 reg = &func->stack[j].spilled_ptr;
4618 if (reg->type != SCALAR_VALUE || reg->precise)
4619 continue;
4620 reg->precise = true;
4621 if (env->log.level & BPF_LOG_LEVEL2) {
4622 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4623 i, -(j + 1) * 8);
4624 }
4625 }
4626 }
4627 }
4628 }
4629
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4630 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4631 {
4632 struct bpf_func_state *func;
4633 struct bpf_reg_state *reg;
4634 int i, j;
4635
4636 for (i = 0; i <= st->curframe; i++) {
4637 func = st->frame[i];
4638 for (j = 0; j < BPF_REG_FP; j++) {
4639 reg = &func->regs[j];
4640 if (reg->type != SCALAR_VALUE)
4641 continue;
4642 reg->precise = false;
4643 }
4644 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4645 if (!is_spilled_reg(&func->stack[j]))
4646 continue;
4647 reg = &func->stack[j].spilled_ptr;
4648 if (reg->type != SCALAR_VALUE)
4649 continue;
4650 reg->precise = false;
4651 }
4652 }
4653 }
4654
4655 /*
4656 * __mark_chain_precision() backtracks BPF program instruction sequence and
4657 * chain of verifier states making sure that register *regno* (if regno >= 0)
4658 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4659 * SCALARS, as well as any other registers and slots that contribute to
4660 * a tracked state of given registers/stack slots, depending on specific BPF
4661 * assembly instructions (see backtrack_insns() for exact instruction handling
4662 * logic). This backtracking relies on recorded jmp_history and is able to
4663 * traverse entire chain of parent states. This process ends only when all the
4664 * necessary registers/slots and their transitive dependencies are marked as
4665 * precise.
4666 *
4667 * One important and subtle aspect is that precise marks *do not matter* in
4668 * the currently verified state (current state). It is important to understand
4669 * why this is the case.
4670 *
4671 * First, note that current state is the state that is not yet "checkpointed",
4672 * i.e., it is not yet put into env->explored_states, and it has no children
4673 * states as well. It's ephemeral, and can end up either a) being discarded if
4674 * compatible explored state is found at some point or BPF_EXIT instruction is
4675 * reached or b) checkpointed and put into env->explored_states, branching out
4676 * into one or more children states.
4677 *
4678 * In the former case, precise markings in current state are completely
4679 * ignored by state comparison code (see regsafe() for details). Only
4680 * checkpointed ("old") state precise markings are important, and if old
4681 * state's register/slot is precise, regsafe() assumes current state's
4682 * register/slot as precise and checks value ranges exactly and precisely. If
4683 * states turn out to be compatible, current state's necessary precise
4684 * markings and any required parent states' precise markings are enforced
4685 * after the fact with propagate_precision() logic, after the fact. But it's
4686 * important to realize that in this case, even after marking current state
4687 * registers/slots as precise, we immediately discard current state. So what
4688 * actually matters is any of the precise markings propagated into current
4689 * state's parent states, which are always checkpointed (due to b) case above).
4690 * As such, for scenario a) it doesn't matter if current state has precise
4691 * markings set or not.
4692 *
4693 * Now, for the scenario b), checkpointing and forking into child(ren)
4694 * state(s). Note that before current state gets to checkpointing step, any
4695 * processed instruction always assumes precise SCALAR register/slot
4696 * knowledge: if precise value or range is useful to prune jump branch, BPF
4697 * verifier takes this opportunity enthusiastically. Similarly, when
4698 * register's value is used to calculate offset or memory address, exact
4699 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4700 * what we mentioned above about state comparison ignoring precise markings
4701 * during state comparison, BPF verifier ignores and also assumes precise
4702 * markings *at will* during instruction verification process. But as verifier
4703 * assumes precision, it also propagates any precision dependencies across
4704 * parent states, which are not yet finalized, so can be further restricted
4705 * based on new knowledge gained from restrictions enforced by their children
4706 * states. This is so that once those parent states are finalized, i.e., when
4707 * they have no more active children state, state comparison logic in
4708 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4709 * required for correctness.
4710 *
4711 * To build a bit more intuition, note also that once a state is checkpointed,
4712 * the path we took to get to that state is not important. This is crucial
4713 * property for state pruning. When state is checkpointed and finalized at
4714 * some instruction index, it can be correctly and safely used to "short
4715 * circuit" any *compatible* state that reaches exactly the same instruction
4716 * index. I.e., if we jumped to that instruction from a completely different
4717 * code path than original finalized state was derived from, it doesn't
4718 * matter, current state can be discarded because from that instruction
4719 * forward having a compatible state will ensure we will safely reach the
4720 * exit. States describe preconditions for further exploration, but completely
4721 * forget the history of how we got here.
4722 *
4723 * This also means that even if we needed precise SCALAR range to get to
4724 * finalized state, but from that point forward *that same* SCALAR register is
4725 * never used in a precise context (i.e., it's precise value is not needed for
4726 * correctness), it's correct and safe to mark such register as "imprecise"
4727 * (i.e., precise marking set to false). This is what we rely on when we do
4728 * not set precise marking in current state. If no child state requires
4729 * precision for any given SCALAR register, it's safe to dictate that it can
4730 * be imprecise. If any child state does require this register to be precise,
4731 * we'll mark it precise later retroactively during precise markings
4732 * propagation from child state to parent states.
4733 *
4734 * Skipping precise marking setting in current state is a mild version of
4735 * relying on the above observation. But we can utilize this property even
4736 * more aggressively by proactively forgetting any precise marking in the
4737 * current state (which we inherited from the parent state), right before we
4738 * checkpoint it and branch off into new child state. This is done by
4739 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4740 * finalized states which help in short circuiting more future states.
4741 */
__mark_chain_precision(struct bpf_verifier_env * env,struct bpf_verifier_state * starting_state,int regno,bool * changed)4742 static int __mark_chain_precision(struct bpf_verifier_env *env,
4743 struct bpf_verifier_state *starting_state,
4744 int regno,
4745 bool *changed)
4746 {
4747 struct bpf_verifier_state *st = starting_state;
4748 struct backtrack_state *bt = &env->bt;
4749 int first_idx = st->first_insn_idx;
4750 int last_idx = starting_state->insn_idx;
4751 int subseq_idx = -1;
4752 struct bpf_func_state *func;
4753 bool tmp, skip_first = true;
4754 struct bpf_reg_state *reg;
4755 int i, fr, err;
4756
4757 if (!env->bpf_capable)
4758 return 0;
4759
4760 changed = changed ?: &tmp;
4761 /* set frame number from which we are starting to backtrack */
4762 bt_init(bt, starting_state->curframe);
4763
4764 /* Do sanity checks against current state of register and/or stack
4765 * slot, but don't set precise flag in current state, as precision
4766 * tracking in the current state is unnecessary.
4767 */
4768 func = st->frame[bt->frame];
4769 if (regno >= 0) {
4770 reg = &func->regs[regno];
4771 if (reg->type != SCALAR_VALUE) {
4772 verifier_bug(env, "backtracking misuse");
4773 return -EFAULT;
4774 }
4775 bt_set_reg(bt, regno);
4776 }
4777
4778 if (bt_empty(bt))
4779 return 0;
4780
4781 for (;;) {
4782 DECLARE_BITMAP(mask, 64);
4783 u32 history = st->jmp_history_cnt;
4784 struct bpf_jmp_history_entry *hist;
4785
4786 if (env->log.level & BPF_LOG_LEVEL2) {
4787 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4788 bt->frame, last_idx, first_idx, subseq_idx);
4789 }
4790
4791 if (last_idx < 0) {
4792 /* we are at the entry into subprog, which
4793 * is expected for global funcs, but only if
4794 * requested precise registers are R1-R5
4795 * (which are global func's input arguments)
4796 */
4797 if (st->curframe == 0 &&
4798 st->frame[0]->subprogno > 0 &&
4799 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4800 bt_stack_mask(bt) == 0 &&
4801 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4802 bitmap_from_u64(mask, bt_reg_mask(bt));
4803 for_each_set_bit(i, mask, 32) {
4804 reg = &st->frame[0]->regs[i];
4805 bt_clear_reg(bt, i);
4806 if (reg->type == SCALAR_VALUE) {
4807 reg->precise = true;
4808 *changed = true;
4809 }
4810 }
4811 return 0;
4812 }
4813
4814 verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx",
4815 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4816 return -EFAULT;
4817 }
4818
4819 for (i = last_idx;;) {
4820 if (skip_first) {
4821 err = 0;
4822 skip_first = false;
4823 } else {
4824 hist = get_jmp_hist_entry(st, history, i);
4825 err = backtrack_insn(env, i, subseq_idx, hist, bt);
4826 }
4827 if (err == -ENOTSUPP) {
4828 mark_all_scalars_precise(env, starting_state);
4829 bt_reset(bt);
4830 return 0;
4831 } else if (err) {
4832 return err;
4833 }
4834 if (bt_empty(bt))
4835 /* Found assignment(s) into tracked register in this state.
4836 * Since this state is already marked, just return.
4837 * Nothing to be tracked further in the parent state.
4838 */
4839 return 0;
4840 subseq_idx = i;
4841 i = get_prev_insn_idx(st, i, &history);
4842 if (i == -ENOENT)
4843 break;
4844 if (i >= env->prog->len) {
4845 /* This can happen if backtracking reached insn 0
4846 * and there are still reg_mask or stack_mask
4847 * to backtrack.
4848 * It means the backtracking missed the spot where
4849 * particular register was initialized with a constant.
4850 */
4851 verifier_bug(env, "backtracking idx %d", i);
4852 return -EFAULT;
4853 }
4854 }
4855 st = st->parent;
4856 if (!st)
4857 break;
4858
4859 for (fr = bt->frame; fr >= 0; fr--) {
4860 func = st->frame[fr];
4861 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4862 for_each_set_bit(i, mask, 32) {
4863 reg = &func->regs[i];
4864 if (reg->type != SCALAR_VALUE) {
4865 bt_clear_frame_reg(bt, fr, i);
4866 continue;
4867 }
4868 if (reg->precise) {
4869 bt_clear_frame_reg(bt, fr, i);
4870 } else {
4871 reg->precise = true;
4872 *changed = true;
4873 }
4874 }
4875
4876 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4877 for_each_set_bit(i, mask, 64) {
4878 if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE,
4879 env, "stack slot %d, total slots %d",
4880 i, func->allocated_stack / BPF_REG_SIZE))
4881 return -EFAULT;
4882
4883 if (!is_spilled_scalar_reg(&func->stack[i])) {
4884 bt_clear_frame_slot(bt, fr, i);
4885 continue;
4886 }
4887 reg = &func->stack[i].spilled_ptr;
4888 if (reg->precise) {
4889 bt_clear_frame_slot(bt, fr, i);
4890 } else {
4891 reg->precise = true;
4892 *changed = true;
4893 }
4894 }
4895 if (env->log.level & BPF_LOG_LEVEL2) {
4896 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4897 bt_frame_reg_mask(bt, fr));
4898 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4899 fr, env->tmp_str_buf);
4900 bpf_fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4901 bt_frame_stack_mask(bt, fr));
4902 verbose(env, "stack=%s: ", env->tmp_str_buf);
4903 print_verifier_state(env, st, fr, true);
4904 }
4905 }
4906
4907 if (bt_empty(bt))
4908 return 0;
4909
4910 subseq_idx = first_idx;
4911 last_idx = st->last_insn_idx;
4912 first_idx = st->first_insn_idx;
4913 }
4914
4915 /* if we still have requested precise regs or slots, we missed
4916 * something (e.g., stack access through non-r10 register), so
4917 * fallback to marking all precise
4918 */
4919 if (!bt_empty(bt)) {
4920 mark_all_scalars_precise(env, starting_state);
4921 bt_reset(bt);
4922 }
4923
4924 return 0;
4925 }
4926
mark_chain_precision(struct bpf_verifier_env * env,int regno)4927 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4928 {
4929 return __mark_chain_precision(env, env->cur_state, regno, NULL);
4930 }
4931
4932 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4933 * desired reg and stack masks across all relevant frames
4934 */
mark_chain_precision_batch(struct bpf_verifier_env * env,struct bpf_verifier_state * starting_state)4935 static int mark_chain_precision_batch(struct bpf_verifier_env *env,
4936 struct bpf_verifier_state *starting_state)
4937 {
4938 return __mark_chain_precision(env, starting_state, -1, NULL);
4939 }
4940
is_spillable_regtype(enum bpf_reg_type type)4941 static bool is_spillable_regtype(enum bpf_reg_type type)
4942 {
4943 switch (base_type(type)) {
4944 case PTR_TO_MAP_VALUE:
4945 case PTR_TO_STACK:
4946 case PTR_TO_CTX:
4947 case PTR_TO_PACKET:
4948 case PTR_TO_PACKET_META:
4949 case PTR_TO_PACKET_END:
4950 case PTR_TO_FLOW_KEYS:
4951 case CONST_PTR_TO_MAP:
4952 case PTR_TO_SOCKET:
4953 case PTR_TO_SOCK_COMMON:
4954 case PTR_TO_TCP_SOCK:
4955 case PTR_TO_XDP_SOCK:
4956 case PTR_TO_BTF_ID:
4957 case PTR_TO_BUF:
4958 case PTR_TO_MEM:
4959 case PTR_TO_FUNC:
4960 case PTR_TO_MAP_KEY:
4961 case PTR_TO_ARENA:
4962 return true;
4963 default:
4964 return false;
4965 }
4966 }
4967
4968 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4969 static bool register_is_null(struct bpf_reg_state *reg)
4970 {
4971 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4972 }
4973
4974 /* check if register is a constant scalar value */
is_reg_const(struct bpf_reg_state * reg,bool subreg32)4975 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32)
4976 {
4977 return reg->type == SCALAR_VALUE &&
4978 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off);
4979 }
4980
4981 /* assuming is_reg_const() is true, return constant value of a register */
reg_const_value(struct bpf_reg_state * reg,bool subreg32)4982 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32)
4983 {
4984 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value;
4985 }
4986
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)4987 static bool __is_pointer_value(bool allow_ptr_leaks,
4988 const struct bpf_reg_state *reg)
4989 {
4990 if (allow_ptr_leaks)
4991 return false;
4992
4993 return reg->type != SCALAR_VALUE;
4994 }
4995
assign_scalar_id_before_mov(struct bpf_verifier_env * env,struct bpf_reg_state * src_reg)4996 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
4997 struct bpf_reg_state *src_reg)
4998 {
4999 if (src_reg->type != SCALAR_VALUE)
5000 return;
5001
5002 if (src_reg->id & BPF_ADD_CONST) {
5003 /*
5004 * The verifier is processing rX = rY insn and
5005 * rY->id has special linked register already.
5006 * Cleared it, since multiple rX += const are not supported.
5007 */
5008 src_reg->id = 0;
5009 src_reg->off = 0;
5010 }
5011
5012 if (!src_reg->id && !tnum_is_const(src_reg->var_off))
5013 /* Ensure that src_reg has a valid ID that will be copied to
5014 * dst_reg and then will be used by sync_linked_regs() to
5015 * propagate min/max range.
5016 */
5017 src_reg->id = ++env->id_gen;
5018 }
5019
5020 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)5021 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
5022 {
5023 *dst = *src;
5024 }
5025
save_register_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)5026 static void save_register_state(struct bpf_verifier_env *env,
5027 struct bpf_func_state *state,
5028 int spi, struct bpf_reg_state *reg,
5029 int size)
5030 {
5031 int i;
5032
5033 copy_register_state(&state->stack[spi].spilled_ptr, reg);
5034
5035 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
5036 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
5037
5038 /* size < 8 bytes spill */
5039 for (; i; i--)
5040 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]);
5041 }
5042
is_bpf_st_mem(struct bpf_insn * insn)5043 static bool is_bpf_st_mem(struct bpf_insn *insn)
5044 {
5045 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
5046 }
5047
get_reg_width(struct bpf_reg_state * reg)5048 static int get_reg_width(struct bpf_reg_state *reg)
5049 {
5050 return fls64(reg->umax_value);
5051 }
5052
5053 /* See comment for mark_fastcall_pattern_for_call() */
check_fastcall_stack_contract(struct bpf_verifier_env * env,struct bpf_func_state * state,int insn_idx,int off)5054 static void check_fastcall_stack_contract(struct bpf_verifier_env *env,
5055 struct bpf_func_state *state, int insn_idx, int off)
5056 {
5057 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno];
5058 struct bpf_insn_aux_data *aux = env->insn_aux_data;
5059 int i;
5060
5061 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern)
5062 return;
5063 /* access to the region [max_stack_depth .. fastcall_stack_off)
5064 * from something that is not a part of the fastcall pattern,
5065 * disable fastcall rewrites for current subprogram by setting
5066 * fastcall_stack_off to a value smaller than any possible offset.
5067 */
5068 subprog->fastcall_stack_off = S16_MIN;
5069 /* reset fastcall aux flags within subprogram,
5070 * happens at most once per subprogram
5071 */
5072 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
5073 aux[i].fastcall_spills_num = 0;
5074 aux[i].fastcall_pattern = 0;
5075 }
5076 }
5077
5078 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
5079 * stack boundary and alignment are checked in check_mem_access()
5080 */
check_stack_write_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int off,int size,int value_regno,int insn_idx)5081 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
5082 /* stack frame we're writing to */
5083 struct bpf_func_state *state,
5084 int off, int size, int value_regno,
5085 int insn_idx)
5086 {
5087 struct bpf_func_state *cur; /* state of the current function */
5088 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
5089 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5090 struct bpf_reg_state *reg = NULL;
5091 int insn_flags = insn_stack_access_flags(state->frameno, spi);
5092
5093 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
5094 * so it's aligned access and [off, off + size) are within stack limits
5095 */
5096 if (!env->allow_ptr_leaks &&
5097 is_spilled_reg(&state->stack[spi]) &&
5098 !is_spilled_scalar_reg(&state->stack[spi]) &&
5099 size != BPF_REG_SIZE) {
5100 verbose(env, "attempt to corrupt spilled pointer on stack\n");
5101 return -EACCES;
5102 }
5103
5104 cur = env->cur_state->frame[env->cur_state->curframe];
5105 if (value_regno >= 0)
5106 reg = &cur->regs[value_regno];
5107 if (!env->bypass_spec_v4) {
5108 bool sanitize = reg && is_spillable_regtype(reg->type);
5109
5110 for (i = 0; i < size; i++) {
5111 u8 type = state->stack[spi].slot_type[i];
5112
5113 if (type != STACK_MISC && type != STACK_ZERO) {
5114 sanitize = true;
5115 break;
5116 }
5117 }
5118
5119 if (sanitize)
5120 env->insn_aux_data[insn_idx].nospec_result = true;
5121 }
5122
5123 err = destroy_if_dynptr_stack_slot(env, state, spi);
5124 if (err)
5125 return err;
5126
5127 if (!(off % BPF_REG_SIZE) && size == BPF_REG_SIZE) {
5128 /* only mark the slot as written if all 8 bytes were written
5129 * otherwise read propagation may incorrectly stop too soon
5130 * when stack slots are partially written.
5131 * This heuristic means that read propagation will be
5132 * conservative, since it will add reg_live_read marks
5133 * to stack slots all the way to first state when programs
5134 * writes+reads less than 8 bytes
5135 */
5136 bpf_mark_stack_write(env, state->frameno, BIT(spi));
5137 }
5138
5139 check_fastcall_stack_contract(env, state, insn_idx, off);
5140 mark_stack_slot_scratched(env, spi);
5141 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) {
5142 bool reg_value_fits;
5143
5144 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size;
5145 /* Make sure that reg had an ID to build a relation on spill. */
5146 if (reg_value_fits)
5147 assign_scalar_id_before_mov(env, reg);
5148 save_register_state(env, state, spi, reg, size);
5149 /* Break the relation on a narrowing spill. */
5150 if (!reg_value_fits)
5151 state->stack[spi].spilled_ptr.id = 0;
5152 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
5153 env->bpf_capable) {
5154 struct bpf_reg_state *tmp_reg = &env->fake_reg[0];
5155
5156 memset(tmp_reg, 0, sizeof(*tmp_reg));
5157 __mark_reg_known(tmp_reg, insn->imm);
5158 tmp_reg->type = SCALAR_VALUE;
5159 save_register_state(env, state, spi, tmp_reg, size);
5160 } else if (reg && is_spillable_regtype(reg->type)) {
5161 /* register containing pointer is being spilled into stack */
5162 if (size != BPF_REG_SIZE) {
5163 verbose_linfo(env, insn_idx, "; ");
5164 verbose(env, "invalid size of register spill\n");
5165 return -EACCES;
5166 }
5167 if (state != cur && reg->type == PTR_TO_STACK) {
5168 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
5169 return -EINVAL;
5170 }
5171 save_register_state(env, state, spi, reg, size);
5172 } else {
5173 u8 type = STACK_MISC;
5174
5175 /* regular write of data into stack destroys any spilled ptr */
5176 state->stack[spi].spilled_ptr.type = NOT_INIT;
5177 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
5178 if (is_stack_slot_special(&state->stack[spi]))
5179 for (i = 0; i < BPF_REG_SIZE; i++)
5180 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
5181
5182 /* when we zero initialize stack slots mark them as such */
5183 if ((reg && register_is_null(reg)) ||
5184 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
5185 /* STACK_ZERO case happened because register spill
5186 * wasn't properly aligned at the stack slot boundary,
5187 * so it's not a register spill anymore; force
5188 * originating register to be precise to make
5189 * STACK_ZERO correct for subsequent states
5190 */
5191 err = mark_chain_precision(env, value_regno);
5192 if (err)
5193 return err;
5194 type = STACK_ZERO;
5195 }
5196
5197 /* Mark slots affected by this stack write. */
5198 for (i = 0; i < size; i++)
5199 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type;
5200 insn_flags = 0; /* not a register spill */
5201 }
5202
5203 if (insn_flags)
5204 return push_jmp_history(env, env->cur_state, insn_flags, 0);
5205 return 0;
5206 }
5207
5208 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
5209 * known to contain a variable offset.
5210 * This function checks whether the write is permitted and conservatively
5211 * tracks the effects of the write, considering that each stack slot in the
5212 * dynamic range is potentially written to.
5213 *
5214 * 'off' includes 'regno->off'.
5215 * 'value_regno' can be -1, meaning that an unknown value is being written to
5216 * the stack.
5217 *
5218 * Spilled pointers in range are not marked as written because we don't know
5219 * what's going to be actually written. This means that read propagation for
5220 * future reads cannot be terminated by this write.
5221 *
5222 * For privileged programs, uninitialized stack slots are considered
5223 * initialized by this write (even though we don't know exactly what offsets
5224 * are going to be written to). The idea is that we don't want the verifier to
5225 * reject future reads that access slots written to through variable offsets.
5226 */
check_stack_write_var_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int ptr_regno,int off,int size,int value_regno,int insn_idx)5227 static int check_stack_write_var_off(struct bpf_verifier_env *env,
5228 /* func where register points to */
5229 struct bpf_func_state *state,
5230 int ptr_regno, int off, int size,
5231 int value_regno, int insn_idx)
5232 {
5233 struct bpf_func_state *cur; /* state of the current function */
5234 int min_off, max_off;
5235 int i, err;
5236 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
5237 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5238 bool writing_zero = false;
5239 /* set if the fact that we're writing a zero is used to let any
5240 * stack slots remain STACK_ZERO
5241 */
5242 bool zero_used = false;
5243
5244 cur = env->cur_state->frame[env->cur_state->curframe];
5245 ptr_reg = &cur->regs[ptr_regno];
5246 min_off = ptr_reg->smin_value + off;
5247 max_off = ptr_reg->smax_value + off + size;
5248 if (value_regno >= 0)
5249 value_reg = &cur->regs[value_regno];
5250 if ((value_reg && register_is_null(value_reg)) ||
5251 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
5252 writing_zero = true;
5253
5254 for (i = min_off; i < max_off; i++) {
5255 int spi;
5256
5257 spi = __get_spi(i);
5258 err = destroy_if_dynptr_stack_slot(env, state, spi);
5259 if (err)
5260 return err;
5261 }
5262
5263 check_fastcall_stack_contract(env, state, insn_idx, min_off);
5264 /* Variable offset writes destroy any spilled pointers in range. */
5265 for (i = min_off; i < max_off; i++) {
5266 u8 new_type, *stype;
5267 int slot, spi;
5268
5269 slot = -i - 1;
5270 spi = slot / BPF_REG_SIZE;
5271 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5272 mark_stack_slot_scratched(env, spi);
5273
5274 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
5275 /* Reject the write if range we may write to has not
5276 * been initialized beforehand. If we didn't reject
5277 * here, the ptr status would be erased below (even
5278 * though not all slots are actually overwritten),
5279 * possibly opening the door to leaks.
5280 *
5281 * We do however catch STACK_INVALID case below, and
5282 * only allow reading possibly uninitialized memory
5283 * later for CAP_PERFMON, as the write may not happen to
5284 * that slot.
5285 */
5286 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
5287 insn_idx, i);
5288 return -EINVAL;
5289 }
5290
5291 /* If writing_zero and the spi slot contains a spill of value 0,
5292 * maintain the spill type.
5293 */
5294 if (writing_zero && *stype == STACK_SPILL &&
5295 is_spilled_scalar_reg(&state->stack[spi])) {
5296 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr;
5297
5298 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) {
5299 zero_used = true;
5300 continue;
5301 }
5302 }
5303
5304 /* Erase all other spilled pointers. */
5305 state->stack[spi].spilled_ptr.type = NOT_INIT;
5306
5307 /* Update the slot type. */
5308 new_type = STACK_MISC;
5309 if (writing_zero && *stype == STACK_ZERO) {
5310 new_type = STACK_ZERO;
5311 zero_used = true;
5312 }
5313 /* If the slot is STACK_INVALID, we check whether it's OK to
5314 * pretend that it will be initialized by this write. The slot
5315 * might not actually be written to, and so if we mark it as
5316 * initialized future reads might leak uninitialized memory.
5317 * For privileged programs, we will accept such reads to slots
5318 * that may or may not be written because, if we're reject
5319 * them, the error would be too confusing.
5320 */
5321 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
5322 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
5323 insn_idx, i);
5324 return -EINVAL;
5325 }
5326 *stype = new_type;
5327 }
5328 if (zero_used) {
5329 /* backtracking doesn't work for STACK_ZERO yet. */
5330 err = mark_chain_precision(env, value_regno);
5331 if (err)
5332 return err;
5333 }
5334 return 0;
5335 }
5336
5337 /* When register 'dst_regno' is assigned some values from stack[min_off,
5338 * max_off), we set the register's type according to the types of the
5339 * respective stack slots. If all the stack values are known to be zeros, then
5340 * so is the destination reg. Otherwise, the register is considered to be
5341 * SCALAR. This function does not deal with register filling; the caller must
5342 * ensure that all spilled registers in the stack range have been marked as
5343 * read.
5344 */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)5345 static void mark_reg_stack_read(struct bpf_verifier_env *env,
5346 /* func where src register points to */
5347 struct bpf_func_state *ptr_state,
5348 int min_off, int max_off, int dst_regno)
5349 {
5350 struct bpf_verifier_state *vstate = env->cur_state;
5351 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5352 int i, slot, spi;
5353 u8 *stype;
5354 int zeros = 0;
5355
5356 for (i = min_off; i < max_off; i++) {
5357 slot = -i - 1;
5358 spi = slot / BPF_REG_SIZE;
5359 mark_stack_slot_scratched(env, spi);
5360 stype = ptr_state->stack[spi].slot_type;
5361 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
5362 break;
5363 zeros++;
5364 }
5365 if (zeros == max_off - min_off) {
5366 /* Any access_size read into register is zero extended,
5367 * so the whole register == const_zero.
5368 */
5369 __mark_reg_const_zero(env, &state->regs[dst_regno]);
5370 } else {
5371 /* have read misc data from the stack */
5372 mark_reg_unknown(env, state->regs, dst_regno);
5373 }
5374 }
5375
5376 /* Read the stack at 'off' and put the results into the register indicated by
5377 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
5378 * spilled reg.
5379 *
5380 * 'dst_regno' can be -1, meaning that the read value is not going to a
5381 * register.
5382 *
5383 * The access is assumed to be within the current stack bounds.
5384 */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)5385 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
5386 /* func where src register points to */
5387 struct bpf_func_state *reg_state,
5388 int off, int size, int dst_regno)
5389 {
5390 struct bpf_verifier_state *vstate = env->cur_state;
5391 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5392 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
5393 struct bpf_reg_state *reg;
5394 u8 *stype, type;
5395 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi);
5396 int err;
5397
5398 stype = reg_state->stack[spi].slot_type;
5399 reg = ®_state->stack[spi].spilled_ptr;
5400
5401 mark_stack_slot_scratched(env, spi);
5402 check_fastcall_stack_contract(env, state, env->insn_idx, off);
5403 err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi));
5404 if (err)
5405 return err;
5406
5407 if (is_spilled_reg(®_state->stack[spi])) {
5408 u8 spill_size = 1;
5409
5410 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
5411 spill_size++;
5412
5413 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
5414 if (reg->type != SCALAR_VALUE) {
5415 verbose_linfo(env, env->insn_idx, "; ");
5416 verbose(env, "invalid size of register fill\n");
5417 return -EACCES;
5418 }
5419
5420 if (dst_regno < 0)
5421 return 0;
5422
5423 if (size <= spill_size &&
5424 bpf_stack_narrow_access_ok(off, size, spill_size)) {
5425 /* The earlier check_reg_arg() has decided the
5426 * subreg_def for this insn. Save it first.
5427 */
5428 s32 subreg_def = state->regs[dst_regno].subreg_def;
5429
5430 copy_register_state(&state->regs[dst_regno], reg);
5431 state->regs[dst_regno].subreg_def = subreg_def;
5432
5433 /* Break the relation on a narrowing fill.
5434 * coerce_reg_to_size will adjust the boundaries.
5435 */
5436 if (get_reg_width(reg) > size * BITS_PER_BYTE)
5437 state->regs[dst_regno].id = 0;
5438 } else {
5439 int spill_cnt = 0, zero_cnt = 0;
5440
5441 for (i = 0; i < size; i++) {
5442 type = stype[(slot - i) % BPF_REG_SIZE];
5443 if (type == STACK_SPILL) {
5444 spill_cnt++;
5445 continue;
5446 }
5447 if (type == STACK_MISC)
5448 continue;
5449 if (type == STACK_ZERO) {
5450 zero_cnt++;
5451 continue;
5452 }
5453 if (type == STACK_INVALID && env->allow_uninit_stack)
5454 continue;
5455 verbose(env, "invalid read from stack off %d+%d size %d\n",
5456 off, i, size);
5457 return -EACCES;
5458 }
5459
5460 if (spill_cnt == size &&
5461 tnum_is_const(reg->var_off) && reg->var_off.value == 0) {
5462 __mark_reg_const_zero(env, &state->regs[dst_regno]);
5463 /* this IS register fill, so keep insn_flags */
5464 } else if (zero_cnt == size) {
5465 /* similarly to mark_reg_stack_read(), preserve zeroes */
5466 __mark_reg_const_zero(env, &state->regs[dst_regno]);
5467 insn_flags = 0; /* not restoring original register state */
5468 } else {
5469 mark_reg_unknown(env, state->regs, dst_regno);
5470 insn_flags = 0; /* not restoring original register state */
5471 }
5472 }
5473 } else if (dst_regno >= 0) {
5474 /* restore register state from stack */
5475 copy_register_state(&state->regs[dst_regno], reg);
5476 /* mark reg as written since spilled pointer state likely
5477 * has its liveness marks cleared by is_state_visited()
5478 * which resets stack/reg liveness for state transitions
5479 */
5480 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
5481 /* If dst_regno==-1, the caller is asking us whether
5482 * it is acceptable to use this value as a SCALAR_VALUE
5483 * (e.g. for XADD).
5484 * We must not allow unprivileged callers to do that
5485 * with spilled pointers.
5486 */
5487 verbose(env, "leaking pointer from stack off %d\n",
5488 off);
5489 return -EACCES;
5490 }
5491 } else {
5492 for (i = 0; i < size; i++) {
5493 type = stype[(slot - i) % BPF_REG_SIZE];
5494 if (type == STACK_MISC)
5495 continue;
5496 if (type == STACK_ZERO)
5497 continue;
5498 if (type == STACK_INVALID && env->allow_uninit_stack)
5499 continue;
5500 verbose(env, "invalid read from stack off %d+%d size %d\n",
5501 off, i, size);
5502 return -EACCES;
5503 }
5504 if (dst_regno >= 0)
5505 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5506 insn_flags = 0; /* we are not restoring spilled register */
5507 }
5508 if (insn_flags)
5509 return push_jmp_history(env, env->cur_state, insn_flags, 0);
5510 return 0;
5511 }
5512
5513 enum bpf_access_src {
5514 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
5515 ACCESS_HELPER = 2, /* the access is performed by a helper */
5516 };
5517
5518 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5519 int regno, int off, int access_size,
5520 bool zero_size_allowed,
5521 enum bpf_access_type type,
5522 struct bpf_call_arg_meta *meta);
5523
reg_state(struct bpf_verifier_env * env,int regno)5524 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5525 {
5526 return cur_regs(env) + regno;
5527 }
5528
5529 /* Read the stack at 'ptr_regno + off' and put the result into the register
5530 * 'dst_regno'.
5531 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5532 * but not its variable offset.
5533 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5534 *
5535 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5536 * filling registers (i.e. reads of spilled register cannot be detected when
5537 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5538 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5539 * offset; for a fixed offset check_stack_read_fixed_off should be used
5540 * instead.
5541 */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5542 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5543 int ptr_regno, int off, int size, int dst_regno)
5544 {
5545 /* The state of the source register. */
5546 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5547 struct bpf_func_state *ptr_state = func(env, reg);
5548 int err;
5549 int min_off, max_off;
5550
5551 /* Note that we pass a NULL meta, so raw access will not be permitted.
5552 */
5553 err = check_stack_range_initialized(env, ptr_regno, off, size,
5554 false, BPF_READ, NULL);
5555 if (err)
5556 return err;
5557
5558 min_off = reg->smin_value + off;
5559 max_off = reg->smax_value + off;
5560 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5561 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off);
5562 return 0;
5563 }
5564
5565 /* check_stack_read dispatches to check_stack_read_fixed_off or
5566 * check_stack_read_var_off.
5567 *
5568 * The caller must ensure that the offset falls within the allocated stack
5569 * bounds.
5570 *
5571 * 'dst_regno' is a register which will receive the value from the stack. It
5572 * can be -1, meaning that the read value is not going to a register.
5573 */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5574 static int check_stack_read(struct bpf_verifier_env *env,
5575 int ptr_regno, int off, int size,
5576 int dst_regno)
5577 {
5578 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5579 struct bpf_func_state *state = func(env, reg);
5580 int err;
5581 /* Some accesses are only permitted with a static offset. */
5582 bool var_off = !tnum_is_const(reg->var_off);
5583
5584 /* The offset is required to be static when reads don't go to a
5585 * register, in order to not leak pointers (see
5586 * check_stack_read_fixed_off).
5587 */
5588 if (dst_regno < 0 && var_off) {
5589 char tn_buf[48];
5590
5591 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5592 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5593 tn_buf, off, size);
5594 return -EACCES;
5595 }
5596 /* Variable offset is prohibited for unprivileged mode for simplicity
5597 * since it requires corresponding support in Spectre masking for stack
5598 * ALU. See also retrieve_ptr_limit(). The check in
5599 * check_stack_access_for_ptr_arithmetic() called by
5600 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5601 * with variable offsets, therefore no check is required here. Further,
5602 * just checking it here would be insufficient as speculative stack
5603 * writes could still lead to unsafe speculative behaviour.
5604 */
5605 if (!var_off) {
5606 off += reg->var_off.value;
5607 err = check_stack_read_fixed_off(env, state, off, size,
5608 dst_regno);
5609 } else {
5610 /* Variable offset stack reads need more conservative handling
5611 * than fixed offset ones. Note that dst_regno >= 0 on this
5612 * branch.
5613 */
5614 err = check_stack_read_var_off(env, ptr_regno, off, size,
5615 dst_regno);
5616 }
5617 return err;
5618 }
5619
5620
5621 /* check_stack_write dispatches to check_stack_write_fixed_off or
5622 * check_stack_write_var_off.
5623 *
5624 * 'ptr_regno' is the register used as a pointer into the stack.
5625 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5626 * 'value_regno' is the register whose value we're writing to the stack. It can
5627 * be -1, meaning that we're not writing from a register.
5628 *
5629 * The caller must ensure that the offset falls within the maximum stack size.
5630 */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5631 static int check_stack_write(struct bpf_verifier_env *env,
5632 int ptr_regno, int off, int size,
5633 int value_regno, int insn_idx)
5634 {
5635 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5636 struct bpf_func_state *state = func(env, reg);
5637 int err;
5638
5639 if (tnum_is_const(reg->var_off)) {
5640 off += reg->var_off.value;
5641 err = check_stack_write_fixed_off(env, state, off, size,
5642 value_regno, insn_idx);
5643 } else {
5644 /* Variable offset stack reads need more conservative handling
5645 * than fixed offset ones.
5646 */
5647 err = check_stack_write_var_off(env, state,
5648 ptr_regno, off, size,
5649 value_regno, insn_idx);
5650 }
5651 return err;
5652 }
5653
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5654 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5655 int off, int size, enum bpf_access_type type)
5656 {
5657 struct bpf_reg_state *regs = cur_regs(env);
5658 struct bpf_map *map = regs[regno].map_ptr;
5659 u32 cap = bpf_map_flags_to_cap(map);
5660
5661 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5662 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5663 map->value_size, off, size);
5664 return -EACCES;
5665 }
5666
5667 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5668 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5669 map->value_size, off, size);
5670 return -EACCES;
5671 }
5672
5673 return 0;
5674 }
5675
5676 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
__check_mem_access(struct bpf_verifier_env * env,int regno,int off,int size,u32 mem_size,bool zero_size_allowed)5677 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5678 int off, int size, u32 mem_size,
5679 bool zero_size_allowed)
5680 {
5681 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5682 struct bpf_reg_state *reg;
5683
5684 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5685 return 0;
5686
5687 reg = &cur_regs(env)[regno];
5688 switch (reg->type) {
5689 case PTR_TO_MAP_KEY:
5690 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5691 mem_size, off, size);
5692 break;
5693 case PTR_TO_MAP_VALUE:
5694 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5695 mem_size, off, size);
5696 break;
5697 case PTR_TO_PACKET:
5698 case PTR_TO_PACKET_META:
5699 case PTR_TO_PACKET_END:
5700 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5701 off, size, regno, reg->id, off, mem_size);
5702 break;
5703 case PTR_TO_MEM:
5704 default:
5705 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5706 mem_size, off, size);
5707 }
5708
5709 return -EACCES;
5710 }
5711
5712 /* check read/write into a memory region with possible variable offset */
check_mem_region_access(struct bpf_verifier_env * env,u32 regno,int off,int size,u32 mem_size,bool zero_size_allowed)5713 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5714 int off, int size, u32 mem_size,
5715 bool zero_size_allowed)
5716 {
5717 struct bpf_verifier_state *vstate = env->cur_state;
5718 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5719 struct bpf_reg_state *reg = &state->regs[regno];
5720 int err;
5721
5722 /* We may have adjusted the register pointing to memory region, so we
5723 * need to try adding each of min_value and max_value to off
5724 * to make sure our theoretical access will be safe.
5725 *
5726 * The minimum value is only important with signed
5727 * comparisons where we can't assume the floor of a
5728 * value is 0. If we are using signed variables for our
5729 * index'es we need to make sure that whatever we use
5730 * will have a set floor within our range.
5731 */
5732 if (reg->smin_value < 0 &&
5733 (reg->smin_value == S64_MIN ||
5734 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5735 reg->smin_value + off < 0)) {
5736 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5737 regno);
5738 return -EACCES;
5739 }
5740 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5741 mem_size, zero_size_allowed);
5742 if (err) {
5743 verbose(env, "R%d min value is outside of the allowed memory range\n",
5744 regno);
5745 return err;
5746 }
5747
5748 /* If we haven't set a max value then we need to bail since we can't be
5749 * sure we won't do bad things.
5750 * If reg->umax_value + off could overflow, treat that as unbounded too.
5751 */
5752 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5753 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5754 regno);
5755 return -EACCES;
5756 }
5757 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5758 mem_size, zero_size_allowed);
5759 if (err) {
5760 verbose(env, "R%d max value is outside of the allowed memory range\n",
5761 regno);
5762 return err;
5763 }
5764
5765 return 0;
5766 }
5767
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5768 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5769 const struct bpf_reg_state *reg, int regno,
5770 bool fixed_off_ok)
5771 {
5772 /* Access to this pointer-typed register or passing it to a helper
5773 * is only allowed in its original, unmodified form.
5774 */
5775
5776 if (reg->off < 0) {
5777 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5778 reg_type_str(env, reg->type), regno, reg->off);
5779 return -EACCES;
5780 }
5781
5782 if (!fixed_off_ok && reg->off) {
5783 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5784 reg_type_str(env, reg->type), regno, reg->off);
5785 return -EACCES;
5786 }
5787
5788 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5789 char tn_buf[48];
5790
5791 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5792 verbose(env, "variable %s access var_off=%s disallowed\n",
5793 reg_type_str(env, reg->type), tn_buf);
5794 return -EACCES;
5795 }
5796
5797 return 0;
5798 }
5799
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5800 static int check_ptr_off_reg(struct bpf_verifier_env *env,
5801 const struct bpf_reg_state *reg, int regno)
5802 {
5803 return __check_ptr_off_reg(env, reg, regno, false);
5804 }
5805
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5806 static int map_kptr_match_type(struct bpf_verifier_env *env,
5807 struct btf_field *kptr_field,
5808 struct bpf_reg_state *reg, u32 regno)
5809 {
5810 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5811 int perm_flags;
5812 const char *reg_name = "";
5813
5814 if (btf_is_kernel(reg->btf)) {
5815 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5816
5817 /* Only unreferenced case accepts untrusted pointers */
5818 if (kptr_field->type == BPF_KPTR_UNREF)
5819 perm_flags |= PTR_UNTRUSTED;
5820 } else {
5821 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5822 if (kptr_field->type == BPF_KPTR_PERCPU)
5823 perm_flags |= MEM_PERCPU;
5824 }
5825
5826 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5827 goto bad_type;
5828
5829 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5830 reg_name = btf_type_name(reg->btf, reg->btf_id);
5831
5832 /* For ref_ptr case, release function check should ensure we get one
5833 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5834 * normal store of unreferenced kptr, we must ensure var_off is zero.
5835 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5836 * reg->off and reg->ref_obj_id are not needed here.
5837 */
5838 if (__check_ptr_off_reg(env, reg, regno, true))
5839 return -EACCES;
5840
5841 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5842 * we also need to take into account the reg->off.
5843 *
5844 * We want to support cases like:
5845 *
5846 * struct foo {
5847 * struct bar br;
5848 * struct baz bz;
5849 * };
5850 *
5851 * struct foo *v;
5852 * v = func(); // PTR_TO_BTF_ID
5853 * val->foo = v; // reg->off is zero, btf and btf_id match type
5854 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5855 * // first member type of struct after comparison fails
5856 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5857 * // to match type
5858 *
5859 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5860 * is zero. We must also ensure that btf_struct_ids_match does not walk
5861 * the struct to match type against first member of struct, i.e. reject
5862 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5863 * strict mode to true for type match.
5864 */
5865 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5866 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5867 kptr_field->type != BPF_KPTR_UNREF))
5868 goto bad_type;
5869 return 0;
5870 bad_type:
5871 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5872 reg_type_str(env, reg->type), reg_name);
5873 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5874 if (kptr_field->type == BPF_KPTR_UNREF)
5875 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5876 targ_name);
5877 else
5878 verbose(env, "\n");
5879 return -EINVAL;
5880 }
5881
in_sleepable(struct bpf_verifier_env * env)5882 static bool in_sleepable(struct bpf_verifier_env *env)
5883 {
5884 return env->cur_state->in_sleepable;
5885 }
5886
5887 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5888 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5889 */
in_rcu_cs(struct bpf_verifier_env * env)5890 static bool in_rcu_cs(struct bpf_verifier_env *env)
5891 {
5892 return env->cur_state->active_rcu_locks ||
5893 env->cur_state->active_locks ||
5894 !in_sleepable(env);
5895 }
5896
5897 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5898 BTF_SET_START(rcu_protected_types)
5899 #ifdef CONFIG_NET
BTF_ID(struct,prog_test_ref_kfunc)5900 BTF_ID(struct, prog_test_ref_kfunc)
5901 #endif
5902 #ifdef CONFIG_CGROUPS
5903 BTF_ID(struct, cgroup)
5904 #endif
5905 #ifdef CONFIG_BPF_JIT
5906 BTF_ID(struct, bpf_cpumask)
5907 #endif
5908 BTF_ID(struct, task_struct)
5909 #ifdef CONFIG_CRYPTO
5910 BTF_ID(struct, bpf_crypto_ctx)
5911 #endif
5912 BTF_SET_END(rcu_protected_types)
5913
5914 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5915 {
5916 if (!btf_is_kernel(btf))
5917 return true;
5918 return btf_id_set_contains(&rcu_protected_types, btf_id);
5919 }
5920
kptr_pointee_btf_record(struct btf_field * kptr_field)5921 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field)
5922 {
5923 struct btf_struct_meta *meta;
5924
5925 if (btf_is_kernel(kptr_field->kptr.btf))
5926 return NULL;
5927
5928 meta = btf_find_struct_meta(kptr_field->kptr.btf,
5929 kptr_field->kptr.btf_id);
5930
5931 return meta ? meta->record : NULL;
5932 }
5933
rcu_safe_kptr(const struct btf_field * field)5934 static bool rcu_safe_kptr(const struct btf_field *field)
5935 {
5936 const struct btf_field_kptr *kptr = &field->kptr;
5937
5938 return field->type == BPF_KPTR_PERCPU ||
5939 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5940 }
5941
btf_ld_kptr_type(struct bpf_verifier_env * env,struct btf_field * kptr_field)5942 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5943 {
5944 struct btf_record *rec;
5945 u32 ret;
5946
5947 ret = PTR_MAYBE_NULL;
5948 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5949 ret |= MEM_RCU;
5950 if (kptr_field->type == BPF_KPTR_PERCPU)
5951 ret |= MEM_PERCPU;
5952 else if (!btf_is_kernel(kptr_field->kptr.btf))
5953 ret |= MEM_ALLOC;
5954
5955 rec = kptr_pointee_btf_record(kptr_field);
5956 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE))
5957 ret |= NON_OWN_REF;
5958 } else {
5959 ret |= PTR_UNTRUSTED;
5960 }
5961
5962 return ret;
5963 }
5964
mark_uptr_ld_reg(struct bpf_verifier_env * env,u32 regno,struct btf_field * field)5965 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno,
5966 struct btf_field *field)
5967 {
5968 struct bpf_reg_state *reg;
5969 const struct btf_type *t;
5970
5971 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id);
5972 mark_reg_known_zero(env, cur_regs(env), regno);
5973 reg = reg_state(env, regno);
5974 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
5975 reg->mem_size = t->size;
5976 reg->id = ++env->id_gen;
5977
5978 return 0;
5979 }
5980
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)5981 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5982 int value_regno, int insn_idx,
5983 struct btf_field *kptr_field)
5984 {
5985 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5986 int class = BPF_CLASS(insn->code);
5987 struct bpf_reg_state *val_reg;
5988 int ret;
5989
5990 /* Things we already checked for in check_map_access and caller:
5991 * - Reject cases where variable offset may touch kptr
5992 * - size of access (must be BPF_DW)
5993 * - tnum_is_const(reg->var_off)
5994 * - kptr_field->offset == off + reg->var_off.value
5995 */
5996 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5997 if (BPF_MODE(insn->code) != BPF_MEM) {
5998 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5999 return -EACCES;
6000 }
6001
6002 /* We only allow loading referenced kptr, since it will be marked as
6003 * untrusted, similar to unreferenced kptr.
6004 */
6005 if (class != BPF_LDX &&
6006 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
6007 verbose(env, "store to referenced kptr disallowed\n");
6008 return -EACCES;
6009 }
6010 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) {
6011 verbose(env, "store to uptr disallowed\n");
6012 return -EACCES;
6013 }
6014
6015 if (class == BPF_LDX) {
6016 if (kptr_field->type == BPF_UPTR)
6017 return mark_uptr_ld_reg(env, value_regno, kptr_field);
6018
6019 /* We can simply mark the value_regno receiving the pointer
6020 * value from map as PTR_TO_BTF_ID, with the correct type.
6021 */
6022 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID,
6023 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
6024 btf_ld_kptr_type(env, kptr_field));
6025 if (ret < 0)
6026 return ret;
6027 } else if (class == BPF_STX) {
6028 val_reg = reg_state(env, value_regno);
6029 if (!register_is_null(val_reg) &&
6030 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
6031 return -EACCES;
6032 } else if (class == BPF_ST) {
6033 if (insn->imm) {
6034 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
6035 kptr_field->offset);
6036 return -EACCES;
6037 }
6038 } else {
6039 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
6040 return -EACCES;
6041 }
6042 return 0;
6043 }
6044
6045 /*
6046 * Return the size of the memory region accessible from a pointer to map value.
6047 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible.
6048 */
map_mem_size(const struct bpf_map * map)6049 static u32 map_mem_size(const struct bpf_map *map)
6050 {
6051 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6052 return map->max_entries * sizeof(long);
6053
6054 return map->value_size;
6055 }
6056
6057 /* check read/write into a map element with possible variable offset */
check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed,enum bpf_access_src src)6058 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
6059 int off, int size, bool zero_size_allowed,
6060 enum bpf_access_src src)
6061 {
6062 struct bpf_verifier_state *vstate = env->cur_state;
6063 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6064 struct bpf_reg_state *reg = &state->regs[regno];
6065 struct bpf_map *map = reg->map_ptr;
6066 u32 mem_size = map_mem_size(map);
6067 struct btf_record *rec;
6068 int err, i;
6069
6070 err = check_mem_region_access(env, regno, off, size, mem_size, zero_size_allowed);
6071 if (err)
6072 return err;
6073
6074 if (IS_ERR_OR_NULL(map->record))
6075 return 0;
6076 rec = map->record;
6077 for (i = 0; i < rec->cnt; i++) {
6078 struct btf_field *field = &rec->fields[i];
6079 u32 p = field->offset;
6080
6081 /* If any part of a field can be touched by load/store, reject
6082 * this program. To check that [x1, x2) overlaps with [y1, y2),
6083 * it is sufficient to check x1 < y2 && y1 < x2.
6084 */
6085 if (reg->smin_value + off < p + field->size &&
6086 p < reg->umax_value + off + size) {
6087 switch (field->type) {
6088 case BPF_KPTR_UNREF:
6089 case BPF_KPTR_REF:
6090 case BPF_KPTR_PERCPU:
6091 case BPF_UPTR:
6092 if (src != ACCESS_DIRECT) {
6093 verbose(env, "%s cannot be accessed indirectly by helper\n",
6094 btf_field_type_name(field->type));
6095 return -EACCES;
6096 }
6097 if (!tnum_is_const(reg->var_off)) {
6098 verbose(env, "%s access cannot have variable offset\n",
6099 btf_field_type_name(field->type));
6100 return -EACCES;
6101 }
6102 if (p != off + reg->var_off.value) {
6103 verbose(env, "%s access misaligned expected=%u off=%llu\n",
6104 btf_field_type_name(field->type),
6105 p, off + reg->var_off.value);
6106 return -EACCES;
6107 }
6108 if (size != bpf_size_to_bytes(BPF_DW)) {
6109 verbose(env, "%s access size must be BPF_DW\n",
6110 btf_field_type_name(field->type));
6111 return -EACCES;
6112 }
6113 break;
6114 default:
6115 verbose(env, "%s cannot be accessed directly by load/store\n",
6116 btf_field_type_name(field->type));
6117 return -EACCES;
6118 }
6119 }
6120 }
6121 return 0;
6122 }
6123
6124 #define MAX_PACKET_OFF 0xffff
6125
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)6126 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
6127 const struct bpf_call_arg_meta *meta,
6128 enum bpf_access_type t)
6129 {
6130 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6131
6132 switch (prog_type) {
6133 /* Program types only with direct read access go here! */
6134 case BPF_PROG_TYPE_LWT_IN:
6135 case BPF_PROG_TYPE_LWT_OUT:
6136 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
6137 case BPF_PROG_TYPE_SK_REUSEPORT:
6138 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6139 case BPF_PROG_TYPE_CGROUP_SKB:
6140 if (t == BPF_WRITE)
6141 return false;
6142 fallthrough;
6143
6144 /* Program types with direct read + write access go here! */
6145 case BPF_PROG_TYPE_SCHED_CLS:
6146 case BPF_PROG_TYPE_SCHED_ACT:
6147 case BPF_PROG_TYPE_XDP:
6148 case BPF_PROG_TYPE_LWT_XMIT:
6149 case BPF_PROG_TYPE_SK_SKB:
6150 case BPF_PROG_TYPE_SK_MSG:
6151 if (meta)
6152 return meta->pkt_access;
6153
6154 env->seen_direct_write = true;
6155 return true;
6156
6157 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6158 if (t == BPF_WRITE)
6159 env->seen_direct_write = true;
6160
6161 return true;
6162
6163 default:
6164 return false;
6165 }
6166 }
6167
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)6168 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
6169 int size, bool zero_size_allowed)
6170 {
6171 struct bpf_reg_state *regs = cur_regs(env);
6172 struct bpf_reg_state *reg = ®s[regno];
6173 int err;
6174
6175 /* We may have added a variable offset to the packet pointer; but any
6176 * reg->range we have comes after that. We are only checking the fixed
6177 * offset.
6178 */
6179
6180 /* We don't allow negative numbers, because we aren't tracking enough
6181 * detail to prove they're safe.
6182 */
6183 if (reg->smin_value < 0) {
6184 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6185 regno);
6186 return -EACCES;
6187 }
6188
6189 err = reg->range < 0 ? -EINVAL :
6190 __check_mem_access(env, regno, off, size, reg->range,
6191 zero_size_allowed);
6192 if (err) {
6193 verbose(env, "R%d offset is outside of the packet\n", regno);
6194 return err;
6195 }
6196
6197 /* __check_mem_access has made sure "off + size - 1" is within u16.
6198 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
6199 * otherwise find_good_pkt_pointers would have refused to set range info
6200 * that __check_mem_access would have rejected this pkt access.
6201 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
6202 */
6203 env->prog->aux->max_pkt_offset =
6204 max_t(u32, env->prog->aux->max_pkt_offset,
6205 off + reg->umax_value + size - 1);
6206
6207 return err;
6208 }
6209
6210 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,struct bpf_insn_access_aux * info)6211 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
6212 enum bpf_access_type t, struct bpf_insn_access_aux *info)
6213 {
6214 if (env->ops->is_valid_access &&
6215 env->ops->is_valid_access(off, size, t, env->prog, info)) {
6216 /* A non zero info.ctx_field_size indicates that this field is a
6217 * candidate for later verifier transformation to load the whole
6218 * field and then apply a mask when accessed with a narrower
6219 * access than actual ctx access size. A zero info.ctx_field_size
6220 * will only allow for whole field access and rejects any other
6221 * type of narrower access.
6222 */
6223 if (base_type(info->reg_type) == PTR_TO_BTF_ID) {
6224 if (info->ref_obj_id &&
6225 !find_reference_state(env->cur_state, info->ref_obj_id)) {
6226 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n",
6227 off);
6228 return -EACCES;
6229 }
6230 } else {
6231 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size;
6232 }
6233 /* remember the offset of last byte accessed in ctx */
6234 if (env->prog->aux->max_ctx_offset < off + size)
6235 env->prog->aux->max_ctx_offset = off + size;
6236 return 0;
6237 }
6238
6239 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
6240 return -EACCES;
6241 }
6242
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)6243 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
6244 int size)
6245 {
6246 if (size < 0 || off < 0 ||
6247 (u64)off + size > sizeof(struct bpf_flow_keys)) {
6248 verbose(env, "invalid access to flow keys off=%d size=%d\n",
6249 off, size);
6250 return -EACCES;
6251 }
6252 return 0;
6253 }
6254
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)6255 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
6256 u32 regno, int off, int size,
6257 enum bpf_access_type t)
6258 {
6259 struct bpf_reg_state *regs = cur_regs(env);
6260 struct bpf_reg_state *reg = ®s[regno];
6261 struct bpf_insn_access_aux info = {};
6262 bool valid;
6263
6264 if (reg->smin_value < 0) {
6265 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
6266 regno);
6267 return -EACCES;
6268 }
6269
6270 switch (reg->type) {
6271 case PTR_TO_SOCK_COMMON:
6272 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
6273 break;
6274 case PTR_TO_SOCKET:
6275 valid = bpf_sock_is_valid_access(off, size, t, &info);
6276 break;
6277 case PTR_TO_TCP_SOCK:
6278 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
6279 break;
6280 case PTR_TO_XDP_SOCK:
6281 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
6282 break;
6283 default:
6284 valid = false;
6285 }
6286
6287
6288 if (valid) {
6289 env->insn_aux_data[insn_idx].ctx_field_size =
6290 info.ctx_field_size;
6291 return 0;
6292 }
6293
6294 verbose(env, "R%d invalid %s access off=%d size=%d\n",
6295 regno, reg_type_str(env, reg->type), off, size);
6296
6297 return -EACCES;
6298 }
6299
is_pointer_value(struct bpf_verifier_env * env,int regno)6300 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
6301 {
6302 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
6303 }
6304
is_ctx_reg(struct bpf_verifier_env * env,int regno)6305 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
6306 {
6307 const struct bpf_reg_state *reg = reg_state(env, regno);
6308
6309 return reg->type == PTR_TO_CTX;
6310 }
6311
is_sk_reg(struct bpf_verifier_env * env,int regno)6312 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
6313 {
6314 const struct bpf_reg_state *reg = reg_state(env, regno);
6315
6316 return type_is_sk_pointer(reg->type);
6317 }
6318
is_pkt_reg(struct bpf_verifier_env * env,int regno)6319 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
6320 {
6321 const struct bpf_reg_state *reg = reg_state(env, regno);
6322
6323 return type_is_pkt_pointer(reg->type);
6324 }
6325
is_flow_key_reg(struct bpf_verifier_env * env,int regno)6326 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
6327 {
6328 const struct bpf_reg_state *reg = reg_state(env, regno);
6329
6330 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
6331 return reg->type == PTR_TO_FLOW_KEYS;
6332 }
6333
is_arena_reg(struct bpf_verifier_env * env,int regno)6334 static bool is_arena_reg(struct bpf_verifier_env *env, int regno)
6335 {
6336 const struct bpf_reg_state *reg = reg_state(env, regno);
6337
6338 return reg->type == PTR_TO_ARENA;
6339 }
6340
6341 /* Return false if @regno contains a pointer whose type isn't supported for
6342 * atomic instruction @insn.
6343 */
atomic_ptr_type_ok(struct bpf_verifier_env * env,int regno,struct bpf_insn * insn)6344 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno,
6345 struct bpf_insn *insn)
6346 {
6347 if (is_ctx_reg(env, regno))
6348 return false;
6349 if (is_pkt_reg(env, regno))
6350 return false;
6351 if (is_flow_key_reg(env, regno))
6352 return false;
6353 if (is_sk_reg(env, regno))
6354 return false;
6355 if (is_arena_reg(env, regno))
6356 return bpf_jit_supports_insn(insn, true);
6357
6358 return true;
6359 }
6360
6361 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
6362 #ifdef CONFIG_NET
6363 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
6364 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
6365 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
6366 #endif
6367 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
6368 };
6369
is_trusted_reg(const struct bpf_reg_state * reg)6370 static bool is_trusted_reg(const struct bpf_reg_state *reg)
6371 {
6372 /* A referenced register is always trusted. */
6373 if (reg->ref_obj_id)
6374 return true;
6375
6376 /* Types listed in the reg2btf_ids are always trusted */
6377 if (reg2btf_ids[base_type(reg->type)] &&
6378 !bpf_type_has_unsafe_modifiers(reg->type))
6379 return true;
6380
6381 /* If a register is not referenced, it is trusted if it has the
6382 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
6383 * other type modifiers may be safe, but we elect to take an opt-in
6384 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
6385 * not.
6386 *
6387 * Eventually, we should make PTR_TRUSTED the single source of truth
6388 * for whether a register is trusted.
6389 */
6390 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
6391 !bpf_type_has_unsafe_modifiers(reg->type);
6392 }
6393
is_rcu_reg(const struct bpf_reg_state * reg)6394 static bool is_rcu_reg(const struct bpf_reg_state *reg)
6395 {
6396 return reg->type & MEM_RCU;
6397 }
6398
clear_trusted_flags(enum bpf_type_flag * flag)6399 static void clear_trusted_flags(enum bpf_type_flag *flag)
6400 {
6401 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
6402 }
6403
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)6404 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
6405 const struct bpf_reg_state *reg,
6406 int off, int size, bool strict)
6407 {
6408 struct tnum reg_off;
6409 int ip_align;
6410
6411 /* Byte size accesses are always allowed. */
6412 if (!strict || size == 1)
6413 return 0;
6414
6415 /* For platforms that do not have a Kconfig enabling
6416 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
6417 * NET_IP_ALIGN is universally set to '2'. And on platforms
6418 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
6419 * to this code only in strict mode where we want to emulate
6420 * the NET_IP_ALIGN==2 checking. Therefore use an
6421 * unconditional IP align value of '2'.
6422 */
6423 ip_align = 2;
6424
6425 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
6426 if (!tnum_is_aligned(reg_off, size)) {
6427 char tn_buf[48];
6428
6429 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6430 verbose(env,
6431 "misaligned packet access off %d+%s+%d+%d size %d\n",
6432 ip_align, tn_buf, reg->off, off, size);
6433 return -EACCES;
6434 }
6435
6436 return 0;
6437 }
6438
check_generic_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,const char * pointer_desc,int off,int size,bool strict)6439 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
6440 const struct bpf_reg_state *reg,
6441 const char *pointer_desc,
6442 int off, int size, bool strict)
6443 {
6444 struct tnum reg_off;
6445
6446 /* Byte size accesses are always allowed. */
6447 if (!strict || size == 1)
6448 return 0;
6449
6450 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
6451 if (!tnum_is_aligned(reg_off, size)) {
6452 char tn_buf[48];
6453
6454 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6455 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
6456 pointer_desc, tn_buf, reg->off, off, size);
6457 return -EACCES;
6458 }
6459
6460 return 0;
6461 }
6462
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)6463 static int check_ptr_alignment(struct bpf_verifier_env *env,
6464 const struct bpf_reg_state *reg, int off,
6465 int size, bool strict_alignment_once)
6466 {
6467 bool strict = env->strict_alignment || strict_alignment_once;
6468 const char *pointer_desc = "";
6469
6470 switch (reg->type) {
6471 case PTR_TO_PACKET:
6472 case PTR_TO_PACKET_META:
6473 /* Special case, because of NET_IP_ALIGN. Given metadata sits
6474 * right in front, treat it the very same way.
6475 */
6476 return check_pkt_ptr_alignment(env, reg, off, size, strict);
6477 case PTR_TO_FLOW_KEYS:
6478 pointer_desc = "flow keys ";
6479 break;
6480 case PTR_TO_MAP_KEY:
6481 pointer_desc = "key ";
6482 break;
6483 case PTR_TO_MAP_VALUE:
6484 pointer_desc = "value ";
6485 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY)
6486 strict = true;
6487 break;
6488 case PTR_TO_CTX:
6489 pointer_desc = "context ";
6490 break;
6491 case PTR_TO_STACK:
6492 pointer_desc = "stack ";
6493 /* The stack spill tracking logic in check_stack_write_fixed_off()
6494 * and check_stack_read_fixed_off() relies on stack accesses being
6495 * aligned.
6496 */
6497 strict = true;
6498 break;
6499 case PTR_TO_SOCKET:
6500 pointer_desc = "sock ";
6501 break;
6502 case PTR_TO_SOCK_COMMON:
6503 pointer_desc = "sock_common ";
6504 break;
6505 case PTR_TO_TCP_SOCK:
6506 pointer_desc = "tcp_sock ";
6507 break;
6508 case PTR_TO_XDP_SOCK:
6509 pointer_desc = "xdp_sock ";
6510 break;
6511 case PTR_TO_ARENA:
6512 return 0;
6513 default:
6514 break;
6515 }
6516 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
6517 strict);
6518 }
6519
bpf_enable_priv_stack(struct bpf_prog * prog)6520 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog)
6521 {
6522 if (!bpf_jit_supports_private_stack())
6523 return NO_PRIV_STACK;
6524
6525 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline
6526 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked
6527 * explicitly.
6528 */
6529 switch (prog->type) {
6530 case BPF_PROG_TYPE_KPROBE:
6531 case BPF_PROG_TYPE_TRACEPOINT:
6532 case BPF_PROG_TYPE_PERF_EVENT:
6533 case BPF_PROG_TYPE_RAW_TRACEPOINT:
6534 return PRIV_STACK_ADAPTIVE;
6535 case BPF_PROG_TYPE_TRACING:
6536 case BPF_PROG_TYPE_LSM:
6537 case BPF_PROG_TYPE_STRUCT_OPS:
6538 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog))
6539 return PRIV_STACK_ADAPTIVE;
6540 fallthrough;
6541 default:
6542 break;
6543 }
6544
6545 return NO_PRIV_STACK;
6546 }
6547
round_up_stack_depth(struct bpf_verifier_env * env,int stack_depth)6548 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth)
6549 {
6550 if (env->prog->jit_requested)
6551 return round_up(stack_depth, 16);
6552
6553 /* round up to 32-bytes, since this is granularity
6554 * of interpreter stack size
6555 */
6556 return round_up(max_t(u32, stack_depth, 1), 32);
6557 }
6558
6559 /* starting from main bpf function walk all instructions of the function
6560 * and recursively walk all callees that given function can call.
6561 * Ignore jump and exit insns.
6562 * Since recursion is prevented by check_cfg() this algorithm
6563 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
6564 */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx,bool priv_stack_supported)6565 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
6566 bool priv_stack_supported)
6567 {
6568 struct bpf_subprog_info *subprog = env->subprog_info;
6569 struct bpf_insn *insn = env->prog->insnsi;
6570 int depth = 0, frame = 0, i, subprog_end, subprog_depth;
6571 bool tail_call_reachable = false;
6572 int ret_insn[MAX_CALL_FRAMES];
6573 int ret_prog[MAX_CALL_FRAMES];
6574 int j;
6575
6576 i = subprog[idx].start;
6577 if (!priv_stack_supported)
6578 subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6579 process_func:
6580 /* protect against potential stack overflow that might happen when
6581 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
6582 * depth for such case down to 256 so that the worst case scenario
6583 * would result in 8k stack size (32 which is tailcall limit * 256 =
6584 * 8k).
6585 *
6586 * To get the idea what might happen, see an example:
6587 * func1 -> sub rsp, 128
6588 * subfunc1 -> sub rsp, 256
6589 * tailcall1 -> add rsp, 256
6590 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
6591 * subfunc2 -> sub rsp, 64
6592 * subfunc22 -> sub rsp, 128
6593 * tailcall2 -> add rsp, 128
6594 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
6595 *
6596 * tailcall will unwind the current stack frame but it will not get rid
6597 * of caller's stack as shown on the example above.
6598 */
6599 if (idx && subprog[idx].has_tail_call && depth >= 256) {
6600 verbose(env,
6601 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
6602 depth);
6603 return -EACCES;
6604 }
6605
6606 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth);
6607 if (priv_stack_supported) {
6608 /* Request private stack support only if the subprog stack
6609 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
6610 * avoid jit penalty if the stack usage is small.
6611 */
6612 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN &&
6613 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE)
6614 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE;
6615 }
6616
6617 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6618 if (subprog_depth > MAX_BPF_STACK) {
6619 verbose(env, "stack size of subprog %d is %d. Too large\n",
6620 idx, subprog_depth);
6621 return -EACCES;
6622 }
6623 } else {
6624 depth += subprog_depth;
6625 if (depth > MAX_BPF_STACK) {
6626 verbose(env, "combined stack size of %d calls is %d. Too large\n",
6627 frame + 1, depth);
6628 return -EACCES;
6629 }
6630 }
6631 continue_func:
6632 subprog_end = subprog[idx + 1].start;
6633 for (; i < subprog_end; i++) {
6634 int next_insn, sidx;
6635
6636 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
6637 bool err = false;
6638
6639 if (!is_bpf_throw_kfunc(insn + i))
6640 continue;
6641 if (subprog[idx].is_cb)
6642 err = true;
6643 for (int c = 0; c < frame && !err; c++) {
6644 if (subprog[ret_prog[c]].is_cb) {
6645 err = true;
6646 break;
6647 }
6648 }
6649 if (!err)
6650 continue;
6651 verbose(env,
6652 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
6653 i, idx);
6654 return -EINVAL;
6655 }
6656
6657 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6658 continue;
6659 /* remember insn and function to return to */
6660 ret_insn[frame] = i + 1;
6661 ret_prog[frame] = idx;
6662
6663 /* find the callee */
6664 next_insn = i + insn[i].imm + 1;
6665 sidx = find_subprog(env, next_insn);
6666 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn))
6667 return -EFAULT;
6668 if (subprog[sidx].is_async_cb) {
6669 if (subprog[sidx].has_tail_call) {
6670 verifier_bug(env, "subprog has tail_call and async cb");
6671 return -EFAULT;
6672 }
6673 /* async callbacks don't increase bpf prog stack size unless called directly */
6674 if (!bpf_pseudo_call(insn + i))
6675 continue;
6676 if (subprog[sidx].is_exception_cb) {
6677 verbose(env, "insn %d cannot call exception cb directly", i);
6678 return -EINVAL;
6679 }
6680 }
6681 i = next_insn;
6682 idx = sidx;
6683 if (!priv_stack_supported)
6684 subprog[idx].priv_stack_mode = NO_PRIV_STACK;
6685
6686 if (subprog[idx].has_tail_call)
6687 tail_call_reachable = true;
6688
6689 frame++;
6690 if (frame >= MAX_CALL_FRAMES) {
6691 verbose(env, "the call stack of %d frames is too deep !\n",
6692 frame);
6693 return -E2BIG;
6694 }
6695 goto process_func;
6696 }
6697 /* if tail call got detected across bpf2bpf calls then mark each of the
6698 * currently present subprog frames as tail call reachable subprogs;
6699 * this info will be utilized by JIT so that we will be preserving the
6700 * tail call counter throughout bpf2bpf calls combined with tailcalls
6701 */
6702 if (tail_call_reachable)
6703 for (j = 0; j < frame; j++) {
6704 if (subprog[ret_prog[j]].is_exception_cb) {
6705 verbose(env, "cannot tail call within exception cb\n");
6706 return -EINVAL;
6707 }
6708 subprog[ret_prog[j]].tail_call_reachable = true;
6709 }
6710 if (subprog[0].tail_call_reachable)
6711 env->prog->aux->tail_call_reachable = true;
6712
6713 /* end of for() loop means the last insn of the 'subprog'
6714 * was reached. Doesn't matter whether it was JA or EXIT
6715 */
6716 if (frame == 0)
6717 return 0;
6718 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE)
6719 depth -= round_up_stack_depth(env, subprog[idx].stack_depth);
6720 frame--;
6721 i = ret_insn[frame];
6722 idx = ret_prog[frame];
6723 goto continue_func;
6724 }
6725
check_max_stack_depth(struct bpf_verifier_env * env)6726 static int check_max_stack_depth(struct bpf_verifier_env *env)
6727 {
6728 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN;
6729 struct bpf_subprog_info *si = env->subprog_info;
6730 bool priv_stack_supported;
6731 int ret;
6732
6733 for (int i = 0; i < env->subprog_cnt; i++) {
6734 if (si[i].has_tail_call) {
6735 priv_stack_mode = NO_PRIV_STACK;
6736 break;
6737 }
6738 }
6739
6740 if (priv_stack_mode == PRIV_STACK_UNKNOWN)
6741 priv_stack_mode = bpf_enable_priv_stack(env->prog);
6742
6743 /* All async_cb subprogs use normal kernel stack. If a particular
6744 * subprog appears in both main prog and async_cb subtree, that
6745 * subprog will use normal kernel stack to avoid potential nesting.
6746 * The reverse subprog traversal ensures when main prog subtree is
6747 * checked, the subprogs appearing in async_cb subtrees are already
6748 * marked as using normal kernel stack, so stack size checking can
6749 * be done properly.
6750 */
6751 for (int i = env->subprog_cnt - 1; i >= 0; i--) {
6752 if (!i || si[i].is_async_cb) {
6753 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE;
6754 ret = check_max_stack_depth_subprog(env, i, priv_stack_supported);
6755 if (ret < 0)
6756 return ret;
6757 }
6758 }
6759
6760 for (int i = 0; i < env->subprog_cnt; i++) {
6761 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) {
6762 env->prog->aux->jits_use_priv_stack = true;
6763 break;
6764 }
6765 }
6766
6767 return 0;
6768 }
6769
6770 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)6771 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6772 const struct bpf_insn *insn, int idx)
6773 {
6774 int start = idx + insn->imm + 1, subprog;
6775
6776 subprog = find_subprog(env, start);
6777 if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
6778 return -EFAULT;
6779 return env->subprog_info[subprog].stack_depth;
6780 }
6781 #endif
6782
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)6783 static int __check_buffer_access(struct bpf_verifier_env *env,
6784 const char *buf_info,
6785 const struct bpf_reg_state *reg,
6786 int regno, int off, int size)
6787 {
6788 if (off < 0) {
6789 verbose(env,
6790 "R%d invalid %s buffer access: off=%d, size=%d\n",
6791 regno, buf_info, off, size);
6792 return -EACCES;
6793 }
6794 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6795 char tn_buf[48];
6796
6797 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6798 verbose(env,
6799 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6800 regno, off, tn_buf);
6801 return -EACCES;
6802 }
6803
6804 return 0;
6805 }
6806
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)6807 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6808 const struct bpf_reg_state *reg,
6809 int regno, int off, int size)
6810 {
6811 int err;
6812
6813 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6814 if (err)
6815 return err;
6816
6817 if (off + size > env->prog->aux->max_tp_access)
6818 env->prog->aux->max_tp_access = off + size;
6819
6820 return 0;
6821 }
6822
check_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size,bool zero_size_allowed,u32 * max_access)6823 static int check_buffer_access(struct bpf_verifier_env *env,
6824 const struct bpf_reg_state *reg,
6825 int regno, int off, int size,
6826 bool zero_size_allowed,
6827 u32 *max_access)
6828 {
6829 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6830 int err;
6831
6832 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6833 if (err)
6834 return err;
6835
6836 if (off + size > *max_access)
6837 *max_access = off + size;
6838
6839 return 0;
6840 }
6841
6842 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6843 static void zext_32_to_64(struct bpf_reg_state *reg)
6844 {
6845 reg->var_off = tnum_subreg(reg->var_off);
6846 __reg_assign_32_into_64(reg);
6847 }
6848
6849 /* truncate register to smaller size (in bytes)
6850 * must be called with size < BPF_REG_SIZE
6851 */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6852 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6853 {
6854 u64 mask;
6855
6856 /* clear high bits in bit representation */
6857 reg->var_off = tnum_cast(reg->var_off, size);
6858
6859 /* fix arithmetic bounds */
6860 mask = ((u64)1 << (size * 8)) - 1;
6861 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6862 reg->umin_value &= mask;
6863 reg->umax_value &= mask;
6864 } else {
6865 reg->umin_value = 0;
6866 reg->umax_value = mask;
6867 }
6868 reg->smin_value = reg->umin_value;
6869 reg->smax_value = reg->umax_value;
6870
6871 /* If size is smaller than 32bit register the 32bit register
6872 * values are also truncated so we push 64-bit bounds into
6873 * 32-bit bounds. Above were truncated < 32-bits already.
6874 */
6875 if (size < 4)
6876 __mark_reg32_unbounded(reg);
6877
6878 reg_bounds_sync(reg);
6879 }
6880
set_sext64_default_val(struct bpf_reg_state * reg,int size)6881 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6882 {
6883 if (size == 1) {
6884 reg->smin_value = reg->s32_min_value = S8_MIN;
6885 reg->smax_value = reg->s32_max_value = S8_MAX;
6886 } else if (size == 2) {
6887 reg->smin_value = reg->s32_min_value = S16_MIN;
6888 reg->smax_value = reg->s32_max_value = S16_MAX;
6889 } else {
6890 /* size == 4 */
6891 reg->smin_value = reg->s32_min_value = S32_MIN;
6892 reg->smax_value = reg->s32_max_value = S32_MAX;
6893 }
6894 reg->umin_value = reg->u32_min_value = 0;
6895 reg->umax_value = U64_MAX;
6896 reg->u32_max_value = U32_MAX;
6897 reg->var_off = tnum_unknown;
6898 }
6899
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6900 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6901 {
6902 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6903 u64 top_smax_value, top_smin_value;
6904 u64 num_bits = size * 8;
6905
6906 if (tnum_is_const(reg->var_off)) {
6907 u64_cval = reg->var_off.value;
6908 if (size == 1)
6909 reg->var_off = tnum_const((s8)u64_cval);
6910 else if (size == 2)
6911 reg->var_off = tnum_const((s16)u64_cval);
6912 else
6913 /* size == 4 */
6914 reg->var_off = tnum_const((s32)u64_cval);
6915
6916 u64_cval = reg->var_off.value;
6917 reg->smax_value = reg->smin_value = u64_cval;
6918 reg->umax_value = reg->umin_value = u64_cval;
6919 reg->s32_max_value = reg->s32_min_value = u64_cval;
6920 reg->u32_max_value = reg->u32_min_value = u64_cval;
6921 return;
6922 }
6923
6924 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6925 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6926
6927 if (top_smax_value != top_smin_value)
6928 goto out;
6929
6930 /* find the s64_min and s64_min after sign extension */
6931 if (size == 1) {
6932 init_s64_max = (s8)reg->smax_value;
6933 init_s64_min = (s8)reg->smin_value;
6934 } else if (size == 2) {
6935 init_s64_max = (s16)reg->smax_value;
6936 init_s64_min = (s16)reg->smin_value;
6937 } else {
6938 init_s64_max = (s32)reg->smax_value;
6939 init_s64_min = (s32)reg->smin_value;
6940 }
6941
6942 s64_max = max(init_s64_max, init_s64_min);
6943 s64_min = min(init_s64_max, init_s64_min);
6944
6945 /* both of s64_max/s64_min positive or negative */
6946 if ((s64_max >= 0) == (s64_min >= 0)) {
6947 reg->s32_min_value = reg->smin_value = s64_min;
6948 reg->s32_max_value = reg->smax_value = s64_max;
6949 reg->u32_min_value = reg->umin_value = s64_min;
6950 reg->u32_max_value = reg->umax_value = s64_max;
6951 reg->var_off = tnum_range(s64_min, s64_max);
6952 return;
6953 }
6954
6955 out:
6956 set_sext64_default_val(reg, size);
6957 }
6958
set_sext32_default_val(struct bpf_reg_state * reg,int size)6959 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6960 {
6961 if (size == 1) {
6962 reg->s32_min_value = S8_MIN;
6963 reg->s32_max_value = S8_MAX;
6964 } else {
6965 /* size == 2 */
6966 reg->s32_min_value = S16_MIN;
6967 reg->s32_max_value = S16_MAX;
6968 }
6969 reg->u32_min_value = 0;
6970 reg->u32_max_value = U32_MAX;
6971 reg->var_off = tnum_subreg(tnum_unknown);
6972 }
6973
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6974 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6975 {
6976 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6977 u32 top_smax_value, top_smin_value;
6978 u32 num_bits = size * 8;
6979
6980 if (tnum_is_const(reg->var_off)) {
6981 u32_val = reg->var_off.value;
6982 if (size == 1)
6983 reg->var_off = tnum_const((s8)u32_val);
6984 else
6985 reg->var_off = tnum_const((s16)u32_val);
6986
6987 u32_val = reg->var_off.value;
6988 reg->s32_min_value = reg->s32_max_value = u32_val;
6989 reg->u32_min_value = reg->u32_max_value = u32_val;
6990 return;
6991 }
6992
6993 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6994 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6995
6996 if (top_smax_value != top_smin_value)
6997 goto out;
6998
6999 /* find the s32_min and s32_min after sign extension */
7000 if (size == 1) {
7001 init_s32_max = (s8)reg->s32_max_value;
7002 init_s32_min = (s8)reg->s32_min_value;
7003 } else {
7004 /* size == 2 */
7005 init_s32_max = (s16)reg->s32_max_value;
7006 init_s32_min = (s16)reg->s32_min_value;
7007 }
7008 s32_max = max(init_s32_max, init_s32_min);
7009 s32_min = min(init_s32_max, init_s32_min);
7010
7011 if ((s32_min >= 0) == (s32_max >= 0)) {
7012 reg->s32_min_value = s32_min;
7013 reg->s32_max_value = s32_max;
7014 reg->u32_min_value = (u32)s32_min;
7015 reg->u32_max_value = (u32)s32_max;
7016 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
7017 return;
7018 }
7019
7020 out:
7021 set_sext32_default_val(reg, size);
7022 }
7023
bpf_map_is_rdonly(const struct bpf_map * map)7024 static bool bpf_map_is_rdonly(const struct bpf_map *map)
7025 {
7026 /* A map is considered read-only if the following condition are true:
7027 *
7028 * 1) BPF program side cannot change any of the map content. The
7029 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
7030 * and was set at map creation time.
7031 * 2) The map value(s) have been initialized from user space by a
7032 * loader and then "frozen", such that no new map update/delete
7033 * operations from syscall side are possible for the rest of
7034 * the map's lifetime from that point onwards.
7035 * 3) Any parallel/pending map update/delete operations from syscall
7036 * side have been completed. Only after that point, it's safe to
7037 * assume that map value(s) are immutable.
7038 */
7039 return (map->map_flags & BPF_F_RDONLY_PROG) &&
7040 READ_ONCE(map->frozen) &&
7041 !bpf_map_write_active(map);
7042 }
7043
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)7044 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
7045 bool is_ldsx)
7046 {
7047 void *ptr;
7048 u64 addr;
7049 int err;
7050
7051 err = map->ops->map_direct_value_addr(map, &addr, off);
7052 if (err)
7053 return err;
7054 ptr = (void *)(long)addr + off;
7055
7056 switch (size) {
7057 case sizeof(u8):
7058 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
7059 break;
7060 case sizeof(u16):
7061 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
7062 break;
7063 case sizeof(u32):
7064 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
7065 break;
7066 case sizeof(u64):
7067 *val = *(u64 *)ptr;
7068 break;
7069 default:
7070 return -EINVAL;
7071 }
7072 return 0;
7073 }
7074
7075 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
7076 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
7077 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
7078 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null)
7079
7080 /*
7081 * Allow list few fields as RCU trusted or full trusted.
7082 * This logic doesn't allow mix tagging and will be removed once GCC supports
7083 * btf_type_tag.
7084 */
7085
7086 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)7087 BTF_TYPE_SAFE_RCU(struct task_struct) {
7088 const cpumask_t *cpus_ptr;
7089 struct css_set __rcu *cgroups;
7090 struct task_struct __rcu *real_parent;
7091 struct task_struct *group_leader;
7092 };
7093
BTF_TYPE_SAFE_RCU(struct cgroup)7094 BTF_TYPE_SAFE_RCU(struct cgroup) {
7095 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
7096 struct kernfs_node *kn;
7097 };
7098
BTF_TYPE_SAFE_RCU(struct css_set)7099 BTF_TYPE_SAFE_RCU(struct css_set) {
7100 struct cgroup *dfl_cgrp;
7101 };
7102
BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)7103 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) {
7104 struct cgroup *cgroup;
7105 };
7106
7107 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)7108 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
7109 struct file __rcu *exe_file;
7110 #ifdef CONFIG_MEMCG
7111 struct task_struct __rcu *owner;
7112 #endif
7113 };
7114
7115 /* skb->sk, req->sk are not RCU protected, but we mark them as such
7116 * because bpf prog accessible sockets are SOCK_RCU_FREE.
7117 */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)7118 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
7119 struct sock *sk;
7120 };
7121
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)7122 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
7123 struct sock *sk;
7124 };
7125
7126 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)7127 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
7128 struct seq_file *seq;
7129 };
7130
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)7131 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
7132 struct bpf_iter_meta *meta;
7133 struct task_struct *task;
7134 };
7135
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)7136 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
7137 struct file *file;
7138 };
7139
BTF_TYPE_SAFE_TRUSTED(struct file)7140 BTF_TYPE_SAFE_TRUSTED(struct file) {
7141 struct inode *f_inode;
7142 };
7143
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)7144 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {
7145 struct inode *d_inode;
7146 };
7147
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)7148 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
7149 struct sock *sk;
7150 };
7151
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)7152 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
7153 struct mm_struct *vm_mm;
7154 struct file *vm_file;
7155 };
7156
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7157 static bool type_is_rcu(struct bpf_verifier_env *env,
7158 struct bpf_reg_state *reg,
7159 const char *field_name, u32 btf_id)
7160 {
7161 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
7162 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
7163 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
7164 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state));
7165
7166 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
7167 }
7168
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7169 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
7170 struct bpf_reg_state *reg,
7171 const char *field_name, u32 btf_id)
7172 {
7173 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
7174 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
7175 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
7176
7177 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
7178 }
7179
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7180 static bool type_is_trusted(struct bpf_verifier_env *env,
7181 struct bpf_reg_state *reg,
7182 const char *field_name, u32 btf_id)
7183 {
7184 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
7185 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
7186 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
7187 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
7188
7189 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
7190 }
7191
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)7192 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
7193 struct bpf_reg_state *reg,
7194 const char *field_name, u32 btf_id)
7195 {
7196 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
7197 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
7198 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
7199
7200 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
7201 "__safe_trusted_or_null");
7202 }
7203
check_ptr_to_btf_access(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int regno,int off,int size,enum bpf_access_type atype,int value_regno)7204 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
7205 struct bpf_reg_state *regs,
7206 int regno, int off, int size,
7207 enum bpf_access_type atype,
7208 int value_regno)
7209 {
7210 struct bpf_reg_state *reg = regs + regno;
7211 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
7212 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
7213 const char *field_name = NULL;
7214 enum bpf_type_flag flag = 0;
7215 u32 btf_id = 0;
7216 int ret;
7217
7218 if (!env->allow_ptr_leaks) {
7219 verbose(env,
7220 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7221 tname);
7222 return -EPERM;
7223 }
7224 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
7225 verbose(env,
7226 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
7227 tname);
7228 return -EINVAL;
7229 }
7230 if (off < 0) {
7231 verbose(env,
7232 "R%d is ptr_%s invalid negative access: off=%d\n",
7233 regno, tname, off);
7234 return -EACCES;
7235 }
7236 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
7237 char tn_buf[48];
7238
7239 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7240 verbose(env,
7241 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
7242 regno, tname, off, tn_buf);
7243 return -EACCES;
7244 }
7245
7246 if (reg->type & MEM_USER) {
7247 verbose(env,
7248 "R%d is ptr_%s access user memory: off=%d\n",
7249 regno, tname, off);
7250 return -EACCES;
7251 }
7252
7253 if (reg->type & MEM_PERCPU) {
7254 verbose(env,
7255 "R%d is ptr_%s access percpu memory: off=%d\n",
7256 regno, tname, off);
7257 return -EACCES;
7258 }
7259
7260 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
7261 if (!btf_is_kernel(reg->btf)) {
7262 verifier_bug(env, "reg->btf must be kernel btf");
7263 return -EFAULT;
7264 }
7265 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
7266 } else {
7267 /* Writes are permitted with default btf_struct_access for
7268 * program allocated objects (which always have ref_obj_id > 0),
7269 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
7270 */
7271 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
7272 verbose(env, "only read is supported\n");
7273 return -EACCES;
7274 }
7275
7276 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
7277 !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
7278 verifier_bug(env, "ref_obj_id for allocated object must be non-zero");
7279 return -EFAULT;
7280 }
7281
7282 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
7283 }
7284
7285 if (ret < 0)
7286 return ret;
7287
7288 if (ret != PTR_TO_BTF_ID) {
7289 /* just mark; */
7290
7291 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
7292 /* If this is an untrusted pointer, all pointers formed by walking it
7293 * also inherit the untrusted flag.
7294 */
7295 flag = PTR_UNTRUSTED;
7296
7297 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
7298 /* By default any pointer obtained from walking a trusted pointer is no
7299 * longer trusted, unless the field being accessed has explicitly been
7300 * marked as inheriting its parent's state of trust (either full or RCU).
7301 * For example:
7302 * 'cgroups' pointer is untrusted if task->cgroups dereference
7303 * happened in a sleepable program outside of bpf_rcu_read_lock()
7304 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
7305 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
7306 *
7307 * A regular RCU-protected pointer with __rcu tag can also be deemed
7308 * trusted if we are in an RCU CS. Such pointer can be NULL.
7309 */
7310 if (type_is_trusted(env, reg, field_name, btf_id)) {
7311 flag |= PTR_TRUSTED;
7312 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
7313 flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
7314 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
7315 if (type_is_rcu(env, reg, field_name, btf_id)) {
7316 /* ignore __rcu tag and mark it MEM_RCU */
7317 flag |= MEM_RCU;
7318 } else if (flag & MEM_RCU ||
7319 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
7320 /* __rcu tagged pointers can be NULL */
7321 flag |= MEM_RCU | PTR_MAYBE_NULL;
7322
7323 /* We always trust them */
7324 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
7325 flag & PTR_UNTRUSTED)
7326 flag &= ~PTR_UNTRUSTED;
7327 } else if (flag & (MEM_PERCPU | MEM_USER)) {
7328 /* keep as-is */
7329 } else {
7330 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
7331 clear_trusted_flags(&flag);
7332 }
7333 } else {
7334 /*
7335 * If not in RCU CS or MEM_RCU pointer can be NULL then
7336 * aggressively mark as untrusted otherwise such
7337 * pointers will be plain PTR_TO_BTF_ID without flags
7338 * and will be allowed to be passed into helpers for
7339 * compat reasons.
7340 */
7341 flag = PTR_UNTRUSTED;
7342 }
7343 } else {
7344 /* Old compat. Deprecated */
7345 clear_trusted_flags(&flag);
7346 }
7347
7348 if (atype == BPF_READ && value_regno >= 0) {
7349 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
7350 if (ret < 0)
7351 return ret;
7352 }
7353
7354 return 0;
7355 }
7356
check_ptr_to_map_access(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int regno,int off,int size,enum bpf_access_type atype,int value_regno)7357 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
7358 struct bpf_reg_state *regs,
7359 int regno, int off, int size,
7360 enum bpf_access_type atype,
7361 int value_regno)
7362 {
7363 struct bpf_reg_state *reg = regs + regno;
7364 struct bpf_map *map = reg->map_ptr;
7365 struct bpf_reg_state map_reg;
7366 enum bpf_type_flag flag = 0;
7367 const struct btf_type *t;
7368 const char *tname;
7369 u32 btf_id;
7370 int ret;
7371
7372 if (!btf_vmlinux) {
7373 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
7374 return -ENOTSUPP;
7375 }
7376
7377 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
7378 verbose(env, "map_ptr access not supported for map type %d\n",
7379 map->map_type);
7380 return -ENOTSUPP;
7381 }
7382
7383 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
7384 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
7385
7386 if (!env->allow_ptr_leaks) {
7387 verbose(env,
7388 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
7389 tname);
7390 return -EPERM;
7391 }
7392
7393 if (off < 0) {
7394 verbose(env, "R%d is %s invalid negative access: off=%d\n",
7395 regno, tname, off);
7396 return -EACCES;
7397 }
7398
7399 if (atype != BPF_READ) {
7400 verbose(env, "only read from %s is supported\n", tname);
7401 return -EACCES;
7402 }
7403
7404 /* Simulate access to a PTR_TO_BTF_ID */
7405 memset(&map_reg, 0, sizeof(map_reg));
7406 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID,
7407 btf_vmlinux, *map->ops->map_btf_id, 0);
7408 if (ret < 0)
7409 return ret;
7410 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
7411 if (ret < 0)
7412 return ret;
7413
7414 if (value_regno >= 0) {
7415 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
7416 if (ret < 0)
7417 return ret;
7418 }
7419
7420 return 0;
7421 }
7422
7423 /* Check that the stack access at the given offset is within bounds. The
7424 * maximum valid offset is -1.
7425 *
7426 * The minimum valid offset is -MAX_BPF_STACK for writes, and
7427 * -state->allocated_stack for reads.
7428 */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)7429 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
7430 s64 off,
7431 struct bpf_func_state *state,
7432 enum bpf_access_type t)
7433 {
7434 int min_valid_off;
7435
7436 if (t == BPF_WRITE || env->allow_uninit_stack)
7437 min_valid_off = -MAX_BPF_STACK;
7438 else
7439 min_valid_off = -state->allocated_stack;
7440
7441 if (off < min_valid_off || off > -1)
7442 return -EACCES;
7443 return 0;
7444 }
7445
7446 /* Check that the stack access at 'regno + off' falls within the maximum stack
7447 * bounds.
7448 *
7449 * 'off' includes `regno->offset`, but not its dynamic part (if any).
7450 */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_type type)7451 static int check_stack_access_within_bounds(
7452 struct bpf_verifier_env *env,
7453 int regno, int off, int access_size,
7454 enum bpf_access_type type)
7455 {
7456 struct bpf_reg_state *regs = cur_regs(env);
7457 struct bpf_reg_state *reg = regs + regno;
7458 struct bpf_func_state *state = func(env, reg);
7459 s64 min_off, max_off;
7460 int err;
7461 char *err_extra;
7462
7463 if (type == BPF_READ)
7464 err_extra = " read from";
7465 else
7466 err_extra = " write to";
7467
7468 if (tnum_is_const(reg->var_off)) {
7469 min_off = (s64)reg->var_off.value + off;
7470 max_off = min_off + access_size;
7471 } else {
7472 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
7473 reg->smin_value <= -BPF_MAX_VAR_OFF) {
7474 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
7475 err_extra, regno);
7476 return -EACCES;
7477 }
7478 min_off = reg->smin_value + off;
7479 max_off = reg->smax_value + off + access_size;
7480 }
7481
7482 err = check_stack_slot_within_bounds(env, min_off, state, type);
7483 if (!err && max_off > 0)
7484 err = -EINVAL; /* out of stack access into non-negative offsets */
7485 if (!err && access_size < 0)
7486 /* access_size should not be negative (or overflow an int); others checks
7487 * along the way should have prevented such an access.
7488 */
7489 err = -EFAULT; /* invalid negative access size; integer overflow? */
7490
7491 if (err) {
7492 if (tnum_is_const(reg->var_off)) {
7493 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
7494 err_extra, regno, off, access_size);
7495 } else {
7496 char tn_buf[48];
7497
7498 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7499 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n",
7500 err_extra, regno, tn_buf, off, access_size);
7501 }
7502 return err;
7503 }
7504
7505 /* Note that there is no stack access with offset zero, so the needed stack
7506 * size is -min_off, not -min_off+1.
7507 */
7508 return grow_stack_state(env, state, -min_off /* size */);
7509 }
7510
get_func_retval_range(struct bpf_prog * prog,struct bpf_retval_range * range)7511 static bool get_func_retval_range(struct bpf_prog *prog,
7512 struct bpf_retval_range *range)
7513 {
7514 if (prog->type == BPF_PROG_TYPE_LSM &&
7515 prog->expected_attach_type == BPF_LSM_MAC &&
7516 !bpf_lsm_get_retval_range(prog, range)) {
7517 return true;
7518 }
7519 return false;
7520 }
7521
7522 /* check whether memory at (regno + off) is accessible for t = (read | write)
7523 * if t==write, value_regno is a register which value is stored into memory
7524 * if t==read, value_regno is a register which will receive the value from memory
7525 * if t==write && value_regno==-1, some unknown value is stored into memory
7526 * if t==read && value_regno==-1, don't care what we read from memory
7527 */
check_mem_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int bpf_size,enum bpf_access_type t,int value_regno,bool strict_alignment_once,bool is_ldsx)7528 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
7529 int off, int bpf_size, enum bpf_access_type t,
7530 int value_regno, bool strict_alignment_once, bool is_ldsx)
7531 {
7532 struct bpf_reg_state *regs = cur_regs(env);
7533 struct bpf_reg_state *reg = regs + regno;
7534 int size, err = 0;
7535
7536 size = bpf_size_to_bytes(bpf_size);
7537 if (size < 0)
7538 return size;
7539
7540 /* alignment checks will add in reg->off themselves */
7541 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
7542 if (err)
7543 return err;
7544
7545 /* for access checks, reg->off is just part of off */
7546 off += reg->off;
7547
7548 if (reg->type == PTR_TO_MAP_KEY) {
7549 if (t == BPF_WRITE) {
7550 verbose(env, "write to change key R%d not allowed\n", regno);
7551 return -EACCES;
7552 }
7553
7554 err = check_mem_region_access(env, regno, off, size,
7555 reg->map_ptr->key_size, false);
7556 if (err)
7557 return err;
7558 if (value_regno >= 0)
7559 mark_reg_unknown(env, regs, value_regno);
7560 } else if (reg->type == PTR_TO_MAP_VALUE) {
7561 struct btf_field *kptr_field = NULL;
7562
7563 if (t == BPF_WRITE && value_regno >= 0 &&
7564 is_pointer_value(env, value_regno)) {
7565 verbose(env, "R%d leaks addr into map\n", value_regno);
7566 return -EACCES;
7567 }
7568 err = check_map_access_type(env, regno, off, size, t);
7569 if (err)
7570 return err;
7571 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
7572 if (err)
7573 return err;
7574 if (tnum_is_const(reg->var_off))
7575 kptr_field = btf_record_find(reg->map_ptr->record,
7576 off + reg->var_off.value, BPF_KPTR | BPF_UPTR);
7577 if (kptr_field) {
7578 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
7579 } else if (t == BPF_READ && value_regno >= 0) {
7580 struct bpf_map *map = reg->map_ptr;
7581
7582 /*
7583 * If map is read-only, track its contents as scalars,
7584 * unless it is an insn array (see the special case below)
7585 */
7586 if (tnum_is_const(reg->var_off) &&
7587 bpf_map_is_rdonly(map) &&
7588 map->ops->map_direct_value_addr &&
7589 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) {
7590 int map_off = off + reg->var_off.value;
7591 u64 val = 0;
7592
7593 err = bpf_map_direct_read(map, map_off, size,
7594 &val, is_ldsx);
7595 if (err)
7596 return err;
7597
7598 regs[value_regno].type = SCALAR_VALUE;
7599 __mark_reg_known(®s[value_regno], val);
7600 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
7601 if (bpf_size != BPF_DW) {
7602 verbose(env, "Invalid read of %d bytes from insn_array\n",
7603 size);
7604 return -EACCES;
7605 }
7606 copy_register_state(®s[value_regno], reg);
7607 regs[value_regno].type = PTR_TO_INSN;
7608 } else {
7609 mark_reg_unknown(env, regs, value_regno);
7610 }
7611 }
7612 } else if (base_type(reg->type) == PTR_TO_MEM) {
7613 bool rdonly_mem = type_is_rdonly_mem(reg->type);
7614 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED);
7615
7616 if (type_may_be_null(reg->type)) {
7617 verbose(env, "R%d invalid mem access '%s'\n", regno,
7618 reg_type_str(env, reg->type));
7619 return -EACCES;
7620 }
7621
7622 if (t == BPF_WRITE && rdonly_mem) {
7623 verbose(env, "R%d cannot write into %s\n",
7624 regno, reg_type_str(env, reg->type));
7625 return -EACCES;
7626 }
7627
7628 if (t == BPF_WRITE && value_regno >= 0 &&
7629 is_pointer_value(env, value_regno)) {
7630 verbose(env, "R%d leaks addr into mem\n", value_regno);
7631 return -EACCES;
7632 }
7633
7634 /*
7635 * Accesses to untrusted PTR_TO_MEM are done through probe
7636 * instructions, hence no need to check bounds in that case.
7637 */
7638 if (!rdonly_untrusted)
7639 err = check_mem_region_access(env, regno, off, size,
7640 reg->mem_size, false);
7641 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
7642 mark_reg_unknown(env, regs, value_regno);
7643 } else if (reg->type == PTR_TO_CTX) {
7644 struct bpf_retval_range range;
7645 struct bpf_insn_access_aux info = {
7646 .reg_type = SCALAR_VALUE,
7647 .is_ldsx = is_ldsx,
7648 .log = &env->log,
7649 };
7650
7651 if (t == BPF_WRITE && value_regno >= 0 &&
7652 is_pointer_value(env, value_regno)) {
7653 verbose(env, "R%d leaks addr into ctx\n", value_regno);
7654 return -EACCES;
7655 }
7656
7657 err = check_ptr_off_reg(env, reg, regno);
7658 if (err < 0)
7659 return err;
7660
7661 err = check_ctx_access(env, insn_idx, off, size, t, &info);
7662 if (err)
7663 verbose_linfo(env, insn_idx, "; ");
7664 if (!err && t == BPF_READ && value_regno >= 0) {
7665 /* ctx access returns either a scalar, or a
7666 * PTR_TO_PACKET[_META,_END]. In the latter
7667 * case, we know the offset is zero.
7668 */
7669 if (info.reg_type == SCALAR_VALUE) {
7670 if (info.is_retval && get_func_retval_range(env->prog, &range)) {
7671 err = __mark_reg_s32_range(env, regs, value_regno,
7672 range.minval, range.maxval);
7673 if (err)
7674 return err;
7675 } else {
7676 mark_reg_unknown(env, regs, value_regno);
7677 }
7678 } else {
7679 mark_reg_known_zero(env, regs,
7680 value_regno);
7681 if (type_may_be_null(info.reg_type))
7682 regs[value_regno].id = ++env->id_gen;
7683 /* A load of ctx field could have different
7684 * actual load size with the one encoded in the
7685 * insn. When the dst is PTR, it is for sure not
7686 * a sub-register.
7687 */
7688 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
7689 if (base_type(info.reg_type) == PTR_TO_BTF_ID) {
7690 regs[value_regno].btf = info.btf;
7691 regs[value_regno].btf_id = info.btf_id;
7692 regs[value_regno].ref_obj_id = info.ref_obj_id;
7693 }
7694 }
7695 regs[value_regno].type = info.reg_type;
7696 }
7697
7698 } else if (reg->type == PTR_TO_STACK) {
7699 /* Basic bounds checks. */
7700 err = check_stack_access_within_bounds(env, regno, off, size, t);
7701 if (err)
7702 return err;
7703
7704 if (t == BPF_READ)
7705 err = check_stack_read(env, regno, off, size,
7706 value_regno);
7707 else
7708 err = check_stack_write(env, regno, off, size,
7709 value_regno, insn_idx);
7710 } else if (reg_is_pkt_pointer(reg)) {
7711 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
7712 verbose(env, "cannot write into packet\n");
7713 return -EACCES;
7714 }
7715 if (t == BPF_WRITE && value_regno >= 0 &&
7716 is_pointer_value(env, value_regno)) {
7717 verbose(env, "R%d leaks addr into packet\n",
7718 value_regno);
7719 return -EACCES;
7720 }
7721 err = check_packet_access(env, regno, off, size, false);
7722 if (!err && t == BPF_READ && value_regno >= 0)
7723 mark_reg_unknown(env, regs, value_regno);
7724 } else if (reg->type == PTR_TO_FLOW_KEYS) {
7725 if (t == BPF_WRITE && value_regno >= 0 &&
7726 is_pointer_value(env, value_regno)) {
7727 verbose(env, "R%d leaks addr into flow keys\n",
7728 value_regno);
7729 return -EACCES;
7730 }
7731
7732 err = check_flow_keys_access(env, off, size);
7733 if (!err && t == BPF_READ && value_regno >= 0)
7734 mark_reg_unknown(env, regs, value_regno);
7735 } else if (type_is_sk_pointer(reg->type)) {
7736 if (t == BPF_WRITE) {
7737 verbose(env, "R%d cannot write into %s\n",
7738 regno, reg_type_str(env, reg->type));
7739 return -EACCES;
7740 }
7741 err = check_sock_access(env, insn_idx, regno, off, size, t);
7742 if (!err && value_regno >= 0)
7743 mark_reg_unknown(env, regs, value_regno);
7744 } else if (reg->type == PTR_TO_TP_BUFFER) {
7745 err = check_tp_buffer_access(env, reg, regno, off, size);
7746 if (!err && t == BPF_READ && value_regno >= 0)
7747 mark_reg_unknown(env, regs, value_regno);
7748 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
7749 !type_may_be_null(reg->type)) {
7750 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
7751 value_regno);
7752 } else if (reg->type == CONST_PTR_TO_MAP) {
7753 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7754 value_regno);
7755 } else if (base_type(reg->type) == PTR_TO_BUF) {
7756 bool rdonly_mem = type_is_rdonly_mem(reg->type);
7757 u32 *max_access;
7758
7759 if (rdonly_mem) {
7760 if (t == BPF_WRITE) {
7761 verbose(env, "R%d cannot write into %s\n",
7762 regno, reg_type_str(env, reg->type));
7763 return -EACCES;
7764 }
7765 max_access = &env->prog->aux->max_rdonly_access;
7766 } else {
7767 max_access = &env->prog->aux->max_rdwr_access;
7768 }
7769
7770 err = check_buffer_access(env, reg, regno, off, size, false,
7771 max_access);
7772
7773 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7774 mark_reg_unknown(env, regs, value_regno);
7775 } else if (reg->type == PTR_TO_ARENA) {
7776 if (t == BPF_READ && value_regno >= 0)
7777 mark_reg_unknown(env, regs, value_regno);
7778 } else {
7779 verbose(env, "R%d invalid mem access '%s'\n", regno,
7780 reg_type_str(env, reg->type));
7781 return -EACCES;
7782 }
7783
7784 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7785 regs[value_regno].type == SCALAR_VALUE) {
7786 if (!is_ldsx)
7787 /* b/h/w load zero-extends, mark upper bits as known 0 */
7788 coerce_reg_to_size(®s[value_regno], size);
7789 else
7790 coerce_reg_to_size_sx(®s[value_regno], size);
7791 }
7792 return err;
7793 }
7794
7795 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
7796 bool allow_trust_mismatch);
7797
check_load_mem(struct bpf_verifier_env * env,struct bpf_insn * insn,bool strict_alignment_once,bool is_ldsx,bool allow_trust_mismatch,const char * ctx)7798 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
7799 bool strict_alignment_once, bool is_ldsx,
7800 bool allow_trust_mismatch, const char *ctx)
7801 {
7802 struct bpf_reg_state *regs = cur_regs(env);
7803 enum bpf_reg_type src_reg_type;
7804 int err;
7805
7806 /* check src operand */
7807 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7808 if (err)
7809 return err;
7810
7811 /* check dst operand */
7812 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7813 if (err)
7814 return err;
7815
7816 src_reg_type = regs[insn->src_reg].type;
7817
7818 /* Check if (src_reg + off) is readable. The state of dst_reg will be
7819 * updated by this call.
7820 */
7821 err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off,
7822 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg,
7823 strict_alignment_once, is_ldsx);
7824 err = err ?: save_aux_ptr_type(env, src_reg_type,
7825 allow_trust_mismatch);
7826 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx);
7827
7828 return err;
7829 }
7830
check_store_reg(struct bpf_verifier_env * env,struct bpf_insn * insn,bool strict_alignment_once)7831 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
7832 bool strict_alignment_once)
7833 {
7834 struct bpf_reg_state *regs = cur_regs(env);
7835 enum bpf_reg_type dst_reg_type;
7836 int err;
7837
7838 /* check src1 operand */
7839 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7840 if (err)
7841 return err;
7842
7843 /* check src2 operand */
7844 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7845 if (err)
7846 return err;
7847
7848 dst_reg_type = regs[insn->dst_reg].type;
7849
7850 /* Check if (dst_reg + off) is writeable. */
7851 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7852 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg,
7853 strict_alignment_once, false);
7854 err = err ?: save_aux_ptr_type(env, dst_reg_type, false);
7855
7856 return err;
7857 }
7858
check_atomic_rmw(struct bpf_verifier_env * env,struct bpf_insn * insn)7859 static int check_atomic_rmw(struct bpf_verifier_env *env,
7860 struct bpf_insn *insn)
7861 {
7862 int load_reg;
7863 int err;
7864
7865 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7866 verbose(env, "invalid atomic operand size\n");
7867 return -EINVAL;
7868 }
7869
7870 /* check src1 operand */
7871 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7872 if (err)
7873 return err;
7874
7875 /* check src2 operand */
7876 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7877 if (err)
7878 return err;
7879
7880 if (insn->imm == BPF_CMPXCHG) {
7881 /* Check comparison of R0 with memory location */
7882 const u32 aux_reg = BPF_REG_0;
7883
7884 err = check_reg_arg(env, aux_reg, SRC_OP);
7885 if (err)
7886 return err;
7887
7888 if (is_pointer_value(env, aux_reg)) {
7889 verbose(env, "R%d leaks addr into mem\n", aux_reg);
7890 return -EACCES;
7891 }
7892 }
7893
7894 if (is_pointer_value(env, insn->src_reg)) {
7895 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7896 return -EACCES;
7897 }
7898
7899 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7900 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7901 insn->dst_reg,
7902 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7903 return -EACCES;
7904 }
7905
7906 if (insn->imm & BPF_FETCH) {
7907 if (insn->imm == BPF_CMPXCHG)
7908 load_reg = BPF_REG_0;
7909 else
7910 load_reg = insn->src_reg;
7911
7912 /* check and record load of old value */
7913 err = check_reg_arg(env, load_reg, DST_OP);
7914 if (err)
7915 return err;
7916 } else {
7917 /* This instruction accesses a memory location but doesn't
7918 * actually load it into a register.
7919 */
7920 load_reg = -1;
7921 }
7922
7923 /* Check whether we can read the memory, with second call for fetch
7924 * case to simulate the register fill.
7925 */
7926 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7927 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7928 if (!err && load_reg >= 0)
7929 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7930 insn->off, BPF_SIZE(insn->code),
7931 BPF_READ, load_reg, true, false);
7932 if (err)
7933 return err;
7934
7935 if (is_arena_reg(env, insn->dst_reg)) {
7936 err = save_aux_ptr_type(env, PTR_TO_ARENA, false);
7937 if (err)
7938 return err;
7939 }
7940 /* Check whether we can write into the same memory. */
7941 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off,
7942 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7943 if (err)
7944 return err;
7945 return 0;
7946 }
7947
check_atomic_load(struct bpf_verifier_env * env,struct bpf_insn * insn)7948 static int check_atomic_load(struct bpf_verifier_env *env,
7949 struct bpf_insn *insn)
7950 {
7951 int err;
7952
7953 err = check_load_mem(env, insn, true, false, false, "atomic_load");
7954 if (err)
7955 return err;
7956
7957 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) {
7958 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n",
7959 insn->src_reg,
7960 reg_type_str(env, reg_state(env, insn->src_reg)->type));
7961 return -EACCES;
7962 }
7963
7964 return 0;
7965 }
7966
check_atomic_store(struct bpf_verifier_env * env,struct bpf_insn * insn)7967 static int check_atomic_store(struct bpf_verifier_env *env,
7968 struct bpf_insn *insn)
7969 {
7970 int err;
7971
7972 err = check_store_reg(env, insn, true);
7973 if (err)
7974 return err;
7975
7976 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) {
7977 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7978 insn->dst_reg,
7979 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7980 return -EACCES;
7981 }
7982
7983 return 0;
7984 }
7985
check_atomic(struct bpf_verifier_env * env,struct bpf_insn * insn)7986 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn)
7987 {
7988 switch (insn->imm) {
7989 case BPF_ADD:
7990 case BPF_ADD | BPF_FETCH:
7991 case BPF_AND:
7992 case BPF_AND | BPF_FETCH:
7993 case BPF_OR:
7994 case BPF_OR | BPF_FETCH:
7995 case BPF_XOR:
7996 case BPF_XOR | BPF_FETCH:
7997 case BPF_XCHG:
7998 case BPF_CMPXCHG:
7999 return check_atomic_rmw(env, insn);
8000 case BPF_LOAD_ACQ:
8001 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8002 verbose(env,
8003 "64-bit load-acquires are only supported on 64-bit arches\n");
8004 return -EOPNOTSUPP;
8005 }
8006 return check_atomic_load(env, insn);
8007 case BPF_STORE_REL:
8008 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) {
8009 verbose(env,
8010 "64-bit store-releases are only supported on 64-bit arches\n");
8011 return -EOPNOTSUPP;
8012 }
8013 return check_atomic_store(env, insn);
8014 default:
8015 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n",
8016 insn->imm);
8017 return -EINVAL;
8018 }
8019 }
8020
8021 /* When register 'regno' is used to read the stack (either directly or through
8022 * a helper function) make sure that it's within stack boundary and, depending
8023 * on the access type and privileges, that all elements of the stack are
8024 * initialized.
8025 *
8026 * 'off' includes 'regno->off', but not its dynamic part (if any).
8027 *
8028 * All registers that have been spilled on the stack in the slots within the
8029 * read offsets are marked as read.
8030 */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum bpf_access_type type,struct bpf_call_arg_meta * meta)8031 static int check_stack_range_initialized(
8032 struct bpf_verifier_env *env, int regno, int off,
8033 int access_size, bool zero_size_allowed,
8034 enum bpf_access_type type, struct bpf_call_arg_meta *meta)
8035 {
8036 struct bpf_reg_state *reg = reg_state(env, regno);
8037 struct bpf_func_state *state = func(env, reg);
8038 int err, min_off, max_off, i, j, slot, spi;
8039 /* Some accesses can write anything into the stack, others are
8040 * read-only.
8041 */
8042 bool clobber = false;
8043
8044 if (access_size == 0 && !zero_size_allowed) {
8045 verbose(env, "invalid zero-sized read\n");
8046 return -EACCES;
8047 }
8048
8049 if (type == BPF_WRITE)
8050 clobber = true;
8051
8052 err = check_stack_access_within_bounds(env, regno, off, access_size, type);
8053 if (err)
8054 return err;
8055
8056
8057 if (tnum_is_const(reg->var_off)) {
8058 min_off = max_off = reg->var_off.value + off;
8059 } else {
8060 /* Variable offset is prohibited for unprivileged mode for
8061 * simplicity since it requires corresponding support in
8062 * Spectre masking for stack ALU.
8063 * See also retrieve_ptr_limit().
8064 */
8065 if (!env->bypass_spec_v1) {
8066 char tn_buf[48];
8067
8068 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8069 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
8070 regno, tn_buf);
8071 return -EACCES;
8072 }
8073 /* Only initialized buffer on stack is allowed to be accessed
8074 * with variable offset. With uninitialized buffer it's hard to
8075 * guarantee that whole memory is marked as initialized on
8076 * helper return since specific bounds are unknown what may
8077 * cause uninitialized stack leaking.
8078 */
8079 if (meta && meta->raw_mode)
8080 meta = NULL;
8081
8082 min_off = reg->smin_value + off;
8083 max_off = reg->smax_value + off;
8084 }
8085
8086 if (meta && meta->raw_mode) {
8087 /* Ensure we won't be overwriting dynptrs when simulating byte
8088 * by byte access in check_helper_call using meta.access_size.
8089 * This would be a problem if we have a helper in the future
8090 * which takes:
8091 *
8092 * helper(uninit_mem, len, dynptr)
8093 *
8094 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
8095 * may end up writing to dynptr itself when touching memory from
8096 * arg 1. This can be relaxed on a case by case basis for known
8097 * safe cases, but reject due to the possibilitiy of aliasing by
8098 * default.
8099 */
8100 for (i = min_off; i < max_off + access_size; i++) {
8101 int stack_off = -i - 1;
8102
8103 spi = __get_spi(i);
8104 /* raw_mode may write past allocated_stack */
8105 if (state->allocated_stack <= stack_off)
8106 continue;
8107 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
8108 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
8109 return -EACCES;
8110 }
8111 }
8112 meta->access_size = access_size;
8113 meta->regno = regno;
8114 return 0;
8115 }
8116
8117 for (i = min_off; i < max_off + access_size; i++) {
8118 u8 *stype;
8119
8120 slot = -i - 1;
8121 spi = slot / BPF_REG_SIZE;
8122 if (state->allocated_stack <= slot) {
8123 verbose(env, "allocated_stack too small\n");
8124 return -EFAULT;
8125 }
8126
8127 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
8128 if (*stype == STACK_MISC)
8129 goto mark;
8130 if ((*stype == STACK_ZERO) ||
8131 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
8132 if (clobber) {
8133 /* helper can write anything into the stack */
8134 *stype = STACK_MISC;
8135 }
8136 goto mark;
8137 }
8138
8139 if (is_spilled_reg(&state->stack[spi]) &&
8140 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
8141 env->allow_ptr_leaks)) {
8142 if (clobber) {
8143 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
8144 for (j = 0; j < BPF_REG_SIZE; j++)
8145 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
8146 }
8147 goto mark;
8148 }
8149
8150 if (tnum_is_const(reg->var_off)) {
8151 verbose(env, "invalid read from stack R%d off %d+%d size %d\n",
8152 regno, min_off, i - min_off, access_size);
8153 } else {
8154 char tn_buf[48];
8155
8156 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8157 verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n",
8158 regno, tn_buf, i - min_off, access_size);
8159 }
8160 return -EACCES;
8161 mark:
8162 /* reading any byte out of 8-byte 'spill_slot' will cause
8163 * the whole slot to be marked as 'read'
8164 */
8165 err = bpf_mark_stack_read(env, reg->frameno, env->insn_idx, BIT(spi));
8166 if (err)
8167 return err;
8168 /* We do not call bpf_mark_stack_write(), as we can not
8169 * be sure that whether stack slot is written to or not. Hence,
8170 * we must still conservatively propagate reads upwards even if
8171 * helper may write to the entire memory range.
8172 */
8173 }
8174 return 0;
8175 }
8176
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,enum bpf_access_type access_type,bool zero_size_allowed,struct bpf_call_arg_meta * meta)8177 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
8178 int access_size, enum bpf_access_type access_type,
8179 bool zero_size_allowed,
8180 struct bpf_call_arg_meta *meta)
8181 {
8182 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8183 u32 *max_access;
8184
8185 switch (base_type(reg->type)) {
8186 case PTR_TO_PACKET:
8187 case PTR_TO_PACKET_META:
8188 return check_packet_access(env, regno, reg->off, access_size,
8189 zero_size_allowed);
8190 case PTR_TO_MAP_KEY:
8191 if (access_type == BPF_WRITE) {
8192 verbose(env, "R%d cannot write into %s\n", regno,
8193 reg_type_str(env, reg->type));
8194 return -EACCES;
8195 }
8196 return check_mem_region_access(env, regno, reg->off, access_size,
8197 reg->map_ptr->key_size, false);
8198 case PTR_TO_MAP_VALUE:
8199 if (check_map_access_type(env, regno, reg->off, access_size, access_type))
8200 return -EACCES;
8201 return check_map_access(env, regno, reg->off, access_size,
8202 zero_size_allowed, ACCESS_HELPER);
8203 case PTR_TO_MEM:
8204 if (type_is_rdonly_mem(reg->type)) {
8205 if (access_type == BPF_WRITE) {
8206 verbose(env, "R%d cannot write into %s\n", regno,
8207 reg_type_str(env, reg->type));
8208 return -EACCES;
8209 }
8210 }
8211 return check_mem_region_access(env, regno, reg->off,
8212 access_size, reg->mem_size,
8213 zero_size_allowed);
8214 case PTR_TO_BUF:
8215 if (type_is_rdonly_mem(reg->type)) {
8216 if (access_type == BPF_WRITE) {
8217 verbose(env, "R%d cannot write into %s\n", regno,
8218 reg_type_str(env, reg->type));
8219 return -EACCES;
8220 }
8221
8222 max_access = &env->prog->aux->max_rdonly_access;
8223 } else {
8224 max_access = &env->prog->aux->max_rdwr_access;
8225 }
8226 return check_buffer_access(env, reg, regno, reg->off,
8227 access_size, zero_size_allowed,
8228 max_access);
8229 case PTR_TO_STACK:
8230 return check_stack_range_initialized(
8231 env,
8232 regno, reg->off, access_size,
8233 zero_size_allowed, access_type, meta);
8234 case PTR_TO_BTF_ID:
8235 return check_ptr_to_btf_access(env, regs, regno, reg->off,
8236 access_size, BPF_READ, -1);
8237 case PTR_TO_CTX:
8238 /* in case the function doesn't know how to access the context,
8239 * (because we are in a program of type SYSCALL for example), we
8240 * can not statically check its size.
8241 * Dynamically check it now.
8242 */
8243 if (!env->ops->convert_ctx_access) {
8244 int offset = access_size - 1;
8245
8246 /* Allow zero-byte read from PTR_TO_CTX */
8247 if (access_size == 0)
8248 return zero_size_allowed ? 0 : -EACCES;
8249
8250 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
8251 access_type, -1, false, false);
8252 }
8253
8254 fallthrough;
8255 default: /* scalar_value or invalid ptr */
8256 /* Allow zero-byte read from NULL, regardless of pointer type */
8257 if (zero_size_allowed && access_size == 0 &&
8258 register_is_null(reg))
8259 return 0;
8260
8261 verbose(env, "R%d type=%s ", regno,
8262 reg_type_str(env, reg->type));
8263 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
8264 return -EACCES;
8265 }
8266 }
8267
8268 /* verify arguments to helpers or kfuncs consisting of a pointer and an access
8269 * size.
8270 *
8271 * @regno is the register containing the access size. regno-1 is the register
8272 * containing the pointer.
8273 */
check_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,enum bpf_access_type access_type,bool zero_size_allowed,struct bpf_call_arg_meta * meta)8274 static int check_mem_size_reg(struct bpf_verifier_env *env,
8275 struct bpf_reg_state *reg, u32 regno,
8276 enum bpf_access_type access_type,
8277 bool zero_size_allowed,
8278 struct bpf_call_arg_meta *meta)
8279 {
8280 int err;
8281
8282 /* This is used to refine r0 return value bounds for helpers
8283 * that enforce this value as an upper bound on return values.
8284 * See do_refine_retval_range() for helpers that can refine
8285 * the return value. C type of helper is u32 so we pull register
8286 * bound from umax_value however, if negative verifier errors
8287 * out. Only upper bounds can be learned because retval is an
8288 * int type and negative retvals are allowed.
8289 */
8290 meta->msize_max_value = reg->umax_value;
8291
8292 /* The register is SCALAR_VALUE; the access check happens using
8293 * its boundaries. For unprivileged variable accesses, disable
8294 * raw mode so that the program is required to initialize all
8295 * the memory that the helper could just partially fill up.
8296 */
8297 if (!tnum_is_const(reg->var_off))
8298 meta = NULL;
8299
8300 if (reg->smin_value < 0) {
8301 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
8302 regno);
8303 return -EACCES;
8304 }
8305
8306 if (reg->umin_value == 0 && !zero_size_allowed) {
8307 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n",
8308 regno, reg->umin_value, reg->umax_value);
8309 return -EACCES;
8310 }
8311
8312 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
8313 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
8314 regno);
8315 return -EACCES;
8316 }
8317 err = check_helper_mem_access(env, regno - 1, reg->umax_value,
8318 access_type, zero_size_allowed, meta);
8319 if (!err)
8320 err = mark_chain_precision(env, regno);
8321 return err;
8322 }
8323
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)8324 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8325 u32 regno, u32 mem_size)
8326 {
8327 bool may_be_null = type_may_be_null(reg->type);
8328 struct bpf_reg_state saved_reg;
8329 int err;
8330
8331 if (register_is_null(reg))
8332 return 0;
8333
8334 /* Assuming that the register contains a value check if the memory
8335 * access is safe. Temporarily save and restore the register's state as
8336 * the conversion shouldn't be visible to a caller.
8337 */
8338 if (may_be_null) {
8339 saved_reg = *reg;
8340 mark_ptr_not_null_reg(reg);
8341 }
8342
8343 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL);
8344 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL);
8345
8346 if (may_be_null)
8347 *reg = saved_reg;
8348
8349 return err;
8350 }
8351
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)8352 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
8353 u32 regno)
8354 {
8355 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
8356 bool may_be_null = type_may_be_null(mem_reg->type);
8357 struct bpf_reg_state saved_reg;
8358 struct bpf_call_arg_meta meta;
8359 int err;
8360
8361 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
8362
8363 memset(&meta, 0, sizeof(meta));
8364
8365 if (may_be_null) {
8366 saved_reg = *mem_reg;
8367 mark_ptr_not_null_reg(mem_reg);
8368 }
8369
8370 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta);
8371 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta);
8372
8373 if (may_be_null)
8374 *mem_reg = saved_reg;
8375
8376 return err;
8377 }
8378
8379 enum {
8380 PROCESS_SPIN_LOCK = (1 << 0),
8381 PROCESS_RES_LOCK = (1 << 1),
8382 PROCESS_LOCK_IRQ = (1 << 2),
8383 };
8384
8385 /* Implementation details:
8386 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
8387 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
8388 * Two bpf_map_lookups (even with the same key) will have different reg->id.
8389 * Two separate bpf_obj_new will also have different reg->id.
8390 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
8391 * clears reg->id after value_or_null->value transition, since the verifier only
8392 * cares about the range of access to valid map value pointer and doesn't care
8393 * about actual address of the map element.
8394 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
8395 * reg->id > 0 after value_or_null->value transition. By doing so
8396 * two bpf_map_lookups will be considered two different pointers that
8397 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
8398 * returned from bpf_obj_new.
8399 * The verifier allows taking only one bpf_spin_lock at a time to avoid
8400 * dead-locks.
8401 * Since only one bpf_spin_lock is allowed the checks are simpler than
8402 * reg_is_refcounted() logic. The verifier needs to remember only
8403 * one spin_lock instead of array of acquired_refs.
8404 * env->cur_state->active_locks remembers which map value element or allocated
8405 * object got locked and clears it after bpf_spin_unlock.
8406 */
process_spin_lock(struct bpf_verifier_env * env,int regno,int flags)8407 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags)
8408 {
8409 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK;
8410 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin";
8411 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8412 struct bpf_verifier_state *cur = env->cur_state;
8413 bool is_const = tnum_is_const(reg->var_off);
8414 bool is_irq = flags & PROCESS_LOCK_IRQ;
8415 u64 val = reg->var_off.value;
8416 struct bpf_map *map = NULL;
8417 struct btf *btf = NULL;
8418 struct btf_record *rec;
8419 u32 spin_lock_off;
8420 int err;
8421
8422 if (!is_const) {
8423 verbose(env,
8424 "R%d doesn't have constant offset. %s_lock has to be at the constant offset\n",
8425 regno, lock_str);
8426 return -EINVAL;
8427 }
8428 if (reg->type == PTR_TO_MAP_VALUE) {
8429 map = reg->map_ptr;
8430 if (!map->btf) {
8431 verbose(env,
8432 "map '%s' has to have BTF in order to use %s_lock\n",
8433 map->name, lock_str);
8434 return -EINVAL;
8435 }
8436 } else {
8437 btf = reg->btf;
8438 }
8439
8440 rec = reg_btf_record(reg);
8441 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) {
8442 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local",
8443 map ? map->name : "kptr", lock_str);
8444 return -EINVAL;
8445 }
8446 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off;
8447 if (spin_lock_off != val + reg->off) {
8448 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n",
8449 val + reg->off, lock_str, spin_lock_off);
8450 return -EINVAL;
8451 }
8452 if (is_lock) {
8453 void *ptr;
8454 int type;
8455
8456 if (map)
8457 ptr = map;
8458 else
8459 ptr = btf;
8460
8461 if (!is_res_lock && cur->active_locks) {
8462 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) {
8463 verbose(env,
8464 "Locking two bpf_spin_locks are not allowed\n");
8465 return -EINVAL;
8466 }
8467 } else if (is_res_lock && cur->active_locks) {
8468 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) {
8469 verbose(env, "Acquiring the same lock again, AA deadlock detected\n");
8470 return -EINVAL;
8471 }
8472 }
8473
8474 if (is_res_lock && is_irq)
8475 type = REF_TYPE_RES_LOCK_IRQ;
8476 else if (is_res_lock)
8477 type = REF_TYPE_RES_LOCK;
8478 else
8479 type = REF_TYPE_LOCK;
8480 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr);
8481 if (err < 0) {
8482 verbose(env, "Failed to acquire lock state\n");
8483 return err;
8484 }
8485 } else {
8486 void *ptr;
8487 int type;
8488
8489 if (map)
8490 ptr = map;
8491 else
8492 ptr = btf;
8493
8494 if (!cur->active_locks) {
8495 verbose(env, "%s_unlock without taking a lock\n", lock_str);
8496 return -EINVAL;
8497 }
8498
8499 if (is_res_lock && is_irq)
8500 type = REF_TYPE_RES_LOCK_IRQ;
8501 else if (is_res_lock)
8502 type = REF_TYPE_RES_LOCK;
8503 else
8504 type = REF_TYPE_LOCK;
8505 if (!find_lock_state(cur, type, reg->id, ptr)) {
8506 verbose(env, "%s_unlock of different lock\n", lock_str);
8507 return -EINVAL;
8508 }
8509 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) {
8510 verbose(env, "%s_unlock cannot be out of order\n", lock_str);
8511 return -EINVAL;
8512 }
8513 if (release_lock_state(cur, type, reg->id, ptr)) {
8514 verbose(env, "%s_unlock of different lock\n", lock_str);
8515 return -EINVAL;
8516 }
8517
8518 invalidate_non_owning_refs(env);
8519 }
8520 return 0;
8521 }
8522
8523 /* Check if @regno is a pointer to a specific field in a map value */
check_map_field_pointer(struct bpf_verifier_env * env,u32 regno,enum btf_field_type field_type)8524 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno,
8525 enum btf_field_type field_type)
8526 {
8527 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8528 bool is_const = tnum_is_const(reg->var_off);
8529 struct bpf_map *map = reg->map_ptr;
8530 u64 val = reg->var_off.value;
8531 const char *struct_name = btf_field_type_name(field_type);
8532 int field_off = -1;
8533
8534 if (!is_const) {
8535 verbose(env,
8536 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
8537 regno, struct_name);
8538 return -EINVAL;
8539 }
8540 if (!map->btf) {
8541 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name,
8542 struct_name);
8543 return -EINVAL;
8544 }
8545 if (!btf_record_has_field(map->record, field_type)) {
8546 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name);
8547 return -EINVAL;
8548 }
8549 switch (field_type) {
8550 case BPF_TIMER:
8551 field_off = map->record->timer_off;
8552 break;
8553 case BPF_TASK_WORK:
8554 field_off = map->record->task_work_off;
8555 break;
8556 case BPF_WORKQUEUE:
8557 field_off = map->record->wq_off;
8558 break;
8559 default:
8560 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name);
8561 return -EINVAL;
8562 }
8563 if (field_off != val + reg->off) {
8564 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n",
8565 val + reg->off, struct_name, field_off);
8566 return -EINVAL;
8567 }
8568 return 0;
8569 }
8570
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)8571 static int process_timer_func(struct bpf_verifier_env *env, int regno,
8572 struct bpf_call_arg_meta *meta)
8573 {
8574 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8575 struct bpf_map *map = reg->map_ptr;
8576 int err;
8577
8578 err = check_map_field_pointer(env, regno, BPF_TIMER);
8579 if (err)
8580 return err;
8581
8582 if (meta->map_ptr) {
8583 verifier_bug(env, "Two map pointers in a timer helper");
8584 return -EFAULT;
8585 }
8586 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
8587 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n");
8588 return -EOPNOTSUPP;
8589 }
8590 meta->map_uid = reg->map_uid;
8591 meta->map_ptr = map;
8592 return 0;
8593 }
8594
process_wq_func(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)8595 static int process_wq_func(struct bpf_verifier_env *env, int regno,
8596 struct bpf_kfunc_call_arg_meta *meta)
8597 {
8598 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8599 struct bpf_map *map = reg->map_ptr;
8600 int err;
8601
8602 err = check_map_field_pointer(env, regno, BPF_WORKQUEUE);
8603 if (err)
8604 return err;
8605
8606 if (meta->map.ptr) {
8607 verifier_bug(env, "Two map pointers in a bpf_wq helper");
8608 return -EFAULT;
8609 }
8610
8611 meta->map.uid = reg->map_uid;
8612 meta->map.ptr = map;
8613 return 0;
8614 }
8615
process_task_work_func(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)8616 static int process_task_work_func(struct bpf_verifier_env *env, int regno,
8617 struct bpf_kfunc_call_arg_meta *meta)
8618 {
8619 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8620 struct bpf_map *map = reg->map_ptr;
8621 int err;
8622
8623 err = check_map_field_pointer(env, regno, BPF_TASK_WORK);
8624 if (err)
8625 return err;
8626
8627 if (meta->map.ptr) {
8628 verifier_bug(env, "Two map pointers in a bpf_task_work helper");
8629 return -EFAULT;
8630 }
8631 meta->map.uid = reg->map_uid;
8632 meta->map.ptr = map;
8633 return 0;
8634 }
8635
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)8636 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
8637 struct bpf_call_arg_meta *meta)
8638 {
8639 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8640 struct btf_field *kptr_field;
8641 struct bpf_map *map_ptr;
8642 struct btf_record *rec;
8643 u32 kptr_off;
8644
8645 if (type_is_ptr_alloc_obj(reg->type)) {
8646 rec = reg_btf_record(reg);
8647 } else { /* PTR_TO_MAP_VALUE */
8648 map_ptr = reg->map_ptr;
8649 if (!map_ptr->btf) {
8650 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
8651 map_ptr->name);
8652 return -EINVAL;
8653 }
8654 rec = map_ptr->record;
8655 meta->map_ptr = map_ptr;
8656 }
8657
8658 if (!tnum_is_const(reg->var_off)) {
8659 verbose(env,
8660 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
8661 regno);
8662 return -EINVAL;
8663 }
8664
8665 if (!btf_record_has_field(rec, BPF_KPTR)) {
8666 verbose(env, "R%d has no valid kptr\n", regno);
8667 return -EINVAL;
8668 }
8669
8670 kptr_off = reg->off + reg->var_off.value;
8671 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR);
8672 if (!kptr_field) {
8673 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
8674 return -EACCES;
8675 }
8676 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
8677 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
8678 return -EACCES;
8679 }
8680 meta->kptr_field = kptr_field;
8681 return 0;
8682 }
8683
8684 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
8685 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
8686 *
8687 * In both cases we deal with the first 8 bytes, but need to mark the next 8
8688 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
8689 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
8690 *
8691 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
8692 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
8693 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
8694 * mutate the view of the dynptr and also possibly destroy it. In the latter
8695 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
8696 * memory that dynptr points to.
8697 *
8698 * The verifier will keep track both levels of mutation (bpf_dynptr's in
8699 * reg->type and the memory's in reg->dynptr.type), but there is no support for
8700 * readonly dynptr view yet, hence only the first case is tracked and checked.
8701 *
8702 * This is consistent with how C applies the const modifier to a struct object,
8703 * where the pointer itself inside bpf_dynptr becomes const but not what it
8704 * points to.
8705 *
8706 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
8707 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
8708 */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)8709 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
8710 enum bpf_arg_type arg_type, int clone_ref_obj_id)
8711 {
8712 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8713 int err;
8714
8715 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
8716 verbose(env,
8717 "arg#%d expected pointer to stack or const struct bpf_dynptr\n",
8718 regno - 1);
8719 return -EINVAL;
8720 }
8721
8722 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
8723 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
8724 */
8725 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
8726 verifier_bug(env, "misconfigured dynptr helper type flags");
8727 return -EFAULT;
8728 }
8729
8730 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
8731 * constructing a mutable bpf_dynptr object.
8732 *
8733 * Currently, this is only possible with PTR_TO_STACK
8734 * pointing to a region of at least 16 bytes which doesn't
8735 * contain an existing bpf_dynptr.
8736 *
8737 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
8738 * mutated or destroyed. However, the memory it points to
8739 * may be mutated.
8740 *
8741 * None - Points to a initialized dynptr that can be mutated and
8742 * destroyed, including mutation of the memory it points
8743 * to.
8744 */
8745 if (arg_type & MEM_UNINIT) {
8746 int i;
8747
8748 if (!is_dynptr_reg_valid_uninit(env, reg)) {
8749 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
8750 return -EINVAL;
8751 }
8752
8753 /* we write BPF_DW bits (8 bytes) at a time */
8754 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
8755 err = check_mem_access(env, insn_idx, regno,
8756 i, BPF_DW, BPF_WRITE, -1, false, false);
8757 if (err)
8758 return err;
8759 }
8760
8761 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
8762 } else /* MEM_RDONLY and None case from above */ {
8763 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
8764 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
8765 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
8766 return -EINVAL;
8767 }
8768
8769 if (!is_dynptr_reg_valid_init(env, reg)) {
8770 verbose(env,
8771 "Expected an initialized dynptr as arg #%d\n",
8772 regno - 1);
8773 return -EINVAL;
8774 }
8775
8776 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
8777 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
8778 verbose(env,
8779 "Expected a dynptr of type %s as arg #%d\n",
8780 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1);
8781 return -EINVAL;
8782 }
8783
8784 err = mark_dynptr_read(env, reg);
8785 }
8786 return err;
8787 }
8788
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)8789 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
8790 {
8791 struct bpf_func_state *state = func(env, reg);
8792
8793 return state->stack[spi].spilled_ptr.ref_obj_id;
8794 }
8795
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)8796 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8797 {
8798 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
8799 }
8800
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)8801 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8802 {
8803 return meta->kfunc_flags & KF_ITER_NEW;
8804 }
8805
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)8806 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8807 {
8808 return meta->kfunc_flags & KF_ITER_NEXT;
8809 }
8810
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)8811 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
8812 {
8813 return meta->kfunc_flags & KF_ITER_DESTROY;
8814 }
8815
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg_idx,const struct btf_param * arg)8816 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx,
8817 const struct btf_param *arg)
8818 {
8819 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
8820 * kfunc is iter state pointer
8821 */
8822 if (is_iter_kfunc(meta))
8823 return arg_idx == 0;
8824
8825 /* iter passed as an argument to a generic kfunc */
8826 return btf_param_match_suffix(meta->btf, arg, "__iter");
8827 }
8828
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)8829 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
8830 struct bpf_kfunc_call_arg_meta *meta)
8831 {
8832 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8833 const struct btf_type *t;
8834 int spi, err, i, nr_slots, btf_id;
8835
8836 if (reg->type != PTR_TO_STACK) {
8837 verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1);
8838 return -EINVAL;
8839 }
8840
8841 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs()
8842 * ensures struct convention, so we wouldn't need to do any BTF
8843 * validation here. But given iter state can be passed as a parameter
8844 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more
8845 * conservative here.
8846 */
8847 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1);
8848 if (btf_id < 0) {
8849 verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1);
8850 return -EINVAL;
8851 }
8852 t = btf_type_by_id(meta->btf, btf_id);
8853 nr_slots = t->size / BPF_REG_SIZE;
8854
8855 if (is_iter_new_kfunc(meta)) {
8856 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
8857 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
8858 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
8859 iter_type_str(meta->btf, btf_id), regno - 1);
8860 return -EINVAL;
8861 }
8862
8863 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
8864 err = check_mem_access(env, insn_idx, regno,
8865 i, BPF_DW, BPF_WRITE, -1, false, false);
8866 if (err)
8867 return err;
8868 }
8869
8870 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
8871 if (err)
8872 return err;
8873 } else {
8874 /* iter_next() or iter_destroy(), as well as any kfunc
8875 * accepting iter argument, expect initialized iter state
8876 */
8877 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
8878 switch (err) {
8879 case 0:
8880 break;
8881 case -EINVAL:
8882 verbose(env, "expected an initialized iter_%s as arg #%d\n",
8883 iter_type_str(meta->btf, btf_id), regno - 1);
8884 return err;
8885 case -EPROTO:
8886 verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
8887 return err;
8888 default:
8889 return err;
8890 }
8891
8892 spi = iter_get_spi(env, reg, nr_slots);
8893 if (spi < 0)
8894 return spi;
8895
8896 err = mark_iter_read(env, reg, spi, nr_slots);
8897 if (err)
8898 return err;
8899
8900 /* remember meta->iter info for process_iter_next_call() */
8901 meta->iter.spi = spi;
8902 meta->iter.frameno = reg->frameno;
8903 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
8904
8905 if (is_iter_destroy_kfunc(meta)) {
8906 err = unmark_stack_slots_iter(env, reg, nr_slots);
8907 if (err)
8908 return err;
8909 }
8910 }
8911
8912 return 0;
8913 }
8914
8915 /* Look for a previous loop entry at insn_idx: nearest parent state
8916 * stopped at insn_idx with callsites matching those in cur->frame.
8917 */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)8918 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
8919 struct bpf_verifier_state *cur,
8920 int insn_idx)
8921 {
8922 struct bpf_verifier_state_list *sl;
8923 struct bpf_verifier_state *st;
8924 struct list_head *pos, *head;
8925
8926 /* Explored states are pushed in stack order, most recent states come first */
8927 head = explored_state(env, insn_idx);
8928 list_for_each(pos, head) {
8929 sl = container_of(pos, struct bpf_verifier_state_list, node);
8930 /* If st->branches != 0 state is a part of current DFS verification path,
8931 * hence cur & st for a loop.
8932 */
8933 st = &sl->state;
8934 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
8935 st->dfs_depth < cur->dfs_depth)
8936 return st;
8937 }
8938
8939 return NULL;
8940 }
8941
8942 static void reset_idmap_scratch(struct bpf_verifier_env *env);
8943 static bool regs_exact(const struct bpf_reg_state *rold,
8944 const struct bpf_reg_state *rcur,
8945 struct bpf_idmap *idmap);
8946
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)8947 static void maybe_widen_reg(struct bpf_verifier_env *env,
8948 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
8949 struct bpf_idmap *idmap)
8950 {
8951 if (rold->type != SCALAR_VALUE)
8952 return;
8953 if (rold->type != rcur->type)
8954 return;
8955 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
8956 return;
8957 __mark_reg_unknown(env, rcur);
8958 }
8959
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)8960 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
8961 struct bpf_verifier_state *old,
8962 struct bpf_verifier_state *cur)
8963 {
8964 struct bpf_func_state *fold, *fcur;
8965 int i, fr, num_slots;
8966
8967 reset_idmap_scratch(env);
8968 for (fr = old->curframe; fr >= 0; fr--) {
8969 fold = old->frame[fr];
8970 fcur = cur->frame[fr];
8971
8972 for (i = 0; i < MAX_BPF_REG; i++)
8973 maybe_widen_reg(env,
8974 &fold->regs[i],
8975 &fcur->regs[i],
8976 &env->idmap_scratch);
8977
8978 num_slots = min(fold->allocated_stack / BPF_REG_SIZE,
8979 fcur->allocated_stack / BPF_REG_SIZE);
8980 for (i = 0; i < num_slots; i++) {
8981 if (!is_spilled_reg(&fold->stack[i]) ||
8982 !is_spilled_reg(&fcur->stack[i]))
8983 continue;
8984
8985 maybe_widen_reg(env,
8986 &fold->stack[i].spilled_ptr,
8987 &fcur->stack[i].spilled_ptr,
8988 &env->idmap_scratch);
8989 }
8990 }
8991 return 0;
8992 }
8993
get_iter_from_state(struct bpf_verifier_state * cur_st,struct bpf_kfunc_call_arg_meta * meta)8994 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st,
8995 struct bpf_kfunc_call_arg_meta *meta)
8996 {
8997 int iter_frameno = meta->iter.frameno;
8998 int iter_spi = meta->iter.spi;
8999
9000 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
9001 }
9002
9003 /* process_iter_next_call() is called when verifier gets to iterator's next
9004 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
9005 * to it as just "iter_next()" in comments below.
9006 *
9007 * BPF verifier relies on a crucial contract for any iter_next()
9008 * implementation: it should *eventually* return NULL, and once that happens
9009 * it should keep returning NULL. That is, once iterator exhausts elements to
9010 * iterate, it should never reset or spuriously return new elements.
9011 *
9012 * With the assumption of such contract, process_iter_next_call() simulates
9013 * a fork in the verifier state to validate loop logic correctness and safety
9014 * without having to simulate infinite amount of iterations.
9015 *
9016 * In current state, we first assume that iter_next() returned NULL and
9017 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
9018 * conditions we should not form an infinite loop and should eventually reach
9019 * exit.
9020 *
9021 * Besides that, we also fork current state and enqueue it for later
9022 * verification. In a forked state we keep iterator state as ACTIVE
9023 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
9024 * also bump iteration depth to prevent erroneous infinite loop detection
9025 * later on (see iter_active_depths_differ() comment for details). In this
9026 * state we assume that we'll eventually loop back to another iter_next()
9027 * calls (it could be in exactly same location or in some other instruction,
9028 * it doesn't matter, we don't make any unnecessary assumptions about this,
9029 * everything revolves around iterator state in a stack slot, not which
9030 * instruction is calling iter_next()). When that happens, we either will come
9031 * to iter_next() with equivalent state and can conclude that next iteration
9032 * will proceed in exactly the same way as we just verified, so it's safe to
9033 * assume that loop converges. If not, we'll go on another iteration
9034 * simulation with a different input state, until all possible starting states
9035 * are validated or we reach maximum number of instructions limit.
9036 *
9037 * This way, we will either exhaustively discover all possible input states
9038 * that iterator loop can start with and eventually will converge, or we'll
9039 * effectively regress into bounded loop simulation logic and either reach
9040 * maximum number of instructions if loop is not provably convergent, or there
9041 * is some statically known limit on number of iterations (e.g., if there is
9042 * an explicit `if n > 100 then break;` statement somewhere in the loop).
9043 *
9044 * Iteration convergence logic in is_state_visited() relies on exact
9045 * states comparison, which ignores read and precision marks.
9046 * This is necessary because read and precision marks are not finalized
9047 * while in the loop. Exact comparison might preclude convergence for
9048 * simple programs like below:
9049 *
9050 * i = 0;
9051 * while(iter_next(&it))
9052 * i++;
9053 *
9054 * At each iteration step i++ would produce a new distinct state and
9055 * eventually instruction processing limit would be reached.
9056 *
9057 * To avoid such behavior speculatively forget (widen) range for
9058 * imprecise scalar registers, if those registers were not precise at the
9059 * end of the previous iteration and do not match exactly.
9060 *
9061 * This is a conservative heuristic that allows to verify wide range of programs,
9062 * however it precludes verification of programs that conjure an
9063 * imprecise value on the first loop iteration and use it as precise on a second.
9064 * For example, the following safe program would fail to verify:
9065 *
9066 * struct bpf_num_iter it;
9067 * int arr[10];
9068 * int i = 0, a = 0;
9069 * bpf_iter_num_new(&it, 0, 10);
9070 * while (bpf_iter_num_next(&it)) {
9071 * if (a == 0) {
9072 * a = 1;
9073 * i = 7; // Because i changed verifier would forget
9074 * // it's range on second loop entry.
9075 * } else {
9076 * arr[i] = 42; // This would fail to verify.
9077 * }
9078 * }
9079 * bpf_iter_num_destroy(&it);
9080 */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)9081 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
9082 struct bpf_kfunc_call_arg_meta *meta)
9083 {
9084 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
9085 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
9086 struct bpf_reg_state *cur_iter, *queued_iter;
9087
9088 BTF_TYPE_EMIT(struct bpf_iter);
9089
9090 cur_iter = get_iter_from_state(cur_st, meta);
9091
9092 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
9093 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
9094 verifier_bug(env, "unexpected iterator state %d (%s)",
9095 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
9096 return -EFAULT;
9097 }
9098
9099 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
9100 /* Because iter_next() call is a checkpoint is_state_visitied()
9101 * should guarantee parent state with same call sites and insn_idx.
9102 */
9103 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
9104 !same_callsites(cur_st->parent, cur_st)) {
9105 verifier_bug(env, "bad parent state for iter next call");
9106 return -EFAULT;
9107 }
9108 /* Note cur_st->parent in the call below, it is necessary to skip
9109 * checkpoint created for cur_st by is_state_visited()
9110 * right at this instruction.
9111 */
9112 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
9113 /* branch out active iter state */
9114 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
9115 if (IS_ERR(queued_st))
9116 return PTR_ERR(queued_st);
9117
9118 queued_iter = get_iter_from_state(queued_st, meta);
9119 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
9120 queued_iter->iter.depth++;
9121 if (prev_st)
9122 widen_imprecise_scalars(env, prev_st, queued_st);
9123
9124 queued_fr = queued_st->frame[queued_st->curframe];
9125 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
9126 }
9127
9128 /* switch to DRAINED state, but keep the depth unchanged */
9129 /* mark current iter state as drained and assume returned NULL */
9130 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
9131 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]);
9132
9133 return 0;
9134 }
9135
arg_type_is_mem_size(enum bpf_arg_type type)9136 static bool arg_type_is_mem_size(enum bpf_arg_type type)
9137 {
9138 return type == ARG_CONST_SIZE ||
9139 type == ARG_CONST_SIZE_OR_ZERO;
9140 }
9141
arg_type_is_raw_mem(enum bpf_arg_type type)9142 static bool arg_type_is_raw_mem(enum bpf_arg_type type)
9143 {
9144 return base_type(type) == ARG_PTR_TO_MEM &&
9145 type & MEM_UNINIT;
9146 }
9147
arg_type_is_release(enum bpf_arg_type type)9148 static bool arg_type_is_release(enum bpf_arg_type type)
9149 {
9150 return type & OBJ_RELEASE;
9151 }
9152
arg_type_is_dynptr(enum bpf_arg_type type)9153 static bool arg_type_is_dynptr(enum bpf_arg_type type)
9154 {
9155 return base_type(type) == ARG_PTR_TO_DYNPTR;
9156 }
9157
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)9158 static int resolve_map_arg_type(struct bpf_verifier_env *env,
9159 const struct bpf_call_arg_meta *meta,
9160 enum bpf_arg_type *arg_type)
9161 {
9162 if (!meta->map_ptr) {
9163 /* kernel subsystem misconfigured verifier */
9164 verifier_bug(env, "invalid map_ptr to access map->type");
9165 return -EFAULT;
9166 }
9167
9168 switch (meta->map_ptr->map_type) {
9169 case BPF_MAP_TYPE_SOCKMAP:
9170 case BPF_MAP_TYPE_SOCKHASH:
9171 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
9172 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
9173 } else {
9174 verbose(env, "invalid arg_type for sockmap/sockhash\n");
9175 return -EINVAL;
9176 }
9177 break;
9178 case BPF_MAP_TYPE_BLOOM_FILTER:
9179 if (meta->func_id == BPF_FUNC_map_peek_elem)
9180 *arg_type = ARG_PTR_TO_MAP_VALUE;
9181 break;
9182 default:
9183 break;
9184 }
9185 return 0;
9186 }
9187
9188 struct bpf_reg_types {
9189 const enum bpf_reg_type types[10];
9190 u32 *btf_id;
9191 };
9192
9193 static const struct bpf_reg_types sock_types = {
9194 .types = {
9195 PTR_TO_SOCK_COMMON,
9196 PTR_TO_SOCKET,
9197 PTR_TO_TCP_SOCK,
9198 PTR_TO_XDP_SOCK,
9199 },
9200 };
9201
9202 #ifdef CONFIG_NET
9203 static const struct bpf_reg_types btf_id_sock_common_types = {
9204 .types = {
9205 PTR_TO_SOCK_COMMON,
9206 PTR_TO_SOCKET,
9207 PTR_TO_TCP_SOCK,
9208 PTR_TO_XDP_SOCK,
9209 PTR_TO_BTF_ID,
9210 PTR_TO_BTF_ID | PTR_TRUSTED,
9211 },
9212 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
9213 };
9214 #endif
9215
9216 static const struct bpf_reg_types mem_types = {
9217 .types = {
9218 PTR_TO_STACK,
9219 PTR_TO_PACKET,
9220 PTR_TO_PACKET_META,
9221 PTR_TO_MAP_KEY,
9222 PTR_TO_MAP_VALUE,
9223 PTR_TO_MEM,
9224 PTR_TO_MEM | MEM_RINGBUF,
9225 PTR_TO_BUF,
9226 PTR_TO_BTF_ID | PTR_TRUSTED,
9227 },
9228 };
9229
9230 static const struct bpf_reg_types spin_lock_types = {
9231 .types = {
9232 PTR_TO_MAP_VALUE,
9233 PTR_TO_BTF_ID | MEM_ALLOC,
9234 }
9235 };
9236
9237 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
9238 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
9239 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
9240 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
9241 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
9242 static const struct bpf_reg_types btf_ptr_types = {
9243 .types = {
9244 PTR_TO_BTF_ID,
9245 PTR_TO_BTF_ID | PTR_TRUSTED,
9246 PTR_TO_BTF_ID | MEM_RCU,
9247 },
9248 };
9249 static const struct bpf_reg_types percpu_btf_ptr_types = {
9250 .types = {
9251 PTR_TO_BTF_ID | MEM_PERCPU,
9252 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
9253 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
9254 }
9255 };
9256 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
9257 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
9258 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
9259 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
9260 static const struct bpf_reg_types kptr_xchg_dest_types = {
9261 .types = {
9262 PTR_TO_MAP_VALUE,
9263 PTR_TO_BTF_ID | MEM_ALLOC
9264 }
9265 };
9266 static const struct bpf_reg_types dynptr_types = {
9267 .types = {
9268 PTR_TO_STACK,
9269 CONST_PTR_TO_DYNPTR,
9270 }
9271 };
9272
9273 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
9274 [ARG_PTR_TO_MAP_KEY] = &mem_types,
9275 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
9276 [ARG_CONST_SIZE] = &scalar_types,
9277 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
9278 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
9279 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
9280 [ARG_PTR_TO_CTX] = &context_types,
9281 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
9282 #ifdef CONFIG_NET
9283 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
9284 #endif
9285 [ARG_PTR_TO_SOCKET] = &fullsock_types,
9286 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
9287 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
9288 [ARG_PTR_TO_MEM] = &mem_types,
9289 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
9290 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
9291 [ARG_PTR_TO_FUNC] = &func_ptr_types,
9292 [ARG_PTR_TO_STACK] = &stack_ptr_types,
9293 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
9294 [ARG_PTR_TO_TIMER] = &timer_types,
9295 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types,
9296 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
9297 };
9298
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id,struct bpf_call_arg_meta * meta)9299 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
9300 enum bpf_arg_type arg_type,
9301 const u32 *arg_btf_id,
9302 struct bpf_call_arg_meta *meta)
9303 {
9304 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
9305 enum bpf_reg_type expected, type = reg->type;
9306 const struct bpf_reg_types *compatible;
9307 int i, j;
9308
9309 compatible = compatible_reg_types[base_type(arg_type)];
9310 if (!compatible) {
9311 verifier_bug(env, "unsupported arg type %d", arg_type);
9312 return -EFAULT;
9313 }
9314
9315 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
9316 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
9317 *
9318 * Same for MAYBE_NULL:
9319 *
9320 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
9321 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
9322 *
9323 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
9324 *
9325 * Therefore we fold these flags depending on the arg_type before comparison.
9326 */
9327 if (arg_type & MEM_RDONLY)
9328 type &= ~MEM_RDONLY;
9329 if (arg_type & PTR_MAYBE_NULL)
9330 type &= ~PTR_MAYBE_NULL;
9331 if (base_type(arg_type) == ARG_PTR_TO_MEM)
9332 type &= ~DYNPTR_TYPE_FLAG_MASK;
9333
9334 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */
9335 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) {
9336 type &= ~MEM_ALLOC;
9337 type &= ~MEM_PERCPU;
9338 }
9339
9340 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
9341 expected = compatible->types[i];
9342 if (expected == NOT_INIT)
9343 break;
9344
9345 if (type == expected)
9346 goto found;
9347 }
9348
9349 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
9350 for (j = 0; j + 1 < i; j++)
9351 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
9352 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
9353 return -EACCES;
9354
9355 found:
9356 if (base_type(reg->type) != PTR_TO_BTF_ID)
9357 return 0;
9358
9359 if (compatible == &mem_types) {
9360 if (!(arg_type & MEM_RDONLY)) {
9361 verbose(env,
9362 "%s() may write into memory pointed by R%d type=%s\n",
9363 func_id_name(meta->func_id),
9364 regno, reg_type_str(env, reg->type));
9365 return -EACCES;
9366 }
9367 return 0;
9368 }
9369
9370 switch ((int)reg->type) {
9371 case PTR_TO_BTF_ID:
9372 case PTR_TO_BTF_ID | PTR_TRUSTED:
9373 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL:
9374 case PTR_TO_BTF_ID | MEM_RCU:
9375 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
9376 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
9377 {
9378 /* For bpf_sk_release, it needs to match against first member
9379 * 'struct sock_common', hence make an exception for it. This
9380 * allows bpf_sk_release to work for multiple socket types.
9381 */
9382 bool strict_type_match = arg_type_is_release(arg_type) &&
9383 meta->func_id != BPF_FUNC_sk_release;
9384
9385 if (type_may_be_null(reg->type) &&
9386 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
9387 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
9388 return -EACCES;
9389 }
9390
9391 if (!arg_btf_id) {
9392 if (!compatible->btf_id) {
9393 verifier_bug(env, "missing arg compatible BTF ID");
9394 return -EFAULT;
9395 }
9396 arg_btf_id = compatible->btf_id;
9397 }
9398
9399 if (meta->func_id == BPF_FUNC_kptr_xchg) {
9400 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9401 return -EACCES;
9402 } else {
9403 if (arg_btf_id == BPF_PTR_POISON) {
9404 verbose(env, "verifier internal error:");
9405 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
9406 regno);
9407 return -EACCES;
9408 }
9409
9410 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
9411 btf_vmlinux, *arg_btf_id,
9412 strict_type_match)) {
9413 verbose(env, "R%d is of type %s but %s is expected\n",
9414 regno, btf_type_name(reg->btf, reg->btf_id),
9415 btf_type_name(btf_vmlinux, *arg_btf_id));
9416 return -EACCES;
9417 }
9418 }
9419 break;
9420 }
9421 case PTR_TO_BTF_ID | MEM_ALLOC:
9422 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
9423 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
9424 meta->func_id != BPF_FUNC_kptr_xchg) {
9425 verifier_bug(env, "unimplemented handling of MEM_ALLOC");
9426 return -EFAULT;
9427 }
9428 /* Check if local kptr in src arg matches kptr in dst arg */
9429 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) {
9430 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
9431 return -EACCES;
9432 }
9433 break;
9434 case PTR_TO_BTF_ID | MEM_PERCPU:
9435 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
9436 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
9437 /* Handled by helper specific checks */
9438 break;
9439 default:
9440 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match");
9441 return -EFAULT;
9442 }
9443 return 0;
9444 }
9445
9446 static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)9447 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
9448 {
9449 struct btf_field *field;
9450 struct btf_record *rec;
9451
9452 rec = reg_btf_record(reg);
9453 if (!rec)
9454 return NULL;
9455
9456 field = btf_record_find(rec, off, fields);
9457 if (!field)
9458 return NULL;
9459
9460 return field;
9461 }
9462
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)9463 static int check_func_arg_reg_off(struct bpf_verifier_env *env,
9464 const struct bpf_reg_state *reg, int regno,
9465 enum bpf_arg_type arg_type)
9466 {
9467 u32 type = reg->type;
9468
9469 /* When referenced register is passed to release function, its fixed
9470 * offset must be 0.
9471 *
9472 * We will check arg_type_is_release reg has ref_obj_id when storing
9473 * meta->release_regno.
9474 */
9475 if (arg_type_is_release(arg_type)) {
9476 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
9477 * may not directly point to the object being released, but to
9478 * dynptr pointing to such object, which might be at some offset
9479 * on the stack. In that case, we simply to fallback to the
9480 * default handling.
9481 */
9482 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
9483 return 0;
9484
9485 /* Doing check_ptr_off_reg check for the offset will catch this
9486 * because fixed_off_ok is false, but checking here allows us
9487 * to give the user a better error message.
9488 */
9489 if (reg->off) {
9490 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
9491 regno);
9492 return -EINVAL;
9493 }
9494 return __check_ptr_off_reg(env, reg, regno, false);
9495 }
9496
9497 switch (type) {
9498 /* Pointer types where both fixed and variable offset is explicitly allowed: */
9499 case PTR_TO_STACK:
9500 case PTR_TO_PACKET:
9501 case PTR_TO_PACKET_META:
9502 case PTR_TO_MAP_KEY:
9503 case PTR_TO_MAP_VALUE:
9504 case PTR_TO_MEM:
9505 case PTR_TO_MEM | MEM_RDONLY:
9506 case PTR_TO_MEM | MEM_RINGBUF:
9507 case PTR_TO_BUF:
9508 case PTR_TO_BUF | MEM_RDONLY:
9509 case PTR_TO_ARENA:
9510 case SCALAR_VALUE:
9511 return 0;
9512 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
9513 * fixed offset.
9514 */
9515 case PTR_TO_BTF_ID:
9516 case PTR_TO_BTF_ID | MEM_ALLOC:
9517 case PTR_TO_BTF_ID | PTR_TRUSTED:
9518 case PTR_TO_BTF_ID | MEM_RCU:
9519 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
9520 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
9521 /* When referenced PTR_TO_BTF_ID is passed to release function,
9522 * its fixed offset must be 0. In the other cases, fixed offset
9523 * can be non-zero. This was already checked above. So pass
9524 * fixed_off_ok as true to allow fixed offset for all other
9525 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
9526 * still need to do checks instead of returning.
9527 */
9528 return __check_ptr_off_reg(env, reg, regno, true);
9529 default:
9530 return __check_ptr_off_reg(env, reg, regno, false);
9531 }
9532 }
9533
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)9534 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
9535 const struct bpf_func_proto *fn,
9536 struct bpf_reg_state *regs)
9537 {
9538 struct bpf_reg_state *state = NULL;
9539 int i;
9540
9541 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
9542 if (arg_type_is_dynptr(fn->arg_type[i])) {
9543 if (state) {
9544 verbose(env, "verifier internal error: multiple dynptr args\n");
9545 return NULL;
9546 }
9547 state = ®s[BPF_REG_1 + i];
9548 }
9549
9550 if (!state)
9551 verbose(env, "verifier internal error: no dynptr arg found\n");
9552
9553 return state;
9554 }
9555
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9556 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9557 {
9558 struct bpf_func_state *state = func(env, reg);
9559 int spi;
9560
9561 if (reg->type == CONST_PTR_TO_DYNPTR)
9562 return reg->id;
9563 spi = dynptr_get_spi(env, reg);
9564 if (spi < 0)
9565 return spi;
9566 return state->stack[spi].spilled_ptr.id;
9567 }
9568
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9569 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
9570 {
9571 struct bpf_func_state *state = func(env, reg);
9572 int spi;
9573
9574 if (reg->type == CONST_PTR_TO_DYNPTR)
9575 return reg->ref_obj_id;
9576 spi = dynptr_get_spi(env, reg);
9577 if (spi < 0)
9578 return spi;
9579 return state->stack[spi].spilled_ptr.ref_obj_id;
9580 }
9581
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)9582 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
9583 struct bpf_reg_state *reg)
9584 {
9585 struct bpf_func_state *state = func(env, reg);
9586 int spi;
9587
9588 if (reg->type == CONST_PTR_TO_DYNPTR)
9589 return reg->dynptr.type;
9590
9591 spi = __get_spi(reg->off);
9592 if (spi < 0) {
9593 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
9594 return BPF_DYNPTR_TYPE_INVALID;
9595 }
9596
9597 return state->stack[spi].spilled_ptr.dynptr.type;
9598 }
9599
check_reg_const_str(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)9600 static int check_reg_const_str(struct bpf_verifier_env *env,
9601 struct bpf_reg_state *reg, u32 regno)
9602 {
9603 struct bpf_map *map = reg->map_ptr;
9604 int err;
9605 int map_off;
9606 u64 map_addr;
9607 char *str_ptr;
9608
9609 if (reg->type != PTR_TO_MAP_VALUE)
9610 return -EINVAL;
9611
9612 if (!bpf_map_is_rdonly(map)) {
9613 verbose(env, "R%d does not point to a readonly map'\n", regno);
9614 return -EACCES;
9615 }
9616
9617 if (!tnum_is_const(reg->var_off)) {
9618 verbose(env, "R%d is not a constant address'\n", regno);
9619 return -EACCES;
9620 }
9621
9622 if (!map->ops->map_direct_value_addr) {
9623 verbose(env, "no direct value access support for this map type\n");
9624 return -EACCES;
9625 }
9626
9627 err = check_map_access(env, regno, reg->off,
9628 map->value_size - reg->off, false,
9629 ACCESS_HELPER);
9630 if (err)
9631 return err;
9632
9633 map_off = reg->off + reg->var_off.value;
9634 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9635 if (err) {
9636 verbose(env, "direct value access on string failed\n");
9637 return err;
9638 }
9639
9640 str_ptr = (char *)(long)(map_addr);
9641 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9642 verbose(env, "string is not zero-terminated\n");
9643 return -EINVAL;
9644 }
9645 return 0;
9646 }
9647
9648 /* Returns constant key value in `value` if possible, else negative error */
get_constant_map_key(struct bpf_verifier_env * env,struct bpf_reg_state * key,u32 key_size,s64 * value)9649 static int get_constant_map_key(struct bpf_verifier_env *env,
9650 struct bpf_reg_state *key,
9651 u32 key_size,
9652 s64 *value)
9653 {
9654 struct bpf_func_state *state = func(env, key);
9655 struct bpf_reg_state *reg;
9656 int slot, spi, off;
9657 int spill_size = 0;
9658 int zero_size = 0;
9659 int stack_off;
9660 int i, err;
9661 u8 *stype;
9662
9663 if (!env->bpf_capable)
9664 return -EOPNOTSUPP;
9665 if (key->type != PTR_TO_STACK)
9666 return -EOPNOTSUPP;
9667 if (!tnum_is_const(key->var_off))
9668 return -EOPNOTSUPP;
9669
9670 stack_off = key->off + key->var_off.value;
9671 slot = -stack_off - 1;
9672 spi = slot / BPF_REG_SIZE;
9673 off = slot % BPF_REG_SIZE;
9674 stype = state->stack[spi].slot_type;
9675
9676 /* First handle precisely tracked STACK_ZERO */
9677 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9678 zero_size++;
9679 if (zero_size >= key_size) {
9680 *value = 0;
9681 return 0;
9682 }
9683
9684 /* Check that stack contains a scalar spill of expected size */
9685 if (!is_spilled_scalar_reg(&state->stack[spi]))
9686 return -EOPNOTSUPP;
9687 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9688 spill_size++;
9689 if (spill_size != key_size)
9690 return -EOPNOTSUPP;
9691
9692 reg = &state->stack[spi].spilled_ptr;
9693 if (!tnum_is_const(reg->var_off))
9694 /* Stack value not statically known */
9695 return -EOPNOTSUPP;
9696
9697 /* We are relying on a constant value. So mark as precise
9698 * to prevent pruning on it.
9699 */
9700 bt_set_frame_slot(&env->bt, key->frameno, spi);
9701 err = mark_chain_precision_batch(env, env->cur_state);
9702 if (err < 0)
9703 return err;
9704
9705 *value = reg->var_off.value;
9706 return 0;
9707 }
9708
9709 static bool can_elide_value_nullness(enum bpf_map_type type);
9710
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn,int insn_idx)9711 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9712 struct bpf_call_arg_meta *meta,
9713 const struct bpf_func_proto *fn,
9714 int insn_idx)
9715 {
9716 u32 regno = BPF_REG_1 + arg;
9717 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
9718 enum bpf_arg_type arg_type = fn->arg_type[arg];
9719 enum bpf_reg_type type = reg->type;
9720 u32 *arg_btf_id = NULL;
9721 u32 key_size;
9722 int err = 0;
9723
9724 if (arg_type == ARG_DONTCARE)
9725 return 0;
9726
9727 err = check_reg_arg(env, regno, SRC_OP);
9728 if (err)
9729 return err;
9730
9731 if (arg_type == ARG_ANYTHING) {
9732 if (is_pointer_value(env, regno)) {
9733 verbose(env, "R%d leaks addr into helper function\n",
9734 regno);
9735 return -EACCES;
9736 }
9737 return 0;
9738 }
9739
9740 if (type_is_pkt_pointer(type) &&
9741 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9742 verbose(env, "helper access to the packet is not allowed\n");
9743 return -EACCES;
9744 }
9745
9746 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9747 err = resolve_map_arg_type(env, meta, &arg_type);
9748 if (err)
9749 return err;
9750 }
9751
9752 if (register_is_null(reg) && type_may_be_null(arg_type))
9753 /* A NULL register has a SCALAR_VALUE type, so skip
9754 * type checking.
9755 */
9756 goto skip_type_check;
9757
9758 /* arg_btf_id and arg_size are in a union. */
9759 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9760 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9761 arg_btf_id = fn->arg_btf_id[arg];
9762
9763 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9764 if (err)
9765 return err;
9766
9767 err = check_func_arg_reg_off(env, reg, regno, arg_type);
9768 if (err)
9769 return err;
9770
9771 skip_type_check:
9772 if (arg_type_is_release(arg_type)) {
9773 if (arg_type_is_dynptr(arg_type)) {
9774 struct bpf_func_state *state = func(env, reg);
9775 int spi;
9776
9777 /* Only dynptr created on stack can be released, thus
9778 * the get_spi and stack state checks for spilled_ptr
9779 * should only be done before process_dynptr_func for
9780 * PTR_TO_STACK.
9781 */
9782 if (reg->type == PTR_TO_STACK) {
9783 spi = dynptr_get_spi(env, reg);
9784 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9785 verbose(env, "arg %d is an unacquired reference\n", regno);
9786 return -EINVAL;
9787 }
9788 } else {
9789 verbose(env, "cannot release unowned const bpf_dynptr\n");
9790 return -EINVAL;
9791 }
9792 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
9793 verbose(env, "R%d must be referenced when passed to release function\n",
9794 regno);
9795 return -EINVAL;
9796 }
9797 if (meta->release_regno) {
9798 verifier_bug(env, "more than one release argument");
9799 return -EFAULT;
9800 }
9801 meta->release_regno = regno;
9802 }
9803
9804 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9805 if (meta->ref_obj_id) {
9806 verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9807 regno, reg->ref_obj_id,
9808 meta->ref_obj_id);
9809 return -EACCES;
9810 }
9811 meta->ref_obj_id = reg->ref_obj_id;
9812 }
9813
9814 switch (base_type(arg_type)) {
9815 case ARG_CONST_MAP_PTR:
9816 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9817 if (meta->map_ptr) {
9818 /* Use map_uid (which is unique id of inner map) to reject:
9819 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9820 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9821 * if (inner_map1 && inner_map2) {
9822 * timer = bpf_map_lookup_elem(inner_map1);
9823 * if (timer)
9824 * // mismatch would have been allowed
9825 * bpf_timer_init(timer, inner_map2);
9826 * }
9827 *
9828 * Comparing map_ptr is enough to distinguish normal and outer maps.
9829 */
9830 if (meta->map_ptr != reg->map_ptr ||
9831 meta->map_uid != reg->map_uid) {
9832 verbose(env,
9833 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9834 meta->map_uid, reg->map_uid);
9835 return -EINVAL;
9836 }
9837 }
9838 meta->map_ptr = reg->map_ptr;
9839 meta->map_uid = reg->map_uid;
9840 break;
9841 case ARG_PTR_TO_MAP_KEY:
9842 /* bpf_map_xxx(..., map_ptr, ..., key) call:
9843 * check that [key, key + map->key_size) are within
9844 * stack limits and initialized
9845 */
9846 if (!meta->map_ptr) {
9847 /* in function declaration map_ptr must come before
9848 * map_key, so that it's verified and known before
9849 * we have to check map_key here. Otherwise it means
9850 * that kernel subsystem misconfigured verifier
9851 */
9852 verifier_bug(env, "invalid map_ptr to access map->key");
9853 return -EFAULT;
9854 }
9855 key_size = meta->map_ptr->key_size;
9856 err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9857 if (err)
9858 return err;
9859 if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9860 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9861 if (err < 0) {
9862 meta->const_map_key = -1;
9863 if (err == -EOPNOTSUPP)
9864 err = 0;
9865 else
9866 return err;
9867 }
9868 }
9869 break;
9870 case ARG_PTR_TO_MAP_VALUE:
9871 if (type_may_be_null(arg_type) && register_is_null(reg))
9872 return 0;
9873
9874 /* bpf_map_xxx(..., map_ptr, ..., value) call:
9875 * check [value, value + map->value_size) validity
9876 */
9877 if (!meta->map_ptr) {
9878 /* kernel subsystem misconfigured verifier */
9879 verifier_bug(env, "invalid map_ptr to access map->value");
9880 return -EFAULT;
9881 }
9882 meta->raw_mode = arg_type & MEM_UNINIT;
9883 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9884 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9885 false, meta);
9886 break;
9887 case ARG_PTR_TO_PERCPU_BTF_ID:
9888 if (!reg->btf_id) {
9889 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9890 return -EACCES;
9891 }
9892 meta->ret_btf = reg->btf;
9893 meta->ret_btf_id = reg->btf_id;
9894 break;
9895 case ARG_PTR_TO_SPIN_LOCK:
9896 if (in_rbtree_lock_required_cb(env)) {
9897 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9898 return -EACCES;
9899 }
9900 if (meta->func_id == BPF_FUNC_spin_lock) {
9901 err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9902 if (err)
9903 return err;
9904 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
9905 err = process_spin_lock(env, regno, 0);
9906 if (err)
9907 return err;
9908 } else {
9909 verifier_bug(env, "spin lock arg on unexpected helper");
9910 return -EFAULT;
9911 }
9912 break;
9913 case ARG_PTR_TO_TIMER:
9914 err = process_timer_func(env, regno, meta);
9915 if (err)
9916 return err;
9917 break;
9918 case ARG_PTR_TO_FUNC:
9919 meta->subprogno = reg->subprogno;
9920 break;
9921 case ARG_PTR_TO_MEM:
9922 /* The access to this pointer is only checked when we hit the
9923 * next is_mem_size argument below.
9924 */
9925 meta->raw_mode = arg_type & MEM_UNINIT;
9926 if (arg_type & MEM_FIXED_SIZE) {
9927 err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9928 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9929 false, meta);
9930 if (err)
9931 return err;
9932 if (arg_type & MEM_ALIGNED)
9933 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9934 }
9935 break;
9936 case ARG_CONST_SIZE:
9937 err = check_mem_size_reg(env, reg, regno,
9938 fn->arg_type[arg - 1] & MEM_WRITE ?
9939 BPF_WRITE : BPF_READ,
9940 false, meta);
9941 break;
9942 case ARG_CONST_SIZE_OR_ZERO:
9943 err = check_mem_size_reg(env, reg, regno,
9944 fn->arg_type[arg - 1] & MEM_WRITE ?
9945 BPF_WRITE : BPF_READ,
9946 true, meta);
9947 break;
9948 case ARG_PTR_TO_DYNPTR:
9949 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9950 if (err)
9951 return err;
9952 break;
9953 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9954 if (!tnum_is_const(reg->var_off)) {
9955 verbose(env, "R%d is not a known constant'\n",
9956 regno);
9957 return -EACCES;
9958 }
9959 meta->mem_size = reg->var_off.value;
9960 err = mark_chain_precision(env, regno);
9961 if (err)
9962 return err;
9963 break;
9964 case ARG_PTR_TO_CONST_STR:
9965 {
9966 err = check_reg_const_str(env, reg, regno);
9967 if (err)
9968 return err;
9969 break;
9970 }
9971 case ARG_KPTR_XCHG_DEST:
9972 err = process_kptr_func(env, regno, meta);
9973 if (err)
9974 return err;
9975 break;
9976 }
9977
9978 return err;
9979 }
9980
may_update_sockmap(struct bpf_verifier_env * env,int func_id)9981 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9982 {
9983 enum bpf_attach_type eatype = env->prog->expected_attach_type;
9984 enum bpf_prog_type type = resolve_prog_type(env->prog);
9985
9986 if (func_id != BPF_FUNC_map_update_elem &&
9987 func_id != BPF_FUNC_map_delete_elem)
9988 return false;
9989
9990 /* It's not possible to get access to a locked struct sock in these
9991 * contexts, so updating is safe.
9992 */
9993 switch (type) {
9994 case BPF_PROG_TYPE_TRACING:
9995 if (eatype == BPF_TRACE_ITER)
9996 return true;
9997 break;
9998 case BPF_PROG_TYPE_SOCK_OPS:
9999 /* map_update allowed only via dedicated helpers with event type checks */
10000 if (func_id == BPF_FUNC_map_delete_elem)
10001 return true;
10002 break;
10003 case BPF_PROG_TYPE_SOCKET_FILTER:
10004 case BPF_PROG_TYPE_SCHED_CLS:
10005 case BPF_PROG_TYPE_SCHED_ACT:
10006 case BPF_PROG_TYPE_XDP:
10007 case BPF_PROG_TYPE_SK_REUSEPORT:
10008 case BPF_PROG_TYPE_FLOW_DISSECTOR:
10009 case BPF_PROG_TYPE_SK_LOOKUP:
10010 return true;
10011 default:
10012 break;
10013 }
10014
10015 verbose(env, "cannot update sockmap in this context\n");
10016 return false;
10017 }
10018
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)10019 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10020 {
10021 return env->prog->jit_requested &&
10022 bpf_jit_supports_subprog_tailcalls();
10023 }
10024
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)10025 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10026 struct bpf_map *map, int func_id)
10027 {
10028 if (!map)
10029 return 0;
10030
10031 /* We need a two way check, first is from map perspective ... */
10032 switch (map->map_type) {
10033 case BPF_MAP_TYPE_PROG_ARRAY:
10034 if (func_id != BPF_FUNC_tail_call)
10035 goto error;
10036 break;
10037 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10038 if (func_id != BPF_FUNC_perf_event_read &&
10039 func_id != BPF_FUNC_perf_event_output &&
10040 func_id != BPF_FUNC_skb_output &&
10041 func_id != BPF_FUNC_perf_event_read_value &&
10042 func_id != BPF_FUNC_xdp_output)
10043 goto error;
10044 break;
10045 case BPF_MAP_TYPE_RINGBUF:
10046 if (func_id != BPF_FUNC_ringbuf_output &&
10047 func_id != BPF_FUNC_ringbuf_reserve &&
10048 func_id != BPF_FUNC_ringbuf_query &&
10049 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10050 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10051 func_id != BPF_FUNC_ringbuf_discard_dynptr)
10052 goto error;
10053 break;
10054 case BPF_MAP_TYPE_USER_RINGBUF:
10055 if (func_id != BPF_FUNC_user_ringbuf_drain)
10056 goto error;
10057 break;
10058 case BPF_MAP_TYPE_STACK_TRACE:
10059 if (func_id != BPF_FUNC_get_stackid)
10060 goto error;
10061 break;
10062 case BPF_MAP_TYPE_CGROUP_ARRAY:
10063 if (func_id != BPF_FUNC_skb_under_cgroup &&
10064 func_id != BPF_FUNC_current_task_under_cgroup)
10065 goto error;
10066 break;
10067 case BPF_MAP_TYPE_CGROUP_STORAGE:
10068 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10069 if (func_id != BPF_FUNC_get_local_storage)
10070 goto error;
10071 break;
10072 case BPF_MAP_TYPE_DEVMAP:
10073 case BPF_MAP_TYPE_DEVMAP_HASH:
10074 if (func_id != BPF_FUNC_redirect_map &&
10075 func_id != BPF_FUNC_map_lookup_elem)
10076 goto error;
10077 break;
10078 /* Restrict bpf side of cpumap and xskmap, open when use-cases
10079 * appear.
10080 */
10081 case BPF_MAP_TYPE_CPUMAP:
10082 if (func_id != BPF_FUNC_redirect_map)
10083 goto error;
10084 break;
10085 case BPF_MAP_TYPE_XSKMAP:
10086 if (func_id != BPF_FUNC_redirect_map &&
10087 func_id != BPF_FUNC_map_lookup_elem)
10088 goto error;
10089 break;
10090 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10091 case BPF_MAP_TYPE_HASH_OF_MAPS:
10092 if (func_id != BPF_FUNC_map_lookup_elem)
10093 goto error;
10094 break;
10095 case BPF_MAP_TYPE_SOCKMAP:
10096 if (func_id != BPF_FUNC_sk_redirect_map &&
10097 func_id != BPF_FUNC_sock_map_update &&
10098 func_id != BPF_FUNC_msg_redirect_map &&
10099 func_id != BPF_FUNC_sk_select_reuseport &&
10100 func_id != BPF_FUNC_map_lookup_elem &&
10101 !may_update_sockmap(env, func_id))
10102 goto error;
10103 break;
10104 case BPF_MAP_TYPE_SOCKHASH:
10105 if (func_id != BPF_FUNC_sk_redirect_hash &&
10106 func_id != BPF_FUNC_sock_hash_update &&
10107 func_id != BPF_FUNC_msg_redirect_hash &&
10108 func_id != BPF_FUNC_sk_select_reuseport &&
10109 func_id != BPF_FUNC_map_lookup_elem &&
10110 !may_update_sockmap(env, func_id))
10111 goto error;
10112 break;
10113 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10114 if (func_id != BPF_FUNC_sk_select_reuseport)
10115 goto error;
10116 break;
10117 case BPF_MAP_TYPE_QUEUE:
10118 case BPF_MAP_TYPE_STACK:
10119 if (func_id != BPF_FUNC_map_peek_elem &&
10120 func_id != BPF_FUNC_map_pop_elem &&
10121 func_id != BPF_FUNC_map_push_elem)
10122 goto error;
10123 break;
10124 case BPF_MAP_TYPE_SK_STORAGE:
10125 if (func_id != BPF_FUNC_sk_storage_get &&
10126 func_id != BPF_FUNC_sk_storage_delete &&
10127 func_id != BPF_FUNC_kptr_xchg)
10128 goto error;
10129 break;
10130 case BPF_MAP_TYPE_INODE_STORAGE:
10131 if (func_id != BPF_FUNC_inode_storage_get &&
10132 func_id != BPF_FUNC_inode_storage_delete &&
10133 func_id != BPF_FUNC_kptr_xchg)
10134 goto error;
10135 break;
10136 case BPF_MAP_TYPE_TASK_STORAGE:
10137 if (func_id != BPF_FUNC_task_storage_get &&
10138 func_id != BPF_FUNC_task_storage_delete &&
10139 func_id != BPF_FUNC_kptr_xchg)
10140 goto error;
10141 break;
10142 case BPF_MAP_TYPE_CGRP_STORAGE:
10143 if (func_id != BPF_FUNC_cgrp_storage_get &&
10144 func_id != BPF_FUNC_cgrp_storage_delete &&
10145 func_id != BPF_FUNC_kptr_xchg)
10146 goto error;
10147 break;
10148 case BPF_MAP_TYPE_BLOOM_FILTER:
10149 if (func_id != BPF_FUNC_map_peek_elem &&
10150 func_id != BPF_FUNC_map_push_elem)
10151 goto error;
10152 break;
10153 case BPF_MAP_TYPE_INSN_ARRAY:
10154 goto error;
10155 default:
10156 break;
10157 }
10158
10159 /* ... and second from the function itself. */
10160 switch (func_id) {
10161 case BPF_FUNC_tail_call:
10162 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10163 goto error;
10164 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10165 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10166 return -EINVAL;
10167 }
10168 break;
10169 case BPF_FUNC_perf_event_read:
10170 case BPF_FUNC_perf_event_output:
10171 case BPF_FUNC_perf_event_read_value:
10172 case BPF_FUNC_skb_output:
10173 case BPF_FUNC_xdp_output:
10174 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10175 goto error;
10176 break;
10177 case BPF_FUNC_ringbuf_output:
10178 case BPF_FUNC_ringbuf_reserve:
10179 case BPF_FUNC_ringbuf_query:
10180 case BPF_FUNC_ringbuf_reserve_dynptr:
10181 case BPF_FUNC_ringbuf_submit_dynptr:
10182 case BPF_FUNC_ringbuf_discard_dynptr:
10183 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10184 goto error;
10185 break;
10186 case BPF_FUNC_user_ringbuf_drain:
10187 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10188 goto error;
10189 break;
10190 case BPF_FUNC_get_stackid:
10191 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10192 goto error;
10193 break;
10194 case BPF_FUNC_current_task_under_cgroup:
10195 case BPF_FUNC_skb_under_cgroup:
10196 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10197 goto error;
10198 break;
10199 case BPF_FUNC_redirect_map:
10200 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10201 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10202 map->map_type != BPF_MAP_TYPE_CPUMAP &&
10203 map->map_type != BPF_MAP_TYPE_XSKMAP)
10204 goto error;
10205 break;
10206 case BPF_FUNC_sk_redirect_map:
10207 case BPF_FUNC_msg_redirect_map:
10208 case BPF_FUNC_sock_map_update:
10209 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10210 goto error;
10211 break;
10212 case BPF_FUNC_sk_redirect_hash:
10213 case BPF_FUNC_msg_redirect_hash:
10214 case BPF_FUNC_sock_hash_update:
10215 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10216 goto error;
10217 break;
10218 case BPF_FUNC_get_local_storage:
10219 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10220 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10221 goto error;
10222 break;
10223 case BPF_FUNC_sk_select_reuseport:
10224 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10225 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10226 map->map_type != BPF_MAP_TYPE_SOCKHASH)
10227 goto error;
10228 break;
10229 case BPF_FUNC_map_pop_elem:
10230 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10231 map->map_type != BPF_MAP_TYPE_STACK)
10232 goto error;
10233 break;
10234 case BPF_FUNC_map_peek_elem:
10235 case BPF_FUNC_map_push_elem:
10236 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10237 map->map_type != BPF_MAP_TYPE_STACK &&
10238 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10239 goto error;
10240 break;
10241 case BPF_FUNC_map_lookup_percpu_elem:
10242 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10243 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10244 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10245 goto error;
10246 break;
10247 case BPF_FUNC_sk_storage_get:
10248 case BPF_FUNC_sk_storage_delete:
10249 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10250 goto error;
10251 break;
10252 case BPF_FUNC_inode_storage_get:
10253 case BPF_FUNC_inode_storage_delete:
10254 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10255 goto error;
10256 break;
10257 case BPF_FUNC_task_storage_get:
10258 case BPF_FUNC_task_storage_delete:
10259 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10260 goto error;
10261 break;
10262 case BPF_FUNC_cgrp_storage_get:
10263 case BPF_FUNC_cgrp_storage_delete:
10264 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10265 goto error;
10266 break;
10267 default:
10268 break;
10269 }
10270
10271 return 0;
10272 error:
10273 verbose(env, "cannot pass map_type %d into func %s#%d\n",
10274 map->map_type, func_id_name(func_id), func_id);
10275 return -EINVAL;
10276 }
10277
check_raw_mode_ok(const struct bpf_func_proto * fn)10278 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10279 {
10280 int count = 0;
10281
10282 if (arg_type_is_raw_mem(fn->arg1_type))
10283 count++;
10284 if (arg_type_is_raw_mem(fn->arg2_type))
10285 count++;
10286 if (arg_type_is_raw_mem(fn->arg3_type))
10287 count++;
10288 if (arg_type_is_raw_mem(fn->arg4_type))
10289 count++;
10290 if (arg_type_is_raw_mem(fn->arg5_type))
10291 count++;
10292
10293 /* We only support one arg being in raw mode at the moment,
10294 * which is sufficient for the helper functions we have
10295 * right now.
10296 */
10297 return count <= 1;
10298 }
10299
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)10300 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10301 {
10302 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10303 bool has_size = fn->arg_size[arg] != 0;
10304 bool is_next_size = false;
10305
10306 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10307 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10308
10309 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10310 return is_next_size;
10311
10312 return has_size == is_next_size || is_next_size == is_fixed;
10313 }
10314
check_arg_pair_ok(const struct bpf_func_proto * fn)10315 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10316 {
10317 /* bpf_xxx(..., buf, len) call will access 'len'
10318 * bytes from memory 'buf'. Both arg types need
10319 * to be paired, so make sure there's no buggy
10320 * helper function specification.
10321 */
10322 if (arg_type_is_mem_size(fn->arg1_type) ||
10323 check_args_pair_invalid(fn, 0) ||
10324 check_args_pair_invalid(fn, 1) ||
10325 check_args_pair_invalid(fn, 2) ||
10326 check_args_pair_invalid(fn, 3) ||
10327 check_args_pair_invalid(fn, 4))
10328 return false;
10329
10330 return true;
10331 }
10332
check_btf_id_ok(const struct bpf_func_proto * fn)10333 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10334 {
10335 int i;
10336
10337 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10338 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10339 return !!fn->arg_btf_id[i];
10340 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10341 return fn->arg_btf_id[i] == BPF_PTR_POISON;
10342 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10343 /* arg_btf_id and arg_size are in a union. */
10344 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10345 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10346 return false;
10347 }
10348
10349 return true;
10350 }
10351
check_func_proto(const struct bpf_func_proto * fn,int func_id)10352 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10353 {
10354 return check_raw_mode_ok(fn) &&
10355 check_arg_pair_ok(fn) &&
10356 check_btf_id_ok(fn) ? 0 : -EINVAL;
10357 }
10358
10359 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10360 * are now invalid, so turn them into unknown SCALAR_VALUE.
10361 *
10362 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10363 * since these slices point to packet data.
10364 */
clear_all_pkt_pointers(struct bpf_verifier_env * env)10365 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10366 {
10367 struct bpf_func_state *state;
10368 struct bpf_reg_state *reg;
10369
10370 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10371 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10372 mark_reg_invalid(env, reg);
10373 }));
10374 }
10375
10376 enum {
10377 AT_PKT_END = -1,
10378 BEYOND_PKT_END = -2,
10379 };
10380
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)10381 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10382 {
10383 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10384 struct bpf_reg_state *reg = &state->regs[regn];
10385
10386 if (reg->type != PTR_TO_PACKET)
10387 /* PTR_TO_PACKET_META is not supported yet */
10388 return;
10389
10390 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10391 * How far beyond pkt_end it goes is unknown.
10392 * if (!range_open) it's the case of pkt >= pkt_end
10393 * if (range_open) it's the case of pkt > pkt_end
10394 * hence this pointer is at least 1 byte bigger than pkt_end
10395 */
10396 if (range_open)
10397 reg->range = BEYOND_PKT_END;
10398 else
10399 reg->range = AT_PKT_END;
10400 }
10401
release_reference_nomark(struct bpf_verifier_state * state,int ref_obj_id)10402 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10403 {
10404 int i;
10405
10406 for (i = 0; i < state->acquired_refs; i++) {
10407 if (state->refs[i].type != REF_TYPE_PTR)
10408 continue;
10409 if (state->refs[i].id == ref_obj_id) {
10410 release_reference_state(state, i);
10411 return 0;
10412 }
10413 }
10414 return -EINVAL;
10415 }
10416
10417 /* The pointer with the specified id has released its reference to kernel
10418 * resources. Identify all copies of the same pointer and clear the reference.
10419 *
10420 * This is the release function corresponding to acquire_reference(). Idempotent.
10421 */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)10422 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10423 {
10424 struct bpf_verifier_state *vstate = env->cur_state;
10425 struct bpf_func_state *state;
10426 struct bpf_reg_state *reg;
10427 int err;
10428
10429 err = release_reference_nomark(vstate, ref_obj_id);
10430 if (err)
10431 return err;
10432
10433 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10434 if (reg->ref_obj_id == ref_obj_id)
10435 mark_reg_invalid(env, reg);
10436 }));
10437
10438 return 0;
10439 }
10440
invalidate_non_owning_refs(struct bpf_verifier_env * env)10441 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10442 {
10443 struct bpf_func_state *unused;
10444 struct bpf_reg_state *reg;
10445
10446 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10447 if (type_is_non_owning_ref(reg->type))
10448 mark_reg_invalid(env, reg);
10449 }));
10450 }
10451
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)10452 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10453 struct bpf_reg_state *regs)
10454 {
10455 int i;
10456
10457 /* after the call registers r0 - r5 were scratched */
10458 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10459 mark_reg_not_init(env, regs, caller_saved[i]);
10460 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10461 }
10462 }
10463
10464 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10465 struct bpf_func_state *caller,
10466 struct bpf_func_state *callee,
10467 int insn_idx);
10468
10469 static int set_callee_state(struct bpf_verifier_env *env,
10470 struct bpf_func_state *caller,
10471 struct bpf_func_state *callee, int insn_idx);
10472
setup_func_entry(struct bpf_verifier_env * env,int subprog,int callsite,set_callee_state_fn set_callee_state_cb,struct bpf_verifier_state * state)10473 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10474 set_callee_state_fn set_callee_state_cb,
10475 struct bpf_verifier_state *state)
10476 {
10477 struct bpf_func_state *caller, *callee;
10478 int err;
10479
10480 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10481 verbose(env, "the call stack of %d frames is too deep\n",
10482 state->curframe + 2);
10483 return -E2BIG;
10484 }
10485
10486 if (state->frame[state->curframe + 1]) {
10487 verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10488 return -EFAULT;
10489 }
10490
10491 caller = state->frame[state->curframe];
10492 callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10493 if (!callee)
10494 return -ENOMEM;
10495 state->frame[state->curframe + 1] = callee;
10496
10497 /* callee cannot access r0, r6 - r9 for reading and has to write
10498 * into its own stack before reading from it.
10499 * callee can read/write into caller's stack
10500 */
10501 init_func_state(env, callee,
10502 /* remember the callsite, it will be used by bpf_exit */
10503 callsite,
10504 state->curframe + 1 /* frameno within this callchain */,
10505 subprog /* subprog number within this prog */);
10506 err = set_callee_state_cb(env, caller, callee, callsite);
10507 if (err)
10508 goto err_out;
10509
10510 /* only increment it after check_reg_arg() finished */
10511 state->curframe++;
10512
10513 return 0;
10514
10515 err_out:
10516 free_func_state(callee);
10517 state->frame[state->curframe + 1] = NULL;
10518 return err;
10519 }
10520
btf_check_func_arg_match(struct bpf_verifier_env * env,int subprog,const struct btf * btf,struct bpf_reg_state * regs)10521 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10522 const struct btf *btf,
10523 struct bpf_reg_state *regs)
10524 {
10525 struct bpf_subprog_info *sub = subprog_info(env, subprog);
10526 struct bpf_verifier_log *log = &env->log;
10527 u32 i;
10528 int ret;
10529
10530 ret = btf_prepare_func_args(env, subprog);
10531 if (ret)
10532 return ret;
10533
10534 /* check that BTF function arguments match actual types that the
10535 * verifier sees.
10536 */
10537 for (i = 0; i < sub->arg_cnt; i++) {
10538 u32 regno = i + 1;
10539 struct bpf_reg_state *reg = ®s[regno];
10540 struct bpf_subprog_arg_info *arg = &sub->args[i];
10541
10542 if (arg->arg_type == ARG_ANYTHING) {
10543 if (reg->type != SCALAR_VALUE) {
10544 bpf_log(log, "R%d is not a scalar\n", regno);
10545 return -EINVAL;
10546 }
10547 } else if (arg->arg_type & PTR_UNTRUSTED) {
10548 /*
10549 * Anything is allowed for untrusted arguments, as these are
10550 * read-only and probe read instructions would protect against
10551 * invalid memory access.
10552 */
10553 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
10554 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10555 if (ret < 0)
10556 return ret;
10557 /* If function expects ctx type in BTF check that caller
10558 * is passing PTR_TO_CTX.
10559 */
10560 if (reg->type != PTR_TO_CTX) {
10561 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10562 return -EINVAL;
10563 }
10564 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10565 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10566 if (ret < 0)
10567 return ret;
10568 if (check_mem_reg(env, reg, regno, arg->mem_size))
10569 return -EINVAL;
10570 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10571 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10572 return -EINVAL;
10573 }
10574 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10575 /*
10576 * Can pass any value and the kernel won't crash, but
10577 * only PTR_TO_ARENA or SCALAR make sense. Everything
10578 * else is a bug in the bpf program. Point it out to
10579 * the user at the verification time instead of
10580 * run-time debug nightmare.
10581 */
10582 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10583 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10584 return -EINVAL;
10585 }
10586 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10587 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10588 if (ret)
10589 return ret;
10590
10591 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10592 if (ret)
10593 return ret;
10594 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10595 struct bpf_call_arg_meta meta;
10596 int err;
10597
10598 if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10599 continue;
10600
10601 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10602 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10603 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10604 if (err)
10605 return err;
10606 } else {
10607 verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10608 return -EFAULT;
10609 }
10610 }
10611
10612 return 0;
10613 }
10614
10615 /* Compare BTF of a function call with given bpf_reg_state.
10616 * Returns:
10617 * EFAULT - there is a verifier bug. Abort verification.
10618 * EINVAL - there is a type mismatch or BTF is not available.
10619 * 0 - BTF matches with what bpf_reg_state expects.
10620 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10621 */
btf_check_subprog_call(struct bpf_verifier_env * env,int subprog,struct bpf_reg_state * regs)10622 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10623 struct bpf_reg_state *regs)
10624 {
10625 struct bpf_prog *prog = env->prog;
10626 struct btf *btf = prog->aux->btf;
10627 u32 btf_id;
10628 int err;
10629
10630 if (!prog->aux->func_info)
10631 return -EINVAL;
10632
10633 btf_id = prog->aux->func_info[subprog].type_id;
10634 if (!btf_id)
10635 return -EFAULT;
10636
10637 if (prog->aux->func_info_aux[subprog].unreliable)
10638 return -EINVAL;
10639
10640 err = btf_check_func_arg_match(env, subprog, btf, regs);
10641 /* Compiler optimizations can remove arguments from static functions
10642 * or mismatched type can be passed into a global function.
10643 * In such cases mark the function as unreliable from BTF point of view.
10644 */
10645 if (err)
10646 prog->aux->func_info_aux[subprog].unreliable = true;
10647 return err;
10648 }
10649
push_callback_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int insn_idx,int subprog,set_callee_state_fn set_callee_state_cb)10650 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10651 int insn_idx, int subprog,
10652 set_callee_state_fn set_callee_state_cb)
10653 {
10654 struct bpf_verifier_state *state = env->cur_state, *callback_state;
10655 struct bpf_func_state *caller, *callee;
10656 int err;
10657
10658 caller = state->frame[state->curframe];
10659 err = btf_check_subprog_call(env, subprog, caller->regs);
10660 if (err == -EFAULT)
10661 return err;
10662
10663 /* set_callee_state is used for direct subprog calls, but we are
10664 * interested in validating only BPF helpers that can call subprogs as
10665 * callbacks
10666 */
10667 env->subprog_info[subprog].is_cb = true;
10668 if (bpf_pseudo_kfunc_call(insn) &&
10669 !is_callback_calling_kfunc(insn->imm)) {
10670 verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10671 func_id_name(insn->imm), insn->imm);
10672 return -EFAULT;
10673 } else if (!bpf_pseudo_kfunc_call(insn) &&
10674 !is_callback_calling_function(insn->imm)) { /* helper */
10675 verifier_bug(env, "helper %s#%d not marked as callback-calling",
10676 func_id_name(insn->imm), insn->imm);
10677 return -EFAULT;
10678 }
10679
10680 if (is_async_callback_calling_insn(insn)) {
10681 struct bpf_verifier_state *async_cb;
10682
10683 /* there is no real recursion here. timer and workqueue callbacks are async */
10684 env->subprog_info[subprog].is_async_cb = true;
10685 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10686 insn_idx, subprog,
10687 is_async_cb_sleepable(env, insn));
10688 if (IS_ERR(async_cb))
10689 return PTR_ERR(async_cb);
10690 callee = async_cb->frame[0];
10691 callee->async_entry_cnt = caller->async_entry_cnt + 1;
10692
10693 /* Convert bpf_timer_set_callback() args into timer callback args */
10694 err = set_callee_state_cb(env, caller, callee, insn_idx);
10695 if (err)
10696 return err;
10697
10698 return 0;
10699 }
10700
10701 /* for callback functions enqueue entry to callback and
10702 * proceed with next instruction within current frame.
10703 */
10704 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10705 if (IS_ERR(callback_state))
10706 return PTR_ERR(callback_state);
10707
10708 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10709 callback_state);
10710 if (err)
10711 return err;
10712
10713 callback_state->callback_unroll_depth++;
10714 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10715 caller->callback_depth = 0;
10716 return 0;
10717 }
10718
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)10719 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10720 int *insn_idx)
10721 {
10722 struct bpf_verifier_state *state = env->cur_state;
10723 struct bpf_func_state *caller;
10724 int err, subprog, target_insn;
10725
10726 target_insn = *insn_idx + insn->imm + 1;
10727 subprog = find_subprog(env, target_insn);
10728 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10729 target_insn))
10730 return -EFAULT;
10731
10732 caller = state->frame[state->curframe];
10733 err = btf_check_subprog_call(env, subprog, caller->regs);
10734 if (err == -EFAULT)
10735 return err;
10736 if (subprog_is_global(env, subprog)) {
10737 const char *sub_name = subprog_name(env, subprog);
10738
10739 if (env->cur_state->active_locks) {
10740 verbose(env, "global function calls are not allowed while holding a lock,\n"
10741 "use static function instead\n");
10742 return -EINVAL;
10743 }
10744
10745 if (env->subprog_info[subprog].might_sleep &&
10746 (env->cur_state->active_rcu_locks || env->cur_state->active_preempt_locks ||
10747 env->cur_state->active_irq_id || !in_sleepable(env))) {
10748 verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10749 "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10750 "a non-sleepable BPF program context\n");
10751 return -EINVAL;
10752 }
10753
10754 if (err) {
10755 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10756 subprog, sub_name);
10757 return err;
10758 }
10759
10760 if (env->log.level & BPF_LOG_LEVEL)
10761 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10762 subprog, sub_name);
10763 if (env->subprog_info[subprog].changes_pkt_data)
10764 clear_all_pkt_pointers(env);
10765 /* mark global subprog for verifying after main prog */
10766 subprog_aux(env, subprog)->called = true;
10767 clear_caller_saved_regs(env, caller->regs);
10768
10769 /* All global functions return a 64-bit SCALAR_VALUE */
10770 mark_reg_unknown(env, caller->regs, BPF_REG_0);
10771 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10772
10773 /* continue with next insn after call */
10774 return 0;
10775 }
10776
10777 /* for regular function entry setup new frame and continue
10778 * from that frame.
10779 */
10780 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10781 if (err)
10782 return err;
10783
10784 clear_caller_saved_regs(env, caller->regs);
10785
10786 /* and go analyze first insn of the callee */
10787 *insn_idx = env->subprog_info[subprog].start - 1;
10788
10789 bpf_reset_live_stack_callchain(env);
10790
10791 if (env->log.level & BPF_LOG_LEVEL) {
10792 verbose(env, "caller:\n");
10793 print_verifier_state(env, state, caller->frameno, true);
10794 verbose(env, "callee:\n");
10795 print_verifier_state(env, state, state->curframe, true);
10796 }
10797
10798 return 0;
10799 }
10800
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)10801 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10802 struct bpf_func_state *caller,
10803 struct bpf_func_state *callee)
10804 {
10805 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10806 * void *callback_ctx, u64 flags);
10807 * callback_fn(struct bpf_map *map, void *key, void *value,
10808 * void *callback_ctx);
10809 */
10810 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10811
10812 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10813 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10814 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10815
10816 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10817 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10818 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10819
10820 /* pointer to stack or null */
10821 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10822
10823 /* unused */
10824 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10825 return 0;
10826 }
10827
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10828 static int set_callee_state(struct bpf_verifier_env *env,
10829 struct bpf_func_state *caller,
10830 struct bpf_func_state *callee, int insn_idx)
10831 {
10832 int i;
10833
10834 /* copy r1 - r5 args that callee can access. The copy includes parent
10835 * pointers, which connects us up to the liveness chain
10836 */
10837 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10838 callee->regs[i] = caller->regs[i];
10839 return 0;
10840 }
10841
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10842 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10843 struct bpf_func_state *caller,
10844 struct bpf_func_state *callee,
10845 int insn_idx)
10846 {
10847 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10848 struct bpf_map *map;
10849 int err;
10850
10851 /* valid map_ptr and poison value does not matter */
10852 map = insn_aux->map_ptr_state.map_ptr;
10853 if (!map->ops->map_set_for_each_callback_args ||
10854 !map->ops->map_for_each_callback) {
10855 verbose(env, "callback function not allowed for map\n");
10856 return -ENOTSUPP;
10857 }
10858
10859 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10860 if (err)
10861 return err;
10862
10863 callee->in_callback_fn = true;
10864 callee->callback_ret_range = retval_range(0, 1);
10865 return 0;
10866 }
10867
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10868 static int set_loop_callback_state(struct bpf_verifier_env *env,
10869 struct bpf_func_state *caller,
10870 struct bpf_func_state *callee,
10871 int insn_idx)
10872 {
10873 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10874 * u64 flags);
10875 * callback_fn(u64 index, void *callback_ctx);
10876 */
10877 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10878 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10879
10880 /* unused */
10881 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10882 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10883 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10884
10885 callee->in_callback_fn = true;
10886 callee->callback_ret_range = retval_range(0, 1);
10887 return 0;
10888 }
10889
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10890 static int set_timer_callback_state(struct bpf_verifier_env *env,
10891 struct bpf_func_state *caller,
10892 struct bpf_func_state *callee,
10893 int insn_idx)
10894 {
10895 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10896
10897 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10898 * callback_fn(struct bpf_map *map, void *key, void *value);
10899 */
10900 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10901 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10902 callee->regs[BPF_REG_1].map_ptr = map_ptr;
10903
10904 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10905 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10906 callee->regs[BPF_REG_2].map_ptr = map_ptr;
10907
10908 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10909 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10910 callee->regs[BPF_REG_3].map_ptr = map_ptr;
10911
10912 /* unused */
10913 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10914 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10915 callee->in_async_callback_fn = true;
10916 callee->callback_ret_range = retval_range(0, 0);
10917 return 0;
10918 }
10919
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10920 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10921 struct bpf_func_state *caller,
10922 struct bpf_func_state *callee,
10923 int insn_idx)
10924 {
10925 /* bpf_find_vma(struct task_struct *task, u64 addr,
10926 * void *callback_fn, void *callback_ctx, u64 flags)
10927 * (callback_fn)(struct task_struct *task,
10928 * struct vm_area_struct *vma, void *callback_ctx);
10929 */
10930 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10931
10932 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10933 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10934 callee->regs[BPF_REG_2].btf = btf_vmlinux;
10935 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10936
10937 /* pointer to stack or null */
10938 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10939
10940 /* unused */
10941 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10942 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10943 callee->in_callback_fn = true;
10944 callee->callback_ret_range = retval_range(0, 1);
10945 return 0;
10946 }
10947
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10948 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10949 struct bpf_func_state *caller,
10950 struct bpf_func_state *callee,
10951 int insn_idx)
10952 {
10953 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10954 * callback_ctx, u64 flags);
10955 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10956 */
10957 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10958 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10959 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10960
10961 /* unused */
10962 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10963 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10964 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10965
10966 callee->in_callback_fn = true;
10967 callee->callback_ret_range = retval_range(0, 1);
10968 return 0;
10969 }
10970
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10971 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10972 struct bpf_func_state *caller,
10973 struct bpf_func_state *callee,
10974 int insn_idx)
10975 {
10976 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10977 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10978 *
10979 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10980 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10981 * by this point, so look at 'root'
10982 */
10983 struct btf_field *field;
10984
10985 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10986 BPF_RB_ROOT);
10987 if (!field || !field->graph_root.value_btf_id)
10988 return -EFAULT;
10989
10990 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10991 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10992 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10993 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10994
10995 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10996 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10997 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10998 callee->in_callback_fn = true;
10999 callee->callback_ret_range = retval_range(0, 1);
11000 return 0;
11001 }
11002
set_task_work_schedule_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)11003 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11004 struct bpf_func_state *caller,
11005 struct bpf_func_state *callee,
11006 int insn_idx)
11007 {
11008 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11009
11010 /*
11011 * callback_fn(struct bpf_map *map, void *key, void *value);
11012 */
11013 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11014 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11015 callee->regs[BPF_REG_1].map_ptr = map_ptr;
11016
11017 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11018 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11019 callee->regs[BPF_REG_2].map_ptr = map_ptr;
11020
11021 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11022 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11023 callee->regs[BPF_REG_3].map_ptr = map_ptr;
11024
11025 /* unused */
11026 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11027 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11028 callee->in_async_callback_fn = true;
11029 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11030 return 0;
11031 }
11032
11033 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11034
11035 /* Are we currently verifying the callback for a rbtree helper that must
11036 * be called with lock held? If so, no need to complain about unreleased
11037 * lock
11038 */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)11039 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11040 {
11041 struct bpf_verifier_state *state = env->cur_state;
11042 struct bpf_insn *insn = env->prog->insnsi;
11043 struct bpf_func_state *callee;
11044 int kfunc_btf_id;
11045
11046 if (!state->curframe)
11047 return false;
11048
11049 callee = state->frame[state->curframe];
11050
11051 if (!callee->in_callback_fn)
11052 return false;
11053
11054 kfunc_btf_id = insn[callee->callsite].imm;
11055 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
11056 }
11057
retval_range_within(struct bpf_retval_range range,const struct bpf_reg_state * reg,bool return_32bit)11058 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
11059 bool return_32bit)
11060 {
11061 if (return_32bit)
11062 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
11063 else
11064 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
11065 }
11066
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)11067 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11068 {
11069 struct bpf_verifier_state *state = env->cur_state, *prev_st;
11070 struct bpf_func_state *caller, *callee;
11071 struct bpf_reg_state *r0;
11072 bool in_callback_fn;
11073 int err;
11074
11075 err = bpf_update_live_stack(env);
11076 if (err)
11077 return err;
11078
11079 callee = state->frame[state->curframe];
11080 r0 = &callee->regs[BPF_REG_0];
11081 if (r0->type == PTR_TO_STACK) {
11082 /* technically it's ok to return caller's stack pointer
11083 * (or caller's caller's pointer) back to the caller,
11084 * since these pointers are valid. Only current stack
11085 * pointer will be invalid as soon as function exits,
11086 * but let's be conservative
11087 */
11088 verbose(env, "cannot return stack pointer to the caller\n");
11089 return -EINVAL;
11090 }
11091
11092 caller = state->frame[state->curframe - 1];
11093 if (callee->in_callback_fn) {
11094 if (r0->type != SCALAR_VALUE) {
11095 verbose(env, "R0 not a scalar value\n");
11096 return -EACCES;
11097 }
11098
11099 /* we are going to rely on register's precise value */
11100 err = mark_chain_precision(env, BPF_REG_0);
11101 if (err)
11102 return err;
11103
11104 /* enforce R0 return value range, and bpf_callback_t returns 64bit */
11105 if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11106 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11107 "At callback return", "R0");
11108 return -EINVAL;
11109 }
11110 if (!bpf_calls_callback(env, callee->callsite)) {
11111 verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11112 *insn_idx, callee->callsite);
11113 return -EFAULT;
11114 }
11115 } else {
11116 /* return to the caller whatever r0 had in the callee */
11117 caller->regs[BPF_REG_0] = *r0;
11118 }
11119
11120 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11121 * there function call logic would reschedule callback visit. If iteration
11122 * converges is_state_visited() would prune that visit eventually.
11123 */
11124 in_callback_fn = callee->in_callback_fn;
11125 if (in_callback_fn)
11126 *insn_idx = callee->callsite;
11127 else
11128 *insn_idx = callee->callsite + 1;
11129
11130 if (env->log.level & BPF_LOG_LEVEL) {
11131 verbose(env, "returning from callee:\n");
11132 print_verifier_state(env, state, callee->frameno, true);
11133 verbose(env, "to caller at %d:\n", *insn_idx);
11134 print_verifier_state(env, state, caller->frameno, true);
11135 }
11136 /* clear everything in the callee. In case of exceptional exits using
11137 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11138 free_func_state(callee);
11139 state->frame[state->curframe--] = NULL;
11140
11141 /* for callbacks widen imprecise scalars to make programs like below verify:
11142 *
11143 * struct ctx { int i; }
11144 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11145 * ...
11146 * struct ctx = { .i = 0; }
11147 * bpf_loop(100, cb, &ctx, 0);
11148 *
11149 * This is similar to what is done in process_iter_next_call() for open
11150 * coded iterators.
11151 */
11152 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11153 if (prev_st) {
11154 err = widen_imprecise_scalars(env, prev_st, state);
11155 if (err)
11156 return err;
11157 }
11158 return 0;
11159 }
11160
do_refine_retval_range(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)11161 static int do_refine_retval_range(struct bpf_verifier_env *env,
11162 struct bpf_reg_state *regs, int ret_type,
11163 int func_id,
11164 struct bpf_call_arg_meta *meta)
11165 {
11166 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
11167
11168 if (ret_type != RET_INTEGER)
11169 return 0;
11170
11171 switch (func_id) {
11172 case BPF_FUNC_get_stack:
11173 case BPF_FUNC_get_task_stack:
11174 case BPF_FUNC_probe_read_str:
11175 case BPF_FUNC_probe_read_kernel_str:
11176 case BPF_FUNC_probe_read_user_str:
11177 ret_reg->smax_value = meta->msize_max_value;
11178 ret_reg->s32_max_value = meta->msize_max_value;
11179 ret_reg->smin_value = -MAX_ERRNO;
11180 ret_reg->s32_min_value = -MAX_ERRNO;
11181 reg_bounds_sync(ret_reg);
11182 break;
11183 case BPF_FUNC_get_smp_processor_id:
11184 ret_reg->umax_value = nr_cpu_ids - 1;
11185 ret_reg->u32_max_value = nr_cpu_ids - 1;
11186 ret_reg->smax_value = nr_cpu_ids - 1;
11187 ret_reg->s32_max_value = nr_cpu_ids - 1;
11188 ret_reg->umin_value = 0;
11189 ret_reg->u32_min_value = 0;
11190 ret_reg->smin_value = 0;
11191 ret_reg->s32_min_value = 0;
11192 reg_bounds_sync(ret_reg);
11193 break;
11194 }
11195
11196 return reg_bounds_sanity_check(env, ret_reg, "retval");
11197 }
11198
11199 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11200 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11201 int func_id, int insn_idx)
11202 {
11203 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11204 struct bpf_map *map = meta->map_ptr;
11205
11206 if (func_id != BPF_FUNC_tail_call &&
11207 func_id != BPF_FUNC_map_lookup_elem &&
11208 func_id != BPF_FUNC_map_update_elem &&
11209 func_id != BPF_FUNC_map_delete_elem &&
11210 func_id != BPF_FUNC_map_push_elem &&
11211 func_id != BPF_FUNC_map_pop_elem &&
11212 func_id != BPF_FUNC_map_peek_elem &&
11213 func_id != BPF_FUNC_for_each_map_elem &&
11214 func_id != BPF_FUNC_redirect_map &&
11215 func_id != BPF_FUNC_map_lookup_percpu_elem)
11216 return 0;
11217
11218 if (map == NULL) {
11219 verifier_bug(env, "expected map for helper call");
11220 return -EFAULT;
11221 }
11222
11223 /* In case of read-only, some additional restrictions
11224 * need to be applied in order to prevent altering the
11225 * state of the map from program side.
11226 */
11227 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11228 (func_id == BPF_FUNC_map_delete_elem ||
11229 func_id == BPF_FUNC_map_update_elem ||
11230 func_id == BPF_FUNC_map_push_elem ||
11231 func_id == BPF_FUNC_map_pop_elem)) {
11232 verbose(env, "write into map forbidden\n");
11233 return -EACCES;
11234 }
11235
11236 if (!aux->map_ptr_state.map_ptr)
11237 bpf_map_ptr_store(aux, meta->map_ptr,
11238 !meta->map_ptr->bypass_spec_v1, false);
11239 else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11240 bpf_map_ptr_store(aux, meta->map_ptr,
11241 !meta->map_ptr->bypass_spec_v1, true);
11242 return 0;
11243 }
11244
11245 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11246 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11247 int func_id, int insn_idx)
11248 {
11249 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11250 struct bpf_reg_state *regs = cur_regs(env), *reg;
11251 struct bpf_map *map = meta->map_ptr;
11252 u64 val, max;
11253 int err;
11254
11255 if (func_id != BPF_FUNC_tail_call)
11256 return 0;
11257 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11258 verbose(env, "expected prog array map for tail call");
11259 return -EINVAL;
11260 }
11261
11262 reg = ®s[BPF_REG_3];
11263 val = reg->var_off.value;
11264 max = map->max_entries;
11265
11266 if (!(is_reg_const(reg, false) && val < max)) {
11267 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11268 return 0;
11269 }
11270
11271 err = mark_chain_precision(env, BPF_REG_3);
11272 if (err)
11273 return err;
11274 if (bpf_map_key_unseen(aux))
11275 bpf_map_key_store(aux, val);
11276 else if (!bpf_map_key_poisoned(aux) &&
11277 bpf_map_key_immediate(aux) != val)
11278 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11279 return 0;
11280 }
11281
check_reference_leak(struct bpf_verifier_env * env,bool exception_exit)11282 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11283 {
11284 struct bpf_verifier_state *state = env->cur_state;
11285 enum bpf_prog_type type = resolve_prog_type(env->prog);
11286 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11287 bool refs_lingering = false;
11288 int i;
11289
11290 if (!exception_exit && cur_func(env)->frameno)
11291 return 0;
11292
11293 for (i = 0; i < state->acquired_refs; i++) {
11294 if (state->refs[i].type != REF_TYPE_PTR)
11295 continue;
11296 /* Allow struct_ops programs to return a referenced kptr back to
11297 * kernel. Type checks are performed later in check_return_code.
11298 */
11299 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11300 reg->ref_obj_id == state->refs[i].id)
11301 continue;
11302 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11303 state->refs[i].id, state->refs[i].insn_idx);
11304 refs_lingering = true;
11305 }
11306 return refs_lingering ? -EINVAL : 0;
11307 }
11308
check_resource_leak(struct bpf_verifier_env * env,bool exception_exit,bool check_lock,const char * prefix)11309 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11310 {
11311 int err;
11312
11313 if (check_lock && env->cur_state->active_locks) {
11314 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11315 return -EINVAL;
11316 }
11317
11318 err = check_reference_leak(env, exception_exit);
11319 if (err) {
11320 verbose(env, "%s would lead to reference leak\n", prefix);
11321 return err;
11322 }
11323
11324 if (check_lock && env->cur_state->active_irq_id) {
11325 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11326 return -EINVAL;
11327 }
11328
11329 if (check_lock && env->cur_state->active_rcu_locks) {
11330 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11331 return -EINVAL;
11332 }
11333
11334 if (check_lock && env->cur_state->active_preempt_locks) {
11335 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11336 return -EINVAL;
11337 }
11338
11339 return 0;
11340 }
11341
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)11342 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11343 struct bpf_reg_state *regs)
11344 {
11345 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
11346 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
11347 struct bpf_map *fmt_map = fmt_reg->map_ptr;
11348 struct bpf_bprintf_data data = {};
11349 int err, fmt_map_off, num_args;
11350 u64 fmt_addr;
11351 char *fmt;
11352
11353 /* data must be an array of u64 */
11354 if (data_len_reg->var_off.value % 8)
11355 return -EINVAL;
11356 num_args = data_len_reg->var_off.value / 8;
11357
11358 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11359 * and map_direct_value_addr is set.
11360 */
11361 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11362 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11363 fmt_map_off);
11364 if (err) {
11365 verbose(env, "failed to retrieve map value address\n");
11366 return -EFAULT;
11367 }
11368 fmt = (char *)(long)fmt_addr + fmt_map_off;
11369
11370 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11371 * can focus on validating the format specifiers.
11372 */
11373 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11374 if (err < 0)
11375 verbose(env, "Invalid format string\n");
11376
11377 return err;
11378 }
11379
check_get_func_ip(struct bpf_verifier_env * env)11380 static int check_get_func_ip(struct bpf_verifier_env *env)
11381 {
11382 enum bpf_prog_type type = resolve_prog_type(env->prog);
11383 int func_id = BPF_FUNC_get_func_ip;
11384
11385 if (type == BPF_PROG_TYPE_TRACING) {
11386 if (!bpf_prog_has_trampoline(env->prog)) {
11387 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11388 func_id_name(func_id), func_id);
11389 return -ENOTSUPP;
11390 }
11391 return 0;
11392 } else if (type == BPF_PROG_TYPE_KPROBE) {
11393 return 0;
11394 }
11395
11396 verbose(env, "func %s#%d not supported for program type %d\n",
11397 func_id_name(func_id), func_id, type);
11398 return -ENOTSUPP;
11399 }
11400
cur_aux(const struct bpf_verifier_env * env)11401 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11402 {
11403 return &env->insn_aux_data[env->insn_idx];
11404 }
11405
loop_flag_is_zero(struct bpf_verifier_env * env)11406 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11407 {
11408 struct bpf_reg_state *regs = cur_regs(env);
11409 struct bpf_reg_state *reg = ®s[BPF_REG_4];
11410 bool reg_is_null = register_is_null(reg);
11411
11412 if (reg_is_null)
11413 mark_chain_precision(env, BPF_REG_4);
11414
11415 return reg_is_null;
11416 }
11417
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)11418 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11419 {
11420 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11421
11422 if (!state->initialized) {
11423 state->initialized = 1;
11424 state->fit_for_inline = loop_flag_is_zero(env);
11425 state->callback_subprogno = subprogno;
11426 return;
11427 }
11428
11429 if (!state->fit_for_inline)
11430 return;
11431
11432 state->fit_for_inline = (loop_flag_is_zero(env) &&
11433 state->callback_subprogno == subprogno);
11434 }
11435
11436 /* Returns whether or not the given map type can potentially elide
11437 * lookup return value nullness check. This is possible if the key
11438 * is statically known.
11439 */
can_elide_value_nullness(enum bpf_map_type type)11440 static bool can_elide_value_nullness(enum bpf_map_type type)
11441 {
11442 switch (type) {
11443 case BPF_MAP_TYPE_ARRAY:
11444 case BPF_MAP_TYPE_PERCPU_ARRAY:
11445 return true;
11446 default:
11447 return false;
11448 }
11449 }
11450
get_helper_proto(struct bpf_verifier_env * env,int func_id,const struct bpf_func_proto ** ptr)11451 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11452 const struct bpf_func_proto **ptr)
11453 {
11454 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11455 return -ERANGE;
11456
11457 if (!env->ops->get_func_proto)
11458 return -EINVAL;
11459
11460 *ptr = env->ops->get_func_proto(func_id, env->prog);
11461 return *ptr && (*ptr)->func ? 0 : -EINVAL;
11462 }
11463
11464 /* Check if we're in a sleepable context. */
in_sleepable_context(struct bpf_verifier_env * env)11465 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
11466 {
11467 return !env->cur_state->active_rcu_locks &&
11468 !env->cur_state->active_preempt_locks &&
11469 !env->cur_state->active_irq_id &&
11470 in_sleepable(env);
11471 }
11472
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11473 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11474 int *insn_idx_p)
11475 {
11476 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11477 bool returns_cpu_specific_alloc_ptr = false;
11478 const struct bpf_func_proto *fn = NULL;
11479 enum bpf_return_type ret_type;
11480 enum bpf_type_flag ret_flag;
11481 struct bpf_reg_state *regs;
11482 struct bpf_call_arg_meta meta;
11483 int insn_idx = *insn_idx_p;
11484 bool changes_data;
11485 int i, err, func_id;
11486
11487 /* find function prototype */
11488 func_id = insn->imm;
11489 err = get_helper_proto(env, insn->imm, &fn);
11490 if (err == -ERANGE) {
11491 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11492 return -EINVAL;
11493 }
11494
11495 if (err) {
11496 verbose(env, "program of this type cannot use helper %s#%d\n",
11497 func_id_name(func_id), func_id);
11498 return err;
11499 }
11500
11501 /* eBPF programs must be GPL compatible to use GPL-ed functions */
11502 if (!env->prog->gpl_compatible && fn->gpl_only) {
11503 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11504 return -EINVAL;
11505 }
11506
11507 if (fn->allowed && !fn->allowed(env->prog)) {
11508 verbose(env, "helper call is not allowed in probe\n");
11509 return -EINVAL;
11510 }
11511
11512 if (!in_sleepable(env) && fn->might_sleep) {
11513 verbose(env, "helper call might sleep in a non-sleepable prog\n");
11514 return -EINVAL;
11515 }
11516
11517 /* With LD_ABS/IND some JITs save/restore skb from r1. */
11518 changes_data = bpf_helper_changes_pkt_data(func_id);
11519 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11520 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11521 return -EFAULT;
11522 }
11523
11524 memset(&meta, 0, sizeof(meta));
11525 meta.pkt_access = fn->pkt_access;
11526
11527 err = check_func_proto(fn, func_id);
11528 if (err) {
11529 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11530 return err;
11531 }
11532
11533 if (env->cur_state->active_rcu_locks) {
11534 if (fn->might_sleep) {
11535 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11536 func_id_name(func_id), func_id);
11537 return -EINVAL;
11538 }
11539 }
11540
11541 if (env->cur_state->active_preempt_locks) {
11542 if (fn->might_sleep) {
11543 verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11544 func_id_name(func_id), func_id);
11545 return -EINVAL;
11546 }
11547 }
11548
11549 if (env->cur_state->active_irq_id) {
11550 if (fn->might_sleep) {
11551 verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11552 func_id_name(func_id), func_id);
11553 return -EINVAL;
11554 }
11555 }
11556
11557 /* Track non-sleepable context for helpers. */
11558 if (!in_sleepable_context(env))
11559 env->insn_aux_data[insn_idx].non_sleepable = true;
11560
11561 meta.func_id = func_id;
11562 /* check args */
11563 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11564 err = check_func_arg(env, i, &meta, fn, insn_idx);
11565 if (err)
11566 return err;
11567 }
11568
11569 err = record_func_map(env, &meta, func_id, insn_idx);
11570 if (err)
11571 return err;
11572
11573 err = record_func_key(env, &meta, func_id, insn_idx);
11574 if (err)
11575 return err;
11576
11577 /* Mark slots with STACK_MISC in case of raw mode, stack offset
11578 * is inferred from register state.
11579 */
11580 for (i = 0; i < meta.access_size; i++) {
11581 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11582 BPF_WRITE, -1, false, false);
11583 if (err)
11584 return err;
11585 }
11586
11587 regs = cur_regs(env);
11588
11589 if (meta.release_regno) {
11590 err = -EINVAL;
11591 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11592 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
11593 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11594 u32 ref_obj_id = meta.ref_obj_id;
11595 bool in_rcu = in_rcu_cs(env);
11596 struct bpf_func_state *state;
11597 struct bpf_reg_state *reg;
11598
11599 err = release_reference_nomark(env->cur_state, ref_obj_id);
11600 if (!err) {
11601 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11602 if (reg->ref_obj_id == ref_obj_id) {
11603 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11604 reg->ref_obj_id = 0;
11605 reg->type &= ~MEM_ALLOC;
11606 reg->type |= MEM_RCU;
11607 } else {
11608 mark_reg_invalid(env, reg);
11609 }
11610 }
11611 }));
11612 }
11613 } else if (meta.ref_obj_id) {
11614 err = release_reference(env, meta.ref_obj_id);
11615 } else if (register_is_null(®s[meta.release_regno])) {
11616 /* meta.ref_obj_id can only be 0 if register that is meant to be
11617 * released is NULL, which must be > R0.
11618 */
11619 err = 0;
11620 }
11621 if (err) {
11622 verbose(env, "func %s#%d reference has not been acquired before\n",
11623 func_id_name(func_id), func_id);
11624 return err;
11625 }
11626 }
11627
11628 switch (func_id) {
11629 case BPF_FUNC_tail_call:
11630 err = check_resource_leak(env, false, true, "tail_call");
11631 if (err)
11632 return err;
11633 break;
11634 case BPF_FUNC_get_local_storage:
11635 /* check that flags argument in get_local_storage(map, flags) is 0,
11636 * this is required because get_local_storage() can't return an error.
11637 */
11638 if (!register_is_null(®s[BPF_REG_2])) {
11639 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11640 return -EINVAL;
11641 }
11642 break;
11643 case BPF_FUNC_for_each_map_elem:
11644 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11645 set_map_elem_callback_state);
11646 break;
11647 case BPF_FUNC_timer_set_callback:
11648 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11649 set_timer_callback_state);
11650 break;
11651 case BPF_FUNC_find_vma:
11652 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11653 set_find_vma_callback_state);
11654 break;
11655 case BPF_FUNC_snprintf:
11656 err = check_bpf_snprintf_call(env, regs);
11657 break;
11658 case BPF_FUNC_loop:
11659 update_loop_inline_state(env, meta.subprogno);
11660 /* Verifier relies on R1 value to determine if bpf_loop() iteration
11661 * is finished, thus mark it precise.
11662 */
11663 err = mark_chain_precision(env, BPF_REG_1);
11664 if (err)
11665 return err;
11666 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11667 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11668 set_loop_callback_state);
11669 } else {
11670 cur_func(env)->callback_depth = 0;
11671 if (env->log.level & BPF_LOG_LEVEL2)
11672 verbose(env, "frame%d bpf_loop iteration limit reached\n",
11673 env->cur_state->curframe);
11674 }
11675 break;
11676 case BPF_FUNC_dynptr_from_mem:
11677 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11678 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11679 reg_type_str(env, regs[BPF_REG_1].type));
11680 return -EACCES;
11681 }
11682 break;
11683 case BPF_FUNC_set_retval:
11684 if (prog_type == BPF_PROG_TYPE_LSM &&
11685 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11686 if (!env->prog->aux->attach_func_proto->type) {
11687 /* Make sure programs that attach to void
11688 * hooks don't try to modify return value.
11689 */
11690 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11691 return -EINVAL;
11692 }
11693 }
11694 break;
11695 case BPF_FUNC_dynptr_data:
11696 {
11697 struct bpf_reg_state *reg;
11698 int id, ref_obj_id;
11699
11700 reg = get_dynptr_arg_reg(env, fn, regs);
11701 if (!reg)
11702 return -EFAULT;
11703
11704
11705 if (meta.dynptr_id) {
11706 verifier_bug(env, "meta.dynptr_id already set");
11707 return -EFAULT;
11708 }
11709 if (meta.ref_obj_id) {
11710 verifier_bug(env, "meta.ref_obj_id already set");
11711 return -EFAULT;
11712 }
11713
11714 id = dynptr_id(env, reg);
11715 if (id < 0) {
11716 verifier_bug(env, "failed to obtain dynptr id");
11717 return id;
11718 }
11719
11720 ref_obj_id = dynptr_ref_obj_id(env, reg);
11721 if (ref_obj_id < 0) {
11722 verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11723 return ref_obj_id;
11724 }
11725
11726 meta.dynptr_id = id;
11727 meta.ref_obj_id = ref_obj_id;
11728
11729 break;
11730 }
11731 case BPF_FUNC_dynptr_write:
11732 {
11733 enum bpf_dynptr_type dynptr_type;
11734 struct bpf_reg_state *reg;
11735
11736 reg = get_dynptr_arg_reg(env, fn, regs);
11737 if (!reg)
11738 return -EFAULT;
11739
11740 dynptr_type = dynptr_get_type(env, reg);
11741 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11742 return -EFAULT;
11743
11744 if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11745 dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11746 /* this will trigger clear_all_pkt_pointers(), which will
11747 * invalidate all dynptr slices associated with the skb
11748 */
11749 changes_data = true;
11750
11751 break;
11752 }
11753 case BPF_FUNC_per_cpu_ptr:
11754 case BPF_FUNC_this_cpu_ptr:
11755 {
11756 struct bpf_reg_state *reg = ®s[BPF_REG_1];
11757 const struct btf_type *type;
11758
11759 if (reg->type & MEM_RCU) {
11760 type = btf_type_by_id(reg->btf, reg->btf_id);
11761 if (!type || !btf_type_is_struct(type)) {
11762 verbose(env, "Helper has invalid btf/btf_id in R1\n");
11763 return -EFAULT;
11764 }
11765 returns_cpu_specific_alloc_ptr = true;
11766 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11767 }
11768 break;
11769 }
11770 case BPF_FUNC_user_ringbuf_drain:
11771 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11772 set_user_ringbuf_callback_state);
11773 break;
11774 }
11775
11776 if (err)
11777 return err;
11778
11779 /* reset caller saved regs */
11780 for (i = 0; i < CALLER_SAVED_REGS; i++) {
11781 mark_reg_not_init(env, regs, caller_saved[i]);
11782 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11783 }
11784
11785 /* helper call returns 64-bit value. */
11786 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11787
11788 /* update return register (already marked as written above) */
11789 ret_type = fn->ret_type;
11790 ret_flag = type_flag(ret_type);
11791
11792 switch (base_type(ret_type)) {
11793 case RET_INTEGER:
11794 /* sets type to SCALAR_VALUE */
11795 mark_reg_unknown(env, regs, BPF_REG_0);
11796 break;
11797 case RET_VOID:
11798 regs[BPF_REG_0].type = NOT_INIT;
11799 break;
11800 case RET_PTR_TO_MAP_VALUE:
11801 /* There is no offset yet applied, variable or fixed */
11802 mark_reg_known_zero(env, regs, BPF_REG_0);
11803 /* remember map_ptr, so that check_map_access()
11804 * can check 'value_size' boundary of memory access
11805 * to map element returned from bpf_map_lookup_elem()
11806 */
11807 if (meta.map_ptr == NULL) {
11808 verifier_bug(env, "unexpected null map_ptr");
11809 return -EFAULT;
11810 }
11811
11812 if (func_id == BPF_FUNC_map_lookup_elem &&
11813 can_elide_value_nullness(meta.map_ptr->map_type) &&
11814 meta.const_map_key >= 0 &&
11815 meta.const_map_key < meta.map_ptr->max_entries)
11816 ret_flag &= ~PTR_MAYBE_NULL;
11817
11818 regs[BPF_REG_0].map_ptr = meta.map_ptr;
11819 regs[BPF_REG_0].map_uid = meta.map_uid;
11820 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11821 if (!type_may_be_null(ret_flag) &&
11822 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11823 regs[BPF_REG_0].id = ++env->id_gen;
11824 }
11825 break;
11826 case RET_PTR_TO_SOCKET:
11827 mark_reg_known_zero(env, regs, BPF_REG_0);
11828 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11829 break;
11830 case RET_PTR_TO_SOCK_COMMON:
11831 mark_reg_known_zero(env, regs, BPF_REG_0);
11832 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11833 break;
11834 case RET_PTR_TO_TCP_SOCK:
11835 mark_reg_known_zero(env, regs, BPF_REG_0);
11836 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11837 break;
11838 case RET_PTR_TO_MEM:
11839 mark_reg_known_zero(env, regs, BPF_REG_0);
11840 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11841 regs[BPF_REG_0].mem_size = meta.mem_size;
11842 break;
11843 case RET_PTR_TO_MEM_OR_BTF_ID:
11844 {
11845 const struct btf_type *t;
11846
11847 mark_reg_known_zero(env, regs, BPF_REG_0);
11848 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11849 if (!btf_type_is_struct(t)) {
11850 u32 tsize;
11851 const struct btf_type *ret;
11852 const char *tname;
11853
11854 /* resolve the type size of ksym. */
11855 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11856 if (IS_ERR(ret)) {
11857 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11858 verbose(env, "unable to resolve the size of type '%s': %ld\n",
11859 tname, PTR_ERR(ret));
11860 return -EINVAL;
11861 }
11862 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11863 regs[BPF_REG_0].mem_size = tsize;
11864 } else {
11865 if (returns_cpu_specific_alloc_ptr) {
11866 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11867 } else {
11868 /* MEM_RDONLY may be carried from ret_flag, but it
11869 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11870 * it will confuse the check of PTR_TO_BTF_ID in
11871 * check_mem_access().
11872 */
11873 ret_flag &= ~MEM_RDONLY;
11874 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11875 }
11876
11877 regs[BPF_REG_0].btf = meta.ret_btf;
11878 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11879 }
11880 break;
11881 }
11882 case RET_PTR_TO_BTF_ID:
11883 {
11884 struct btf *ret_btf;
11885 int ret_btf_id;
11886
11887 mark_reg_known_zero(env, regs, BPF_REG_0);
11888 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11889 if (func_id == BPF_FUNC_kptr_xchg) {
11890 ret_btf = meta.kptr_field->kptr.btf;
11891 ret_btf_id = meta.kptr_field->kptr.btf_id;
11892 if (!btf_is_kernel(ret_btf)) {
11893 regs[BPF_REG_0].type |= MEM_ALLOC;
11894 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11895 regs[BPF_REG_0].type |= MEM_PERCPU;
11896 }
11897 } else {
11898 if (fn->ret_btf_id == BPF_PTR_POISON) {
11899 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11900 func_id_name(func_id));
11901 return -EFAULT;
11902 }
11903 ret_btf = btf_vmlinux;
11904 ret_btf_id = *fn->ret_btf_id;
11905 }
11906 if (ret_btf_id == 0) {
11907 verbose(env, "invalid return type %u of func %s#%d\n",
11908 base_type(ret_type), func_id_name(func_id),
11909 func_id);
11910 return -EINVAL;
11911 }
11912 regs[BPF_REG_0].btf = ret_btf;
11913 regs[BPF_REG_0].btf_id = ret_btf_id;
11914 break;
11915 }
11916 default:
11917 verbose(env, "unknown return type %u of func %s#%d\n",
11918 base_type(ret_type), func_id_name(func_id), func_id);
11919 return -EINVAL;
11920 }
11921
11922 if (type_may_be_null(regs[BPF_REG_0].type))
11923 regs[BPF_REG_0].id = ++env->id_gen;
11924
11925 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11926 verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11927 func_id_name(func_id), func_id);
11928 return -EFAULT;
11929 }
11930
11931 if (is_dynptr_ref_function(func_id))
11932 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11933
11934 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11935 /* For release_reference() */
11936 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11937 } else if (is_acquire_function(func_id, meta.map_ptr)) {
11938 int id = acquire_reference(env, insn_idx);
11939
11940 if (id < 0)
11941 return id;
11942 /* For mark_ptr_or_null_reg() */
11943 regs[BPF_REG_0].id = id;
11944 /* For release_reference() */
11945 regs[BPF_REG_0].ref_obj_id = id;
11946 }
11947
11948 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11949 if (err)
11950 return err;
11951
11952 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11953 if (err)
11954 return err;
11955
11956 if ((func_id == BPF_FUNC_get_stack ||
11957 func_id == BPF_FUNC_get_task_stack) &&
11958 !env->prog->has_callchain_buf) {
11959 const char *err_str;
11960
11961 #ifdef CONFIG_PERF_EVENTS
11962 err = get_callchain_buffers(sysctl_perf_event_max_stack);
11963 err_str = "cannot get callchain buffer for func %s#%d\n";
11964 #else
11965 err = -ENOTSUPP;
11966 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11967 #endif
11968 if (err) {
11969 verbose(env, err_str, func_id_name(func_id), func_id);
11970 return err;
11971 }
11972
11973 env->prog->has_callchain_buf = true;
11974 }
11975
11976 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11977 env->prog->call_get_stack = true;
11978
11979 if (func_id == BPF_FUNC_get_func_ip) {
11980 if (check_get_func_ip(env))
11981 return -ENOTSUPP;
11982 env->prog->call_get_func_ip = true;
11983 }
11984
11985 if (func_id == BPF_FUNC_tail_call) {
11986 if (env->cur_state->curframe) {
11987 struct bpf_verifier_state *branch;
11988
11989 mark_reg_scratched(env, BPF_REG_0);
11990 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
11991 if (IS_ERR(branch))
11992 return PTR_ERR(branch);
11993 clear_all_pkt_pointers(env);
11994 mark_reg_unknown(env, regs, BPF_REG_0);
11995 err = prepare_func_exit(env, &env->insn_idx);
11996 if (err)
11997 return err;
11998 env->insn_idx--;
11999 } else {
12000 changes_data = false;
12001 }
12002 }
12003
12004 if (changes_data)
12005 clear_all_pkt_pointers(env);
12006 return 0;
12007 }
12008
12009 /* mark_btf_func_reg_size() is used when the reg size is determined by
12010 * the BTF func_proto's return value size and argument.
12011 */
__mark_btf_func_reg_size(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,size_t reg_size)12012 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
12013 u32 regno, size_t reg_size)
12014 {
12015 struct bpf_reg_state *reg = ®s[regno];
12016
12017 if (regno == BPF_REG_0) {
12018 /* Function return value */
12019 reg->subreg_def = reg_size == sizeof(u64) ?
12020 DEF_NOT_SUBREG : env->insn_idx + 1;
12021 } else if (reg_size == sizeof(u64)) {
12022 /* Function argument */
12023 mark_insn_zext(env, reg);
12024 }
12025 }
12026
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)12027 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
12028 size_t reg_size)
12029 {
12030 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
12031 }
12032
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)12033 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
12034 {
12035 return meta->kfunc_flags & KF_ACQUIRE;
12036 }
12037
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)12038 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
12039 {
12040 return meta->kfunc_flags & KF_RELEASE;
12041 }
12042
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)12043 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
12044 {
12045 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
12046 }
12047
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)12048 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
12049 {
12050 return meta->kfunc_flags & KF_SLEEPABLE;
12051 }
12052
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)12053 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
12054 {
12055 return meta->kfunc_flags & KF_DESTRUCTIVE;
12056 }
12057
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)12058 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
12059 {
12060 return meta->kfunc_flags & KF_RCU;
12061 }
12062
is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta * meta)12063 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
12064 {
12065 return meta->kfunc_flags & KF_RCU_PROTECTED;
12066 }
12067
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)12068 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12069 const struct btf_param *arg,
12070 const struct bpf_reg_state *reg)
12071 {
12072 const struct btf_type *t;
12073
12074 t = btf_type_skip_modifiers(btf, arg->type, NULL);
12075 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12076 return false;
12077
12078 return btf_param_match_suffix(btf, arg, "__sz");
12079 }
12080
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)12081 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12082 const struct btf_param *arg,
12083 const struct bpf_reg_state *reg)
12084 {
12085 const struct btf_type *t;
12086
12087 t = btf_type_skip_modifiers(btf, arg->type, NULL);
12088 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12089 return false;
12090
12091 return btf_param_match_suffix(btf, arg, "__szk");
12092 }
12093
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)12094 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
12095 {
12096 return btf_param_match_suffix(btf, arg, "__opt");
12097 }
12098
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)12099 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12100 {
12101 return btf_param_match_suffix(btf, arg, "__k");
12102 }
12103
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)12104 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12105 {
12106 return btf_param_match_suffix(btf, arg, "__ign");
12107 }
12108
is_kfunc_arg_map(const struct btf * btf,const struct btf_param * arg)12109 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12110 {
12111 return btf_param_match_suffix(btf, arg, "__map");
12112 }
12113
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)12114 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12115 {
12116 return btf_param_match_suffix(btf, arg, "__alloc");
12117 }
12118
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)12119 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12120 {
12121 return btf_param_match_suffix(btf, arg, "__uninit");
12122 }
12123
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)12124 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12125 {
12126 return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12127 }
12128
is_kfunc_arg_nullable(const struct btf * btf,const struct btf_param * arg)12129 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12130 {
12131 return btf_param_match_suffix(btf, arg, "__nullable");
12132 }
12133
is_kfunc_arg_const_str(const struct btf * btf,const struct btf_param * arg)12134 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12135 {
12136 return btf_param_match_suffix(btf, arg, "__str");
12137 }
12138
is_kfunc_arg_irq_flag(const struct btf * btf,const struct btf_param * arg)12139 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12140 {
12141 return btf_param_match_suffix(btf, arg, "__irq_flag");
12142 }
12143
is_kfunc_arg_prog(const struct btf * btf,const struct btf_param * arg)12144 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12145 {
12146 return btf_param_match_suffix(btf, arg, "__prog");
12147 }
12148
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)12149 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12150 const struct btf_param *arg,
12151 const char *name)
12152 {
12153 int len, target_len = strlen(name);
12154 const char *param_name;
12155
12156 param_name = btf_name_by_offset(btf, arg->name_off);
12157 if (str_is_empty(param_name))
12158 return false;
12159 len = strlen(param_name);
12160 if (len != target_len)
12161 return false;
12162 if (strcmp(param_name, name))
12163 return false;
12164
12165 return true;
12166 }
12167
12168 enum {
12169 KF_ARG_DYNPTR_ID,
12170 KF_ARG_LIST_HEAD_ID,
12171 KF_ARG_LIST_NODE_ID,
12172 KF_ARG_RB_ROOT_ID,
12173 KF_ARG_RB_NODE_ID,
12174 KF_ARG_WORKQUEUE_ID,
12175 KF_ARG_RES_SPIN_LOCK_ID,
12176 KF_ARG_TASK_WORK_ID,
12177 };
12178
12179 BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr)12180 BTF_ID(struct, bpf_dynptr)
12181 BTF_ID(struct, bpf_list_head)
12182 BTF_ID(struct, bpf_list_node)
12183 BTF_ID(struct, bpf_rb_root)
12184 BTF_ID(struct, bpf_rb_node)
12185 BTF_ID(struct, bpf_wq)
12186 BTF_ID(struct, bpf_res_spin_lock)
12187 BTF_ID(struct, bpf_task_work)
12188
12189 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12190 const struct btf_param *arg, int type)
12191 {
12192 const struct btf_type *t;
12193 u32 res_id;
12194
12195 t = btf_type_skip_modifiers(btf, arg->type, NULL);
12196 if (!t)
12197 return false;
12198 if (!btf_type_is_ptr(t))
12199 return false;
12200 t = btf_type_skip_modifiers(btf, t->type, &res_id);
12201 if (!t)
12202 return false;
12203 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12204 }
12205
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)12206 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12207 {
12208 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12209 }
12210
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)12211 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12212 {
12213 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12214 }
12215
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)12216 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12217 {
12218 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12219 }
12220
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)12221 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12222 {
12223 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12224 }
12225
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)12226 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12227 {
12228 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12229 }
12230
is_kfunc_arg_wq(const struct btf * btf,const struct btf_param * arg)12231 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12232 {
12233 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12234 }
12235
is_kfunc_arg_task_work(const struct btf * btf,const struct btf_param * arg)12236 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12237 {
12238 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12239 }
12240
is_kfunc_arg_res_spin_lock(const struct btf * btf,const struct btf_param * arg)12241 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12242 {
12243 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12244 }
12245
is_rbtree_node_type(const struct btf_type * t)12246 static bool is_rbtree_node_type(const struct btf_type *t)
12247 {
12248 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12249 }
12250
is_list_node_type(const struct btf_type * t)12251 static bool is_list_node_type(const struct btf_type *t)
12252 {
12253 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12254 }
12255
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)12256 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12257 const struct btf_param *arg)
12258 {
12259 const struct btf_type *t;
12260
12261 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12262 if (!t)
12263 return false;
12264
12265 return true;
12266 }
12267
12268 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
__btf_type_is_scalar_struct(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_type * t,int rec)12269 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12270 const struct btf *btf,
12271 const struct btf_type *t, int rec)
12272 {
12273 const struct btf_type *member_type;
12274 const struct btf_member *member;
12275 u32 i;
12276
12277 if (!btf_type_is_struct(t))
12278 return false;
12279
12280 for_each_member(i, t, member) {
12281 const struct btf_array *array;
12282
12283 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12284 if (btf_type_is_struct(member_type)) {
12285 if (rec >= 3) {
12286 verbose(env, "max struct nesting depth exceeded\n");
12287 return false;
12288 }
12289 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12290 return false;
12291 continue;
12292 }
12293 if (btf_type_is_array(member_type)) {
12294 array = btf_array(member_type);
12295 if (!array->nelems)
12296 return false;
12297 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12298 if (!btf_type_is_scalar(member_type))
12299 return false;
12300 continue;
12301 }
12302 if (!btf_type_is_scalar(member_type))
12303 return false;
12304 }
12305 return true;
12306 }
12307
12308 enum kfunc_ptr_arg_type {
12309 KF_ARG_PTR_TO_CTX,
12310 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
12311 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12312 KF_ARG_PTR_TO_DYNPTR,
12313 KF_ARG_PTR_TO_ITER,
12314 KF_ARG_PTR_TO_LIST_HEAD,
12315 KF_ARG_PTR_TO_LIST_NODE,
12316 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
12317 KF_ARG_PTR_TO_MEM,
12318 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
12319 KF_ARG_PTR_TO_CALLBACK,
12320 KF_ARG_PTR_TO_RB_ROOT,
12321 KF_ARG_PTR_TO_RB_NODE,
12322 KF_ARG_PTR_TO_NULL,
12323 KF_ARG_PTR_TO_CONST_STR,
12324 KF_ARG_PTR_TO_MAP,
12325 KF_ARG_PTR_TO_WORKQUEUE,
12326 KF_ARG_PTR_TO_IRQ_FLAG,
12327 KF_ARG_PTR_TO_RES_SPIN_LOCK,
12328 KF_ARG_PTR_TO_TASK_WORK,
12329 };
12330
12331 enum special_kfunc_type {
12332 KF_bpf_obj_new_impl,
12333 KF_bpf_obj_drop_impl,
12334 KF_bpf_refcount_acquire_impl,
12335 KF_bpf_list_push_front_impl,
12336 KF_bpf_list_push_back_impl,
12337 KF_bpf_list_pop_front,
12338 KF_bpf_list_pop_back,
12339 KF_bpf_list_front,
12340 KF_bpf_list_back,
12341 KF_bpf_cast_to_kern_ctx,
12342 KF_bpf_rdonly_cast,
12343 KF_bpf_rcu_read_lock,
12344 KF_bpf_rcu_read_unlock,
12345 KF_bpf_rbtree_remove,
12346 KF_bpf_rbtree_add_impl,
12347 KF_bpf_rbtree_first,
12348 KF_bpf_rbtree_root,
12349 KF_bpf_rbtree_left,
12350 KF_bpf_rbtree_right,
12351 KF_bpf_dynptr_from_skb,
12352 KF_bpf_dynptr_from_xdp,
12353 KF_bpf_dynptr_from_skb_meta,
12354 KF_bpf_xdp_pull_data,
12355 KF_bpf_dynptr_slice,
12356 KF_bpf_dynptr_slice_rdwr,
12357 KF_bpf_dynptr_clone,
12358 KF_bpf_percpu_obj_new_impl,
12359 KF_bpf_percpu_obj_drop_impl,
12360 KF_bpf_throw,
12361 KF_bpf_wq_set_callback_impl,
12362 KF_bpf_preempt_disable,
12363 KF_bpf_preempt_enable,
12364 KF_bpf_iter_css_task_new,
12365 KF_bpf_session_cookie,
12366 KF_bpf_get_kmem_cache,
12367 KF_bpf_local_irq_save,
12368 KF_bpf_local_irq_restore,
12369 KF_bpf_iter_num_new,
12370 KF_bpf_iter_num_next,
12371 KF_bpf_iter_num_destroy,
12372 KF_bpf_set_dentry_xattr,
12373 KF_bpf_remove_dentry_xattr,
12374 KF_bpf_res_spin_lock,
12375 KF_bpf_res_spin_unlock,
12376 KF_bpf_res_spin_lock_irqsave,
12377 KF_bpf_res_spin_unlock_irqrestore,
12378 KF_bpf_dynptr_from_file,
12379 KF_bpf_dynptr_file_discard,
12380 KF___bpf_trap,
12381 KF_bpf_task_work_schedule_signal_impl,
12382 KF_bpf_task_work_schedule_resume_impl,
12383 };
12384
12385 BTF_ID_LIST(special_kfunc_list)
BTF_ID(func,bpf_obj_new_impl)12386 BTF_ID(func, bpf_obj_new_impl)
12387 BTF_ID(func, bpf_obj_drop_impl)
12388 BTF_ID(func, bpf_refcount_acquire_impl)
12389 BTF_ID(func, bpf_list_push_front_impl)
12390 BTF_ID(func, bpf_list_push_back_impl)
12391 BTF_ID(func, bpf_list_pop_front)
12392 BTF_ID(func, bpf_list_pop_back)
12393 BTF_ID(func, bpf_list_front)
12394 BTF_ID(func, bpf_list_back)
12395 BTF_ID(func, bpf_cast_to_kern_ctx)
12396 BTF_ID(func, bpf_rdonly_cast)
12397 BTF_ID(func, bpf_rcu_read_lock)
12398 BTF_ID(func, bpf_rcu_read_unlock)
12399 BTF_ID(func, bpf_rbtree_remove)
12400 BTF_ID(func, bpf_rbtree_add_impl)
12401 BTF_ID(func, bpf_rbtree_first)
12402 BTF_ID(func, bpf_rbtree_root)
12403 BTF_ID(func, bpf_rbtree_left)
12404 BTF_ID(func, bpf_rbtree_right)
12405 #ifdef CONFIG_NET
12406 BTF_ID(func, bpf_dynptr_from_skb)
12407 BTF_ID(func, bpf_dynptr_from_xdp)
12408 BTF_ID(func, bpf_dynptr_from_skb_meta)
12409 BTF_ID(func, bpf_xdp_pull_data)
12410 #else
12411 BTF_ID_UNUSED
12412 BTF_ID_UNUSED
12413 BTF_ID_UNUSED
12414 BTF_ID_UNUSED
12415 #endif
12416 BTF_ID(func, bpf_dynptr_slice)
12417 BTF_ID(func, bpf_dynptr_slice_rdwr)
12418 BTF_ID(func, bpf_dynptr_clone)
12419 BTF_ID(func, bpf_percpu_obj_new_impl)
12420 BTF_ID(func, bpf_percpu_obj_drop_impl)
12421 BTF_ID(func, bpf_throw)
12422 BTF_ID(func, bpf_wq_set_callback_impl)
12423 BTF_ID(func, bpf_preempt_disable)
12424 BTF_ID(func, bpf_preempt_enable)
12425 #ifdef CONFIG_CGROUPS
12426 BTF_ID(func, bpf_iter_css_task_new)
12427 #else
12428 BTF_ID_UNUSED
12429 #endif
12430 #ifdef CONFIG_BPF_EVENTS
12431 BTF_ID(func, bpf_session_cookie)
12432 #else
12433 BTF_ID_UNUSED
12434 #endif
12435 BTF_ID(func, bpf_get_kmem_cache)
12436 BTF_ID(func, bpf_local_irq_save)
12437 BTF_ID(func, bpf_local_irq_restore)
12438 BTF_ID(func, bpf_iter_num_new)
12439 BTF_ID(func, bpf_iter_num_next)
12440 BTF_ID(func, bpf_iter_num_destroy)
12441 #ifdef CONFIG_BPF_LSM
12442 BTF_ID(func, bpf_set_dentry_xattr)
12443 BTF_ID(func, bpf_remove_dentry_xattr)
12444 #else
12445 BTF_ID_UNUSED
12446 BTF_ID_UNUSED
12447 #endif
12448 BTF_ID(func, bpf_res_spin_lock)
12449 BTF_ID(func, bpf_res_spin_unlock)
12450 BTF_ID(func, bpf_res_spin_lock_irqsave)
12451 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12452 BTF_ID(func, bpf_dynptr_from_file)
12453 BTF_ID(func, bpf_dynptr_file_discard)
12454 BTF_ID(func, __bpf_trap)
12455 BTF_ID(func, bpf_task_work_schedule_signal_impl)
12456 BTF_ID(func, bpf_task_work_schedule_resume_impl)
12457
12458 static bool is_task_work_add_kfunc(u32 func_id)
12459 {
12460 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal_impl] ||
12461 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume_impl];
12462 }
12463
is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta * meta)12464 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12465 {
12466 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12467 meta->arg_owning_ref) {
12468 return false;
12469 }
12470
12471 return meta->kfunc_flags & KF_RET_NULL;
12472 }
12473
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)12474 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12475 {
12476 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12477 }
12478
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)12479 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12480 {
12481 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12482 }
12483
is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta * meta)12484 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12485 {
12486 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12487 }
12488
is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta * meta)12489 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12490 {
12491 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12492 }
12493
is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta * meta)12494 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12495 {
12496 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12497 }
12498
12499 static enum kfunc_ptr_arg_type
get_kfunc_ptr_arg_type(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,const struct btf_type * t,const struct btf_type * ref_t,const char * ref_tname,const struct btf_param * args,int argno,int nargs)12500 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12501 struct bpf_kfunc_call_arg_meta *meta,
12502 const struct btf_type *t, const struct btf_type *ref_t,
12503 const char *ref_tname, const struct btf_param *args,
12504 int argno, int nargs)
12505 {
12506 u32 regno = argno + 1;
12507 struct bpf_reg_state *regs = cur_regs(env);
12508 struct bpf_reg_state *reg = ®s[regno];
12509 bool arg_mem_size = false;
12510
12511 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12512 return KF_ARG_PTR_TO_CTX;
12513
12514 /* In this function, we verify the kfunc's BTF as per the argument type,
12515 * leaving the rest of the verification with respect to the register
12516 * type to our caller. When a set of conditions hold in the BTF type of
12517 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12518 */
12519 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12520 return KF_ARG_PTR_TO_CTX;
12521
12522 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12523 return KF_ARG_PTR_TO_NULL;
12524
12525 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12526 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12527
12528 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12529 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12530
12531 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12532 return KF_ARG_PTR_TO_DYNPTR;
12533
12534 if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12535 return KF_ARG_PTR_TO_ITER;
12536
12537 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12538 return KF_ARG_PTR_TO_LIST_HEAD;
12539
12540 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12541 return KF_ARG_PTR_TO_LIST_NODE;
12542
12543 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12544 return KF_ARG_PTR_TO_RB_ROOT;
12545
12546 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12547 return KF_ARG_PTR_TO_RB_NODE;
12548
12549 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12550 return KF_ARG_PTR_TO_CONST_STR;
12551
12552 if (is_kfunc_arg_map(meta->btf, &args[argno]))
12553 return KF_ARG_PTR_TO_MAP;
12554
12555 if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12556 return KF_ARG_PTR_TO_WORKQUEUE;
12557
12558 if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12559 return KF_ARG_PTR_TO_TASK_WORK;
12560
12561 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12562 return KF_ARG_PTR_TO_IRQ_FLAG;
12563
12564 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12565 return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12566
12567 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12568 if (!btf_type_is_struct(ref_t)) {
12569 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12570 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12571 return -EINVAL;
12572 }
12573 return KF_ARG_PTR_TO_BTF_ID;
12574 }
12575
12576 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12577 return KF_ARG_PTR_TO_CALLBACK;
12578
12579 if (argno + 1 < nargs &&
12580 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
12581 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
12582 arg_mem_size = true;
12583
12584 /* This is the catch all argument type of register types supported by
12585 * check_helper_mem_access. However, we only allow when argument type is
12586 * pointer to scalar, or struct composed (recursively) of scalars. When
12587 * arg_mem_size is true, the pointer can be void *.
12588 */
12589 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12590 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12591 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12592 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12593 return -EINVAL;
12594 }
12595 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12596 }
12597
process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const struct btf_type * ref_t,const char * ref_tname,u32 ref_id,struct bpf_kfunc_call_arg_meta * meta,int argno)12598 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12599 struct bpf_reg_state *reg,
12600 const struct btf_type *ref_t,
12601 const char *ref_tname, u32 ref_id,
12602 struct bpf_kfunc_call_arg_meta *meta,
12603 int argno)
12604 {
12605 const struct btf_type *reg_ref_t;
12606 bool strict_type_match = false;
12607 const struct btf *reg_btf;
12608 const char *reg_ref_tname;
12609 bool taking_projection;
12610 bool struct_same;
12611 u32 reg_ref_id;
12612
12613 if (base_type(reg->type) == PTR_TO_BTF_ID) {
12614 reg_btf = reg->btf;
12615 reg_ref_id = reg->btf_id;
12616 } else {
12617 reg_btf = btf_vmlinux;
12618 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12619 }
12620
12621 /* Enforce strict type matching for calls to kfuncs that are acquiring
12622 * or releasing a reference, or are no-cast aliases. We do _not_
12623 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12624 * as we want to enable BPF programs to pass types that are bitwise
12625 * equivalent without forcing them to explicitly cast with something
12626 * like bpf_cast_to_kern_ctx().
12627 *
12628 * For example, say we had a type like the following:
12629 *
12630 * struct bpf_cpumask {
12631 * cpumask_t cpumask;
12632 * refcount_t usage;
12633 * };
12634 *
12635 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12636 * to a struct cpumask, so it would be safe to pass a struct
12637 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12638 *
12639 * The philosophy here is similar to how we allow scalars of different
12640 * types to be passed to kfuncs as long as the size is the same. The
12641 * only difference here is that we're simply allowing
12642 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12643 * resolve types.
12644 */
12645 if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12646 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12647 strict_type_match = true;
12648
12649 WARN_ON_ONCE(is_kfunc_release(meta) &&
12650 (reg->off || !tnum_is_const(reg->var_off) ||
12651 reg->var_off.value));
12652
12653 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
12654 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12655 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12656 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12657 * actually use it -- it must cast to the underlying type. So we allow
12658 * caller to pass in the underlying type.
12659 */
12660 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12661 if (!taking_projection && !struct_same) {
12662 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12663 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12664 btf_type_str(reg_ref_t), reg_ref_tname);
12665 return -EINVAL;
12666 }
12667 return 0;
12668 }
12669
process_irq_flag(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)12670 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12671 struct bpf_kfunc_call_arg_meta *meta)
12672 {
12673 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
12674 int err, kfunc_class = IRQ_NATIVE_KFUNC;
12675 bool irq_save;
12676
12677 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12678 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12679 irq_save = true;
12680 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12681 kfunc_class = IRQ_LOCK_KFUNC;
12682 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12683 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12684 irq_save = false;
12685 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12686 kfunc_class = IRQ_LOCK_KFUNC;
12687 } else {
12688 verifier_bug(env, "unknown irq flags kfunc");
12689 return -EFAULT;
12690 }
12691
12692 if (irq_save) {
12693 if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12694 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12695 return -EINVAL;
12696 }
12697
12698 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12699 if (err)
12700 return err;
12701
12702 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12703 if (err)
12704 return err;
12705 } else {
12706 err = is_irq_flag_reg_valid_init(env, reg);
12707 if (err) {
12708 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12709 return err;
12710 }
12711
12712 err = mark_irq_flag_read(env, reg);
12713 if (err)
12714 return err;
12715
12716 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12717 if (err)
12718 return err;
12719 }
12720 return 0;
12721 }
12722
12723
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12724 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12725 {
12726 struct btf_record *rec = reg_btf_record(reg);
12727
12728 if (!env->cur_state->active_locks) {
12729 verifier_bug(env, "%s w/o active lock", __func__);
12730 return -EFAULT;
12731 }
12732
12733 if (type_flag(reg->type) & NON_OWN_REF) {
12734 verifier_bug(env, "NON_OWN_REF already set");
12735 return -EFAULT;
12736 }
12737
12738 reg->type |= NON_OWN_REF;
12739 if (rec->refcount_off >= 0)
12740 reg->type |= MEM_RCU;
12741
12742 return 0;
12743 }
12744
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)12745 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12746 {
12747 struct bpf_verifier_state *state = env->cur_state;
12748 struct bpf_func_state *unused;
12749 struct bpf_reg_state *reg;
12750 int i;
12751
12752 if (!ref_obj_id) {
12753 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12754 return -EFAULT;
12755 }
12756
12757 for (i = 0; i < state->acquired_refs; i++) {
12758 if (state->refs[i].id != ref_obj_id)
12759 continue;
12760
12761 /* Clear ref_obj_id here so release_reference doesn't clobber
12762 * the whole reg
12763 */
12764 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12765 if (reg->ref_obj_id == ref_obj_id) {
12766 reg->ref_obj_id = 0;
12767 ref_set_non_owning(env, reg);
12768 }
12769 }));
12770 return 0;
12771 }
12772
12773 verifier_bug(env, "ref state missing for ref_obj_id");
12774 return -EFAULT;
12775 }
12776
12777 /* Implementation details:
12778 *
12779 * Each register points to some region of memory, which we define as an
12780 * allocation. Each allocation may embed a bpf_spin_lock which protects any
12781 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12782 * allocation. The lock and the data it protects are colocated in the same
12783 * memory region.
12784 *
12785 * Hence, everytime a register holds a pointer value pointing to such
12786 * allocation, the verifier preserves a unique reg->id for it.
12787 *
12788 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12789 * bpf_spin_lock is called.
12790 *
12791 * To enable this, lock state in the verifier captures two values:
12792 * active_lock.ptr = Register's type specific pointer
12793 * active_lock.id = A unique ID for each register pointer value
12794 *
12795 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12796 * supported register types.
12797 *
12798 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12799 * allocated objects is the reg->btf pointer.
12800 *
12801 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12802 * can establish the provenance of the map value statically for each distinct
12803 * lookup into such maps. They always contain a single map value hence unique
12804 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12805 *
12806 * So, in case of global variables, they use array maps with max_entries = 1,
12807 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12808 * into the same map value as max_entries is 1, as described above).
12809 *
12810 * In case of inner map lookups, the inner map pointer has same map_ptr as the
12811 * outer map pointer (in verifier context), but each lookup into an inner map
12812 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12813 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12814 * will get different reg->id assigned to each lookup, hence different
12815 * active_lock.id.
12816 *
12817 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12818 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12819 * returned from bpf_obj_new. Each allocation receives a new reg->id.
12820 */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12821 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12822 {
12823 struct bpf_reference_state *s;
12824 void *ptr;
12825 u32 id;
12826
12827 switch ((int)reg->type) {
12828 case PTR_TO_MAP_VALUE:
12829 ptr = reg->map_ptr;
12830 break;
12831 case PTR_TO_BTF_ID | MEM_ALLOC:
12832 ptr = reg->btf;
12833 break;
12834 default:
12835 verifier_bug(env, "unknown reg type for lock check");
12836 return -EFAULT;
12837 }
12838 id = reg->id;
12839
12840 if (!env->cur_state->active_locks)
12841 return -EINVAL;
12842 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12843 if (!s) {
12844 verbose(env, "held lock and object are not in the same allocation\n");
12845 return -EINVAL;
12846 }
12847 return 0;
12848 }
12849
is_bpf_list_api_kfunc(u32 btf_id)12850 static bool is_bpf_list_api_kfunc(u32 btf_id)
12851 {
12852 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12853 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12854 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12855 btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12856 btf_id == special_kfunc_list[KF_bpf_list_front] ||
12857 btf_id == special_kfunc_list[KF_bpf_list_back];
12858 }
12859
is_bpf_rbtree_api_kfunc(u32 btf_id)12860 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12861 {
12862 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12863 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12864 btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12865 btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12866 btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12867 btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12868 }
12869
is_bpf_iter_num_api_kfunc(u32 btf_id)12870 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12871 {
12872 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12873 btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12874 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12875 }
12876
is_bpf_graph_api_kfunc(u32 btf_id)12877 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12878 {
12879 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12880 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12881 }
12882
is_bpf_res_spin_lock_kfunc(u32 btf_id)12883 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12884 {
12885 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12886 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12887 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12888 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12889 }
12890
kfunc_spin_allowed(u32 btf_id)12891 static bool kfunc_spin_allowed(u32 btf_id)
12892 {
12893 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12894 is_bpf_res_spin_lock_kfunc(btf_id);
12895 }
12896
is_sync_callback_calling_kfunc(u32 btf_id)12897 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12898 {
12899 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12900 }
12901
is_async_callback_calling_kfunc(u32 btf_id)12902 static bool is_async_callback_calling_kfunc(u32 btf_id)
12903 {
12904 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12905 is_task_work_add_kfunc(btf_id);
12906 }
12907
is_bpf_throw_kfunc(struct bpf_insn * insn)12908 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12909 {
12910 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12911 insn->imm == special_kfunc_list[KF_bpf_throw];
12912 }
12913
is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)12914 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12915 {
12916 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12917 }
12918
is_callback_calling_kfunc(u32 btf_id)12919 static bool is_callback_calling_kfunc(u32 btf_id)
12920 {
12921 return is_sync_callback_calling_kfunc(btf_id) ||
12922 is_async_callback_calling_kfunc(btf_id);
12923 }
12924
is_rbtree_lock_required_kfunc(u32 btf_id)12925 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12926 {
12927 return is_bpf_rbtree_api_kfunc(btf_id);
12928 }
12929
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)12930 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12931 enum btf_field_type head_field_type,
12932 u32 kfunc_btf_id)
12933 {
12934 bool ret;
12935
12936 switch (head_field_type) {
12937 case BPF_LIST_HEAD:
12938 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12939 break;
12940 case BPF_RB_ROOT:
12941 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12942 break;
12943 default:
12944 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12945 btf_field_type_name(head_field_type));
12946 return false;
12947 }
12948
12949 if (!ret)
12950 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12951 btf_field_type_name(head_field_type));
12952 return ret;
12953 }
12954
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)12955 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12956 enum btf_field_type node_field_type,
12957 u32 kfunc_btf_id)
12958 {
12959 bool ret;
12960
12961 switch (node_field_type) {
12962 case BPF_LIST_NODE:
12963 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12964 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12965 break;
12966 case BPF_RB_NODE:
12967 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12968 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12969 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12970 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12971 break;
12972 default:
12973 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12974 btf_field_type_name(node_field_type));
12975 return false;
12976 }
12977
12978 if (!ret)
12979 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12980 btf_field_type_name(node_field_type));
12981 return ret;
12982 }
12983
12984 static int
__process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta,enum btf_field_type head_field_type,struct btf_field ** head_field)12985 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12986 struct bpf_reg_state *reg, u32 regno,
12987 struct bpf_kfunc_call_arg_meta *meta,
12988 enum btf_field_type head_field_type,
12989 struct btf_field **head_field)
12990 {
12991 const char *head_type_name;
12992 struct btf_field *field;
12993 struct btf_record *rec;
12994 u32 head_off;
12995
12996 if (meta->btf != btf_vmlinux) {
12997 verifier_bug(env, "unexpected btf mismatch in kfunc call");
12998 return -EFAULT;
12999 }
13000
13001 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
13002 return -EFAULT;
13003
13004 head_type_name = btf_field_type_name(head_field_type);
13005 if (!tnum_is_const(reg->var_off)) {
13006 verbose(env,
13007 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
13008 regno, head_type_name);
13009 return -EINVAL;
13010 }
13011
13012 rec = reg_btf_record(reg);
13013 head_off = reg->off + reg->var_off.value;
13014 field = btf_record_find(rec, head_off, head_field_type);
13015 if (!field) {
13016 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
13017 return -EINVAL;
13018 }
13019
13020 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
13021 if (check_reg_allocation_locked(env, reg)) {
13022 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
13023 rec->spin_lock_off, head_type_name);
13024 return -EINVAL;
13025 }
13026
13027 if (*head_field) {
13028 verifier_bug(env, "repeating %s arg", head_type_name);
13029 return -EFAULT;
13030 }
13031 *head_field = field;
13032 return 0;
13033 }
13034
process_kf_arg_ptr_to_list_head(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)13035 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
13036 struct bpf_reg_state *reg, u32 regno,
13037 struct bpf_kfunc_call_arg_meta *meta)
13038 {
13039 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
13040 &meta->arg_list_head.field);
13041 }
13042
process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)13043 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
13044 struct bpf_reg_state *reg, u32 regno,
13045 struct bpf_kfunc_call_arg_meta *meta)
13046 {
13047 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
13048 &meta->arg_rbtree_root.field);
13049 }
13050
13051 static int
__process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta,enum btf_field_type head_field_type,enum btf_field_type node_field_type,struct btf_field ** node_field)13052 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
13053 struct bpf_reg_state *reg, u32 regno,
13054 struct bpf_kfunc_call_arg_meta *meta,
13055 enum btf_field_type head_field_type,
13056 enum btf_field_type node_field_type,
13057 struct btf_field **node_field)
13058 {
13059 const char *node_type_name;
13060 const struct btf_type *et, *t;
13061 struct btf_field *field;
13062 u32 node_off;
13063
13064 if (meta->btf != btf_vmlinux) {
13065 verifier_bug(env, "unexpected btf mismatch in kfunc call");
13066 return -EFAULT;
13067 }
13068
13069 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
13070 return -EFAULT;
13071
13072 node_type_name = btf_field_type_name(node_field_type);
13073 if (!tnum_is_const(reg->var_off)) {
13074 verbose(env,
13075 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
13076 regno, node_type_name);
13077 return -EINVAL;
13078 }
13079
13080 node_off = reg->off + reg->var_off.value;
13081 field = reg_find_field_offset(reg, node_off, node_field_type);
13082 if (!field) {
13083 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
13084 return -EINVAL;
13085 }
13086
13087 field = *node_field;
13088
13089 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
13090 t = btf_type_by_id(reg->btf, reg->btf_id);
13091 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
13092 field->graph_root.value_btf_id, true)) {
13093 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
13094 "in struct %s, but arg is at offset=%d in struct %s\n",
13095 btf_field_type_name(head_field_type),
13096 btf_field_type_name(node_field_type),
13097 field->graph_root.node_offset,
13098 btf_name_by_offset(field->graph_root.btf, et->name_off),
13099 node_off, btf_name_by_offset(reg->btf, t->name_off));
13100 return -EINVAL;
13101 }
13102 meta->arg_btf = reg->btf;
13103 meta->arg_btf_id = reg->btf_id;
13104
13105 if (node_off != field->graph_root.node_offset) {
13106 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
13107 node_off, btf_field_type_name(node_field_type),
13108 field->graph_root.node_offset,
13109 btf_name_by_offset(field->graph_root.btf, et->name_off));
13110 return -EINVAL;
13111 }
13112
13113 return 0;
13114 }
13115
process_kf_arg_ptr_to_list_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)13116 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
13117 struct bpf_reg_state *reg, u32 regno,
13118 struct bpf_kfunc_call_arg_meta *meta)
13119 {
13120 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13121 BPF_LIST_HEAD, BPF_LIST_NODE,
13122 &meta->arg_list_head.field);
13123 }
13124
process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)13125 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13126 struct bpf_reg_state *reg, u32 regno,
13127 struct bpf_kfunc_call_arg_meta *meta)
13128 {
13129 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13130 BPF_RB_ROOT, BPF_RB_NODE,
13131 &meta->arg_rbtree_root.field);
13132 }
13133
13134 /*
13135 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13136 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13137 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13138 * them can only be attached to some specific hook points.
13139 */
check_css_task_iter_allowlist(struct bpf_verifier_env * env)13140 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13141 {
13142 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13143
13144 switch (prog_type) {
13145 case BPF_PROG_TYPE_LSM:
13146 return true;
13147 case BPF_PROG_TYPE_TRACING:
13148 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13149 return true;
13150 fallthrough;
13151 default:
13152 return in_sleepable(env);
13153 }
13154 }
13155
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)13156 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13157 int insn_idx)
13158 {
13159 const char *func_name = meta->func_name, *ref_tname;
13160 const struct btf *btf = meta->btf;
13161 const struct btf_param *args;
13162 struct btf_record *rec;
13163 u32 i, nargs;
13164 int ret;
13165
13166 args = (const struct btf_param *)(meta->func_proto + 1);
13167 nargs = btf_type_vlen(meta->func_proto);
13168 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13169 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13170 MAX_BPF_FUNC_REG_ARGS);
13171 return -EINVAL;
13172 }
13173
13174 /* Check that BTF function arguments match actual types that the
13175 * verifier sees.
13176 */
13177 for (i = 0; i < nargs; i++) {
13178 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
13179 const struct btf_type *t, *ref_t, *resolve_ret;
13180 enum bpf_arg_type arg_type = ARG_DONTCARE;
13181 u32 regno = i + 1, ref_id, type_size;
13182 bool is_ret_buf_sz = false;
13183 int kf_arg_type;
13184
13185 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13186
13187 if (is_kfunc_arg_ignore(btf, &args[i]))
13188 continue;
13189
13190 if (is_kfunc_arg_prog(btf, &args[i])) {
13191 /* Used to reject repeated use of __prog. */
13192 if (meta->arg_prog) {
13193 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13194 return -EFAULT;
13195 }
13196 meta->arg_prog = true;
13197 cur_aux(env)->arg_prog = regno;
13198 continue;
13199 }
13200
13201 if (btf_type_is_scalar(t)) {
13202 if (reg->type != SCALAR_VALUE) {
13203 verbose(env, "R%d is not a scalar\n", regno);
13204 return -EINVAL;
13205 }
13206
13207 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13208 if (meta->arg_constant.found) {
13209 verifier_bug(env, "only one constant argument permitted");
13210 return -EFAULT;
13211 }
13212 if (!tnum_is_const(reg->var_off)) {
13213 verbose(env, "R%d must be a known constant\n", regno);
13214 return -EINVAL;
13215 }
13216 ret = mark_chain_precision(env, regno);
13217 if (ret < 0)
13218 return ret;
13219 meta->arg_constant.found = true;
13220 meta->arg_constant.value = reg->var_off.value;
13221 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13222 meta->r0_rdonly = true;
13223 is_ret_buf_sz = true;
13224 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13225 is_ret_buf_sz = true;
13226 }
13227
13228 if (is_ret_buf_sz) {
13229 if (meta->r0_size) {
13230 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13231 return -EINVAL;
13232 }
13233
13234 if (!tnum_is_const(reg->var_off)) {
13235 verbose(env, "R%d is not a const\n", regno);
13236 return -EINVAL;
13237 }
13238
13239 meta->r0_size = reg->var_off.value;
13240 ret = mark_chain_precision(env, regno);
13241 if (ret)
13242 return ret;
13243 }
13244 continue;
13245 }
13246
13247 if (!btf_type_is_ptr(t)) {
13248 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13249 return -EINVAL;
13250 }
13251
13252 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13253 (register_is_null(reg) || type_may_be_null(reg->type)) &&
13254 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
13255 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13256 return -EACCES;
13257 }
13258
13259 if (reg->ref_obj_id) {
13260 if (is_kfunc_release(meta) && meta->ref_obj_id) {
13261 verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13262 regno, reg->ref_obj_id,
13263 meta->ref_obj_id);
13264 return -EFAULT;
13265 }
13266 meta->ref_obj_id = reg->ref_obj_id;
13267 if (is_kfunc_release(meta))
13268 meta->release_regno = regno;
13269 }
13270
13271 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13272 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13273
13274 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13275 if (kf_arg_type < 0)
13276 return kf_arg_type;
13277
13278 switch (kf_arg_type) {
13279 case KF_ARG_PTR_TO_NULL:
13280 continue;
13281 case KF_ARG_PTR_TO_MAP:
13282 if (!reg->map_ptr) {
13283 verbose(env, "pointer in R%d isn't map pointer\n", regno);
13284 return -EINVAL;
13285 }
13286 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13287 reg->map_ptr->record->task_work_off >= 0)) {
13288 /* Use map_uid (which is unique id of inner map) to reject:
13289 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13290 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13291 * if (inner_map1 && inner_map2) {
13292 * wq = bpf_map_lookup_elem(inner_map1);
13293 * if (wq)
13294 * // mismatch would have been allowed
13295 * bpf_wq_init(wq, inner_map2);
13296 * }
13297 *
13298 * Comparing map_ptr is enough to distinguish normal and outer maps.
13299 */
13300 if (meta->map.ptr != reg->map_ptr ||
13301 meta->map.uid != reg->map_uid) {
13302 if (reg->map_ptr->record->task_work_off >= 0) {
13303 verbose(env,
13304 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13305 meta->map.uid, reg->map_uid);
13306 return -EINVAL;
13307 }
13308 verbose(env,
13309 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13310 meta->map.uid, reg->map_uid);
13311 return -EINVAL;
13312 }
13313 }
13314 meta->map.ptr = reg->map_ptr;
13315 meta->map.uid = reg->map_uid;
13316 fallthrough;
13317 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13318 case KF_ARG_PTR_TO_BTF_ID:
13319 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13320 break;
13321
13322 if (!is_trusted_reg(reg)) {
13323 if (!is_kfunc_rcu(meta)) {
13324 verbose(env, "R%d must be referenced or trusted\n", regno);
13325 return -EINVAL;
13326 }
13327 if (!is_rcu_reg(reg)) {
13328 verbose(env, "R%d must be a rcu pointer\n", regno);
13329 return -EINVAL;
13330 }
13331 }
13332 fallthrough;
13333 case KF_ARG_PTR_TO_CTX:
13334 case KF_ARG_PTR_TO_DYNPTR:
13335 case KF_ARG_PTR_TO_ITER:
13336 case KF_ARG_PTR_TO_LIST_HEAD:
13337 case KF_ARG_PTR_TO_LIST_NODE:
13338 case KF_ARG_PTR_TO_RB_ROOT:
13339 case KF_ARG_PTR_TO_RB_NODE:
13340 case KF_ARG_PTR_TO_MEM:
13341 case KF_ARG_PTR_TO_MEM_SIZE:
13342 case KF_ARG_PTR_TO_CALLBACK:
13343 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13344 case KF_ARG_PTR_TO_CONST_STR:
13345 case KF_ARG_PTR_TO_WORKQUEUE:
13346 case KF_ARG_PTR_TO_TASK_WORK:
13347 case KF_ARG_PTR_TO_IRQ_FLAG:
13348 case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13349 break;
13350 default:
13351 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13352 return -EFAULT;
13353 }
13354
13355 if (is_kfunc_release(meta) && reg->ref_obj_id)
13356 arg_type |= OBJ_RELEASE;
13357 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13358 if (ret < 0)
13359 return ret;
13360
13361 switch (kf_arg_type) {
13362 case KF_ARG_PTR_TO_CTX:
13363 if (reg->type != PTR_TO_CTX) {
13364 verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13365 i, reg_type_str(env, reg->type));
13366 return -EINVAL;
13367 }
13368
13369 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13370 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13371 if (ret < 0)
13372 return -EINVAL;
13373 meta->ret_btf_id = ret;
13374 }
13375 break;
13376 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13377 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13378 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13379 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13380 return -EINVAL;
13381 }
13382 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13383 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13384 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13385 return -EINVAL;
13386 }
13387 } else {
13388 verbose(env, "arg#%d expected pointer to allocated object\n", i);
13389 return -EINVAL;
13390 }
13391 if (!reg->ref_obj_id) {
13392 verbose(env, "allocated object must be referenced\n");
13393 return -EINVAL;
13394 }
13395 if (meta->btf == btf_vmlinux) {
13396 meta->arg_btf = reg->btf;
13397 meta->arg_btf_id = reg->btf_id;
13398 }
13399 break;
13400 case KF_ARG_PTR_TO_DYNPTR:
13401 {
13402 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13403 int clone_ref_obj_id = 0;
13404
13405 if (reg->type == CONST_PTR_TO_DYNPTR)
13406 dynptr_arg_type |= MEM_RDONLY;
13407
13408 if (is_kfunc_arg_uninit(btf, &args[i]))
13409 dynptr_arg_type |= MEM_UNINIT;
13410
13411 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13412 dynptr_arg_type |= DYNPTR_TYPE_SKB;
13413 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13414 dynptr_arg_type |= DYNPTR_TYPE_XDP;
13415 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13416 dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13417 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
13418 dynptr_arg_type |= DYNPTR_TYPE_FILE;
13419 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
13420 dynptr_arg_type |= DYNPTR_TYPE_FILE;
13421 meta->release_regno = regno;
13422 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13423 (dynptr_arg_type & MEM_UNINIT)) {
13424 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13425
13426 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13427 verifier_bug(env, "no dynptr type for parent of clone");
13428 return -EFAULT;
13429 }
13430
13431 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13432 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13433 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13434 verifier_bug(env, "missing ref obj id for parent of clone");
13435 return -EFAULT;
13436 }
13437 }
13438
13439 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13440 if (ret < 0)
13441 return ret;
13442
13443 if (!(dynptr_arg_type & MEM_UNINIT)) {
13444 int id = dynptr_id(env, reg);
13445
13446 if (id < 0) {
13447 verifier_bug(env, "failed to obtain dynptr id");
13448 return id;
13449 }
13450 meta->initialized_dynptr.id = id;
13451 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13452 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13453 }
13454
13455 break;
13456 }
13457 case KF_ARG_PTR_TO_ITER:
13458 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13459 if (!check_css_task_iter_allowlist(env)) {
13460 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13461 return -EINVAL;
13462 }
13463 }
13464 ret = process_iter_arg(env, regno, insn_idx, meta);
13465 if (ret < 0)
13466 return ret;
13467 break;
13468 case KF_ARG_PTR_TO_LIST_HEAD:
13469 if (reg->type != PTR_TO_MAP_VALUE &&
13470 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13471 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13472 return -EINVAL;
13473 }
13474 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13475 verbose(env, "allocated object must be referenced\n");
13476 return -EINVAL;
13477 }
13478 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13479 if (ret < 0)
13480 return ret;
13481 break;
13482 case KF_ARG_PTR_TO_RB_ROOT:
13483 if (reg->type != PTR_TO_MAP_VALUE &&
13484 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13485 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13486 return -EINVAL;
13487 }
13488 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13489 verbose(env, "allocated object must be referenced\n");
13490 return -EINVAL;
13491 }
13492 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13493 if (ret < 0)
13494 return ret;
13495 break;
13496 case KF_ARG_PTR_TO_LIST_NODE:
13497 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13498 verbose(env, "arg#%d expected pointer to allocated object\n", i);
13499 return -EINVAL;
13500 }
13501 if (!reg->ref_obj_id) {
13502 verbose(env, "allocated object must be referenced\n");
13503 return -EINVAL;
13504 }
13505 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13506 if (ret < 0)
13507 return ret;
13508 break;
13509 case KF_ARG_PTR_TO_RB_NODE:
13510 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13511 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13512 verbose(env, "arg#%d expected pointer to allocated object\n", i);
13513 return -EINVAL;
13514 }
13515 if (!reg->ref_obj_id) {
13516 verbose(env, "allocated object must be referenced\n");
13517 return -EINVAL;
13518 }
13519 } else {
13520 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13521 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13522 return -EINVAL;
13523 }
13524 if (in_rbtree_lock_required_cb(env)) {
13525 verbose(env, "%s not allowed in rbtree cb\n", func_name);
13526 return -EINVAL;
13527 }
13528 }
13529
13530 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13531 if (ret < 0)
13532 return ret;
13533 break;
13534 case KF_ARG_PTR_TO_MAP:
13535 /* If argument has '__map' suffix expect 'struct bpf_map *' */
13536 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13537 ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13538 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13539 fallthrough;
13540 case KF_ARG_PTR_TO_BTF_ID:
13541 /* Only base_type is checked, further checks are done here */
13542 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13543 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13544 !reg2btf_ids[base_type(reg->type)]) {
13545 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13546 verbose(env, "expected %s or socket\n",
13547 reg_type_str(env, base_type(reg->type) |
13548 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13549 return -EINVAL;
13550 }
13551 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13552 if (ret < 0)
13553 return ret;
13554 break;
13555 case KF_ARG_PTR_TO_MEM:
13556 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13557 if (IS_ERR(resolve_ret)) {
13558 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13559 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13560 return -EINVAL;
13561 }
13562 ret = check_mem_reg(env, reg, regno, type_size);
13563 if (ret < 0)
13564 return ret;
13565 break;
13566 case KF_ARG_PTR_TO_MEM_SIZE:
13567 {
13568 struct bpf_reg_state *buff_reg = ®s[regno];
13569 const struct btf_param *buff_arg = &args[i];
13570 struct bpf_reg_state *size_reg = ®s[regno + 1];
13571 const struct btf_param *size_arg = &args[i + 1];
13572
13573 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13574 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13575 if (ret < 0) {
13576 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13577 return ret;
13578 }
13579 }
13580
13581 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13582 if (meta->arg_constant.found) {
13583 verifier_bug(env, "only one constant argument permitted");
13584 return -EFAULT;
13585 }
13586 if (!tnum_is_const(size_reg->var_off)) {
13587 verbose(env, "R%d must be a known constant\n", regno + 1);
13588 return -EINVAL;
13589 }
13590 meta->arg_constant.found = true;
13591 meta->arg_constant.value = size_reg->var_off.value;
13592 }
13593
13594 /* Skip next '__sz' or '__szk' argument */
13595 i++;
13596 break;
13597 }
13598 case KF_ARG_PTR_TO_CALLBACK:
13599 if (reg->type != PTR_TO_FUNC) {
13600 verbose(env, "arg%d expected pointer to func\n", i);
13601 return -EINVAL;
13602 }
13603 meta->subprogno = reg->subprogno;
13604 break;
13605 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13606 if (!type_is_ptr_alloc_obj(reg->type)) {
13607 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13608 return -EINVAL;
13609 }
13610 if (!type_is_non_owning_ref(reg->type))
13611 meta->arg_owning_ref = true;
13612
13613 rec = reg_btf_record(reg);
13614 if (!rec) {
13615 verifier_bug(env, "Couldn't find btf_record");
13616 return -EFAULT;
13617 }
13618
13619 if (rec->refcount_off < 0) {
13620 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13621 return -EINVAL;
13622 }
13623
13624 meta->arg_btf = reg->btf;
13625 meta->arg_btf_id = reg->btf_id;
13626 break;
13627 case KF_ARG_PTR_TO_CONST_STR:
13628 if (reg->type != PTR_TO_MAP_VALUE) {
13629 verbose(env, "arg#%d doesn't point to a const string\n", i);
13630 return -EINVAL;
13631 }
13632 ret = check_reg_const_str(env, reg, regno);
13633 if (ret)
13634 return ret;
13635 break;
13636 case KF_ARG_PTR_TO_WORKQUEUE:
13637 if (reg->type != PTR_TO_MAP_VALUE) {
13638 verbose(env, "arg#%d doesn't point to a map value\n", i);
13639 return -EINVAL;
13640 }
13641 ret = process_wq_func(env, regno, meta);
13642 if (ret < 0)
13643 return ret;
13644 break;
13645 case KF_ARG_PTR_TO_TASK_WORK:
13646 if (reg->type != PTR_TO_MAP_VALUE) {
13647 verbose(env, "arg#%d doesn't point to a map value\n", i);
13648 return -EINVAL;
13649 }
13650 ret = process_task_work_func(env, regno, meta);
13651 if (ret < 0)
13652 return ret;
13653 break;
13654 case KF_ARG_PTR_TO_IRQ_FLAG:
13655 if (reg->type != PTR_TO_STACK) {
13656 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13657 return -EINVAL;
13658 }
13659 ret = process_irq_flag(env, regno, meta);
13660 if (ret < 0)
13661 return ret;
13662 break;
13663 case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13664 {
13665 int flags = PROCESS_RES_LOCK;
13666
13667 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13668 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13669 return -EINVAL;
13670 }
13671
13672 if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13673 return -EFAULT;
13674 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13675 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13676 flags |= PROCESS_SPIN_LOCK;
13677 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13678 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13679 flags |= PROCESS_LOCK_IRQ;
13680 ret = process_spin_lock(env, regno, flags);
13681 if (ret < 0)
13682 return ret;
13683 break;
13684 }
13685 }
13686 }
13687
13688 if (is_kfunc_release(meta) && !meta->release_regno) {
13689 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13690 func_name);
13691 return -EINVAL;
13692 }
13693
13694 return 0;
13695 }
13696
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)13697 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13698 struct bpf_insn *insn,
13699 struct bpf_kfunc_call_arg_meta *meta,
13700 const char **kfunc_name)
13701 {
13702 const struct btf_type *func, *func_proto;
13703 u32 func_id, *kfunc_flags;
13704 const char *func_name;
13705 struct btf *desc_btf;
13706
13707 if (kfunc_name)
13708 *kfunc_name = NULL;
13709
13710 if (!insn->imm)
13711 return -EINVAL;
13712
13713 desc_btf = find_kfunc_desc_btf(env, insn->off);
13714 if (IS_ERR(desc_btf))
13715 return PTR_ERR(desc_btf);
13716
13717 func_id = insn->imm;
13718 func = btf_type_by_id(desc_btf, func_id);
13719 func_name = btf_name_by_offset(desc_btf, func->name_off);
13720 if (kfunc_name)
13721 *kfunc_name = func_name;
13722 func_proto = btf_type_by_id(desc_btf, func->type);
13723
13724 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13725 if (!kfunc_flags) {
13726 return -EACCES;
13727 }
13728
13729 memset(meta, 0, sizeof(*meta));
13730 meta->btf = desc_btf;
13731 meta->func_id = func_id;
13732 meta->kfunc_flags = *kfunc_flags;
13733 meta->func_proto = func_proto;
13734 meta->func_name = func_name;
13735
13736 return 0;
13737 }
13738
13739 /* check special kfuncs and return:
13740 * 1 - not fall-through to 'else' branch, continue verification
13741 * 0 - fall-through to 'else' branch
13742 * < 0 - not fall-through to 'else' branch, return error
13743 */
check_special_kfunc(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,struct bpf_reg_state * regs,struct bpf_insn_aux_data * insn_aux,const struct btf_type * ptr_type,struct btf * desc_btf)13744 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13745 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13746 const struct btf_type *ptr_type, struct btf *desc_btf)
13747 {
13748 const struct btf_type *ret_t;
13749 int err = 0;
13750
13751 if (meta->btf != btf_vmlinux)
13752 return 0;
13753
13754 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13755 meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13756 struct btf_struct_meta *struct_meta;
13757 struct btf *ret_btf;
13758 u32 ret_btf_id;
13759
13760 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13761 return -ENOMEM;
13762
13763 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13764 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13765 return -EINVAL;
13766 }
13767
13768 ret_btf = env->prog->aux->btf;
13769 ret_btf_id = meta->arg_constant.value;
13770
13771 /* This may be NULL due to user not supplying a BTF */
13772 if (!ret_btf) {
13773 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13774 return -EINVAL;
13775 }
13776
13777 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13778 if (!ret_t || !__btf_type_is_struct(ret_t)) {
13779 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13780 return -EINVAL;
13781 }
13782
13783 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13784 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13785 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13786 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13787 return -EINVAL;
13788 }
13789
13790 if (!bpf_global_percpu_ma_set) {
13791 mutex_lock(&bpf_percpu_ma_lock);
13792 if (!bpf_global_percpu_ma_set) {
13793 /* Charge memory allocated with bpf_global_percpu_ma to
13794 * root memcg. The obj_cgroup for root memcg is NULL.
13795 */
13796 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13797 if (!err)
13798 bpf_global_percpu_ma_set = true;
13799 }
13800 mutex_unlock(&bpf_percpu_ma_lock);
13801 if (err)
13802 return err;
13803 }
13804
13805 mutex_lock(&bpf_percpu_ma_lock);
13806 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13807 mutex_unlock(&bpf_percpu_ma_lock);
13808 if (err)
13809 return err;
13810 }
13811
13812 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13813 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13814 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13815 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13816 return -EINVAL;
13817 }
13818
13819 if (struct_meta) {
13820 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13821 return -EINVAL;
13822 }
13823 }
13824
13825 mark_reg_known_zero(env, regs, BPF_REG_0);
13826 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13827 regs[BPF_REG_0].btf = ret_btf;
13828 regs[BPF_REG_0].btf_id = ret_btf_id;
13829 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13830 regs[BPF_REG_0].type |= MEM_PERCPU;
13831
13832 insn_aux->obj_new_size = ret_t->size;
13833 insn_aux->kptr_struct_meta = struct_meta;
13834 } else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13835 mark_reg_known_zero(env, regs, BPF_REG_0);
13836 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13837 regs[BPF_REG_0].btf = meta->arg_btf;
13838 regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13839
13840 insn_aux->kptr_struct_meta =
13841 btf_find_struct_meta(meta->arg_btf,
13842 meta->arg_btf_id);
13843 } else if (is_list_node_type(ptr_type)) {
13844 struct btf_field *field = meta->arg_list_head.field;
13845
13846 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13847 } else if (is_rbtree_node_type(ptr_type)) {
13848 struct btf_field *field = meta->arg_rbtree_root.field;
13849
13850 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13851 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13852 mark_reg_known_zero(env, regs, BPF_REG_0);
13853 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13854 regs[BPF_REG_0].btf = desc_btf;
13855 regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13856 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13857 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13858 if (!ret_t) {
13859 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13860 meta->arg_constant.value);
13861 return -EINVAL;
13862 } else if (btf_type_is_struct(ret_t)) {
13863 mark_reg_known_zero(env, regs, BPF_REG_0);
13864 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13865 regs[BPF_REG_0].btf = desc_btf;
13866 regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13867 } else if (btf_type_is_void(ret_t)) {
13868 mark_reg_known_zero(env, regs, BPF_REG_0);
13869 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13870 regs[BPF_REG_0].mem_size = 0;
13871 } else {
13872 verbose(env,
13873 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13874 return -EINVAL;
13875 }
13876 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13877 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13878 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13879
13880 mark_reg_known_zero(env, regs, BPF_REG_0);
13881
13882 if (!meta->arg_constant.found) {
13883 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13884 return -EFAULT;
13885 }
13886
13887 regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13888
13889 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13890 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13891
13892 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13893 regs[BPF_REG_0].type |= MEM_RDONLY;
13894 } else {
13895 /* this will set env->seen_direct_write to true */
13896 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13897 verbose(env, "the prog does not allow writes to packet data\n");
13898 return -EINVAL;
13899 }
13900 }
13901
13902 if (!meta->initialized_dynptr.id) {
13903 verifier_bug(env, "no dynptr id");
13904 return -EFAULT;
13905 }
13906 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13907
13908 /* we don't need to set BPF_REG_0's ref obj id
13909 * because packet slices are not refcounted (see
13910 * dynptr_type_refcounted)
13911 */
13912 } else {
13913 return 0;
13914 }
13915
13916 return 1;
13917 }
13918
13919 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13920
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)13921 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13922 int *insn_idx_p)
13923 {
13924 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13925 u32 i, nargs, ptr_type_id, release_ref_obj_id;
13926 struct bpf_reg_state *regs = cur_regs(env);
13927 const char *func_name, *ptr_type_name;
13928 const struct btf_type *t, *ptr_type;
13929 struct bpf_kfunc_call_arg_meta meta;
13930 struct bpf_insn_aux_data *insn_aux;
13931 int err, insn_idx = *insn_idx_p;
13932 const struct btf_param *args;
13933 struct btf *desc_btf;
13934
13935 /* skip for now, but return error when we find this in fixup_kfunc_call */
13936 if (!insn->imm)
13937 return 0;
13938
13939 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13940 if (err == -EACCES && func_name)
13941 verbose(env, "calling kernel function %s is not allowed\n", func_name);
13942 if (err)
13943 return err;
13944 desc_btf = meta.btf;
13945 insn_aux = &env->insn_aux_data[insn_idx];
13946
13947 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13948
13949 if (!insn->off &&
13950 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13951 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13952 struct bpf_verifier_state *branch;
13953 struct bpf_reg_state *regs;
13954
13955 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13956 if (IS_ERR(branch)) {
13957 verbose(env, "failed to push state for failed lock acquisition\n");
13958 return PTR_ERR(branch);
13959 }
13960
13961 regs = branch->frame[branch->curframe]->regs;
13962
13963 /* Clear r0-r5 registers in forked state */
13964 for (i = 0; i < CALLER_SAVED_REGS; i++)
13965 mark_reg_not_init(env, regs, caller_saved[i]);
13966
13967 mark_reg_unknown(env, regs, BPF_REG_0);
13968 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13969 if (err) {
13970 verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13971 return err;
13972 }
13973 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13974 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13975 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13976 return -EFAULT;
13977 }
13978
13979 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13980 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13981 return -EACCES;
13982 }
13983
13984 sleepable = is_kfunc_sleepable(&meta);
13985 if (sleepable && !in_sleepable(env)) {
13986 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13987 return -EACCES;
13988 }
13989
13990 /* Track non-sleepable context for kfuncs, same as for helpers. */
13991 if (!in_sleepable_context(env))
13992 insn_aux->non_sleepable = true;
13993
13994 /* Check the arguments */
13995 err = check_kfunc_args(env, &meta, insn_idx);
13996 if (err < 0)
13997 return err;
13998
13999 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14000 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14001 set_rbtree_add_callback_state);
14002 if (err) {
14003 verbose(env, "kfunc %s#%d failed callback verification\n",
14004 func_name, meta.func_id);
14005 return err;
14006 }
14007 }
14008
14009 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
14010 meta.r0_size = sizeof(u64);
14011 meta.r0_rdonly = false;
14012 }
14013
14014 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
14015 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14016 set_timer_callback_state);
14017 if (err) {
14018 verbose(env, "kfunc %s#%d failed callback verification\n",
14019 func_name, meta.func_id);
14020 return err;
14021 }
14022 }
14023
14024 if (is_task_work_add_kfunc(meta.func_id)) {
14025 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14026 set_task_work_schedule_callback_state);
14027 if (err) {
14028 verbose(env, "kfunc %s#%d failed callback verification\n",
14029 func_name, meta.func_id);
14030 return err;
14031 }
14032 }
14033
14034 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
14035 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
14036
14037 preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
14038 preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
14039
14040 if (rcu_lock) {
14041 env->cur_state->active_rcu_locks++;
14042 } else if (rcu_unlock) {
14043 struct bpf_func_state *state;
14044 struct bpf_reg_state *reg;
14045 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
14046
14047 if (env->cur_state->active_rcu_locks == 0) {
14048 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
14049 return -EINVAL;
14050 }
14051 if (--env->cur_state->active_rcu_locks == 0) {
14052 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
14053 if (reg->type & MEM_RCU) {
14054 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
14055 reg->type |= PTR_UNTRUSTED;
14056 }
14057 }));
14058 }
14059 } else if (sleepable && env->cur_state->active_rcu_locks) {
14060 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
14061 return -EACCES;
14062 }
14063
14064 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
14065 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
14066 return -EACCES;
14067 }
14068
14069 if (env->cur_state->active_preempt_locks) {
14070 if (preempt_disable) {
14071 env->cur_state->active_preempt_locks++;
14072 } else if (preempt_enable) {
14073 env->cur_state->active_preempt_locks--;
14074 } else if (sleepable) {
14075 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
14076 return -EACCES;
14077 }
14078 } else if (preempt_disable) {
14079 env->cur_state->active_preempt_locks++;
14080 } else if (preempt_enable) {
14081 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
14082 return -EINVAL;
14083 }
14084
14085 if (env->cur_state->active_irq_id && sleepable) {
14086 verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
14087 return -EACCES;
14088 }
14089
14090 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
14091 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
14092 return -EACCES;
14093 }
14094
14095 /* In case of release function, we get register number of refcounted
14096 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
14097 */
14098 if (meta.release_regno) {
14099 struct bpf_reg_state *reg = ®s[meta.release_regno];
14100
14101 if (meta.initialized_dynptr.ref_obj_id) {
14102 err = unmark_stack_slots_dynptr(env, reg);
14103 } else {
14104 err = release_reference(env, reg->ref_obj_id);
14105 if (err)
14106 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14107 func_name, meta.func_id);
14108 }
14109 if (err)
14110 return err;
14111 }
14112
14113 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
14114 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
14115 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14116 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
14117 insn_aux->insert_off = regs[BPF_REG_2].off;
14118 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
14119 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
14120 if (err) {
14121 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
14122 func_name, meta.func_id);
14123 return err;
14124 }
14125
14126 err = release_reference(env, release_ref_obj_id);
14127 if (err) {
14128 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14129 func_name, meta.func_id);
14130 return err;
14131 }
14132 }
14133
14134 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14135 if (!bpf_jit_supports_exceptions()) {
14136 verbose(env, "JIT does not support calling kfunc %s#%d\n",
14137 func_name, meta.func_id);
14138 return -ENOTSUPP;
14139 }
14140 env->seen_exception = true;
14141
14142 /* In the case of the default callback, the cookie value passed
14143 * to bpf_throw becomes the return value of the program.
14144 */
14145 if (!env->exception_callback_subprog) {
14146 err = check_return_code(env, BPF_REG_1, "R1");
14147 if (err < 0)
14148 return err;
14149 }
14150 }
14151
14152 for (i = 0; i < CALLER_SAVED_REGS; i++)
14153 mark_reg_not_init(env, regs, caller_saved[i]);
14154
14155 /* Check return type */
14156 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14157
14158 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14159 /* Only exception is bpf_obj_new_impl */
14160 if (meta.btf != btf_vmlinux ||
14161 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14162 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14163 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14164 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14165 return -EINVAL;
14166 }
14167 }
14168
14169 if (btf_type_is_scalar(t)) {
14170 mark_reg_unknown(env, regs, BPF_REG_0);
14171 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14172 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14173 __mark_reg_const_zero(env, ®s[BPF_REG_0]);
14174 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14175 } else if (btf_type_is_ptr(t)) {
14176 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14177 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14178 if (err) {
14179 if (err < 0)
14180 return err;
14181 } else if (btf_type_is_void(ptr_type)) {
14182 /* kfunc returning 'void *' is equivalent to returning scalar */
14183 mark_reg_unknown(env, regs, BPF_REG_0);
14184 } else if (!__btf_type_is_struct(ptr_type)) {
14185 if (!meta.r0_size) {
14186 __u32 sz;
14187
14188 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14189 meta.r0_size = sz;
14190 meta.r0_rdonly = true;
14191 }
14192 }
14193 if (!meta.r0_size) {
14194 ptr_type_name = btf_name_by_offset(desc_btf,
14195 ptr_type->name_off);
14196 verbose(env,
14197 "kernel function %s returns pointer type %s %s is not supported\n",
14198 func_name,
14199 btf_type_str(ptr_type),
14200 ptr_type_name);
14201 return -EINVAL;
14202 }
14203
14204 mark_reg_known_zero(env, regs, BPF_REG_0);
14205 regs[BPF_REG_0].type = PTR_TO_MEM;
14206 regs[BPF_REG_0].mem_size = meta.r0_size;
14207
14208 if (meta.r0_rdonly)
14209 regs[BPF_REG_0].type |= MEM_RDONLY;
14210
14211 /* Ensures we don't access the memory after a release_reference() */
14212 if (meta.ref_obj_id)
14213 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14214
14215 if (is_kfunc_rcu_protected(&meta))
14216 regs[BPF_REG_0].type |= MEM_RCU;
14217 } else {
14218 mark_reg_known_zero(env, regs, BPF_REG_0);
14219 regs[BPF_REG_0].btf = desc_btf;
14220 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14221 regs[BPF_REG_0].btf_id = ptr_type_id;
14222
14223 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14224 regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14225 else if (is_kfunc_rcu_protected(&meta))
14226 regs[BPF_REG_0].type |= MEM_RCU;
14227
14228 if (is_iter_next_kfunc(&meta)) {
14229 struct bpf_reg_state *cur_iter;
14230
14231 cur_iter = get_iter_from_state(env->cur_state, &meta);
14232
14233 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14234 regs[BPF_REG_0].type |= MEM_RCU;
14235 else
14236 regs[BPF_REG_0].type |= PTR_TRUSTED;
14237 }
14238 }
14239
14240 if (is_kfunc_ret_null(&meta)) {
14241 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14242 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14243 regs[BPF_REG_0].id = ++env->id_gen;
14244 }
14245 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14246 if (is_kfunc_acquire(&meta)) {
14247 int id = acquire_reference(env, insn_idx);
14248
14249 if (id < 0)
14250 return id;
14251 if (is_kfunc_ret_null(&meta))
14252 regs[BPF_REG_0].id = id;
14253 regs[BPF_REG_0].ref_obj_id = id;
14254 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14255 ref_set_non_owning(env, ®s[BPF_REG_0]);
14256 }
14257
14258 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
14259 regs[BPF_REG_0].id = ++env->id_gen;
14260 } else if (btf_type_is_void(t)) {
14261 if (meta.btf == btf_vmlinux) {
14262 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14263 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14264 insn_aux->kptr_struct_meta =
14265 btf_find_struct_meta(meta.arg_btf,
14266 meta.arg_btf_id);
14267 }
14268 }
14269 }
14270
14271 if (is_kfunc_pkt_changing(&meta))
14272 clear_all_pkt_pointers(env);
14273
14274 nargs = btf_type_vlen(meta.func_proto);
14275 args = (const struct btf_param *)(meta.func_proto + 1);
14276 for (i = 0; i < nargs; i++) {
14277 u32 regno = i + 1;
14278
14279 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14280 if (btf_type_is_ptr(t))
14281 mark_btf_func_reg_size(env, regno, sizeof(void *));
14282 else
14283 /* scalar. ensured by btf_check_kfunc_arg_match() */
14284 mark_btf_func_reg_size(env, regno, t->size);
14285 }
14286
14287 if (is_iter_next_kfunc(&meta)) {
14288 err = process_iter_next_call(env, insn_idx, &meta);
14289 if (err)
14290 return err;
14291 }
14292
14293 return 0;
14294 }
14295
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)14296 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14297 const struct bpf_reg_state *reg,
14298 enum bpf_reg_type type)
14299 {
14300 bool known = tnum_is_const(reg->var_off);
14301 s64 val = reg->var_off.value;
14302 s64 smin = reg->smin_value;
14303
14304 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14305 verbose(env, "math between %s pointer and %lld is not allowed\n",
14306 reg_type_str(env, type), val);
14307 return false;
14308 }
14309
14310 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14311 verbose(env, "%s pointer offset %d is not allowed\n",
14312 reg_type_str(env, type), reg->off);
14313 return false;
14314 }
14315
14316 if (smin == S64_MIN) {
14317 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14318 reg_type_str(env, type));
14319 return false;
14320 }
14321
14322 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14323 verbose(env, "value %lld makes %s pointer be out of bounds\n",
14324 smin, reg_type_str(env, type));
14325 return false;
14326 }
14327
14328 return true;
14329 }
14330
14331 enum {
14332 REASON_BOUNDS = -1,
14333 REASON_TYPE = -2,
14334 REASON_PATHS = -3,
14335 REASON_LIMIT = -4,
14336 REASON_STACK = -5,
14337 };
14338
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)14339 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14340 u32 *alu_limit, bool mask_to_left)
14341 {
14342 u32 max = 0, ptr_limit = 0;
14343
14344 switch (ptr_reg->type) {
14345 case PTR_TO_STACK:
14346 /* Offset 0 is out-of-bounds, but acceptable start for the
14347 * left direction, see BPF_REG_FP. Also, unknown scalar
14348 * offset where we would need to deal with min/max bounds is
14349 * currently prohibited for unprivileged.
14350 */
14351 max = MAX_BPF_STACK + mask_to_left;
14352 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14353 break;
14354 case PTR_TO_MAP_VALUE:
14355 max = ptr_reg->map_ptr->value_size;
14356 ptr_limit = (mask_to_left ?
14357 ptr_reg->smin_value :
14358 ptr_reg->umax_value) + ptr_reg->off;
14359 break;
14360 default:
14361 return REASON_TYPE;
14362 }
14363
14364 if (ptr_limit >= max)
14365 return REASON_LIMIT;
14366 *alu_limit = ptr_limit;
14367 return 0;
14368 }
14369
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)14370 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14371 const struct bpf_insn *insn)
14372 {
14373 return env->bypass_spec_v1 ||
14374 BPF_SRC(insn->code) == BPF_K ||
14375 cur_aux(env)->nospec;
14376 }
14377
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)14378 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14379 u32 alu_state, u32 alu_limit)
14380 {
14381 /* If we arrived here from different branches with different
14382 * state or limits to sanitize, then this won't work.
14383 */
14384 if (aux->alu_state &&
14385 (aux->alu_state != alu_state ||
14386 aux->alu_limit != alu_limit))
14387 return REASON_PATHS;
14388
14389 /* Corresponding fixup done in do_misc_fixups(). */
14390 aux->alu_state = alu_state;
14391 aux->alu_limit = alu_limit;
14392 return 0;
14393 }
14394
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)14395 static int sanitize_val_alu(struct bpf_verifier_env *env,
14396 struct bpf_insn *insn)
14397 {
14398 struct bpf_insn_aux_data *aux = cur_aux(env);
14399
14400 if (can_skip_alu_sanitation(env, insn))
14401 return 0;
14402
14403 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14404 }
14405
sanitize_needed(u8 opcode)14406 static bool sanitize_needed(u8 opcode)
14407 {
14408 return opcode == BPF_ADD || opcode == BPF_SUB;
14409 }
14410
14411 struct bpf_sanitize_info {
14412 struct bpf_insn_aux_data aux;
14413 bool mask_to_left;
14414 };
14415
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)14416 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14417 const struct bpf_insn *insn,
14418 u32 next_idx, u32 curr_idx)
14419 {
14420 struct bpf_verifier_state *branch;
14421 struct bpf_reg_state *regs;
14422
14423 branch = push_stack(env, next_idx, curr_idx, true);
14424 if (!IS_ERR(branch) && insn) {
14425 regs = branch->frame[branch->curframe]->regs;
14426 if (BPF_SRC(insn->code) == BPF_K) {
14427 mark_reg_unknown(env, regs, insn->dst_reg);
14428 } else if (BPF_SRC(insn->code) == BPF_X) {
14429 mark_reg_unknown(env, regs, insn->dst_reg);
14430 mark_reg_unknown(env, regs, insn->src_reg);
14431 }
14432 }
14433 return PTR_ERR_OR_ZERO(branch);
14434 }
14435
sanitize_ptr_alu(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg,struct bpf_reg_state * dst_reg,struct bpf_sanitize_info * info,const bool commit_window)14436 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14437 struct bpf_insn *insn,
14438 const struct bpf_reg_state *ptr_reg,
14439 const struct bpf_reg_state *off_reg,
14440 struct bpf_reg_state *dst_reg,
14441 struct bpf_sanitize_info *info,
14442 const bool commit_window)
14443 {
14444 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14445 struct bpf_verifier_state *vstate = env->cur_state;
14446 bool off_is_imm = tnum_is_const(off_reg->var_off);
14447 bool off_is_neg = off_reg->smin_value < 0;
14448 bool ptr_is_dst_reg = ptr_reg == dst_reg;
14449 u8 opcode = BPF_OP(insn->code);
14450 u32 alu_state, alu_limit;
14451 struct bpf_reg_state tmp;
14452 int err;
14453
14454 if (can_skip_alu_sanitation(env, insn))
14455 return 0;
14456
14457 /* We already marked aux for masking from non-speculative
14458 * paths, thus we got here in the first place. We only care
14459 * to explore bad access from here.
14460 */
14461 if (vstate->speculative)
14462 goto do_sim;
14463
14464 if (!commit_window) {
14465 if (!tnum_is_const(off_reg->var_off) &&
14466 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14467 return REASON_BOUNDS;
14468
14469 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
14470 (opcode == BPF_SUB && !off_is_neg);
14471 }
14472
14473 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14474 if (err < 0)
14475 return err;
14476
14477 if (commit_window) {
14478 /* In commit phase we narrow the masking window based on
14479 * the observed pointer move after the simulated operation.
14480 */
14481 alu_state = info->aux.alu_state;
14482 alu_limit = abs(info->aux.alu_limit - alu_limit);
14483 } else {
14484 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14485 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14486 alu_state |= ptr_is_dst_reg ?
14487 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14488
14489 /* Limit pruning on unknown scalars to enable deep search for
14490 * potential masking differences from other program paths.
14491 */
14492 if (!off_is_imm)
14493 env->explore_alu_limits = true;
14494 }
14495
14496 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14497 if (err < 0)
14498 return err;
14499 do_sim:
14500 /* If we're in commit phase, we're done here given we already
14501 * pushed the truncated dst_reg into the speculative verification
14502 * stack.
14503 *
14504 * Also, when register is a known constant, we rewrite register-based
14505 * operation to immediate-based, and thus do not need masking (and as
14506 * a consequence, do not need to simulate the zero-truncation either).
14507 */
14508 if (commit_window || off_is_imm)
14509 return 0;
14510
14511 /* Simulate and find potential out-of-bounds access under
14512 * speculative execution from truncation as a result of
14513 * masking when off was not within expected range. If off
14514 * sits in dst, then we temporarily need to move ptr there
14515 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14516 * for cases where we use K-based arithmetic in one direction
14517 * and truncated reg-based in the other in order to explore
14518 * bad access.
14519 */
14520 if (!ptr_is_dst_reg) {
14521 tmp = *dst_reg;
14522 copy_register_state(dst_reg, ptr_reg);
14523 }
14524 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14525 if (err < 0)
14526 return REASON_STACK;
14527 if (!ptr_is_dst_reg)
14528 *dst_reg = tmp;
14529 return 0;
14530 }
14531
sanitize_mark_insn_seen(struct bpf_verifier_env * env)14532 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14533 {
14534 struct bpf_verifier_state *vstate = env->cur_state;
14535
14536 /* If we simulate paths under speculation, we don't update the
14537 * insn as 'seen' such that when we verify unreachable paths in
14538 * the non-speculative domain, sanitize_dead_code() can still
14539 * rewrite/sanitize them.
14540 */
14541 if (!vstate->speculative)
14542 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14543 }
14544
sanitize_err(struct bpf_verifier_env * env,const struct bpf_insn * insn,int reason,const struct bpf_reg_state * off_reg,const struct bpf_reg_state * dst_reg)14545 static int sanitize_err(struct bpf_verifier_env *env,
14546 const struct bpf_insn *insn, int reason,
14547 const struct bpf_reg_state *off_reg,
14548 const struct bpf_reg_state *dst_reg)
14549 {
14550 static const char *err = "pointer arithmetic with it prohibited for !root";
14551 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14552 u32 dst = insn->dst_reg, src = insn->src_reg;
14553
14554 switch (reason) {
14555 case REASON_BOUNDS:
14556 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14557 off_reg == dst_reg ? dst : src, err);
14558 break;
14559 case REASON_TYPE:
14560 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14561 off_reg == dst_reg ? src : dst, err);
14562 break;
14563 case REASON_PATHS:
14564 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14565 dst, op, err);
14566 break;
14567 case REASON_LIMIT:
14568 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14569 dst, op, err);
14570 break;
14571 case REASON_STACK:
14572 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14573 dst, err);
14574 return -ENOMEM;
14575 default:
14576 verifier_bug(env, "unknown reason (%d)", reason);
14577 break;
14578 }
14579
14580 return -EACCES;
14581 }
14582
14583 /* check that stack access falls within stack limits and that 'reg' doesn't
14584 * have a variable offset.
14585 *
14586 * Variable offset is prohibited for unprivileged mode for simplicity since it
14587 * requires corresponding support in Spectre masking for stack ALU. See also
14588 * retrieve_ptr_limit().
14589 *
14590 *
14591 * 'off' includes 'reg->off'.
14592 */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)14593 static int check_stack_access_for_ptr_arithmetic(
14594 struct bpf_verifier_env *env,
14595 int regno,
14596 const struct bpf_reg_state *reg,
14597 int off)
14598 {
14599 if (!tnum_is_const(reg->var_off)) {
14600 char tn_buf[48];
14601
14602 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14603 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14604 regno, tn_buf, off);
14605 return -EACCES;
14606 }
14607
14608 if (off >= 0 || off < -MAX_BPF_STACK) {
14609 verbose(env, "R%d stack pointer arithmetic goes out of range, "
14610 "prohibited for !root; off=%d\n", regno, off);
14611 return -EACCES;
14612 }
14613
14614 return 0;
14615 }
14616
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)14617 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14618 const struct bpf_insn *insn,
14619 const struct bpf_reg_state *dst_reg)
14620 {
14621 u32 dst = insn->dst_reg;
14622
14623 /* For unprivileged we require that resulting offset must be in bounds
14624 * in order to be able to sanitize access later on.
14625 */
14626 if (env->bypass_spec_v1)
14627 return 0;
14628
14629 switch (dst_reg->type) {
14630 case PTR_TO_STACK:
14631 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14632 dst_reg->off + dst_reg->var_off.value))
14633 return -EACCES;
14634 break;
14635 case PTR_TO_MAP_VALUE:
14636 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14637 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14638 "prohibited for !root\n", dst);
14639 return -EACCES;
14640 }
14641 break;
14642 default:
14643 return -EOPNOTSUPP;
14644 }
14645
14646 return 0;
14647 }
14648
14649 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14650 * Caller should also handle BPF_MOV case separately.
14651 * If we return -EACCES, caller may want to try again treating pointer as a
14652 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
14653 */
adjust_ptr_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg)14654 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14655 struct bpf_insn *insn,
14656 const struct bpf_reg_state *ptr_reg,
14657 const struct bpf_reg_state *off_reg)
14658 {
14659 struct bpf_verifier_state *vstate = env->cur_state;
14660 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14661 struct bpf_reg_state *regs = state->regs, *dst_reg;
14662 bool known = tnum_is_const(off_reg->var_off);
14663 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14664 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14665 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14666 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14667 struct bpf_sanitize_info info = {};
14668 u8 opcode = BPF_OP(insn->code);
14669 u32 dst = insn->dst_reg;
14670 int ret, bounds_ret;
14671
14672 dst_reg = ®s[dst];
14673
14674 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14675 smin_val > smax_val || umin_val > umax_val) {
14676 /* Taint dst register if offset had invalid bounds derived from
14677 * e.g. dead branches.
14678 */
14679 __mark_reg_unknown(env, dst_reg);
14680 return 0;
14681 }
14682
14683 if (BPF_CLASS(insn->code) != BPF_ALU64) {
14684 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
14685 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14686 __mark_reg_unknown(env, dst_reg);
14687 return 0;
14688 }
14689
14690 verbose(env,
14691 "R%d 32-bit pointer arithmetic prohibited\n",
14692 dst);
14693 return -EACCES;
14694 }
14695
14696 if (ptr_reg->type & PTR_MAYBE_NULL) {
14697 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14698 dst, reg_type_str(env, ptr_reg->type));
14699 return -EACCES;
14700 }
14701
14702 /*
14703 * Accesses to untrusted PTR_TO_MEM are done through probe
14704 * instructions, hence no need to track offsets.
14705 */
14706 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14707 return 0;
14708
14709 switch (base_type(ptr_reg->type)) {
14710 case PTR_TO_CTX:
14711 case PTR_TO_MAP_VALUE:
14712 case PTR_TO_MAP_KEY:
14713 case PTR_TO_STACK:
14714 case PTR_TO_PACKET_META:
14715 case PTR_TO_PACKET:
14716 case PTR_TO_TP_BUFFER:
14717 case PTR_TO_BTF_ID:
14718 case PTR_TO_MEM:
14719 case PTR_TO_BUF:
14720 case PTR_TO_FUNC:
14721 case CONST_PTR_TO_DYNPTR:
14722 break;
14723 case PTR_TO_FLOW_KEYS:
14724 if (known)
14725 break;
14726 fallthrough;
14727 case CONST_PTR_TO_MAP:
14728 /* smin_val represents the known value */
14729 if (known && smin_val == 0 && opcode == BPF_ADD)
14730 break;
14731 fallthrough;
14732 default:
14733 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14734 dst, reg_type_str(env, ptr_reg->type));
14735 return -EACCES;
14736 }
14737
14738 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14739 * The id may be overwritten later if we create a new variable offset.
14740 */
14741 dst_reg->type = ptr_reg->type;
14742 dst_reg->id = ptr_reg->id;
14743
14744 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14745 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14746 return -EINVAL;
14747
14748 /* pointer types do not carry 32-bit bounds at the moment. */
14749 __mark_reg32_unbounded(dst_reg);
14750
14751 if (sanitize_needed(opcode)) {
14752 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14753 &info, false);
14754 if (ret < 0)
14755 return sanitize_err(env, insn, ret, off_reg, dst_reg);
14756 }
14757
14758 switch (opcode) {
14759 case BPF_ADD:
14760 /* We can take a fixed offset as long as it doesn't overflow
14761 * the s32 'off' field
14762 */
14763 if (known && (ptr_reg->off + smin_val ==
14764 (s64)(s32)(ptr_reg->off + smin_val))) {
14765 /* pointer += K. Accumulate it into fixed offset */
14766 dst_reg->smin_value = smin_ptr;
14767 dst_reg->smax_value = smax_ptr;
14768 dst_reg->umin_value = umin_ptr;
14769 dst_reg->umax_value = umax_ptr;
14770 dst_reg->var_off = ptr_reg->var_off;
14771 dst_reg->off = ptr_reg->off + smin_val;
14772 dst_reg->raw = ptr_reg->raw;
14773 break;
14774 }
14775 /* A new variable offset is created. Note that off_reg->off
14776 * == 0, since it's a scalar.
14777 * dst_reg gets the pointer type and since some positive
14778 * integer value was added to the pointer, give it a new 'id'
14779 * if it's a PTR_TO_PACKET.
14780 * this creates a new 'base' pointer, off_reg (variable) gets
14781 * added into the variable offset, and we copy the fixed offset
14782 * from ptr_reg.
14783 */
14784 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14785 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14786 dst_reg->smin_value = S64_MIN;
14787 dst_reg->smax_value = S64_MAX;
14788 }
14789 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14790 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14791 dst_reg->umin_value = 0;
14792 dst_reg->umax_value = U64_MAX;
14793 }
14794 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14795 dst_reg->off = ptr_reg->off;
14796 dst_reg->raw = ptr_reg->raw;
14797 if (reg_is_pkt_pointer(ptr_reg)) {
14798 dst_reg->id = ++env->id_gen;
14799 /* something was added to pkt_ptr, set range to zero */
14800 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14801 }
14802 break;
14803 case BPF_SUB:
14804 if (dst_reg == off_reg) {
14805 /* scalar -= pointer. Creates an unknown scalar */
14806 verbose(env, "R%d tried to subtract pointer from scalar\n",
14807 dst);
14808 return -EACCES;
14809 }
14810 /* We don't allow subtraction from FP, because (according to
14811 * test_verifier.c test "invalid fp arithmetic", JITs might not
14812 * be able to deal with it.
14813 */
14814 if (ptr_reg->type == PTR_TO_STACK) {
14815 verbose(env, "R%d subtraction from stack pointer prohibited\n",
14816 dst);
14817 return -EACCES;
14818 }
14819 if (known && (ptr_reg->off - smin_val ==
14820 (s64)(s32)(ptr_reg->off - smin_val))) {
14821 /* pointer -= K. Subtract it from fixed offset */
14822 dst_reg->smin_value = smin_ptr;
14823 dst_reg->smax_value = smax_ptr;
14824 dst_reg->umin_value = umin_ptr;
14825 dst_reg->umax_value = umax_ptr;
14826 dst_reg->var_off = ptr_reg->var_off;
14827 dst_reg->id = ptr_reg->id;
14828 dst_reg->off = ptr_reg->off - smin_val;
14829 dst_reg->raw = ptr_reg->raw;
14830 break;
14831 }
14832 /* A new variable offset is created. If the subtrahend is known
14833 * nonnegative, then any reg->range we had before is still good.
14834 */
14835 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14836 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14837 /* Overflow possible, we know nothing */
14838 dst_reg->smin_value = S64_MIN;
14839 dst_reg->smax_value = S64_MAX;
14840 }
14841 if (umin_ptr < umax_val) {
14842 /* Overflow possible, we know nothing */
14843 dst_reg->umin_value = 0;
14844 dst_reg->umax_value = U64_MAX;
14845 } else {
14846 /* Cannot overflow (as long as bounds are consistent) */
14847 dst_reg->umin_value = umin_ptr - umax_val;
14848 dst_reg->umax_value = umax_ptr - umin_val;
14849 }
14850 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14851 dst_reg->off = ptr_reg->off;
14852 dst_reg->raw = ptr_reg->raw;
14853 if (reg_is_pkt_pointer(ptr_reg)) {
14854 dst_reg->id = ++env->id_gen;
14855 /* something was added to pkt_ptr, set range to zero */
14856 if (smin_val < 0)
14857 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14858 }
14859 break;
14860 case BPF_AND:
14861 case BPF_OR:
14862 case BPF_XOR:
14863 /* bitwise ops on pointers are troublesome, prohibit. */
14864 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14865 dst, bpf_alu_string[opcode >> 4]);
14866 return -EACCES;
14867 default:
14868 /* other operators (e.g. MUL,LSH) produce non-pointer results */
14869 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14870 dst, bpf_alu_string[opcode >> 4]);
14871 return -EACCES;
14872 }
14873
14874 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14875 return -EINVAL;
14876 reg_bounds_sync(dst_reg);
14877 bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14878 if (bounds_ret == -EACCES)
14879 return bounds_ret;
14880 if (sanitize_needed(opcode)) {
14881 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14882 &info, true);
14883 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14884 && !env->cur_state->speculative
14885 && bounds_ret
14886 && !ret,
14887 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14888 return -EFAULT;
14889 }
14890 if (ret < 0)
14891 return sanitize_err(env, insn, ret, off_reg, dst_reg);
14892 }
14893
14894 return 0;
14895 }
14896
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14897 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14898 struct bpf_reg_state *src_reg)
14899 {
14900 s32 *dst_smin = &dst_reg->s32_min_value;
14901 s32 *dst_smax = &dst_reg->s32_max_value;
14902 u32 *dst_umin = &dst_reg->u32_min_value;
14903 u32 *dst_umax = &dst_reg->u32_max_value;
14904 u32 umin_val = src_reg->u32_min_value;
14905 u32 umax_val = src_reg->u32_max_value;
14906 bool min_overflow, max_overflow;
14907
14908 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14909 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14910 *dst_smin = S32_MIN;
14911 *dst_smax = S32_MAX;
14912 }
14913
14914 /* If either all additions overflow or no additions overflow, then
14915 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14916 * dst_umax + src_umax. Otherwise (some additions overflow), set
14917 * the output bounds to unbounded.
14918 */
14919 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14920 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14921
14922 if (!min_overflow && max_overflow) {
14923 *dst_umin = 0;
14924 *dst_umax = U32_MAX;
14925 }
14926 }
14927
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14928 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14929 struct bpf_reg_state *src_reg)
14930 {
14931 s64 *dst_smin = &dst_reg->smin_value;
14932 s64 *dst_smax = &dst_reg->smax_value;
14933 u64 *dst_umin = &dst_reg->umin_value;
14934 u64 *dst_umax = &dst_reg->umax_value;
14935 u64 umin_val = src_reg->umin_value;
14936 u64 umax_val = src_reg->umax_value;
14937 bool min_overflow, max_overflow;
14938
14939 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14940 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14941 *dst_smin = S64_MIN;
14942 *dst_smax = S64_MAX;
14943 }
14944
14945 /* If either all additions overflow or no additions overflow, then
14946 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14947 * dst_umax + src_umax. Otherwise (some additions overflow), set
14948 * the output bounds to unbounded.
14949 */
14950 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14951 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14952
14953 if (!min_overflow && max_overflow) {
14954 *dst_umin = 0;
14955 *dst_umax = U64_MAX;
14956 }
14957 }
14958
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14959 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14960 struct bpf_reg_state *src_reg)
14961 {
14962 s32 *dst_smin = &dst_reg->s32_min_value;
14963 s32 *dst_smax = &dst_reg->s32_max_value;
14964 u32 *dst_umin = &dst_reg->u32_min_value;
14965 u32 *dst_umax = &dst_reg->u32_max_value;
14966 u32 umin_val = src_reg->u32_min_value;
14967 u32 umax_val = src_reg->u32_max_value;
14968 bool min_underflow, max_underflow;
14969
14970 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14971 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14972 /* Overflow possible, we know nothing */
14973 *dst_smin = S32_MIN;
14974 *dst_smax = S32_MAX;
14975 }
14976
14977 /* If either all subtractions underflow or no subtractions
14978 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14979 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14980 * underflow), set the output bounds to unbounded.
14981 */
14982 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14983 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14984
14985 if (min_underflow && !max_underflow) {
14986 *dst_umin = 0;
14987 *dst_umax = U32_MAX;
14988 }
14989 }
14990
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14991 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14992 struct bpf_reg_state *src_reg)
14993 {
14994 s64 *dst_smin = &dst_reg->smin_value;
14995 s64 *dst_smax = &dst_reg->smax_value;
14996 u64 *dst_umin = &dst_reg->umin_value;
14997 u64 *dst_umax = &dst_reg->umax_value;
14998 u64 umin_val = src_reg->umin_value;
14999 u64 umax_val = src_reg->umax_value;
15000 bool min_underflow, max_underflow;
15001
15002 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
15003 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
15004 /* Overflow possible, we know nothing */
15005 *dst_smin = S64_MIN;
15006 *dst_smax = S64_MAX;
15007 }
15008
15009 /* If either all subtractions underflow or no subtractions
15010 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15011 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15012 * underflow), set the output bounds to unbounded.
15013 */
15014 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15015 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15016
15017 if (min_underflow && !max_underflow) {
15018 *dst_umin = 0;
15019 *dst_umax = U64_MAX;
15020 }
15021 }
15022
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15023 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
15024 struct bpf_reg_state *src_reg)
15025 {
15026 s32 *dst_smin = &dst_reg->s32_min_value;
15027 s32 *dst_smax = &dst_reg->s32_max_value;
15028 u32 *dst_umin = &dst_reg->u32_min_value;
15029 u32 *dst_umax = &dst_reg->u32_max_value;
15030 s32 tmp_prod[4];
15031
15032 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
15033 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
15034 /* Overflow possible, we know nothing */
15035 *dst_umin = 0;
15036 *dst_umax = U32_MAX;
15037 }
15038 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
15039 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
15040 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
15041 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
15042 /* Overflow possible, we know nothing */
15043 *dst_smin = S32_MIN;
15044 *dst_smax = S32_MAX;
15045 } else {
15046 *dst_smin = min_array(tmp_prod, 4);
15047 *dst_smax = max_array(tmp_prod, 4);
15048 }
15049 }
15050
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15051 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
15052 struct bpf_reg_state *src_reg)
15053 {
15054 s64 *dst_smin = &dst_reg->smin_value;
15055 s64 *dst_smax = &dst_reg->smax_value;
15056 u64 *dst_umin = &dst_reg->umin_value;
15057 u64 *dst_umax = &dst_reg->umax_value;
15058 s64 tmp_prod[4];
15059
15060 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
15061 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
15062 /* Overflow possible, we know nothing */
15063 *dst_umin = 0;
15064 *dst_umax = U64_MAX;
15065 }
15066 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
15067 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
15068 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
15069 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
15070 /* Overflow possible, we know nothing */
15071 *dst_smin = S64_MIN;
15072 *dst_smax = S64_MAX;
15073 } else {
15074 *dst_smin = min_array(tmp_prod, 4);
15075 *dst_smax = max_array(tmp_prod, 4);
15076 }
15077 }
15078
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15079 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15080 struct bpf_reg_state *src_reg)
15081 {
15082 bool src_known = tnum_subreg_is_const(src_reg->var_off);
15083 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15084 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15085 u32 umax_val = src_reg->u32_max_value;
15086
15087 if (src_known && dst_known) {
15088 __mark_reg32_known(dst_reg, var32_off.value);
15089 return;
15090 }
15091
15092 /* We get our minimum from the var_off, since that's inherently
15093 * bitwise. Our maximum is the minimum of the operands' maxima.
15094 */
15095 dst_reg->u32_min_value = var32_off.value;
15096 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
15097
15098 /* Safe to set s32 bounds by casting u32 result into s32 when u32
15099 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15100 */
15101 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15102 dst_reg->s32_min_value = dst_reg->u32_min_value;
15103 dst_reg->s32_max_value = dst_reg->u32_max_value;
15104 } else {
15105 dst_reg->s32_min_value = S32_MIN;
15106 dst_reg->s32_max_value = S32_MAX;
15107 }
15108 }
15109
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15110 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15111 struct bpf_reg_state *src_reg)
15112 {
15113 bool src_known = tnum_is_const(src_reg->var_off);
15114 bool dst_known = tnum_is_const(dst_reg->var_off);
15115 u64 umax_val = src_reg->umax_value;
15116
15117 if (src_known && dst_known) {
15118 __mark_reg_known(dst_reg, dst_reg->var_off.value);
15119 return;
15120 }
15121
15122 /* We get our minimum from the var_off, since that's inherently
15123 * bitwise. Our maximum is the minimum of the operands' maxima.
15124 */
15125 dst_reg->umin_value = dst_reg->var_off.value;
15126 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
15127
15128 /* Safe to set s64 bounds by casting u64 result into s64 when u64
15129 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15130 */
15131 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15132 dst_reg->smin_value = dst_reg->umin_value;
15133 dst_reg->smax_value = dst_reg->umax_value;
15134 } else {
15135 dst_reg->smin_value = S64_MIN;
15136 dst_reg->smax_value = S64_MAX;
15137 }
15138 /* We may learn something more from the var_off */
15139 __update_reg_bounds(dst_reg);
15140 }
15141
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15142 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15143 struct bpf_reg_state *src_reg)
15144 {
15145 bool src_known = tnum_subreg_is_const(src_reg->var_off);
15146 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15147 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15148 u32 umin_val = src_reg->u32_min_value;
15149
15150 if (src_known && dst_known) {
15151 __mark_reg32_known(dst_reg, var32_off.value);
15152 return;
15153 }
15154
15155 /* We get our maximum from the var_off, and our minimum is the
15156 * maximum of the operands' minima
15157 */
15158 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15159 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15160
15161 /* Safe to set s32 bounds by casting u32 result into s32 when u32
15162 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15163 */
15164 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15165 dst_reg->s32_min_value = dst_reg->u32_min_value;
15166 dst_reg->s32_max_value = dst_reg->u32_max_value;
15167 } else {
15168 dst_reg->s32_min_value = S32_MIN;
15169 dst_reg->s32_max_value = S32_MAX;
15170 }
15171 }
15172
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15173 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15174 struct bpf_reg_state *src_reg)
15175 {
15176 bool src_known = tnum_is_const(src_reg->var_off);
15177 bool dst_known = tnum_is_const(dst_reg->var_off);
15178 u64 umin_val = src_reg->umin_value;
15179
15180 if (src_known && dst_known) {
15181 __mark_reg_known(dst_reg, dst_reg->var_off.value);
15182 return;
15183 }
15184
15185 /* We get our maximum from the var_off, and our minimum is the
15186 * maximum of the operands' minima
15187 */
15188 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15189 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15190
15191 /* Safe to set s64 bounds by casting u64 result into s64 when u64
15192 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15193 */
15194 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15195 dst_reg->smin_value = dst_reg->umin_value;
15196 dst_reg->smax_value = dst_reg->umax_value;
15197 } else {
15198 dst_reg->smin_value = S64_MIN;
15199 dst_reg->smax_value = S64_MAX;
15200 }
15201 /* We may learn something more from the var_off */
15202 __update_reg_bounds(dst_reg);
15203 }
15204
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15205 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15206 struct bpf_reg_state *src_reg)
15207 {
15208 bool src_known = tnum_subreg_is_const(src_reg->var_off);
15209 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15210 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15211
15212 if (src_known && dst_known) {
15213 __mark_reg32_known(dst_reg, var32_off.value);
15214 return;
15215 }
15216
15217 /* We get both minimum and maximum from the var32_off. */
15218 dst_reg->u32_min_value = var32_off.value;
15219 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15220
15221 /* Safe to set s32 bounds by casting u32 result into s32 when u32
15222 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15223 */
15224 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15225 dst_reg->s32_min_value = dst_reg->u32_min_value;
15226 dst_reg->s32_max_value = dst_reg->u32_max_value;
15227 } else {
15228 dst_reg->s32_min_value = S32_MIN;
15229 dst_reg->s32_max_value = S32_MAX;
15230 }
15231 }
15232
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15233 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15234 struct bpf_reg_state *src_reg)
15235 {
15236 bool src_known = tnum_is_const(src_reg->var_off);
15237 bool dst_known = tnum_is_const(dst_reg->var_off);
15238
15239 if (src_known && dst_known) {
15240 /* dst_reg->var_off.value has been updated earlier */
15241 __mark_reg_known(dst_reg, dst_reg->var_off.value);
15242 return;
15243 }
15244
15245 /* We get both minimum and maximum from the var_off. */
15246 dst_reg->umin_value = dst_reg->var_off.value;
15247 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15248
15249 /* Safe to set s64 bounds by casting u64 result into s64 when u64
15250 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15251 */
15252 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15253 dst_reg->smin_value = dst_reg->umin_value;
15254 dst_reg->smax_value = dst_reg->umax_value;
15255 } else {
15256 dst_reg->smin_value = S64_MIN;
15257 dst_reg->smax_value = S64_MAX;
15258 }
15259
15260 __update_reg_bounds(dst_reg);
15261 }
15262
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15263 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15264 u64 umin_val, u64 umax_val)
15265 {
15266 /* We lose all sign bit information (except what we can pick
15267 * up from var_off)
15268 */
15269 dst_reg->s32_min_value = S32_MIN;
15270 dst_reg->s32_max_value = S32_MAX;
15271 /* If we might shift our top bit out, then we know nothing */
15272 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15273 dst_reg->u32_min_value = 0;
15274 dst_reg->u32_max_value = U32_MAX;
15275 } else {
15276 dst_reg->u32_min_value <<= umin_val;
15277 dst_reg->u32_max_value <<= umax_val;
15278 }
15279 }
15280
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15281 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15282 struct bpf_reg_state *src_reg)
15283 {
15284 u32 umax_val = src_reg->u32_max_value;
15285 u32 umin_val = src_reg->u32_min_value;
15286 /* u32 alu operation will zext upper bits */
15287 struct tnum subreg = tnum_subreg(dst_reg->var_off);
15288
15289 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15290 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15291 /* Not required but being careful mark reg64 bounds as unknown so
15292 * that we are forced to pick them up from tnum and zext later and
15293 * if some path skips this step we are still safe.
15294 */
15295 __mark_reg64_unbounded(dst_reg);
15296 __update_reg32_bounds(dst_reg);
15297 }
15298
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15299 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15300 u64 umin_val, u64 umax_val)
15301 {
15302 /* Special case <<32 because it is a common compiler pattern to sign
15303 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15304 * positive we know this shift will also be positive so we can track
15305 * bounds correctly. Otherwise we lose all sign bit information except
15306 * what we can pick up from var_off. Perhaps we can generalize this
15307 * later to shifts of any length.
15308 */
15309 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15310 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15311 else
15312 dst_reg->smax_value = S64_MAX;
15313
15314 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15315 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15316 else
15317 dst_reg->smin_value = S64_MIN;
15318
15319 /* If we might shift our top bit out, then we know nothing */
15320 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15321 dst_reg->umin_value = 0;
15322 dst_reg->umax_value = U64_MAX;
15323 } else {
15324 dst_reg->umin_value <<= umin_val;
15325 dst_reg->umax_value <<= umax_val;
15326 }
15327 }
15328
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15329 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15330 struct bpf_reg_state *src_reg)
15331 {
15332 u64 umax_val = src_reg->umax_value;
15333 u64 umin_val = src_reg->umin_value;
15334
15335 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
15336 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15337 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15338
15339 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15340 /* We may learn something more from the var_off */
15341 __update_reg_bounds(dst_reg);
15342 }
15343
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15344 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15345 struct bpf_reg_state *src_reg)
15346 {
15347 struct tnum subreg = tnum_subreg(dst_reg->var_off);
15348 u32 umax_val = src_reg->u32_max_value;
15349 u32 umin_val = src_reg->u32_min_value;
15350
15351 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
15352 * be negative, then either:
15353 * 1) src_reg might be zero, so the sign bit of the result is
15354 * unknown, so we lose our signed bounds
15355 * 2) it's known negative, thus the unsigned bounds capture the
15356 * signed bounds
15357 * 3) the signed bounds cross zero, so they tell us nothing
15358 * about the result
15359 * If the value in dst_reg is known nonnegative, then again the
15360 * unsigned bounds capture the signed bounds.
15361 * Thus, in all cases it suffices to blow away our signed bounds
15362 * and rely on inferring new ones from the unsigned bounds and
15363 * var_off of the result.
15364 */
15365 dst_reg->s32_min_value = S32_MIN;
15366 dst_reg->s32_max_value = S32_MAX;
15367
15368 dst_reg->var_off = tnum_rshift(subreg, umin_val);
15369 dst_reg->u32_min_value >>= umax_val;
15370 dst_reg->u32_max_value >>= umin_val;
15371
15372 __mark_reg64_unbounded(dst_reg);
15373 __update_reg32_bounds(dst_reg);
15374 }
15375
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15376 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15377 struct bpf_reg_state *src_reg)
15378 {
15379 u64 umax_val = src_reg->umax_value;
15380 u64 umin_val = src_reg->umin_value;
15381
15382 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
15383 * be negative, then either:
15384 * 1) src_reg might be zero, so the sign bit of the result is
15385 * unknown, so we lose our signed bounds
15386 * 2) it's known negative, thus the unsigned bounds capture the
15387 * signed bounds
15388 * 3) the signed bounds cross zero, so they tell us nothing
15389 * about the result
15390 * If the value in dst_reg is known nonnegative, then again the
15391 * unsigned bounds capture the signed bounds.
15392 * Thus, in all cases it suffices to blow away our signed bounds
15393 * and rely on inferring new ones from the unsigned bounds and
15394 * var_off of the result.
15395 */
15396 dst_reg->smin_value = S64_MIN;
15397 dst_reg->smax_value = S64_MAX;
15398 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15399 dst_reg->umin_value >>= umax_val;
15400 dst_reg->umax_value >>= umin_val;
15401
15402 /* Its not easy to operate on alu32 bounds here because it depends
15403 * on bits being shifted in. Take easy way out and mark unbounded
15404 * so we can recalculate later from tnum.
15405 */
15406 __mark_reg32_unbounded(dst_reg);
15407 __update_reg_bounds(dst_reg);
15408 }
15409
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15410 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15411 struct bpf_reg_state *src_reg)
15412 {
15413 u64 umin_val = src_reg->u32_min_value;
15414
15415 /* Upon reaching here, src_known is true and
15416 * umax_val is equal to umin_val.
15417 */
15418 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15419 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15420
15421 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15422
15423 /* blow away the dst_reg umin_value/umax_value and rely on
15424 * dst_reg var_off to refine the result.
15425 */
15426 dst_reg->u32_min_value = 0;
15427 dst_reg->u32_max_value = U32_MAX;
15428
15429 __mark_reg64_unbounded(dst_reg);
15430 __update_reg32_bounds(dst_reg);
15431 }
15432
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15433 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15434 struct bpf_reg_state *src_reg)
15435 {
15436 u64 umin_val = src_reg->umin_value;
15437
15438 /* Upon reaching here, src_known is true and umax_val is equal
15439 * to umin_val.
15440 */
15441 dst_reg->smin_value >>= umin_val;
15442 dst_reg->smax_value >>= umin_val;
15443
15444 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15445
15446 /* blow away the dst_reg umin_value/umax_value and rely on
15447 * dst_reg var_off to refine the result.
15448 */
15449 dst_reg->umin_value = 0;
15450 dst_reg->umax_value = U64_MAX;
15451
15452 /* Its not easy to operate on alu32 bounds here because it depends
15453 * on bits being shifted in from upper 32-bits. Take easy way out
15454 * and mark unbounded so we can recalculate later from tnum.
15455 */
15456 __mark_reg32_unbounded(dst_reg);
15457 __update_reg_bounds(dst_reg);
15458 }
15459
is_safe_to_compute_dst_reg_range(struct bpf_insn * insn,const struct bpf_reg_state * src_reg)15460 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15461 const struct bpf_reg_state *src_reg)
15462 {
15463 bool src_is_const = false;
15464 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15465
15466 if (insn_bitness == 32) {
15467 if (tnum_subreg_is_const(src_reg->var_off)
15468 && src_reg->s32_min_value == src_reg->s32_max_value
15469 && src_reg->u32_min_value == src_reg->u32_max_value)
15470 src_is_const = true;
15471 } else {
15472 if (tnum_is_const(src_reg->var_off)
15473 && src_reg->smin_value == src_reg->smax_value
15474 && src_reg->umin_value == src_reg->umax_value)
15475 src_is_const = true;
15476 }
15477
15478 switch (BPF_OP(insn->code)) {
15479 case BPF_ADD:
15480 case BPF_SUB:
15481 case BPF_NEG:
15482 case BPF_AND:
15483 case BPF_XOR:
15484 case BPF_OR:
15485 case BPF_MUL:
15486 return true;
15487
15488 /* Shift operators range is only computable if shift dimension operand
15489 * is a constant. Shifts greater than 31 or 63 are undefined. This
15490 * includes shifts by a negative number.
15491 */
15492 case BPF_LSH:
15493 case BPF_RSH:
15494 case BPF_ARSH:
15495 return (src_is_const && src_reg->umax_value < insn_bitness);
15496 default:
15497 return false;
15498 }
15499 }
15500
15501 /* WARNING: This function does calculations on 64-bit values, but the actual
15502 * execution may occur on 32-bit values. Therefore, things like bitshifts
15503 * need extra checks in the 32-bit case.
15504 */
adjust_scalar_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state src_reg)15505 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15506 struct bpf_insn *insn,
15507 struct bpf_reg_state *dst_reg,
15508 struct bpf_reg_state src_reg)
15509 {
15510 u8 opcode = BPF_OP(insn->code);
15511 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15512 int ret;
15513
15514 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15515 __mark_reg_unknown(env, dst_reg);
15516 return 0;
15517 }
15518
15519 if (sanitize_needed(opcode)) {
15520 ret = sanitize_val_alu(env, insn);
15521 if (ret < 0)
15522 return sanitize_err(env, insn, ret, NULL, NULL);
15523 }
15524
15525 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15526 * There are two classes of instructions: The first class we track both
15527 * alu32 and alu64 sign/unsigned bounds independently this provides the
15528 * greatest amount of precision when alu operations are mixed with jmp32
15529 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15530 * and BPF_OR. This is possible because these ops have fairly easy to
15531 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15532 * See alu32 verifier tests for examples. The second class of
15533 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15534 * with regards to tracking sign/unsigned bounds because the bits may
15535 * cross subreg boundaries in the alu64 case. When this happens we mark
15536 * the reg unbounded in the subreg bound space and use the resulting
15537 * tnum to calculate an approximation of the sign/unsigned bounds.
15538 */
15539 switch (opcode) {
15540 case BPF_ADD:
15541 scalar32_min_max_add(dst_reg, &src_reg);
15542 scalar_min_max_add(dst_reg, &src_reg);
15543 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15544 break;
15545 case BPF_SUB:
15546 scalar32_min_max_sub(dst_reg, &src_reg);
15547 scalar_min_max_sub(dst_reg, &src_reg);
15548 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15549 break;
15550 case BPF_NEG:
15551 env->fake_reg[0] = *dst_reg;
15552 __mark_reg_known(dst_reg, 0);
15553 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15554 scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15555 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15556 break;
15557 case BPF_MUL:
15558 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15559 scalar32_min_max_mul(dst_reg, &src_reg);
15560 scalar_min_max_mul(dst_reg, &src_reg);
15561 break;
15562 case BPF_AND:
15563 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15564 scalar32_min_max_and(dst_reg, &src_reg);
15565 scalar_min_max_and(dst_reg, &src_reg);
15566 break;
15567 case BPF_OR:
15568 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15569 scalar32_min_max_or(dst_reg, &src_reg);
15570 scalar_min_max_or(dst_reg, &src_reg);
15571 break;
15572 case BPF_XOR:
15573 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15574 scalar32_min_max_xor(dst_reg, &src_reg);
15575 scalar_min_max_xor(dst_reg, &src_reg);
15576 break;
15577 case BPF_LSH:
15578 if (alu32)
15579 scalar32_min_max_lsh(dst_reg, &src_reg);
15580 else
15581 scalar_min_max_lsh(dst_reg, &src_reg);
15582 break;
15583 case BPF_RSH:
15584 if (alu32)
15585 scalar32_min_max_rsh(dst_reg, &src_reg);
15586 else
15587 scalar_min_max_rsh(dst_reg, &src_reg);
15588 break;
15589 case BPF_ARSH:
15590 if (alu32)
15591 scalar32_min_max_arsh(dst_reg, &src_reg);
15592 else
15593 scalar_min_max_arsh(dst_reg, &src_reg);
15594 break;
15595 default:
15596 break;
15597 }
15598
15599 /* ALU32 ops are zero extended into 64bit register */
15600 if (alu32)
15601 zext_32_to_64(dst_reg);
15602 reg_bounds_sync(dst_reg);
15603 return 0;
15604 }
15605
15606 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15607 * and var_off.
15608 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)15609 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15610 struct bpf_insn *insn)
15611 {
15612 struct bpf_verifier_state *vstate = env->cur_state;
15613 struct bpf_func_state *state = vstate->frame[vstate->curframe];
15614 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15615 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15616 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15617 u8 opcode = BPF_OP(insn->code);
15618 int err;
15619
15620 dst_reg = ®s[insn->dst_reg];
15621 src_reg = NULL;
15622
15623 if (dst_reg->type == PTR_TO_ARENA) {
15624 struct bpf_insn_aux_data *aux = cur_aux(env);
15625
15626 if (BPF_CLASS(insn->code) == BPF_ALU64)
15627 /*
15628 * 32-bit operations zero upper bits automatically.
15629 * 64-bit operations need to be converted to 32.
15630 */
15631 aux->needs_zext = true;
15632
15633 /* Any arithmetic operations are allowed on arena pointers */
15634 return 0;
15635 }
15636
15637 if (dst_reg->type != SCALAR_VALUE)
15638 ptr_reg = dst_reg;
15639
15640 if (BPF_SRC(insn->code) == BPF_X) {
15641 src_reg = ®s[insn->src_reg];
15642 if (src_reg->type != SCALAR_VALUE) {
15643 if (dst_reg->type != SCALAR_VALUE) {
15644 /* Combining two pointers by any ALU op yields
15645 * an arbitrary scalar. Disallow all math except
15646 * pointer subtraction
15647 */
15648 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15649 mark_reg_unknown(env, regs, insn->dst_reg);
15650 return 0;
15651 }
15652 verbose(env, "R%d pointer %s pointer prohibited\n",
15653 insn->dst_reg,
15654 bpf_alu_string[opcode >> 4]);
15655 return -EACCES;
15656 } else {
15657 /* scalar += pointer
15658 * This is legal, but we have to reverse our
15659 * src/dest handling in computing the range
15660 */
15661 err = mark_chain_precision(env, insn->dst_reg);
15662 if (err)
15663 return err;
15664 return adjust_ptr_min_max_vals(env, insn,
15665 src_reg, dst_reg);
15666 }
15667 } else if (ptr_reg) {
15668 /* pointer += scalar */
15669 err = mark_chain_precision(env, insn->src_reg);
15670 if (err)
15671 return err;
15672 return adjust_ptr_min_max_vals(env, insn,
15673 dst_reg, src_reg);
15674 } else if (dst_reg->precise) {
15675 /* if dst_reg is precise, src_reg should be precise as well */
15676 err = mark_chain_precision(env, insn->src_reg);
15677 if (err)
15678 return err;
15679 }
15680 } else {
15681 /* Pretend the src is a reg with a known value, since we only
15682 * need to be able to read from this state.
15683 */
15684 off_reg.type = SCALAR_VALUE;
15685 __mark_reg_known(&off_reg, insn->imm);
15686 src_reg = &off_reg;
15687 if (ptr_reg) /* pointer += K */
15688 return adjust_ptr_min_max_vals(env, insn,
15689 ptr_reg, src_reg);
15690 }
15691
15692 /* Got here implies adding two SCALAR_VALUEs */
15693 if (WARN_ON_ONCE(ptr_reg)) {
15694 print_verifier_state(env, vstate, vstate->curframe, true);
15695 verbose(env, "verifier internal error: unexpected ptr_reg\n");
15696 return -EFAULT;
15697 }
15698 if (WARN_ON(!src_reg)) {
15699 print_verifier_state(env, vstate, vstate->curframe, true);
15700 verbose(env, "verifier internal error: no src_reg\n");
15701 return -EFAULT;
15702 }
15703 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15704 if (err)
15705 return err;
15706 /*
15707 * Compilers can generate the code
15708 * r1 = r2
15709 * r1 += 0x1
15710 * if r2 < 1000 goto ...
15711 * use r1 in memory access
15712 * So for 64-bit alu remember constant delta between r2 and r1 and
15713 * update r1 after 'if' condition.
15714 */
15715 if (env->bpf_capable &&
15716 BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15717 dst_reg->id && is_reg_const(src_reg, false)) {
15718 u64 val = reg_const_value(src_reg, false);
15719
15720 if ((dst_reg->id & BPF_ADD_CONST) ||
15721 /* prevent overflow in sync_linked_regs() later */
15722 val > (u32)S32_MAX) {
15723 /*
15724 * If the register already went through rX += val
15725 * we cannot accumulate another val into rx->off.
15726 */
15727 dst_reg->off = 0;
15728 dst_reg->id = 0;
15729 } else {
15730 dst_reg->id |= BPF_ADD_CONST;
15731 dst_reg->off = val;
15732 }
15733 } else {
15734 /*
15735 * Make sure ID is cleared otherwise dst_reg min/max could be
15736 * incorrectly propagated into other registers by sync_linked_regs()
15737 */
15738 dst_reg->id = 0;
15739 }
15740 return 0;
15741 }
15742
15743 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)15744 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15745 {
15746 struct bpf_reg_state *regs = cur_regs(env);
15747 u8 opcode = BPF_OP(insn->code);
15748 int err;
15749
15750 if (opcode == BPF_END || opcode == BPF_NEG) {
15751 if (opcode == BPF_NEG) {
15752 if (BPF_SRC(insn->code) != BPF_K ||
15753 insn->src_reg != BPF_REG_0 ||
15754 insn->off != 0 || insn->imm != 0) {
15755 verbose(env, "BPF_NEG uses reserved fields\n");
15756 return -EINVAL;
15757 }
15758 } else {
15759 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15760 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15761 (BPF_CLASS(insn->code) == BPF_ALU64 &&
15762 BPF_SRC(insn->code) != BPF_TO_LE)) {
15763 verbose(env, "BPF_END uses reserved fields\n");
15764 return -EINVAL;
15765 }
15766 }
15767
15768 /* check src operand */
15769 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15770 if (err)
15771 return err;
15772
15773 if (is_pointer_value(env, insn->dst_reg)) {
15774 verbose(env, "R%d pointer arithmetic prohibited\n",
15775 insn->dst_reg);
15776 return -EACCES;
15777 }
15778
15779 /* check dest operand */
15780 if (opcode == BPF_NEG &&
15781 regs[insn->dst_reg].type == SCALAR_VALUE) {
15782 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15783 err = err ?: adjust_scalar_min_max_vals(env, insn,
15784 ®s[insn->dst_reg],
15785 regs[insn->dst_reg]);
15786 } else {
15787 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15788 }
15789 if (err)
15790 return err;
15791
15792 } else if (opcode == BPF_MOV) {
15793
15794 if (BPF_SRC(insn->code) == BPF_X) {
15795 if (BPF_CLASS(insn->code) == BPF_ALU) {
15796 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15797 insn->imm) {
15798 verbose(env, "BPF_MOV uses reserved fields\n");
15799 return -EINVAL;
15800 }
15801 } else if (insn->off == BPF_ADDR_SPACE_CAST) {
15802 if (insn->imm != 1 && insn->imm != 1u << 16) {
15803 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15804 return -EINVAL;
15805 }
15806 if (!env->prog->aux->arena) {
15807 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15808 return -EINVAL;
15809 }
15810 } else {
15811 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15812 insn->off != 32) || insn->imm) {
15813 verbose(env, "BPF_MOV uses reserved fields\n");
15814 return -EINVAL;
15815 }
15816 }
15817
15818 /* check src operand */
15819 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15820 if (err)
15821 return err;
15822 } else {
15823 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15824 verbose(env, "BPF_MOV uses reserved fields\n");
15825 return -EINVAL;
15826 }
15827 }
15828
15829 /* check dest operand, mark as required later */
15830 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15831 if (err)
15832 return err;
15833
15834 if (BPF_SRC(insn->code) == BPF_X) {
15835 struct bpf_reg_state *src_reg = regs + insn->src_reg;
15836 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15837
15838 if (BPF_CLASS(insn->code) == BPF_ALU64) {
15839 if (insn->imm) {
15840 /* off == BPF_ADDR_SPACE_CAST */
15841 mark_reg_unknown(env, regs, insn->dst_reg);
15842 if (insn->imm == 1) { /* cast from as(1) to as(0) */
15843 dst_reg->type = PTR_TO_ARENA;
15844 /* PTR_TO_ARENA is 32-bit */
15845 dst_reg->subreg_def = env->insn_idx + 1;
15846 }
15847 } else if (insn->off == 0) {
15848 /* case: R1 = R2
15849 * copy register state to dest reg
15850 */
15851 assign_scalar_id_before_mov(env, src_reg);
15852 copy_register_state(dst_reg, src_reg);
15853 dst_reg->subreg_def = DEF_NOT_SUBREG;
15854 } else {
15855 /* case: R1 = (s8, s16 s32)R2 */
15856 if (is_pointer_value(env, insn->src_reg)) {
15857 verbose(env,
15858 "R%d sign-extension part of pointer\n",
15859 insn->src_reg);
15860 return -EACCES;
15861 } else if (src_reg->type == SCALAR_VALUE) {
15862 bool no_sext;
15863
15864 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15865 if (no_sext)
15866 assign_scalar_id_before_mov(env, src_reg);
15867 copy_register_state(dst_reg, src_reg);
15868 if (!no_sext)
15869 dst_reg->id = 0;
15870 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15871 dst_reg->subreg_def = DEF_NOT_SUBREG;
15872 } else {
15873 mark_reg_unknown(env, regs, insn->dst_reg);
15874 }
15875 }
15876 } else {
15877 /* R1 = (u32) R2 */
15878 if (is_pointer_value(env, insn->src_reg)) {
15879 verbose(env,
15880 "R%d partial copy of pointer\n",
15881 insn->src_reg);
15882 return -EACCES;
15883 } else if (src_reg->type == SCALAR_VALUE) {
15884 if (insn->off == 0) {
15885 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15886
15887 if (is_src_reg_u32)
15888 assign_scalar_id_before_mov(env, src_reg);
15889 copy_register_state(dst_reg, src_reg);
15890 /* Make sure ID is cleared if src_reg is not in u32
15891 * range otherwise dst_reg min/max could be incorrectly
15892 * propagated into src_reg by sync_linked_regs()
15893 */
15894 if (!is_src_reg_u32)
15895 dst_reg->id = 0;
15896 dst_reg->subreg_def = env->insn_idx + 1;
15897 } else {
15898 /* case: W1 = (s8, s16)W2 */
15899 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15900
15901 if (no_sext)
15902 assign_scalar_id_before_mov(env, src_reg);
15903 copy_register_state(dst_reg, src_reg);
15904 if (!no_sext)
15905 dst_reg->id = 0;
15906 dst_reg->subreg_def = env->insn_idx + 1;
15907 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15908 }
15909 } else {
15910 mark_reg_unknown(env, regs,
15911 insn->dst_reg);
15912 }
15913 zext_32_to_64(dst_reg);
15914 reg_bounds_sync(dst_reg);
15915 }
15916 } else {
15917 /* case: R = imm
15918 * remember the value we stored into this reg
15919 */
15920 /* clear any state __mark_reg_known doesn't set */
15921 mark_reg_unknown(env, regs, insn->dst_reg);
15922 regs[insn->dst_reg].type = SCALAR_VALUE;
15923 if (BPF_CLASS(insn->code) == BPF_ALU64) {
15924 __mark_reg_known(regs + insn->dst_reg,
15925 insn->imm);
15926 } else {
15927 __mark_reg_known(regs + insn->dst_reg,
15928 (u32)insn->imm);
15929 }
15930 }
15931
15932 } else if (opcode > BPF_END) {
15933 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15934 return -EINVAL;
15935
15936 } else { /* all other ALU ops: and, sub, xor, add, ... */
15937
15938 if (BPF_SRC(insn->code) == BPF_X) {
15939 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
15940 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15941 verbose(env, "BPF_ALU uses reserved fields\n");
15942 return -EINVAL;
15943 }
15944 /* check src1 operand */
15945 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15946 if (err)
15947 return err;
15948 } else {
15949 if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
15950 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15951 verbose(env, "BPF_ALU uses reserved fields\n");
15952 return -EINVAL;
15953 }
15954 }
15955
15956 /* check src2 operand */
15957 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15958 if (err)
15959 return err;
15960
15961 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15962 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15963 verbose(env, "div by zero\n");
15964 return -EINVAL;
15965 }
15966
15967 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15968 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15969 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15970
15971 if (insn->imm < 0 || insn->imm >= size) {
15972 verbose(env, "invalid shift %d\n", insn->imm);
15973 return -EINVAL;
15974 }
15975 }
15976
15977 /* check dest operand */
15978 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15979 err = err ?: adjust_reg_min_max_vals(env, insn);
15980 if (err)
15981 return err;
15982 }
15983
15984 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
15985 }
15986
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)15987 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15988 struct bpf_reg_state *dst_reg,
15989 enum bpf_reg_type type,
15990 bool range_right_open)
15991 {
15992 struct bpf_func_state *state;
15993 struct bpf_reg_state *reg;
15994 int new_range;
15995
15996 if (dst_reg->off < 0 ||
15997 (dst_reg->off == 0 && range_right_open))
15998 /* This doesn't give us any range */
15999 return;
16000
16001 if (dst_reg->umax_value > MAX_PACKET_OFF ||
16002 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
16003 /* Risk of overflow. For instance, ptr + (1<<63) may be less
16004 * than pkt_end, but that's because it's also less than pkt.
16005 */
16006 return;
16007
16008 new_range = dst_reg->off;
16009 if (range_right_open)
16010 new_range++;
16011
16012 /* Examples for register markings:
16013 *
16014 * pkt_data in dst register:
16015 *
16016 * r2 = r3;
16017 * r2 += 8;
16018 * if (r2 > pkt_end) goto <handle exception>
16019 * <access okay>
16020 *
16021 * r2 = r3;
16022 * r2 += 8;
16023 * if (r2 < pkt_end) goto <access okay>
16024 * <handle exception>
16025 *
16026 * Where:
16027 * r2 == dst_reg, pkt_end == src_reg
16028 * r2=pkt(id=n,off=8,r=0)
16029 * r3=pkt(id=n,off=0,r=0)
16030 *
16031 * pkt_data in src register:
16032 *
16033 * r2 = r3;
16034 * r2 += 8;
16035 * if (pkt_end >= r2) goto <access okay>
16036 * <handle exception>
16037 *
16038 * r2 = r3;
16039 * r2 += 8;
16040 * if (pkt_end <= r2) goto <handle exception>
16041 * <access okay>
16042 *
16043 * Where:
16044 * pkt_end == dst_reg, r2 == src_reg
16045 * r2=pkt(id=n,off=8,r=0)
16046 * r3=pkt(id=n,off=0,r=0)
16047 *
16048 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16049 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16050 * and [r3, r3 + 8-1) respectively is safe to access depending on
16051 * the check.
16052 */
16053
16054 /* If our ids match, then we must have the same max_value. And we
16055 * don't care about the other reg's fixed offset, since if it's too big
16056 * the range won't allow anything.
16057 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
16058 */
16059 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16060 if (reg->type == type && reg->id == dst_reg->id)
16061 /* keep the maximum range already checked */
16062 reg->range = max(reg->range, new_range);
16063 }));
16064 }
16065
16066 /*
16067 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16068 */
is_scalar_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16069 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16070 u8 opcode, bool is_jmp32)
16071 {
16072 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16073 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16074 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
16075 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
16076 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
16077 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
16078 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
16079 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
16080 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
16081 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
16082
16083 if (reg1 == reg2) {
16084 switch (opcode) {
16085 case BPF_JGE:
16086 case BPF_JLE:
16087 case BPF_JSGE:
16088 case BPF_JSLE:
16089 case BPF_JEQ:
16090 return 1;
16091 case BPF_JGT:
16092 case BPF_JLT:
16093 case BPF_JSGT:
16094 case BPF_JSLT:
16095 case BPF_JNE:
16096 return 0;
16097 case BPF_JSET:
16098 if (tnum_is_const(t1))
16099 return t1.value != 0;
16100 else
16101 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16102 default:
16103 return -1;
16104 }
16105 }
16106
16107 switch (opcode) {
16108 case BPF_JEQ:
16109 /* constants, umin/umax and smin/smax checks would be
16110 * redundant in this case because they all should match
16111 */
16112 if (tnum_is_const(t1) && tnum_is_const(t2))
16113 return t1.value == t2.value;
16114 if (!tnum_overlap(t1, t2))
16115 return 0;
16116 /* non-overlapping ranges */
16117 if (umin1 > umax2 || umax1 < umin2)
16118 return 0;
16119 if (smin1 > smax2 || smax1 < smin2)
16120 return 0;
16121 if (!is_jmp32) {
16122 /* if 64-bit ranges are inconclusive, see if we can
16123 * utilize 32-bit subrange knowledge to eliminate
16124 * branches that can't be taken a priori
16125 */
16126 if (reg1->u32_min_value > reg2->u32_max_value ||
16127 reg1->u32_max_value < reg2->u32_min_value)
16128 return 0;
16129 if (reg1->s32_min_value > reg2->s32_max_value ||
16130 reg1->s32_max_value < reg2->s32_min_value)
16131 return 0;
16132 }
16133 break;
16134 case BPF_JNE:
16135 /* constants, umin/umax and smin/smax checks would be
16136 * redundant in this case because they all should match
16137 */
16138 if (tnum_is_const(t1) && tnum_is_const(t2))
16139 return t1.value != t2.value;
16140 if (!tnum_overlap(t1, t2))
16141 return 1;
16142 /* non-overlapping ranges */
16143 if (umin1 > umax2 || umax1 < umin2)
16144 return 1;
16145 if (smin1 > smax2 || smax1 < smin2)
16146 return 1;
16147 if (!is_jmp32) {
16148 /* if 64-bit ranges are inconclusive, see if we can
16149 * utilize 32-bit subrange knowledge to eliminate
16150 * branches that can't be taken a priori
16151 */
16152 if (reg1->u32_min_value > reg2->u32_max_value ||
16153 reg1->u32_max_value < reg2->u32_min_value)
16154 return 1;
16155 if (reg1->s32_min_value > reg2->s32_max_value ||
16156 reg1->s32_max_value < reg2->s32_min_value)
16157 return 1;
16158 }
16159 break;
16160 case BPF_JSET:
16161 if (!is_reg_const(reg2, is_jmp32)) {
16162 swap(reg1, reg2);
16163 swap(t1, t2);
16164 }
16165 if (!is_reg_const(reg2, is_jmp32))
16166 return -1;
16167 if ((~t1.mask & t1.value) & t2.value)
16168 return 1;
16169 if (!((t1.mask | t1.value) & t2.value))
16170 return 0;
16171 break;
16172 case BPF_JGT:
16173 if (umin1 > umax2)
16174 return 1;
16175 else if (umax1 <= umin2)
16176 return 0;
16177 break;
16178 case BPF_JSGT:
16179 if (smin1 > smax2)
16180 return 1;
16181 else if (smax1 <= smin2)
16182 return 0;
16183 break;
16184 case BPF_JLT:
16185 if (umax1 < umin2)
16186 return 1;
16187 else if (umin1 >= umax2)
16188 return 0;
16189 break;
16190 case BPF_JSLT:
16191 if (smax1 < smin2)
16192 return 1;
16193 else if (smin1 >= smax2)
16194 return 0;
16195 break;
16196 case BPF_JGE:
16197 if (umin1 >= umax2)
16198 return 1;
16199 else if (umax1 < umin2)
16200 return 0;
16201 break;
16202 case BPF_JSGE:
16203 if (smin1 >= smax2)
16204 return 1;
16205 else if (smax1 < smin2)
16206 return 0;
16207 break;
16208 case BPF_JLE:
16209 if (umax1 <= umin2)
16210 return 1;
16211 else if (umin1 > umax2)
16212 return 0;
16213 break;
16214 case BPF_JSLE:
16215 if (smax1 <= smin2)
16216 return 1;
16217 else if (smin1 > smax2)
16218 return 0;
16219 break;
16220 }
16221
16222 return -1;
16223 }
16224
flip_opcode(u32 opcode)16225 static int flip_opcode(u32 opcode)
16226 {
16227 /* How can we transform "a <op> b" into "b <op> a"? */
16228 static const u8 opcode_flip[16] = {
16229 /* these stay the same */
16230 [BPF_JEQ >> 4] = BPF_JEQ,
16231 [BPF_JNE >> 4] = BPF_JNE,
16232 [BPF_JSET >> 4] = BPF_JSET,
16233 /* these swap "lesser" and "greater" (L and G in the opcodes) */
16234 [BPF_JGE >> 4] = BPF_JLE,
16235 [BPF_JGT >> 4] = BPF_JLT,
16236 [BPF_JLE >> 4] = BPF_JGE,
16237 [BPF_JLT >> 4] = BPF_JGT,
16238 [BPF_JSGE >> 4] = BPF_JSLE,
16239 [BPF_JSGT >> 4] = BPF_JSLT,
16240 [BPF_JSLE >> 4] = BPF_JSGE,
16241 [BPF_JSLT >> 4] = BPF_JSGT
16242 };
16243 return opcode_flip[opcode >> 4];
16244 }
16245
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)16246 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16247 struct bpf_reg_state *src_reg,
16248 u8 opcode)
16249 {
16250 struct bpf_reg_state *pkt;
16251
16252 if (src_reg->type == PTR_TO_PACKET_END) {
16253 pkt = dst_reg;
16254 } else if (dst_reg->type == PTR_TO_PACKET_END) {
16255 pkt = src_reg;
16256 opcode = flip_opcode(opcode);
16257 } else {
16258 return -1;
16259 }
16260
16261 if (pkt->range >= 0)
16262 return -1;
16263
16264 switch (opcode) {
16265 case BPF_JLE:
16266 /* pkt <= pkt_end */
16267 fallthrough;
16268 case BPF_JGT:
16269 /* pkt > pkt_end */
16270 if (pkt->range == BEYOND_PKT_END)
16271 /* pkt has at last one extra byte beyond pkt_end */
16272 return opcode == BPF_JGT;
16273 break;
16274 case BPF_JLT:
16275 /* pkt < pkt_end */
16276 fallthrough;
16277 case BPF_JGE:
16278 /* pkt >= pkt_end */
16279 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16280 return opcode == BPF_JGE;
16281 break;
16282 }
16283 return -1;
16284 }
16285
16286 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16287 * and return:
16288 * 1 - branch will be taken and "goto target" will be executed
16289 * 0 - branch will not be taken and fall-through to next insn
16290 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16291 * range [0,10]
16292 */
is_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16293 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16294 u8 opcode, bool is_jmp32)
16295 {
16296 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16297 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16298
16299 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16300 u64 val;
16301
16302 /* arrange that reg2 is a scalar, and reg1 is a pointer */
16303 if (!is_reg_const(reg2, is_jmp32)) {
16304 opcode = flip_opcode(opcode);
16305 swap(reg1, reg2);
16306 }
16307 /* and ensure that reg2 is a constant */
16308 if (!is_reg_const(reg2, is_jmp32))
16309 return -1;
16310
16311 if (!reg_not_null(reg1))
16312 return -1;
16313
16314 /* If pointer is valid tests against zero will fail so we can
16315 * use this to direct branch taken.
16316 */
16317 val = reg_const_value(reg2, is_jmp32);
16318 if (val != 0)
16319 return -1;
16320
16321 switch (opcode) {
16322 case BPF_JEQ:
16323 return 0;
16324 case BPF_JNE:
16325 return 1;
16326 default:
16327 return -1;
16328 }
16329 }
16330
16331 /* now deal with two scalars, but not necessarily constants */
16332 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16333 }
16334
16335 /* Opcode that corresponds to a *false* branch condition.
16336 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16337 */
rev_opcode(u8 opcode)16338 static u8 rev_opcode(u8 opcode)
16339 {
16340 switch (opcode) {
16341 case BPF_JEQ: return BPF_JNE;
16342 case BPF_JNE: return BPF_JEQ;
16343 /* JSET doesn't have it's reverse opcode in BPF, so add
16344 * BPF_X flag to denote the reverse of that operation
16345 */
16346 case BPF_JSET: return BPF_JSET | BPF_X;
16347 case BPF_JSET | BPF_X: return BPF_JSET;
16348 case BPF_JGE: return BPF_JLT;
16349 case BPF_JGT: return BPF_JLE;
16350 case BPF_JLE: return BPF_JGT;
16351 case BPF_JLT: return BPF_JGE;
16352 case BPF_JSGE: return BPF_JSLT;
16353 case BPF_JSGT: return BPF_JSLE;
16354 case BPF_JSLE: return BPF_JSGT;
16355 case BPF_JSLT: return BPF_JSGE;
16356 default: return 0;
16357 }
16358 }
16359
16360 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */
regs_refine_cond_op(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16361 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16362 u8 opcode, bool is_jmp32)
16363 {
16364 struct tnum t;
16365 u64 val;
16366
16367 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16368 switch (opcode) {
16369 case BPF_JGE:
16370 case BPF_JGT:
16371 case BPF_JSGE:
16372 case BPF_JSGT:
16373 opcode = flip_opcode(opcode);
16374 swap(reg1, reg2);
16375 break;
16376 default:
16377 break;
16378 }
16379
16380 switch (opcode) {
16381 case BPF_JEQ:
16382 if (is_jmp32) {
16383 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16384 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16385 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16386 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16387 reg2->u32_min_value = reg1->u32_min_value;
16388 reg2->u32_max_value = reg1->u32_max_value;
16389 reg2->s32_min_value = reg1->s32_min_value;
16390 reg2->s32_max_value = reg1->s32_max_value;
16391
16392 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16393 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16394 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16395 } else {
16396 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16397 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16398 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16399 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16400 reg2->umin_value = reg1->umin_value;
16401 reg2->umax_value = reg1->umax_value;
16402 reg2->smin_value = reg1->smin_value;
16403 reg2->smax_value = reg1->smax_value;
16404
16405 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16406 reg2->var_off = reg1->var_off;
16407 }
16408 break;
16409 case BPF_JNE:
16410 if (!is_reg_const(reg2, is_jmp32))
16411 swap(reg1, reg2);
16412 if (!is_reg_const(reg2, is_jmp32))
16413 break;
16414
16415 /* try to recompute the bound of reg1 if reg2 is a const and
16416 * is exactly the edge of reg1.
16417 */
16418 val = reg_const_value(reg2, is_jmp32);
16419 if (is_jmp32) {
16420 /* u32_min_value is not equal to 0xffffffff at this point,
16421 * because otherwise u32_max_value is 0xffffffff as well,
16422 * in such a case both reg1 and reg2 would be constants,
16423 * jump would be predicted and reg_set_min_max() won't
16424 * be called.
16425 *
16426 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16427 * below.
16428 */
16429 if (reg1->u32_min_value == (u32)val)
16430 reg1->u32_min_value++;
16431 if (reg1->u32_max_value == (u32)val)
16432 reg1->u32_max_value--;
16433 if (reg1->s32_min_value == (s32)val)
16434 reg1->s32_min_value++;
16435 if (reg1->s32_max_value == (s32)val)
16436 reg1->s32_max_value--;
16437 } else {
16438 if (reg1->umin_value == (u64)val)
16439 reg1->umin_value++;
16440 if (reg1->umax_value == (u64)val)
16441 reg1->umax_value--;
16442 if (reg1->smin_value == (s64)val)
16443 reg1->smin_value++;
16444 if (reg1->smax_value == (s64)val)
16445 reg1->smax_value--;
16446 }
16447 break;
16448 case BPF_JSET:
16449 if (!is_reg_const(reg2, is_jmp32))
16450 swap(reg1, reg2);
16451 if (!is_reg_const(reg2, is_jmp32))
16452 break;
16453 val = reg_const_value(reg2, is_jmp32);
16454 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16455 * requires single bit to learn something useful. E.g., if we
16456 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16457 * are actually set? We can learn something definite only if
16458 * it's a single-bit value to begin with.
16459 *
16460 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16461 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16462 * bit 1 is set, which we can readily use in adjustments.
16463 */
16464 if (!is_power_of_2(val))
16465 break;
16466 if (is_jmp32) {
16467 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16468 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16469 } else {
16470 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16471 }
16472 break;
16473 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16474 if (!is_reg_const(reg2, is_jmp32))
16475 swap(reg1, reg2);
16476 if (!is_reg_const(reg2, is_jmp32))
16477 break;
16478 val = reg_const_value(reg2, is_jmp32);
16479 /* Forget the ranges before narrowing tnums, to avoid invariant
16480 * violations if we're on a dead branch.
16481 */
16482 __mark_reg_unbounded(reg1);
16483 if (is_jmp32) {
16484 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16485 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16486 } else {
16487 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16488 }
16489 break;
16490 case BPF_JLE:
16491 if (is_jmp32) {
16492 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16493 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16494 } else {
16495 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16496 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16497 }
16498 break;
16499 case BPF_JLT:
16500 if (is_jmp32) {
16501 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16502 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16503 } else {
16504 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16505 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16506 }
16507 break;
16508 case BPF_JSLE:
16509 if (is_jmp32) {
16510 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16511 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16512 } else {
16513 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16514 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16515 }
16516 break;
16517 case BPF_JSLT:
16518 if (is_jmp32) {
16519 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16520 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16521 } else {
16522 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16523 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16524 }
16525 break;
16526 default:
16527 return;
16528 }
16529 }
16530
16531 /* Adjusts the register min/max values in the case that the dst_reg and
16532 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16533 * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16534 * Technically we can do similar adjustments for pointers to the same object,
16535 * but we don't support that right now.
16536 */
reg_set_min_max(struct bpf_verifier_env * env,struct bpf_reg_state * true_reg1,struct bpf_reg_state * true_reg2,struct bpf_reg_state * false_reg1,struct bpf_reg_state * false_reg2,u8 opcode,bool is_jmp32)16537 static int reg_set_min_max(struct bpf_verifier_env *env,
16538 struct bpf_reg_state *true_reg1,
16539 struct bpf_reg_state *true_reg2,
16540 struct bpf_reg_state *false_reg1,
16541 struct bpf_reg_state *false_reg2,
16542 u8 opcode, bool is_jmp32)
16543 {
16544 int err;
16545
16546 /* If either register is a pointer, we can't learn anything about its
16547 * variable offset from the compare (unless they were a pointer into
16548 * the same object, but we don't bother with that).
16549 */
16550 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16551 return 0;
16552
16553 /* We compute branch direction for same SCALAR_VALUE registers in
16554 * is_scalar_branch_taken(). For unknown branch directions (e.g., BPF_JSET)
16555 * on the same registers, we don't need to adjust the min/max values.
16556 */
16557 if (false_reg1 == false_reg2)
16558 return 0;
16559
16560 /* fallthrough (FALSE) branch */
16561 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16562 reg_bounds_sync(false_reg1);
16563 reg_bounds_sync(false_reg2);
16564
16565 /* jump (TRUE) branch */
16566 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16567 reg_bounds_sync(true_reg1);
16568 reg_bounds_sync(true_reg2);
16569
16570 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16571 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16572 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16573 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16574 return err;
16575 }
16576
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)16577 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16578 struct bpf_reg_state *reg, u32 id,
16579 bool is_null)
16580 {
16581 if (type_may_be_null(reg->type) && reg->id == id &&
16582 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16583 /* Old offset (both fixed and variable parts) should have been
16584 * known-zero, because we don't allow pointer arithmetic on
16585 * pointers that might be NULL. If we see this happening, don't
16586 * convert the register.
16587 *
16588 * But in some cases, some helpers that return local kptrs
16589 * advance offset for the returned pointer. In those cases, it
16590 * is fine to expect to see reg->off.
16591 */
16592 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16593 return;
16594 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16595 WARN_ON_ONCE(reg->off))
16596 return;
16597
16598 if (is_null) {
16599 reg->type = SCALAR_VALUE;
16600 /* We don't need id and ref_obj_id from this point
16601 * onwards anymore, thus we should better reset it,
16602 * so that state pruning has chances to take effect.
16603 */
16604 reg->id = 0;
16605 reg->ref_obj_id = 0;
16606
16607 return;
16608 }
16609
16610 mark_ptr_not_null_reg(reg);
16611
16612 if (!reg_may_point_to_spin_lock(reg)) {
16613 /* For not-NULL ptr, reg->ref_obj_id will be reset
16614 * in release_reference().
16615 *
16616 * reg->id is still used by spin_lock ptr. Other
16617 * than spin_lock ptr type, reg->id can be reset.
16618 */
16619 reg->id = 0;
16620 }
16621 }
16622 }
16623
16624 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16625 * be folded together at some point.
16626 */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)16627 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16628 bool is_null)
16629 {
16630 struct bpf_func_state *state = vstate->frame[vstate->curframe];
16631 struct bpf_reg_state *regs = state->regs, *reg;
16632 u32 ref_obj_id = regs[regno].ref_obj_id;
16633 u32 id = regs[regno].id;
16634
16635 if (ref_obj_id && ref_obj_id == id && is_null)
16636 /* regs[regno] is in the " == NULL" branch.
16637 * No one could have freed the reference state before
16638 * doing the NULL check.
16639 */
16640 WARN_ON_ONCE(release_reference_nomark(vstate, id));
16641
16642 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16643 mark_ptr_or_null_reg(state, reg, id, is_null);
16644 }));
16645 }
16646
try_match_pkt_pointers(const struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,struct bpf_verifier_state * this_branch,struct bpf_verifier_state * other_branch)16647 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16648 struct bpf_reg_state *dst_reg,
16649 struct bpf_reg_state *src_reg,
16650 struct bpf_verifier_state *this_branch,
16651 struct bpf_verifier_state *other_branch)
16652 {
16653 if (BPF_SRC(insn->code) != BPF_X)
16654 return false;
16655
16656 /* Pointers are always 64-bit. */
16657 if (BPF_CLASS(insn->code) == BPF_JMP32)
16658 return false;
16659
16660 switch (BPF_OP(insn->code)) {
16661 case BPF_JGT:
16662 if ((dst_reg->type == PTR_TO_PACKET &&
16663 src_reg->type == PTR_TO_PACKET_END) ||
16664 (dst_reg->type == PTR_TO_PACKET_META &&
16665 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16666 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16667 find_good_pkt_pointers(this_branch, dst_reg,
16668 dst_reg->type, false);
16669 mark_pkt_end(other_branch, insn->dst_reg, true);
16670 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16671 src_reg->type == PTR_TO_PACKET) ||
16672 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16673 src_reg->type == PTR_TO_PACKET_META)) {
16674 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
16675 find_good_pkt_pointers(other_branch, src_reg,
16676 src_reg->type, true);
16677 mark_pkt_end(this_branch, insn->src_reg, false);
16678 } else {
16679 return false;
16680 }
16681 break;
16682 case BPF_JLT:
16683 if ((dst_reg->type == PTR_TO_PACKET &&
16684 src_reg->type == PTR_TO_PACKET_END) ||
16685 (dst_reg->type == PTR_TO_PACKET_META &&
16686 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16687 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16688 find_good_pkt_pointers(other_branch, dst_reg,
16689 dst_reg->type, true);
16690 mark_pkt_end(this_branch, insn->dst_reg, false);
16691 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16692 src_reg->type == PTR_TO_PACKET) ||
16693 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16694 src_reg->type == PTR_TO_PACKET_META)) {
16695 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
16696 find_good_pkt_pointers(this_branch, src_reg,
16697 src_reg->type, false);
16698 mark_pkt_end(other_branch, insn->src_reg, true);
16699 } else {
16700 return false;
16701 }
16702 break;
16703 case BPF_JGE:
16704 if ((dst_reg->type == PTR_TO_PACKET &&
16705 src_reg->type == PTR_TO_PACKET_END) ||
16706 (dst_reg->type == PTR_TO_PACKET_META &&
16707 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16708 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16709 find_good_pkt_pointers(this_branch, dst_reg,
16710 dst_reg->type, true);
16711 mark_pkt_end(other_branch, insn->dst_reg, false);
16712 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16713 src_reg->type == PTR_TO_PACKET) ||
16714 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16715 src_reg->type == PTR_TO_PACKET_META)) {
16716 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16717 find_good_pkt_pointers(other_branch, src_reg,
16718 src_reg->type, false);
16719 mark_pkt_end(this_branch, insn->src_reg, true);
16720 } else {
16721 return false;
16722 }
16723 break;
16724 case BPF_JLE:
16725 if ((dst_reg->type == PTR_TO_PACKET &&
16726 src_reg->type == PTR_TO_PACKET_END) ||
16727 (dst_reg->type == PTR_TO_PACKET_META &&
16728 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16729 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16730 find_good_pkt_pointers(other_branch, dst_reg,
16731 dst_reg->type, false);
16732 mark_pkt_end(this_branch, insn->dst_reg, true);
16733 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16734 src_reg->type == PTR_TO_PACKET) ||
16735 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16736 src_reg->type == PTR_TO_PACKET_META)) {
16737 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16738 find_good_pkt_pointers(this_branch, src_reg,
16739 src_reg->type, true);
16740 mark_pkt_end(other_branch, insn->src_reg, false);
16741 } else {
16742 return false;
16743 }
16744 break;
16745 default:
16746 return false;
16747 }
16748
16749 return true;
16750 }
16751
__collect_linked_regs(struct linked_regs * reg_set,struct bpf_reg_state * reg,u32 id,u32 frameno,u32 spi_or_reg,bool is_reg)16752 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16753 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16754 {
16755 struct linked_reg *e;
16756
16757 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16758 return;
16759
16760 e = linked_regs_push(reg_set);
16761 if (e) {
16762 e->frameno = frameno;
16763 e->is_reg = is_reg;
16764 e->regno = spi_or_reg;
16765 } else {
16766 reg->id = 0;
16767 }
16768 }
16769
16770 /* For all R being scalar registers or spilled scalar registers
16771 * in verifier state, save R in linked_regs if R->id == id.
16772 * If there are too many Rs sharing same id, reset id for leftover Rs.
16773 */
collect_linked_regs(struct bpf_verifier_state * vstate,u32 id,struct linked_regs * linked_regs)16774 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16775 struct linked_regs *linked_regs)
16776 {
16777 struct bpf_func_state *func;
16778 struct bpf_reg_state *reg;
16779 int i, j;
16780
16781 id = id & ~BPF_ADD_CONST;
16782 for (i = vstate->curframe; i >= 0; i--) {
16783 func = vstate->frame[i];
16784 for (j = 0; j < BPF_REG_FP; j++) {
16785 reg = &func->regs[j];
16786 __collect_linked_regs(linked_regs, reg, id, i, j, true);
16787 }
16788 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16789 if (!is_spilled_reg(&func->stack[j]))
16790 continue;
16791 reg = &func->stack[j].spilled_ptr;
16792 __collect_linked_regs(linked_regs, reg, id, i, j, false);
16793 }
16794 }
16795 }
16796
16797 /* For all R in linked_regs, copy known_reg range into R
16798 * if R->id == known_reg->id.
16799 */
sync_linked_regs(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg,struct linked_regs * linked_regs)16800 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16801 struct linked_regs *linked_regs)
16802 {
16803 struct bpf_reg_state fake_reg;
16804 struct bpf_reg_state *reg;
16805 struct linked_reg *e;
16806 int i;
16807
16808 for (i = 0; i < linked_regs->cnt; ++i) {
16809 e = &linked_regs->entries[i];
16810 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16811 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16812 if (reg->type != SCALAR_VALUE || reg == known_reg)
16813 continue;
16814 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16815 continue;
16816 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16817 reg->off == known_reg->off) {
16818 s32 saved_subreg_def = reg->subreg_def;
16819
16820 copy_register_state(reg, known_reg);
16821 reg->subreg_def = saved_subreg_def;
16822 } else {
16823 s32 saved_subreg_def = reg->subreg_def;
16824 s32 saved_off = reg->off;
16825
16826 fake_reg.type = SCALAR_VALUE;
16827 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16828
16829 /* reg = known_reg; reg += delta */
16830 copy_register_state(reg, known_reg);
16831 /*
16832 * Must preserve off, id and add_const flag,
16833 * otherwise another sync_linked_regs() will be incorrect.
16834 */
16835 reg->off = saved_off;
16836 reg->subreg_def = saved_subreg_def;
16837
16838 scalar32_min_max_add(reg, &fake_reg);
16839 scalar_min_max_add(reg, &fake_reg);
16840 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16841 }
16842 }
16843 }
16844
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)16845 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16846 struct bpf_insn *insn, int *insn_idx)
16847 {
16848 struct bpf_verifier_state *this_branch = env->cur_state;
16849 struct bpf_verifier_state *other_branch;
16850 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16851 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16852 struct bpf_reg_state *eq_branch_regs;
16853 struct linked_regs linked_regs = {};
16854 u8 opcode = BPF_OP(insn->code);
16855 int insn_flags = 0;
16856 bool is_jmp32;
16857 int pred = -1;
16858 int err;
16859
16860 /* Only conditional jumps are expected to reach here. */
16861 if (opcode == BPF_JA || opcode > BPF_JCOND) {
16862 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16863 return -EINVAL;
16864 }
16865
16866 if (opcode == BPF_JCOND) {
16867 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16868 int idx = *insn_idx;
16869
16870 if (insn->code != (BPF_JMP | BPF_JCOND) ||
16871 insn->src_reg != BPF_MAY_GOTO ||
16872 insn->dst_reg || insn->imm) {
16873 verbose(env, "invalid may_goto imm %d\n", insn->imm);
16874 return -EINVAL;
16875 }
16876 prev_st = find_prev_entry(env, cur_st->parent, idx);
16877
16878 /* branch out 'fallthrough' insn as a new state to explore */
16879 queued_st = push_stack(env, idx + 1, idx, false);
16880 if (IS_ERR(queued_st))
16881 return PTR_ERR(queued_st);
16882
16883 queued_st->may_goto_depth++;
16884 if (prev_st)
16885 widen_imprecise_scalars(env, prev_st, queued_st);
16886 *insn_idx += insn->off;
16887 return 0;
16888 }
16889
16890 /* check src2 operand */
16891 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16892 if (err)
16893 return err;
16894
16895 dst_reg = ®s[insn->dst_reg];
16896 if (BPF_SRC(insn->code) == BPF_X) {
16897 if (insn->imm != 0) {
16898 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16899 return -EINVAL;
16900 }
16901
16902 /* check src1 operand */
16903 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16904 if (err)
16905 return err;
16906
16907 src_reg = ®s[insn->src_reg];
16908 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16909 is_pointer_value(env, insn->src_reg)) {
16910 verbose(env, "R%d pointer comparison prohibited\n",
16911 insn->src_reg);
16912 return -EACCES;
16913 }
16914
16915 if (src_reg->type == PTR_TO_STACK)
16916 insn_flags |= INSN_F_SRC_REG_STACK;
16917 if (dst_reg->type == PTR_TO_STACK)
16918 insn_flags |= INSN_F_DST_REG_STACK;
16919 } else {
16920 if (insn->src_reg != BPF_REG_0) {
16921 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16922 return -EINVAL;
16923 }
16924 src_reg = &env->fake_reg[0];
16925 memset(src_reg, 0, sizeof(*src_reg));
16926 src_reg->type = SCALAR_VALUE;
16927 __mark_reg_known(src_reg, insn->imm);
16928
16929 if (dst_reg->type == PTR_TO_STACK)
16930 insn_flags |= INSN_F_DST_REG_STACK;
16931 }
16932
16933 if (insn_flags) {
16934 err = push_jmp_history(env, this_branch, insn_flags, 0);
16935 if (err)
16936 return err;
16937 }
16938
16939 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16940 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16941 if (pred >= 0) {
16942 /* If we get here with a dst_reg pointer type it is because
16943 * above is_branch_taken() special cased the 0 comparison.
16944 */
16945 if (!__is_pointer_value(false, dst_reg))
16946 err = mark_chain_precision(env, insn->dst_reg);
16947 if (BPF_SRC(insn->code) == BPF_X && !err &&
16948 !__is_pointer_value(false, src_reg))
16949 err = mark_chain_precision(env, insn->src_reg);
16950 if (err)
16951 return err;
16952 }
16953
16954 if (pred == 1) {
16955 /* Only follow the goto, ignore fall-through. If needed, push
16956 * the fall-through branch for simulation under speculative
16957 * execution.
16958 */
16959 if (!env->bypass_spec_v1) {
16960 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
16961 if (err < 0)
16962 return err;
16963 }
16964 if (env->log.level & BPF_LOG_LEVEL)
16965 print_insn_state(env, this_branch, this_branch->curframe);
16966 *insn_idx += insn->off;
16967 return 0;
16968 } else if (pred == 0) {
16969 /* Only follow the fall-through branch, since that's where the
16970 * program will go. If needed, push the goto branch for
16971 * simulation under speculative execution.
16972 */
16973 if (!env->bypass_spec_v1) {
16974 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
16975 *insn_idx);
16976 if (err < 0)
16977 return err;
16978 }
16979 if (env->log.level & BPF_LOG_LEVEL)
16980 print_insn_state(env, this_branch, this_branch->curframe);
16981 return 0;
16982 }
16983
16984 /* Push scalar registers sharing same ID to jump history,
16985 * do this before creating 'other_branch', so that both
16986 * 'this_branch' and 'other_branch' share this history
16987 * if parent state is created.
16988 */
16989 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16990 collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16991 if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16992 collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16993 if (linked_regs.cnt > 1) {
16994 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
16995 if (err)
16996 return err;
16997 }
16998
16999 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17000 if (IS_ERR(other_branch))
17001 return PTR_ERR(other_branch);
17002 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17003
17004 if (BPF_SRC(insn->code) == BPF_X) {
17005 err = reg_set_min_max(env,
17006 &other_branch_regs[insn->dst_reg],
17007 &other_branch_regs[insn->src_reg],
17008 dst_reg, src_reg, opcode, is_jmp32);
17009 } else /* BPF_SRC(insn->code) == BPF_K */ {
17010 /* reg_set_min_max() can mangle the fake_reg. Make a copy
17011 * so that these are two different memory locations. The
17012 * src_reg is not used beyond here in context of K.
17013 */
17014 memcpy(&env->fake_reg[1], &env->fake_reg[0],
17015 sizeof(env->fake_reg[0]));
17016 err = reg_set_min_max(env,
17017 &other_branch_regs[insn->dst_reg],
17018 &env->fake_reg[0],
17019 dst_reg, &env->fake_reg[1],
17020 opcode, is_jmp32);
17021 }
17022 if (err)
17023 return err;
17024
17025 if (BPF_SRC(insn->code) == BPF_X &&
17026 src_reg->type == SCALAR_VALUE && src_reg->id &&
17027 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17028 sync_linked_regs(this_branch, src_reg, &linked_regs);
17029 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
17030 }
17031 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17032 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17033 sync_linked_regs(this_branch, dst_reg, &linked_regs);
17034 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
17035 }
17036
17037 /* if one pointer register is compared to another pointer
17038 * register check if PTR_MAYBE_NULL could be lifted.
17039 * E.g. register A - maybe null
17040 * register B - not null
17041 * for JNE A, B, ... - A is not null in the false branch;
17042 * for JEQ A, B, ... - A is not null in the true branch.
17043 *
17044 * Since PTR_TO_BTF_ID points to a kernel struct that does
17045 * not need to be null checked by the BPF program, i.e.,
17046 * could be null even without PTR_MAYBE_NULL marking, so
17047 * only propagate nullness when neither reg is that type.
17048 */
17049 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17050 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17051 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
17052 base_type(src_reg->type) != PTR_TO_BTF_ID &&
17053 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17054 eq_branch_regs = NULL;
17055 switch (opcode) {
17056 case BPF_JEQ:
17057 eq_branch_regs = other_branch_regs;
17058 break;
17059 case BPF_JNE:
17060 eq_branch_regs = regs;
17061 break;
17062 default:
17063 /* do nothing */
17064 break;
17065 }
17066 if (eq_branch_regs) {
17067 if (type_may_be_null(src_reg->type))
17068 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17069 else
17070 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17071 }
17072 }
17073
17074 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17075 * NOTE: these optimizations below are related with pointer comparison
17076 * which will never be JMP32.
17077 */
17078 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
17079 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17080 type_may_be_null(dst_reg->type)) {
17081 /* Mark all identical registers in each branch as either
17082 * safe or unknown depending R == 0 or R != 0 conditional.
17083 */
17084 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17085 opcode == BPF_JNE);
17086 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17087 opcode == BPF_JEQ);
17088 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
17089 this_branch, other_branch) &&
17090 is_pointer_value(env, insn->dst_reg)) {
17091 verbose(env, "R%d pointer comparison prohibited\n",
17092 insn->dst_reg);
17093 return -EACCES;
17094 }
17095 if (env->log.level & BPF_LOG_LEVEL)
17096 print_insn_state(env, this_branch, this_branch->curframe);
17097 return 0;
17098 }
17099
17100 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)17101 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17102 {
17103 struct bpf_insn_aux_data *aux = cur_aux(env);
17104 struct bpf_reg_state *regs = cur_regs(env);
17105 struct bpf_reg_state *dst_reg;
17106 struct bpf_map *map;
17107 int err;
17108
17109 if (BPF_SIZE(insn->code) != BPF_DW) {
17110 verbose(env, "invalid BPF_LD_IMM insn\n");
17111 return -EINVAL;
17112 }
17113 if (insn->off != 0) {
17114 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17115 return -EINVAL;
17116 }
17117
17118 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17119 if (err)
17120 return err;
17121
17122 dst_reg = ®s[insn->dst_reg];
17123 if (insn->src_reg == 0) {
17124 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17125
17126 dst_reg->type = SCALAR_VALUE;
17127 __mark_reg_known(®s[insn->dst_reg], imm);
17128 return 0;
17129 }
17130
17131 /* All special src_reg cases are listed below. From this point onwards
17132 * we either succeed and assign a corresponding dst_reg->type after
17133 * zeroing the offset, or fail and reject the program.
17134 */
17135 mark_reg_known_zero(env, regs, insn->dst_reg);
17136
17137 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17138 dst_reg->type = aux->btf_var.reg_type;
17139 switch (base_type(dst_reg->type)) {
17140 case PTR_TO_MEM:
17141 dst_reg->mem_size = aux->btf_var.mem_size;
17142 break;
17143 case PTR_TO_BTF_ID:
17144 dst_reg->btf = aux->btf_var.btf;
17145 dst_reg->btf_id = aux->btf_var.btf_id;
17146 break;
17147 default:
17148 verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17149 return -EFAULT;
17150 }
17151 return 0;
17152 }
17153
17154 if (insn->src_reg == BPF_PSEUDO_FUNC) {
17155 struct bpf_prog_aux *aux = env->prog->aux;
17156 u32 subprogno = find_subprog(env,
17157 env->insn_idx + insn->imm + 1);
17158
17159 if (!aux->func_info) {
17160 verbose(env, "missing btf func_info\n");
17161 return -EINVAL;
17162 }
17163 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17164 verbose(env, "callback function not static\n");
17165 return -EINVAL;
17166 }
17167
17168 dst_reg->type = PTR_TO_FUNC;
17169 dst_reg->subprogno = subprogno;
17170 return 0;
17171 }
17172
17173 map = env->used_maps[aux->map_index];
17174 dst_reg->map_ptr = map;
17175
17176 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17177 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17178 if (map->map_type == BPF_MAP_TYPE_ARENA) {
17179 __mark_reg_unknown(env, dst_reg);
17180 return 0;
17181 }
17182 dst_reg->type = PTR_TO_MAP_VALUE;
17183 dst_reg->off = aux->map_off;
17184 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17185 map->max_entries != 1);
17186 /* We want reg->id to be same (0) as map_value is not distinct */
17187 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17188 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17189 dst_reg->type = CONST_PTR_TO_MAP;
17190 } else {
17191 verifier_bug(env, "unexpected src reg value for ldimm64");
17192 return -EFAULT;
17193 }
17194
17195 return 0;
17196 }
17197
may_access_skb(enum bpf_prog_type type)17198 static bool may_access_skb(enum bpf_prog_type type)
17199 {
17200 switch (type) {
17201 case BPF_PROG_TYPE_SOCKET_FILTER:
17202 case BPF_PROG_TYPE_SCHED_CLS:
17203 case BPF_PROG_TYPE_SCHED_ACT:
17204 return true;
17205 default:
17206 return false;
17207 }
17208 }
17209
17210 /* verify safety of LD_ABS|LD_IND instructions:
17211 * - they can only appear in the programs where ctx == skb
17212 * - since they are wrappers of function calls, they scratch R1-R5 registers,
17213 * preserve R6-R9, and store return value into R0
17214 *
17215 * Implicit input:
17216 * ctx == skb == R6 == CTX
17217 *
17218 * Explicit input:
17219 * SRC == any register
17220 * IMM == 32-bit immediate
17221 *
17222 * Output:
17223 * R0 - 8/16/32-bit skb data converted to cpu endianness
17224 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)17225 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17226 {
17227 struct bpf_reg_state *regs = cur_regs(env);
17228 static const int ctx_reg = BPF_REG_6;
17229 u8 mode = BPF_MODE(insn->code);
17230 int i, err;
17231
17232 if (!may_access_skb(resolve_prog_type(env->prog))) {
17233 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17234 return -EINVAL;
17235 }
17236
17237 if (!env->ops->gen_ld_abs) {
17238 verifier_bug(env, "gen_ld_abs is null");
17239 return -EFAULT;
17240 }
17241
17242 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17243 BPF_SIZE(insn->code) == BPF_DW ||
17244 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17245 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17246 return -EINVAL;
17247 }
17248
17249 /* check whether implicit source operand (register R6) is readable */
17250 err = check_reg_arg(env, ctx_reg, SRC_OP);
17251 if (err)
17252 return err;
17253
17254 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17255 * gen_ld_abs() may terminate the program at runtime, leading to
17256 * reference leak.
17257 */
17258 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17259 if (err)
17260 return err;
17261
17262 if (regs[ctx_reg].type != PTR_TO_CTX) {
17263 verbose(env,
17264 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17265 return -EINVAL;
17266 }
17267
17268 if (mode == BPF_IND) {
17269 /* check explicit source operand */
17270 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17271 if (err)
17272 return err;
17273 }
17274
17275 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
17276 if (err < 0)
17277 return err;
17278
17279 /* reset caller saved regs to unreadable */
17280 for (i = 0; i < CALLER_SAVED_REGS; i++) {
17281 mark_reg_not_init(env, regs, caller_saved[i]);
17282 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17283 }
17284
17285 /* mark destination R0 register as readable, since it contains
17286 * the value fetched from the packet.
17287 * Already marked as written above.
17288 */
17289 mark_reg_unknown(env, regs, BPF_REG_0);
17290 /* ld_abs load up to 32-bit skb data. */
17291 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17292 return 0;
17293 }
17294
check_return_code(struct bpf_verifier_env * env,int regno,const char * reg_name)17295 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17296 {
17297 const char *exit_ctx = "At program exit";
17298 struct tnum enforce_attach_type_range = tnum_unknown;
17299 const struct bpf_prog *prog = env->prog;
17300 struct bpf_reg_state *reg = reg_state(env, regno);
17301 struct bpf_retval_range range = retval_range(0, 1);
17302 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17303 int err;
17304 struct bpf_func_state *frame = env->cur_state->frame[0];
17305 const bool is_subprog = frame->subprogno;
17306 bool return_32bit = false;
17307 const struct btf_type *reg_type, *ret_type = NULL;
17308
17309 /* LSM and struct_ops func-ptr's return type could be "void" */
17310 if (!is_subprog || frame->in_exception_callback_fn) {
17311 switch (prog_type) {
17312 case BPF_PROG_TYPE_LSM:
17313 if (prog->expected_attach_type == BPF_LSM_CGROUP)
17314 /* See below, can be 0 or 0-1 depending on hook. */
17315 break;
17316 if (!prog->aux->attach_func_proto->type)
17317 return 0;
17318 break;
17319 case BPF_PROG_TYPE_STRUCT_OPS:
17320 if (!prog->aux->attach_func_proto->type)
17321 return 0;
17322
17323 if (frame->in_exception_callback_fn)
17324 break;
17325
17326 /* Allow a struct_ops program to return a referenced kptr if it
17327 * matches the operator's return type and is in its unmodified
17328 * form. A scalar zero (i.e., a null pointer) is also allowed.
17329 */
17330 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17331 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17332 prog->aux->attach_func_proto->type,
17333 NULL);
17334 if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17335 return __check_ptr_off_reg(env, reg, regno, false);
17336 break;
17337 default:
17338 break;
17339 }
17340 }
17341
17342 /* eBPF calling convention is such that R0 is used
17343 * to return the value from eBPF program.
17344 * Make sure that it's readable at this time
17345 * of bpf_exit, which means that program wrote
17346 * something into it earlier
17347 */
17348 err = check_reg_arg(env, regno, SRC_OP);
17349 if (err)
17350 return err;
17351
17352 if (is_pointer_value(env, regno)) {
17353 verbose(env, "R%d leaks addr as return value\n", regno);
17354 return -EACCES;
17355 }
17356
17357 if (frame->in_async_callback_fn) {
17358 exit_ctx = "At async callback return";
17359 range = frame->callback_ret_range;
17360 goto enforce_retval;
17361 }
17362
17363 if (is_subprog && !frame->in_exception_callback_fn) {
17364 if (reg->type != SCALAR_VALUE) {
17365 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17366 regno, reg_type_str(env, reg->type));
17367 return -EINVAL;
17368 }
17369 return 0;
17370 }
17371
17372 switch (prog_type) {
17373 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17374 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17375 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17376 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17377 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17378 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17379 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17380 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17381 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17382 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17383 range = retval_range(1, 1);
17384 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17385 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17386 range = retval_range(0, 3);
17387 break;
17388 case BPF_PROG_TYPE_CGROUP_SKB:
17389 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17390 range = retval_range(0, 3);
17391 enforce_attach_type_range = tnum_range(2, 3);
17392 }
17393 break;
17394 case BPF_PROG_TYPE_CGROUP_SOCK:
17395 case BPF_PROG_TYPE_SOCK_OPS:
17396 case BPF_PROG_TYPE_CGROUP_DEVICE:
17397 case BPF_PROG_TYPE_CGROUP_SYSCTL:
17398 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17399 break;
17400 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17401 if (!env->prog->aux->attach_btf_id)
17402 return 0;
17403 range = retval_range(0, 0);
17404 break;
17405 case BPF_PROG_TYPE_TRACING:
17406 switch (env->prog->expected_attach_type) {
17407 case BPF_TRACE_FENTRY:
17408 case BPF_TRACE_FEXIT:
17409 range = retval_range(0, 0);
17410 break;
17411 case BPF_TRACE_RAW_TP:
17412 case BPF_MODIFY_RETURN:
17413 return 0;
17414 case BPF_TRACE_ITER:
17415 break;
17416 default:
17417 return -ENOTSUPP;
17418 }
17419 break;
17420 case BPF_PROG_TYPE_KPROBE:
17421 switch (env->prog->expected_attach_type) {
17422 case BPF_TRACE_KPROBE_SESSION:
17423 case BPF_TRACE_UPROBE_SESSION:
17424 range = retval_range(0, 1);
17425 break;
17426 default:
17427 return 0;
17428 }
17429 break;
17430 case BPF_PROG_TYPE_SK_LOOKUP:
17431 range = retval_range(SK_DROP, SK_PASS);
17432 break;
17433
17434 case BPF_PROG_TYPE_LSM:
17435 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17436 /* no range found, any return value is allowed */
17437 if (!get_func_retval_range(env->prog, &range))
17438 return 0;
17439 /* no restricted range, any return value is allowed */
17440 if (range.minval == S32_MIN && range.maxval == S32_MAX)
17441 return 0;
17442 return_32bit = true;
17443 } else if (!env->prog->aux->attach_func_proto->type) {
17444 /* Make sure programs that attach to void
17445 * hooks don't try to modify return value.
17446 */
17447 range = retval_range(1, 1);
17448 }
17449 break;
17450
17451 case BPF_PROG_TYPE_NETFILTER:
17452 range = retval_range(NF_DROP, NF_ACCEPT);
17453 break;
17454 case BPF_PROG_TYPE_STRUCT_OPS:
17455 if (!ret_type)
17456 return 0;
17457 range = retval_range(0, 0);
17458 break;
17459 case BPF_PROG_TYPE_EXT:
17460 /* freplace program can return anything as its return value
17461 * depends on the to-be-replaced kernel func or bpf program.
17462 */
17463 default:
17464 return 0;
17465 }
17466
17467 enforce_retval:
17468 if (reg->type != SCALAR_VALUE) {
17469 verbose(env, "%s the register R%d is not a known value (%s)\n",
17470 exit_ctx, regno, reg_type_str(env, reg->type));
17471 return -EINVAL;
17472 }
17473
17474 err = mark_chain_precision(env, regno);
17475 if (err)
17476 return err;
17477
17478 if (!retval_range_within(range, reg, return_32bit)) {
17479 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17480 if (!is_subprog &&
17481 prog->expected_attach_type == BPF_LSM_CGROUP &&
17482 prog_type == BPF_PROG_TYPE_LSM &&
17483 !prog->aux->attach_func_proto->type)
17484 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17485 return -EINVAL;
17486 }
17487
17488 if (!tnum_is_unknown(enforce_attach_type_range) &&
17489 tnum_in(enforce_attach_type_range, reg->var_off))
17490 env->prog->enforce_expected_attach_type = 1;
17491 return 0;
17492 }
17493
mark_subprog_changes_pkt_data(struct bpf_verifier_env * env,int off)17494 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17495 {
17496 struct bpf_subprog_info *subprog;
17497
17498 subprog = bpf_find_containing_subprog(env, off);
17499 subprog->changes_pkt_data = true;
17500 }
17501
mark_subprog_might_sleep(struct bpf_verifier_env * env,int off)17502 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17503 {
17504 struct bpf_subprog_info *subprog;
17505
17506 subprog = bpf_find_containing_subprog(env, off);
17507 subprog->might_sleep = true;
17508 }
17509
17510 /* 't' is an index of a call-site.
17511 * 'w' is a callee entry point.
17512 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17513 * Rely on DFS traversal order and absence of recursive calls to guarantee that
17514 * callee's change_pkt_data marks would be correct at that moment.
17515 */
merge_callee_effects(struct bpf_verifier_env * env,int t,int w)17516 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17517 {
17518 struct bpf_subprog_info *caller, *callee;
17519
17520 caller = bpf_find_containing_subprog(env, t);
17521 callee = bpf_find_containing_subprog(env, w);
17522 caller->changes_pkt_data |= callee->changes_pkt_data;
17523 caller->might_sleep |= callee->might_sleep;
17524 }
17525
17526 /* non-recursive DFS pseudo code
17527 * 1 procedure DFS-iterative(G,v):
17528 * 2 label v as discovered
17529 * 3 let S be a stack
17530 * 4 S.push(v)
17531 * 5 while S is not empty
17532 * 6 t <- S.peek()
17533 * 7 if t is what we're looking for:
17534 * 8 return t
17535 * 9 for all edges e in G.adjacentEdges(t) do
17536 * 10 if edge e is already labelled
17537 * 11 continue with the next edge
17538 * 12 w <- G.adjacentVertex(t,e)
17539 * 13 if vertex w is not discovered and not explored
17540 * 14 label e as tree-edge
17541 * 15 label w as discovered
17542 * 16 S.push(w)
17543 * 17 continue at 5
17544 * 18 else if vertex w is discovered
17545 * 19 label e as back-edge
17546 * 20 else
17547 * 21 // vertex w is explored
17548 * 22 label e as forward- or cross-edge
17549 * 23 label t as explored
17550 * 24 S.pop()
17551 *
17552 * convention:
17553 * 0x10 - discovered
17554 * 0x11 - discovered and fall-through edge labelled
17555 * 0x12 - discovered and fall-through and branch edges labelled
17556 * 0x20 - explored
17557 */
17558
17559 enum {
17560 DISCOVERED = 0x10,
17561 EXPLORED = 0x20,
17562 FALLTHROUGH = 1,
17563 BRANCH = 2,
17564 };
17565
mark_prune_point(struct bpf_verifier_env * env,int idx)17566 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17567 {
17568 env->insn_aux_data[idx].prune_point = true;
17569 }
17570
is_prune_point(struct bpf_verifier_env * env,int insn_idx)17571 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17572 {
17573 return env->insn_aux_data[insn_idx].prune_point;
17574 }
17575
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)17576 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17577 {
17578 env->insn_aux_data[idx].force_checkpoint = true;
17579 }
17580
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)17581 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17582 {
17583 return env->insn_aux_data[insn_idx].force_checkpoint;
17584 }
17585
mark_calls_callback(struct bpf_verifier_env * env,int idx)17586 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17587 {
17588 env->insn_aux_data[idx].calls_callback = true;
17589 }
17590
bpf_calls_callback(struct bpf_verifier_env * env,int insn_idx)17591 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17592 {
17593 return env->insn_aux_data[insn_idx].calls_callback;
17594 }
17595
17596 enum {
17597 DONE_EXPLORING = 0,
17598 KEEP_EXPLORING = 1,
17599 };
17600
17601 /* t, w, e - match pseudo-code above:
17602 * t - index of current instruction
17603 * w - next instruction
17604 * e - edge
17605 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)17606 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17607 {
17608 int *insn_stack = env->cfg.insn_stack;
17609 int *insn_state = env->cfg.insn_state;
17610
17611 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17612 return DONE_EXPLORING;
17613
17614 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17615 return DONE_EXPLORING;
17616
17617 if (w < 0 || w >= env->prog->len) {
17618 verbose_linfo(env, t, "%d: ", t);
17619 verbose(env, "jump out of range from insn %d to %d\n", t, w);
17620 return -EINVAL;
17621 }
17622
17623 if (e == BRANCH) {
17624 /* mark branch target for state pruning */
17625 mark_prune_point(env, w);
17626 mark_jmp_point(env, w);
17627 }
17628
17629 if (insn_state[w] == 0) {
17630 /* tree-edge */
17631 insn_state[t] = DISCOVERED | e;
17632 insn_state[w] = DISCOVERED;
17633 if (env->cfg.cur_stack >= env->prog->len)
17634 return -E2BIG;
17635 insn_stack[env->cfg.cur_stack++] = w;
17636 return KEEP_EXPLORING;
17637 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17638 if (env->bpf_capable)
17639 return DONE_EXPLORING;
17640 verbose_linfo(env, t, "%d: ", t);
17641 verbose_linfo(env, w, "%d: ", w);
17642 verbose(env, "back-edge from insn %d to %d\n", t, w);
17643 return -EINVAL;
17644 } else if (insn_state[w] == EXPLORED) {
17645 /* forward- or cross-edge */
17646 insn_state[t] = DISCOVERED | e;
17647 } else {
17648 verifier_bug(env, "insn state internal bug");
17649 return -EFAULT;
17650 }
17651 return DONE_EXPLORING;
17652 }
17653
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)17654 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17655 struct bpf_verifier_env *env,
17656 bool visit_callee)
17657 {
17658 int ret, insn_sz;
17659 int w;
17660
17661 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17662 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17663 if (ret)
17664 return ret;
17665
17666 mark_prune_point(env, t + insn_sz);
17667 /* when we exit from subprog, we need to record non-linear history */
17668 mark_jmp_point(env, t + insn_sz);
17669
17670 if (visit_callee) {
17671 w = t + insns[t].imm + 1;
17672 mark_prune_point(env, t);
17673 merge_callee_effects(env, t, w);
17674 ret = push_insn(t, w, BRANCH, env);
17675 }
17676 return ret;
17677 }
17678
17679 /* Bitmask with 1s for all caller saved registers */
17680 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17681
17682 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17683 * replacement patch is presumed to follow bpf_fastcall contract
17684 * (see mark_fastcall_pattern_for_call() below).
17685 */
verifier_inlines_helper_call(struct bpf_verifier_env * env,s32 imm)17686 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17687 {
17688 switch (imm) {
17689 #ifdef CONFIG_X86_64
17690 case BPF_FUNC_get_smp_processor_id:
17691 return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17692 #endif
17693 default:
17694 return false;
17695 }
17696 }
17697
17698 struct call_summary {
17699 u8 num_params;
17700 bool is_void;
17701 bool fastcall;
17702 };
17703
17704 /* If @call is a kfunc or helper call, fills @cs and returns true,
17705 * otherwise returns false.
17706 */
get_call_summary(struct bpf_verifier_env * env,struct bpf_insn * call,struct call_summary * cs)17707 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17708 struct call_summary *cs)
17709 {
17710 struct bpf_kfunc_call_arg_meta meta;
17711 const struct bpf_func_proto *fn;
17712 int i;
17713
17714 if (bpf_helper_call(call)) {
17715
17716 if (get_helper_proto(env, call->imm, &fn) < 0)
17717 /* error would be reported later */
17718 return false;
17719 cs->fastcall = fn->allow_fastcall &&
17720 (verifier_inlines_helper_call(env, call->imm) ||
17721 bpf_jit_inlines_helper_call(call->imm));
17722 cs->is_void = fn->ret_type == RET_VOID;
17723 cs->num_params = 0;
17724 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17725 if (fn->arg_type[i] == ARG_DONTCARE)
17726 break;
17727 cs->num_params++;
17728 }
17729 return true;
17730 }
17731
17732 if (bpf_pseudo_kfunc_call(call)) {
17733 int err;
17734
17735 err = fetch_kfunc_meta(env, call, &meta, NULL);
17736 if (err < 0)
17737 /* error would be reported later */
17738 return false;
17739 cs->num_params = btf_type_vlen(meta.func_proto);
17740 cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17741 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17742 return true;
17743 }
17744
17745 return false;
17746 }
17747
17748 /* LLVM define a bpf_fastcall function attribute.
17749 * This attribute means that function scratches only some of
17750 * the caller saved registers defined by ABI.
17751 * For BPF the set of such registers could be defined as follows:
17752 * - R0 is scratched only if function is non-void;
17753 * - R1-R5 are scratched only if corresponding parameter type is defined
17754 * in the function prototype.
17755 *
17756 * The contract between kernel and clang allows to simultaneously use
17757 * such functions and maintain backwards compatibility with old
17758 * kernels that don't understand bpf_fastcall calls:
17759 *
17760 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17761 * registers are not scratched by the call;
17762 *
17763 * - as a post-processing step, clang visits each bpf_fastcall call and adds
17764 * spill/fill for every live r0-r5;
17765 *
17766 * - stack offsets used for the spill/fill are allocated as lowest
17767 * stack offsets in whole function and are not used for any other
17768 * purposes;
17769 *
17770 * - when kernel loads a program, it looks for such patterns
17771 * (bpf_fastcall function surrounded by spills/fills) and checks if
17772 * spill/fill stack offsets are used exclusively in fastcall patterns;
17773 *
17774 * - if so, and if verifier or current JIT inlines the call to the
17775 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17776 * spill/fill pairs;
17777 *
17778 * - when old kernel loads a program, presence of spill/fill pairs
17779 * keeps BPF program valid, albeit slightly less efficient.
17780 *
17781 * For example:
17782 *
17783 * r1 = 1;
17784 * r2 = 2;
17785 * *(u64 *)(r10 - 8) = r1; r1 = 1;
17786 * *(u64 *)(r10 - 16) = r2; r2 = 2;
17787 * call %[to_be_inlined] --> call %[to_be_inlined]
17788 * r2 = *(u64 *)(r10 - 16); r0 = r1;
17789 * r1 = *(u64 *)(r10 - 8); r0 += r2;
17790 * r0 = r1; exit;
17791 * r0 += r2;
17792 * exit;
17793 *
17794 * The purpose of mark_fastcall_pattern_for_call is to:
17795 * - look for such patterns;
17796 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17797 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17798 * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17799 * at which bpf_fastcall spill/fill stack slots start;
17800 * - update env->subprog_info[*]->keep_fastcall_stack.
17801 *
17802 * The .fastcall_pattern and .fastcall_stack_off are used by
17803 * check_fastcall_stack_contract() to check if every stack access to
17804 * fastcall spill/fill stack slot originates from spill/fill
17805 * instructions, members of fastcall patterns.
17806 *
17807 * If such condition holds true for a subprogram, fastcall patterns could
17808 * be rewritten by remove_fastcall_spills_fills().
17809 * Otherwise bpf_fastcall patterns are not changed in the subprogram
17810 * (code, presumably, generated by an older clang version).
17811 *
17812 * For example, it is *not* safe to remove spill/fill below:
17813 *
17814 * r1 = 1;
17815 * *(u64 *)(r10 - 8) = r1; r1 = 1;
17816 * call %[to_be_inlined] --> call %[to_be_inlined]
17817 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!!
17818 * r0 = *(u64 *)(r10 - 8); r0 += r1;
17819 * r0 += r1; exit;
17820 * exit;
17821 */
mark_fastcall_pattern_for_call(struct bpf_verifier_env * env,struct bpf_subprog_info * subprog,int insn_idx,s16 lowest_off)17822 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17823 struct bpf_subprog_info *subprog,
17824 int insn_idx, s16 lowest_off)
17825 {
17826 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17827 struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17828 u32 clobbered_regs_mask;
17829 struct call_summary cs;
17830 u32 expected_regs_mask;
17831 s16 off;
17832 int i;
17833
17834 if (!get_call_summary(env, call, &cs))
17835 return;
17836
17837 /* A bitmask specifying which caller saved registers are clobbered
17838 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17839 * bpf_fastcall contract:
17840 * - includes R0 if function is non-void;
17841 * - includes R1-R5 if corresponding parameter has is described
17842 * in the function prototype.
17843 */
17844 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17845 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17846 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17847
17848 /* match pairs of form:
17849 *
17850 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0)
17851 * ...
17852 * call %[to_be_inlined]
17853 * ...
17854 * rX = *(u64 *)(r10 - Y)
17855 */
17856 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17857 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17858 break;
17859 stx = &insns[insn_idx - i];
17860 ldx = &insns[insn_idx + i];
17861 /* must be a stack spill/fill pair */
17862 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17863 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17864 stx->dst_reg != BPF_REG_10 ||
17865 ldx->src_reg != BPF_REG_10)
17866 break;
17867 /* must be a spill/fill for the same reg */
17868 if (stx->src_reg != ldx->dst_reg)
17869 break;
17870 /* must be one of the previously unseen registers */
17871 if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17872 break;
17873 /* must be a spill/fill for the same expected offset,
17874 * no need to check offset alignment, BPF_DW stack access
17875 * is always 8-byte aligned.
17876 */
17877 if (stx->off != off || ldx->off != off)
17878 break;
17879 expected_regs_mask &= ~BIT(stx->src_reg);
17880 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17881 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17882 }
17883 if (i == 1)
17884 return;
17885
17886 /* Conditionally set 'fastcall_spills_num' to allow forward
17887 * compatibility when more helper functions are marked as
17888 * bpf_fastcall at compile time than current kernel supports, e.g:
17889 *
17890 * 1: *(u64 *)(r10 - 8) = r1
17891 * 2: call A ;; assume A is bpf_fastcall for current kernel
17892 * 3: r1 = *(u64 *)(r10 - 8)
17893 * 4: *(u64 *)(r10 - 8) = r1
17894 * 5: call B ;; assume B is not bpf_fastcall for current kernel
17895 * 6: r1 = *(u64 *)(r10 - 8)
17896 *
17897 * There is no need to block bpf_fastcall rewrite for such program.
17898 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17899 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17900 * does not remove spill/fill pair {4,6}.
17901 */
17902 if (cs.fastcall)
17903 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17904 else
17905 subprog->keep_fastcall_stack = 1;
17906 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17907 }
17908
mark_fastcall_patterns(struct bpf_verifier_env * env)17909 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17910 {
17911 struct bpf_subprog_info *subprog = env->subprog_info;
17912 struct bpf_insn *insn;
17913 s16 lowest_off;
17914 int s, i;
17915
17916 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17917 /* find lowest stack spill offset used in this subprog */
17918 lowest_off = 0;
17919 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17920 insn = env->prog->insnsi + i;
17921 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17922 insn->dst_reg != BPF_REG_10)
17923 continue;
17924 lowest_off = min(lowest_off, insn->off);
17925 }
17926 /* use this offset to find fastcall patterns */
17927 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17928 insn = env->prog->insnsi + i;
17929 if (insn->code != (BPF_JMP | BPF_CALL))
17930 continue;
17931 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17932 }
17933 }
17934 return 0;
17935 }
17936
iarray_realloc(struct bpf_iarray * old,size_t n_elem)17937 static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
17938 {
17939 size_t new_size = sizeof(struct bpf_iarray) + n_elem * sizeof(old->items[0]);
17940 struct bpf_iarray *new;
17941
17942 new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
17943 if (!new) {
17944 /* this is what callers always want, so simplify the call site */
17945 kvfree(old);
17946 return NULL;
17947 }
17948
17949 new->cnt = n_elem;
17950 return new;
17951 }
17952
copy_insn_array(struct bpf_map * map,u32 start,u32 end,u32 * items)17953 static int copy_insn_array(struct bpf_map *map, u32 start, u32 end, u32 *items)
17954 {
17955 struct bpf_insn_array_value *value;
17956 u32 i;
17957
17958 for (i = start; i <= end; i++) {
17959 value = map->ops->map_lookup_elem(map, &i);
17960 /*
17961 * map_lookup_elem of an array map will never return an error,
17962 * but not checking it makes some static analysers to worry
17963 */
17964 if (IS_ERR(value))
17965 return PTR_ERR(value);
17966 else if (!value)
17967 return -EINVAL;
17968 items[i - start] = value->xlated_off;
17969 }
17970 return 0;
17971 }
17972
cmp_ptr_to_u32(const void * a,const void * b)17973 static int cmp_ptr_to_u32(const void *a, const void *b)
17974 {
17975 return *(u32 *)a - *(u32 *)b;
17976 }
17977
sort_insn_array_uniq(u32 * items,int cnt)17978 static int sort_insn_array_uniq(u32 *items, int cnt)
17979 {
17980 int unique = 1;
17981 int i;
17982
17983 sort(items, cnt, sizeof(items[0]), cmp_ptr_to_u32, NULL);
17984
17985 for (i = 1; i < cnt; i++)
17986 if (items[i] != items[unique - 1])
17987 items[unique++] = items[i];
17988
17989 return unique;
17990 }
17991
17992 /*
17993 * sort_unique({map[start], ..., map[end]}) into off
17994 */
copy_insn_array_uniq(struct bpf_map * map,u32 start,u32 end,u32 * off)17995 static int copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off)
17996 {
17997 u32 n = end - start + 1;
17998 int err;
17999
18000 err = copy_insn_array(map, start, end, off);
18001 if (err)
18002 return err;
18003
18004 return sort_insn_array_uniq(off, n);
18005 }
18006
18007 /*
18008 * Copy all unique offsets from the map
18009 */
jt_from_map(struct bpf_map * map)18010 static struct bpf_iarray *jt_from_map(struct bpf_map *map)
18011 {
18012 struct bpf_iarray *jt;
18013 int err;
18014 int n;
18015
18016 jt = iarray_realloc(NULL, map->max_entries);
18017 if (!jt)
18018 return ERR_PTR(-ENOMEM);
18019
18020 n = copy_insn_array_uniq(map, 0, map->max_entries - 1, jt->items);
18021 if (n < 0) {
18022 err = n;
18023 goto err_free;
18024 }
18025 if (n == 0) {
18026 err = -EINVAL;
18027 goto err_free;
18028 }
18029 jt->cnt = n;
18030 return jt;
18031
18032 err_free:
18033 kvfree(jt);
18034 return ERR_PTR(err);
18035 }
18036
18037 /*
18038 * Find and collect all maps which fit in the subprog. Return the result as one
18039 * combined jump table in jt->items (allocated with kvcalloc)
18040 */
jt_from_subprog(struct bpf_verifier_env * env,int subprog_start,int subprog_end)18041 static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
18042 int subprog_start, int subprog_end)
18043 {
18044 struct bpf_iarray *jt = NULL;
18045 struct bpf_map *map;
18046 struct bpf_iarray *jt_cur;
18047 int i;
18048
18049 for (i = 0; i < env->insn_array_map_cnt; i++) {
18050 /*
18051 * TODO (when needed): collect only jump tables, not static keys
18052 * or maps for indirect calls
18053 */
18054 map = env->insn_array_maps[i];
18055
18056 jt_cur = jt_from_map(map);
18057 if (IS_ERR(jt_cur)) {
18058 kvfree(jt);
18059 return jt_cur;
18060 }
18061
18062 /*
18063 * This is enough to check one element. The full table is
18064 * checked to fit inside the subprog later in create_jt()
18065 */
18066 if (jt_cur->items[0] >= subprog_start && jt_cur->items[0] < subprog_end) {
18067 u32 old_cnt = jt ? jt->cnt : 0;
18068 jt = iarray_realloc(jt, old_cnt + jt_cur->cnt);
18069 if (!jt) {
18070 kvfree(jt_cur);
18071 return ERR_PTR(-ENOMEM);
18072 }
18073 memcpy(jt->items + old_cnt, jt_cur->items, jt_cur->cnt << 2);
18074 }
18075
18076 kvfree(jt_cur);
18077 }
18078
18079 if (!jt) {
18080 verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
18081 return ERR_PTR(-EINVAL);
18082 }
18083
18084 jt->cnt = sort_insn_array_uniq(jt->items, jt->cnt);
18085 return jt;
18086 }
18087
18088 static struct bpf_iarray *
create_jt(int t,struct bpf_verifier_env * env)18089 create_jt(int t, struct bpf_verifier_env *env)
18090 {
18091 static struct bpf_subprog_info *subprog;
18092 int subprog_start, subprog_end;
18093 struct bpf_iarray *jt;
18094 int i;
18095
18096 subprog = bpf_find_containing_subprog(env, t);
18097 subprog_start = subprog->start;
18098 subprog_end = (subprog + 1)->start;
18099 jt = jt_from_subprog(env, subprog_start, subprog_end);
18100 if (IS_ERR(jt))
18101 return jt;
18102
18103 /* Check that the every element of the jump table fits within the given subprogram */
18104 for (i = 0; i < jt->cnt; i++) {
18105 if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
18106 verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
18107 t, subprog_start, subprog_end);
18108 kvfree(jt);
18109 return ERR_PTR(-EINVAL);
18110 }
18111 }
18112
18113 return jt;
18114 }
18115
18116 /* "conditional jump with N edges" */
visit_gotox_insn(int t,struct bpf_verifier_env * env)18117 static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
18118 {
18119 int *insn_stack = env->cfg.insn_stack;
18120 int *insn_state = env->cfg.insn_state;
18121 bool keep_exploring = false;
18122 struct bpf_iarray *jt;
18123 int i, w;
18124
18125 jt = env->insn_aux_data[t].jt;
18126 if (!jt) {
18127 jt = create_jt(t, env);
18128 if (IS_ERR(jt))
18129 return PTR_ERR(jt);
18130
18131 env->insn_aux_data[t].jt = jt;
18132 }
18133
18134 mark_prune_point(env, t);
18135 for (i = 0; i < jt->cnt; i++) {
18136 w = jt->items[i];
18137 if (w < 0 || w >= env->prog->len) {
18138 verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
18139 return -EINVAL;
18140 }
18141
18142 mark_jmp_point(env, w);
18143
18144 /* EXPLORED || DISCOVERED */
18145 if (insn_state[w])
18146 continue;
18147
18148 if (env->cfg.cur_stack >= env->prog->len)
18149 return -E2BIG;
18150
18151 insn_stack[env->cfg.cur_stack++] = w;
18152 insn_state[w] |= DISCOVERED;
18153 keep_exploring = true;
18154 }
18155
18156 return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
18157 }
18158
visit_tailcall_insn(struct bpf_verifier_env * env,int t)18159 static int visit_tailcall_insn(struct bpf_verifier_env *env, int t)
18160 {
18161 static struct bpf_subprog_info *subprog;
18162 struct bpf_iarray *jt;
18163
18164 if (env->insn_aux_data[t].jt)
18165 return 0;
18166
18167 jt = iarray_realloc(NULL, 2);
18168 if (!jt)
18169 return -ENOMEM;
18170
18171 subprog = bpf_find_containing_subprog(env, t);
18172 jt->items[0] = t + 1;
18173 jt->items[1] = subprog->exit_idx;
18174 env->insn_aux_data[t].jt = jt;
18175 return 0;
18176 }
18177
18178 /* Visits the instruction at index t and returns one of the following:
18179 * < 0 - an error occurred
18180 * DONE_EXPLORING - the instruction was fully explored
18181 * KEEP_EXPLORING - there is still work to be done before it is fully explored
18182 */
visit_insn(int t,struct bpf_verifier_env * env)18183 static int visit_insn(int t, struct bpf_verifier_env *env)
18184 {
18185 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
18186 int ret, off, insn_sz;
18187
18188 if (bpf_pseudo_func(insn))
18189 return visit_func_call_insn(t, insns, env, true);
18190
18191 /* All non-branch instructions have a single fall-through edge. */
18192 if (BPF_CLASS(insn->code) != BPF_JMP &&
18193 BPF_CLASS(insn->code) != BPF_JMP32) {
18194 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
18195 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
18196 }
18197
18198 switch (BPF_OP(insn->code)) {
18199 case BPF_EXIT:
18200 return DONE_EXPLORING;
18201
18202 case BPF_CALL:
18203 if (is_async_callback_calling_insn(insn))
18204 /* Mark this call insn as a prune point to trigger
18205 * is_state_visited() check before call itself is
18206 * processed by __check_func_call(). Otherwise new
18207 * async state will be pushed for further exploration.
18208 */
18209 mark_prune_point(env, t);
18210 /* For functions that invoke callbacks it is not known how many times
18211 * callback would be called. Verifier models callback calling functions
18212 * by repeatedly visiting callback bodies and returning to origin call
18213 * instruction.
18214 * In order to stop such iteration verifier needs to identify when a
18215 * state identical some state from a previous iteration is reached.
18216 * Check below forces creation of checkpoint before callback calling
18217 * instruction to allow search for such identical states.
18218 */
18219 if (is_sync_callback_calling_insn(insn)) {
18220 mark_calls_callback(env, t);
18221 mark_force_checkpoint(env, t);
18222 mark_prune_point(env, t);
18223 mark_jmp_point(env, t);
18224 }
18225 if (bpf_helper_call(insn)) {
18226 const struct bpf_func_proto *fp;
18227
18228 ret = get_helper_proto(env, insn->imm, &fp);
18229 /* If called in a non-sleepable context program will be
18230 * rejected anyway, so we should end up with precise
18231 * sleepable marks on subprogs, except for dead code
18232 * elimination.
18233 */
18234 if (ret == 0 && fp->might_sleep)
18235 mark_subprog_might_sleep(env, t);
18236 if (bpf_helper_changes_pkt_data(insn->imm))
18237 mark_subprog_changes_pkt_data(env, t);
18238 if (insn->imm == BPF_FUNC_tail_call)
18239 visit_tailcall_insn(env, t);
18240 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18241 struct bpf_kfunc_call_arg_meta meta;
18242
18243 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
18244 if (ret == 0 && is_iter_next_kfunc(&meta)) {
18245 mark_prune_point(env, t);
18246 /* Checking and saving state checkpoints at iter_next() call
18247 * is crucial for fast convergence of open-coded iterator loop
18248 * logic, so we need to force it. If we don't do that,
18249 * is_state_visited() might skip saving a checkpoint, causing
18250 * unnecessarily long sequence of not checkpointed
18251 * instructions and jumps, leading to exhaustion of jump
18252 * history buffer, and potentially other undesired outcomes.
18253 * It is expected that with correct open-coded iterators
18254 * convergence will happen quickly, so we don't run a risk of
18255 * exhausting memory.
18256 */
18257 mark_force_checkpoint(env, t);
18258 }
18259 /* Same as helpers, if called in a non-sleepable context
18260 * program will be rejected anyway, so we should end up
18261 * with precise sleepable marks on subprogs, except for
18262 * dead code elimination.
18263 */
18264 if (ret == 0 && is_kfunc_sleepable(&meta))
18265 mark_subprog_might_sleep(env, t);
18266 if (ret == 0 && is_kfunc_pkt_changing(&meta))
18267 mark_subprog_changes_pkt_data(env, t);
18268 }
18269 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
18270
18271 case BPF_JA:
18272 if (BPF_SRC(insn->code) == BPF_X)
18273 return visit_gotox_insn(t, env);
18274
18275 if (BPF_CLASS(insn->code) == BPF_JMP)
18276 off = insn->off;
18277 else
18278 off = insn->imm;
18279
18280 /* unconditional jump with single edge */
18281 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
18282 if (ret)
18283 return ret;
18284
18285 mark_prune_point(env, t + off + 1);
18286 mark_jmp_point(env, t + off + 1);
18287
18288 return ret;
18289
18290 default:
18291 /* conditional jump with two edges */
18292 mark_prune_point(env, t);
18293 if (is_may_goto_insn(insn))
18294 mark_force_checkpoint(env, t);
18295
18296 ret = push_insn(t, t + 1, FALLTHROUGH, env);
18297 if (ret)
18298 return ret;
18299
18300 return push_insn(t, t + insn->off + 1, BRANCH, env);
18301 }
18302 }
18303
18304 /* non-recursive depth-first-search to detect loops in BPF program
18305 * loop == back-edge in directed graph
18306 */
check_cfg(struct bpf_verifier_env * env)18307 static int check_cfg(struct bpf_verifier_env *env)
18308 {
18309 int insn_cnt = env->prog->len;
18310 int *insn_stack, *insn_state;
18311 int ex_insn_beg, i, ret = 0;
18312
18313 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18314 if (!insn_state)
18315 return -ENOMEM;
18316
18317 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18318 if (!insn_stack) {
18319 kvfree(insn_state);
18320 return -ENOMEM;
18321 }
18322
18323 ex_insn_beg = env->exception_callback_subprog
18324 ? env->subprog_info[env->exception_callback_subprog].start
18325 : 0;
18326
18327 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
18328 insn_stack[0] = 0; /* 0 is the first instruction */
18329 env->cfg.cur_stack = 1;
18330
18331 walk_cfg:
18332 while (env->cfg.cur_stack > 0) {
18333 int t = insn_stack[env->cfg.cur_stack - 1];
18334
18335 ret = visit_insn(t, env);
18336 switch (ret) {
18337 case DONE_EXPLORING:
18338 insn_state[t] = EXPLORED;
18339 env->cfg.cur_stack--;
18340 break;
18341 case KEEP_EXPLORING:
18342 break;
18343 default:
18344 if (ret > 0) {
18345 verifier_bug(env, "visit_insn internal bug");
18346 ret = -EFAULT;
18347 }
18348 goto err_free;
18349 }
18350 }
18351
18352 if (env->cfg.cur_stack < 0) {
18353 verifier_bug(env, "pop stack internal bug");
18354 ret = -EFAULT;
18355 goto err_free;
18356 }
18357
18358 if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
18359 insn_state[ex_insn_beg] = DISCOVERED;
18360 insn_stack[0] = ex_insn_beg;
18361 env->cfg.cur_stack = 1;
18362 goto walk_cfg;
18363 }
18364
18365 for (i = 0; i < insn_cnt; i++) {
18366 struct bpf_insn *insn = &env->prog->insnsi[i];
18367
18368 if (insn_state[i] != EXPLORED) {
18369 verbose(env, "unreachable insn %d\n", i);
18370 ret = -EINVAL;
18371 goto err_free;
18372 }
18373 if (bpf_is_ldimm64(insn)) {
18374 if (insn_state[i + 1] != 0) {
18375 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
18376 ret = -EINVAL;
18377 goto err_free;
18378 }
18379 i++; /* skip second half of ldimm64 */
18380 }
18381 }
18382 ret = 0; /* cfg looks good */
18383 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
18384 env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
18385
18386 err_free:
18387 kvfree(insn_state);
18388 kvfree(insn_stack);
18389 env->cfg.insn_state = env->cfg.insn_stack = NULL;
18390 return ret;
18391 }
18392
18393 /*
18394 * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
18395 * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
18396 * with indices of 'i' instructions in postorder.
18397 */
compute_postorder(struct bpf_verifier_env * env)18398 static int compute_postorder(struct bpf_verifier_env *env)
18399 {
18400 u32 cur_postorder, i, top, stack_sz, s;
18401 int *stack = NULL, *postorder = NULL, *state = NULL;
18402 struct bpf_iarray *succ;
18403
18404 postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18405 state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18406 stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18407 if (!postorder || !state || !stack) {
18408 kvfree(postorder);
18409 kvfree(state);
18410 kvfree(stack);
18411 return -ENOMEM;
18412 }
18413 cur_postorder = 0;
18414 for (i = 0; i < env->subprog_cnt; i++) {
18415 env->subprog_info[i].postorder_start = cur_postorder;
18416 stack[0] = env->subprog_info[i].start;
18417 stack_sz = 1;
18418 do {
18419 top = stack[stack_sz - 1];
18420 state[top] |= DISCOVERED;
18421 if (state[top] & EXPLORED) {
18422 postorder[cur_postorder++] = top;
18423 stack_sz--;
18424 continue;
18425 }
18426 succ = bpf_insn_successors(env, top);
18427 for (s = 0; s < succ->cnt; ++s) {
18428 if (!state[succ->items[s]]) {
18429 stack[stack_sz++] = succ->items[s];
18430 state[succ->items[s]] |= DISCOVERED;
18431 }
18432 }
18433 state[top] |= EXPLORED;
18434 } while (stack_sz);
18435 }
18436 env->subprog_info[i].postorder_start = cur_postorder;
18437 env->cfg.insn_postorder = postorder;
18438 env->cfg.cur_postorder = cur_postorder;
18439 kvfree(stack);
18440 kvfree(state);
18441 return 0;
18442 }
18443
check_abnormal_return(struct bpf_verifier_env * env)18444 static int check_abnormal_return(struct bpf_verifier_env *env)
18445 {
18446 int i;
18447
18448 for (i = 1; i < env->subprog_cnt; i++) {
18449 if (env->subprog_info[i].has_ld_abs) {
18450 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18451 return -EINVAL;
18452 }
18453 if (env->subprog_info[i].has_tail_call) {
18454 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18455 return -EINVAL;
18456 }
18457 }
18458 return 0;
18459 }
18460
18461 /* The minimum supported BTF func info size */
18462 #define MIN_BPF_FUNCINFO_SIZE 8
18463 #define MAX_FUNCINFO_REC_SIZE 252
18464
check_btf_func_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18465 static int check_btf_func_early(struct bpf_verifier_env *env,
18466 const union bpf_attr *attr,
18467 bpfptr_t uattr)
18468 {
18469 u32 krec_size = sizeof(struct bpf_func_info);
18470 const struct btf_type *type, *func_proto;
18471 u32 i, nfuncs, urec_size, min_size;
18472 struct bpf_func_info *krecord;
18473 struct bpf_prog *prog;
18474 const struct btf *btf;
18475 u32 prev_offset = 0;
18476 bpfptr_t urecord;
18477 int ret = -ENOMEM;
18478
18479 nfuncs = attr->func_info_cnt;
18480 if (!nfuncs) {
18481 if (check_abnormal_return(env))
18482 return -EINVAL;
18483 return 0;
18484 }
18485
18486 urec_size = attr->func_info_rec_size;
18487 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18488 urec_size > MAX_FUNCINFO_REC_SIZE ||
18489 urec_size % sizeof(u32)) {
18490 verbose(env, "invalid func info rec size %u\n", urec_size);
18491 return -EINVAL;
18492 }
18493
18494 prog = env->prog;
18495 btf = prog->aux->btf;
18496
18497 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18498 min_size = min_t(u32, krec_size, urec_size);
18499
18500 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18501 if (!krecord)
18502 return -ENOMEM;
18503
18504 for (i = 0; i < nfuncs; i++) {
18505 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18506 if (ret) {
18507 if (ret == -E2BIG) {
18508 verbose(env, "nonzero tailing record in func info");
18509 /* set the size kernel expects so loader can zero
18510 * out the rest of the record.
18511 */
18512 if (copy_to_bpfptr_offset(uattr,
18513 offsetof(union bpf_attr, func_info_rec_size),
18514 &min_size, sizeof(min_size)))
18515 ret = -EFAULT;
18516 }
18517 goto err_free;
18518 }
18519
18520 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18521 ret = -EFAULT;
18522 goto err_free;
18523 }
18524
18525 /* check insn_off */
18526 ret = -EINVAL;
18527 if (i == 0) {
18528 if (krecord[i].insn_off) {
18529 verbose(env,
18530 "nonzero insn_off %u for the first func info record",
18531 krecord[i].insn_off);
18532 goto err_free;
18533 }
18534 } else if (krecord[i].insn_off <= prev_offset) {
18535 verbose(env,
18536 "same or smaller insn offset (%u) than previous func info record (%u)",
18537 krecord[i].insn_off, prev_offset);
18538 goto err_free;
18539 }
18540
18541 /* check type_id */
18542 type = btf_type_by_id(btf, krecord[i].type_id);
18543 if (!type || !btf_type_is_func(type)) {
18544 verbose(env, "invalid type id %d in func info",
18545 krecord[i].type_id);
18546 goto err_free;
18547 }
18548
18549 func_proto = btf_type_by_id(btf, type->type);
18550 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18551 /* btf_func_check() already verified it during BTF load */
18552 goto err_free;
18553
18554 prev_offset = krecord[i].insn_off;
18555 bpfptr_add(&urecord, urec_size);
18556 }
18557
18558 prog->aux->func_info = krecord;
18559 prog->aux->func_info_cnt = nfuncs;
18560 return 0;
18561
18562 err_free:
18563 kvfree(krecord);
18564 return ret;
18565 }
18566
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18567 static int check_btf_func(struct bpf_verifier_env *env,
18568 const union bpf_attr *attr,
18569 bpfptr_t uattr)
18570 {
18571 const struct btf_type *type, *func_proto, *ret_type;
18572 u32 i, nfuncs, urec_size;
18573 struct bpf_func_info *krecord;
18574 struct bpf_func_info_aux *info_aux = NULL;
18575 struct bpf_prog *prog;
18576 const struct btf *btf;
18577 bpfptr_t urecord;
18578 bool scalar_return;
18579 int ret = -ENOMEM;
18580
18581 nfuncs = attr->func_info_cnt;
18582 if (!nfuncs) {
18583 if (check_abnormal_return(env))
18584 return -EINVAL;
18585 return 0;
18586 }
18587 if (nfuncs != env->subprog_cnt) {
18588 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18589 return -EINVAL;
18590 }
18591
18592 urec_size = attr->func_info_rec_size;
18593
18594 prog = env->prog;
18595 btf = prog->aux->btf;
18596
18597 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18598
18599 krecord = prog->aux->func_info;
18600 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18601 if (!info_aux)
18602 return -ENOMEM;
18603
18604 for (i = 0; i < nfuncs; i++) {
18605 /* check insn_off */
18606 ret = -EINVAL;
18607
18608 if (env->subprog_info[i].start != krecord[i].insn_off) {
18609 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18610 goto err_free;
18611 }
18612
18613 /* Already checked type_id */
18614 type = btf_type_by_id(btf, krecord[i].type_id);
18615 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18616 /* Already checked func_proto */
18617 func_proto = btf_type_by_id(btf, type->type);
18618
18619 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18620 scalar_return =
18621 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18622 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18623 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18624 goto err_free;
18625 }
18626 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18627 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18628 goto err_free;
18629 }
18630
18631 bpfptr_add(&urecord, urec_size);
18632 }
18633
18634 prog->aux->func_info_aux = info_aux;
18635 return 0;
18636
18637 err_free:
18638 kfree(info_aux);
18639 return ret;
18640 }
18641
adjust_btf_func(struct bpf_verifier_env * env)18642 static void adjust_btf_func(struct bpf_verifier_env *env)
18643 {
18644 struct bpf_prog_aux *aux = env->prog->aux;
18645 int i;
18646
18647 if (!aux->func_info)
18648 return;
18649
18650 /* func_info is not available for hidden subprogs */
18651 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18652 aux->func_info[i].insn_off = env->subprog_info[i].start;
18653 }
18654
18655 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
18656 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
18657
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18658 static int check_btf_line(struct bpf_verifier_env *env,
18659 const union bpf_attr *attr,
18660 bpfptr_t uattr)
18661 {
18662 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18663 struct bpf_subprog_info *sub;
18664 struct bpf_line_info *linfo;
18665 struct bpf_prog *prog;
18666 const struct btf *btf;
18667 bpfptr_t ulinfo;
18668 int err;
18669
18670 nr_linfo = attr->line_info_cnt;
18671 if (!nr_linfo)
18672 return 0;
18673 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18674 return -EINVAL;
18675
18676 rec_size = attr->line_info_rec_size;
18677 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18678 rec_size > MAX_LINEINFO_REC_SIZE ||
18679 rec_size & (sizeof(u32) - 1))
18680 return -EINVAL;
18681
18682 /* Need to zero it in case the userspace may
18683 * pass in a smaller bpf_line_info object.
18684 */
18685 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18686 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18687 if (!linfo)
18688 return -ENOMEM;
18689
18690 prog = env->prog;
18691 btf = prog->aux->btf;
18692
18693 s = 0;
18694 sub = env->subprog_info;
18695 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18696 expected_size = sizeof(struct bpf_line_info);
18697 ncopy = min_t(u32, expected_size, rec_size);
18698 for (i = 0; i < nr_linfo; i++) {
18699 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18700 if (err) {
18701 if (err == -E2BIG) {
18702 verbose(env, "nonzero tailing record in line_info");
18703 if (copy_to_bpfptr_offset(uattr,
18704 offsetof(union bpf_attr, line_info_rec_size),
18705 &expected_size, sizeof(expected_size)))
18706 err = -EFAULT;
18707 }
18708 goto err_free;
18709 }
18710
18711 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18712 err = -EFAULT;
18713 goto err_free;
18714 }
18715
18716 /*
18717 * Check insn_off to ensure
18718 * 1) strictly increasing AND
18719 * 2) bounded by prog->len
18720 *
18721 * The linfo[0].insn_off == 0 check logically falls into
18722 * the later "missing bpf_line_info for func..." case
18723 * because the first linfo[0].insn_off must be the
18724 * first sub also and the first sub must have
18725 * subprog_info[0].start == 0.
18726 */
18727 if ((i && linfo[i].insn_off <= prev_offset) ||
18728 linfo[i].insn_off >= prog->len) {
18729 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18730 i, linfo[i].insn_off, prev_offset,
18731 prog->len);
18732 err = -EINVAL;
18733 goto err_free;
18734 }
18735
18736 if (!prog->insnsi[linfo[i].insn_off].code) {
18737 verbose(env,
18738 "Invalid insn code at line_info[%u].insn_off\n",
18739 i);
18740 err = -EINVAL;
18741 goto err_free;
18742 }
18743
18744 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18745 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18746 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18747 err = -EINVAL;
18748 goto err_free;
18749 }
18750
18751 if (s != env->subprog_cnt) {
18752 if (linfo[i].insn_off == sub[s].start) {
18753 sub[s].linfo_idx = i;
18754 s++;
18755 } else if (sub[s].start < linfo[i].insn_off) {
18756 verbose(env, "missing bpf_line_info for func#%u\n", s);
18757 err = -EINVAL;
18758 goto err_free;
18759 }
18760 }
18761
18762 prev_offset = linfo[i].insn_off;
18763 bpfptr_add(&ulinfo, rec_size);
18764 }
18765
18766 if (s != env->subprog_cnt) {
18767 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18768 env->subprog_cnt - s, s);
18769 err = -EINVAL;
18770 goto err_free;
18771 }
18772
18773 prog->aux->linfo = linfo;
18774 prog->aux->nr_linfo = nr_linfo;
18775
18776 return 0;
18777
18778 err_free:
18779 kvfree(linfo);
18780 return err;
18781 }
18782
18783 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
18784 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
18785
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18786 static int check_core_relo(struct bpf_verifier_env *env,
18787 const union bpf_attr *attr,
18788 bpfptr_t uattr)
18789 {
18790 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18791 struct bpf_core_relo core_relo = {};
18792 struct bpf_prog *prog = env->prog;
18793 const struct btf *btf = prog->aux->btf;
18794 struct bpf_core_ctx ctx = {
18795 .log = &env->log,
18796 .btf = btf,
18797 };
18798 bpfptr_t u_core_relo;
18799 int err;
18800
18801 nr_core_relo = attr->core_relo_cnt;
18802 if (!nr_core_relo)
18803 return 0;
18804 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18805 return -EINVAL;
18806
18807 rec_size = attr->core_relo_rec_size;
18808 if (rec_size < MIN_CORE_RELO_SIZE ||
18809 rec_size > MAX_CORE_RELO_SIZE ||
18810 rec_size % sizeof(u32))
18811 return -EINVAL;
18812
18813 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18814 expected_size = sizeof(struct bpf_core_relo);
18815 ncopy = min_t(u32, expected_size, rec_size);
18816
18817 /* Unlike func_info and line_info, copy and apply each CO-RE
18818 * relocation record one at a time.
18819 */
18820 for (i = 0; i < nr_core_relo; i++) {
18821 /* future proofing when sizeof(bpf_core_relo) changes */
18822 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18823 if (err) {
18824 if (err == -E2BIG) {
18825 verbose(env, "nonzero tailing record in core_relo");
18826 if (copy_to_bpfptr_offset(uattr,
18827 offsetof(union bpf_attr, core_relo_rec_size),
18828 &expected_size, sizeof(expected_size)))
18829 err = -EFAULT;
18830 }
18831 break;
18832 }
18833
18834 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18835 err = -EFAULT;
18836 break;
18837 }
18838
18839 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18840 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18841 i, core_relo.insn_off, prog->len);
18842 err = -EINVAL;
18843 break;
18844 }
18845
18846 err = bpf_core_apply(&ctx, &core_relo, i,
18847 &prog->insnsi[core_relo.insn_off / 8]);
18848 if (err)
18849 break;
18850 bpfptr_add(&u_core_relo, rec_size);
18851 }
18852 return err;
18853 }
18854
check_btf_info_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18855 static int check_btf_info_early(struct bpf_verifier_env *env,
18856 const union bpf_attr *attr,
18857 bpfptr_t uattr)
18858 {
18859 struct btf *btf;
18860 int err;
18861
18862 if (!attr->func_info_cnt && !attr->line_info_cnt) {
18863 if (check_abnormal_return(env))
18864 return -EINVAL;
18865 return 0;
18866 }
18867
18868 btf = btf_get_by_fd(attr->prog_btf_fd);
18869 if (IS_ERR(btf))
18870 return PTR_ERR(btf);
18871 if (btf_is_kernel(btf)) {
18872 btf_put(btf);
18873 return -EACCES;
18874 }
18875 env->prog->aux->btf = btf;
18876
18877 err = check_btf_func_early(env, attr, uattr);
18878 if (err)
18879 return err;
18880 return 0;
18881 }
18882
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18883 static int check_btf_info(struct bpf_verifier_env *env,
18884 const union bpf_attr *attr,
18885 bpfptr_t uattr)
18886 {
18887 int err;
18888
18889 if (!attr->func_info_cnt && !attr->line_info_cnt) {
18890 if (check_abnormal_return(env))
18891 return -EINVAL;
18892 return 0;
18893 }
18894
18895 err = check_btf_func(env, attr, uattr);
18896 if (err)
18897 return err;
18898
18899 err = check_btf_line(env, attr, uattr);
18900 if (err)
18901 return err;
18902
18903 err = check_core_relo(env, attr, uattr);
18904 if (err)
18905 return err;
18906
18907 return 0;
18908 }
18909
18910 /* check %cur's range satisfies %old's */
range_within(const struct bpf_reg_state * old,const struct bpf_reg_state * cur)18911 static bool range_within(const struct bpf_reg_state *old,
18912 const struct bpf_reg_state *cur)
18913 {
18914 return old->umin_value <= cur->umin_value &&
18915 old->umax_value >= cur->umax_value &&
18916 old->smin_value <= cur->smin_value &&
18917 old->smax_value >= cur->smax_value &&
18918 old->u32_min_value <= cur->u32_min_value &&
18919 old->u32_max_value >= cur->u32_max_value &&
18920 old->s32_min_value <= cur->s32_min_value &&
18921 old->s32_max_value >= cur->s32_max_value;
18922 }
18923
18924 /* If in the old state two registers had the same id, then they need to have
18925 * the same id in the new state as well. But that id could be different from
18926 * the old state, so we need to track the mapping from old to new ids.
18927 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18928 * regs with old id 5 must also have new id 9 for the new state to be safe. But
18929 * regs with a different old id could still have new id 9, we don't care about
18930 * that.
18931 * So we look through our idmap to see if this old id has been seen before. If
18932 * so, we require the new id to match; otherwise, we add the id pair to the map.
18933 */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18934 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18935 {
18936 struct bpf_id_pair *map = idmap->map;
18937 unsigned int i;
18938
18939 /* either both IDs should be set or both should be zero */
18940 if (!!old_id != !!cur_id)
18941 return false;
18942
18943 if (old_id == 0) /* cur_id == 0 as well */
18944 return true;
18945
18946 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18947 if (!map[i].old) {
18948 /* Reached an empty slot; haven't seen this id before */
18949 map[i].old = old_id;
18950 map[i].cur = cur_id;
18951 return true;
18952 }
18953 if (map[i].old == old_id)
18954 return map[i].cur == cur_id;
18955 if (map[i].cur == cur_id)
18956 return false;
18957 }
18958 /* We ran out of idmap slots, which should be impossible */
18959 WARN_ON_ONCE(1);
18960 return false;
18961 }
18962
18963 /* Similar to check_ids(), but allocate a unique temporary ID
18964 * for 'old_id' or 'cur_id' of zero.
18965 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18966 */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18967 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18968 {
18969 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18970 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18971
18972 return check_ids(old_id, cur_id, idmap);
18973 }
18974
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st,u32 ip)18975 static void clean_func_state(struct bpf_verifier_env *env,
18976 struct bpf_func_state *st,
18977 u32 ip)
18978 {
18979 u16 live_regs = env->insn_aux_data[ip].live_regs_before;
18980 int i, j;
18981
18982 for (i = 0; i < BPF_REG_FP; i++) {
18983 /* liveness must not touch this register anymore */
18984 if (!(live_regs & BIT(i)))
18985 /* since the register is unused, clear its state
18986 * to make further comparison simpler
18987 */
18988 __mark_reg_not_init(env, &st->regs[i]);
18989 }
18990
18991 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18992 if (!bpf_stack_slot_alive(env, st->frameno, i)) {
18993 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18994 for (j = 0; j < BPF_REG_SIZE; j++)
18995 st->stack[i].slot_type[j] = STACK_INVALID;
18996 }
18997 }
18998 }
18999
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)19000 static void clean_verifier_state(struct bpf_verifier_env *env,
19001 struct bpf_verifier_state *st)
19002 {
19003 int i, ip;
19004
19005 bpf_live_stack_query_init(env, st);
19006 st->cleaned = true;
19007 for (i = 0; i <= st->curframe; i++) {
19008 ip = frame_insn_idx(st, i);
19009 clean_func_state(env, st->frame[i], ip);
19010 }
19011 }
19012
19013 /* the parentage chains form a tree.
19014 * the verifier states are added to state lists at given insn and
19015 * pushed into state stack for future exploration.
19016 * when the verifier reaches bpf_exit insn some of the verifier states
19017 * stored in the state lists have their final liveness state already,
19018 * but a lot of states will get revised from liveness point of view when
19019 * the verifier explores other branches.
19020 * Example:
19021 * 1: *(u64)(r10 - 8) = 1
19022 * 2: if r1 == 100 goto pc+1
19023 * 3: *(u64)(r10 - 8) = 2
19024 * 4: r0 = *(u64)(r10 - 8)
19025 * 5: exit
19026 * when the verifier reaches exit insn the stack slot -8 in the state list of
19027 * insn 2 is not yet marked alive. Then the verifier pops the other_branch
19028 * of insn 2 and goes exploring further. After the insn 4 read, liveness
19029 * analysis would propagate read mark for -8 at insn 2.
19030 *
19031 * Since the verifier pushes the branch states as it sees them while exploring
19032 * the program the condition of walking the branch instruction for the second
19033 * time means that all states below this branch were already explored and
19034 * their final liveness marks are already propagated.
19035 * Hence when the verifier completes the search of state list in is_state_visited()
19036 * we can call this clean_live_states() function to clear dead the registers and stack
19037 * slots to simplify state merging.
19038 *
19039 * Important note here that walking the same branch instruction in the callee
19040 * doesn't meant that the states are DONE. The verifier has to compare
19041 * the callsites
19042 */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)19043 static void clean_live_states(struct bpf_verifier_env *env, int insn,
19044 struct bpf_verifier_state *cur)
19045 {
19046 struct bpf_verifier_state_list *sl;
19047 struct list_head *pos, *head;
19048
19049 head = explored_state(env, insn);
19050 list_for_each(pos, head) {
19051 sl = container_of(pos, struct bpf_verifier_state_list, node);
19052 if (sl->state.branches)
19053 continue;
19054 if (sl->state.insn_idx != insn ||
19055 !same_callsites(&sl->state, cur))
19056 continue;
19057 if (sl->state.cleaned)
19058 /* all regs in this state in all frames were already marked */
19059 continue;
19060 if (incomplete_read_marks(env, &sl->state))
19061 continue;
19062 clean_verifier_state(env, &sl->state);
19063 }
19064 }
19065
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)19066 static bool regs_exact(const struct bpf_reg_state *rold,
19067 const struct bpf_reg_state *rcur,
19068 struct bpf_idmap *idmap)
19069 {
19070 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19071 check_ids(rold->id, rcur->id, idmap) &&
19072 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19073 }
19074
19075 enum exact_level {
19076 NOT_EXACT,
19077 EXACT,
19078 RANGE_WITHIN
19079 };
19080
19081 /* Returns true if (rold safe implies rcur safe) */
regsafe(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap,enum exact_level exact)19082 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
19083 struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
19084 enum exact_level exact)
19085 {
19086 if (exact == EXACT)
19087 return regs_exact(rold, rcur, idmap);
19088
19089 if (rold->type == NOT_INIT) {
19090 if (exact == NOT_EXACT || rcur->type == NOT_INIT)
19091 /* explored state can't have used this */
19092 return true;
19093 }
19094
19095 /* Enforce that register types have to match exactly, including their
19096 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
19097 * rule.
19098 *
19099 * One can make a point that using a pointer register as unbounded
19100 * SCALAR would be technically acceptable, but this could lead to
19101 * pointer leaks because scalars are allowed to leak while pointers
19102 * are not. We could make this safe in special cases if root is
19103 * calling us, but it's probably not worth the hassle.
19104 *
19105 * Also, register types that are *not* MAYBE_NULL could technically be
19106 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
19107 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
19108 * to the same map).
19109 * However, if the old MAYBE_NULL register then got NULL checked,
19110 * doing so could have affected others with the same id, and we can't
19111 * check for that because we lost the id when we converted to
19112 * a non-MAYBE_NULL variant.
19113 * So, as a general rule we don't allow mixing MAYBE_NULL and
19114 * non-MAYBE_NULL registers as well.
19115 */
19116 if (rold->type != rcur->type)
19117 return false;
19118
19119 switch (base_type(rold->type)) {
19120 case SCALAR_VALUE:
19121 if (env->explore_alu_limits) {
19122 /* explore_alu_limits disables tnum_in() and range_within()
19123 * logic and requires everything to be strict
19124 */
19125 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19126 check_scalar_ids(rold->id, rcur->id, idmap);
19127 }
19128 if (!rold->precise && exact == NOT_EXACT)
19129 return true;
19130 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
19131 return false;
19132 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
19133 return false;
19134 /* Why check_ids() for scalar registers?
19135 *
19136 * Consider the following BPF code:
19137 * 1: r6 = ... unbound scalar, ID=a ...
19138 * 2: r7 = ... unbound scalar, ID=b ...
19139 * 3: if (r6 > r7) goto +1
19140 * 4: r6 = r7
19141 * 5: if (r6 > X) goto ...
19142 * 6: ... memory operation using r7 ...
19143 *
19144 * First verification path is [1-6]:
19145 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
19146 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
19147 * r7 <= X, because r6 and r7 share same id.
19148 * Next verification path is [1-4, 6].
19149 *
19150 * Instruction (6) would be reached in two states:
19151 * I. r6{.id=b}, r7{.id=b} via path 1-6;
19152 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
19153 *
19154 * Use check_ids() to distinguish these states.
19155 * ---
19156 * Also verify that new value satisfies old value range knowledge.
19157 */
19158 return range_within(rold, rcur) &&
19159 tnum_in(rold->var_off, rcur->var_off) &&
19160 check_scalar_ids(rold->id, rcur->id, idmap);
19161 case PTR_TO_MAP_KEY:
19162 case PTR_TO_MAP_VALUE:
19163 case PTR_TO_MEM:
19164 case PTR_TO_BUF:
19165 case PTR_TO_TP_BUFFER:
19166 /* If the new min/max/var_off satisfy the old ones and
19167 * everything else matches, we are OK.
19168 */
19169 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19170 range_within(rold, rcur) &&
19171 tnum_in(rold->var_off, rcur->var_off) &&
19172 check_ids(rold->id, rcur->id, idmap) &&
19173 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19174 case PTR_TO_PACKET_META:
19175 case PTR_TO_PACKET:
19176 /* We must have at least as much range as the old ptr
19177 * did, so that any accesses which were safe before are
19178 * still safe. This is true even if old range < old off,
19179 * since someone could have accessed through (ptr - k), or
19180 * even done ptr -= k in a register, to get a safe access.
19181 */
19182 if (rold->range > rcur->range)
19183 return false;
19184 /* If the offsets don't match, we can't trust our alignment;
19185 * nor can we be sure that we won't fall out of range.
19186 */
19187 if (rold->off != rcur->off)
19188 return false;
19189 /* id relations must be preserved */
19190 if (!check_ids(rold->id, rcur->id, idmap))
19191 return false;
19192 /* new val must satisfy old val knowledge */
19193 return range_within(rold, rcur) &&
19194 tnum_in(rold->var_off, rcur->var_off);
19195 case PTR_TO_STACK:
19196 /* two stack pointers are equal only if they're pointing to
19197 * the same stack frame, since fp-8 in foo != fp-8 in bar
19198 */
19199 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
19200 case PTR_TO_ARENA:
19201 return true;
19202 case PTR_TO_INSN:
19203 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19204 rold->off == rcur->off && range_within(rold, rcur) &&
19205 tnum_in(rold->var_off, rcur->var_off);
19206 default:
19207 return regs_exact(rold, rcur, idmap);
19208 }
19209 }
19210
19211 static struct bpf_reg_state unbound_reg;
19212
unbound_reg_init(void)19213 static __init int unbound_reg_init(void)
19214 {
19215 __mark_reg_unknown_imprecise(&unbound_reg);
19216 return 0;
19217 }
19218 late_initcall(unbound_reg_init);
19219
is_stack_all_misc(struct bpf_verifier_env * env,struct bpf_stack_state * stack)19220 static bool is_stack_all_misc(struct bpf_verifier_env *env,
19221 struct bpf_stack_state *stack)
19222 {
19223 u32 i;
19224
19225 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
19226 if ((stack->slot_type[i] == STACK_MISC) ||
19227 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
19228 continue;
19229 return false;
19230 }
19231
19232 return true;
19233 }
19234
scalar_reg_for_stack(struct bpf_verifier_env * env,struct bpf_stack_state * stack)19235 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
19236 struct bpf_stack_state *stack)
19237 {
19238 if (is_spilled_scalar_reg64(stack))
19239 return &stack->spilled_ptr;
19240
19241 if (is_stack_all_misc(env, stack))
19242 return &unbound_reg;
19243
19244 return NULL;
19245 }
19246
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,enum exact_level exact)19247 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
19248 struct bpf_func_state *cur, struct bpf_idmap *idmap,
19249 enum exact_level exact)
19250 {
19251 int i, spi;
19252
19253 /* walk slots of the explored stack and ignore any additional
19254 * slots in the current stack, since explored(safe) state
19255 * didn't use them
19256 */
19257 for (i = 0; i < old->allocated_stack; i++) {
19258 struct bpf_reg_state *old_reg, *cur_reg;
19259
19260 spi = i / BPF_REG_SIZE;
19261
19262 if (exact != NOT_EXACT &&
19263 (i >= cur->allocated_stack ||
19264 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19265 cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
19266 return false;
19267
19268 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
19269 continue;
19270
19271 if (env->allow_uninit_stack &&
19272 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
19273 continue;
19274
19275 /* explored stack has more populated slots than current stack
19276 * and these slots were used
19277 */
19278 if (i >= cur->allocated_stack)
19279 return false;
19280
19281 /* 64-bit scalar spill vs all slots MISC and vice versa.
19282 * Load from all slots MISC produces unbound scalar.
19283 * Construct a fake register for such stack and call
19284 * regsafe() to ensure scalar ids are compared.
19285 */
19286 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
19287 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
19288 if (old_reg && cur_reg) {
19289 if (!regsafe(env, old_reg, cur_reg, idmap, exact))
19290 return false;
19291 i += BPF_REG_SIZE - 1;
19292 continue;
19293 }
19294
19295 /* if old state was safe with misc data in the stack
19296 * it will be safe with zero-initialized stack.
19297 * The opposite is not true
19298 */
19299 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
19300 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
19301 continue;
19302 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19303 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
19304 /* Ex: old explored (safe) state has STACK_SPILL in
19305 * this stack slot, but current has STACK_MISC ->
19306 * this verifier states are not equivalent,
19307 * return false to continue verification of this path
19308 */
19309 return false;
19310 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
19311 continue;
19312 /* Both old and cur are having same slot_type */
19313 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
19314 case STACK_SPILL:
19315 /* when explored and current stack slot are both storing
19316 * spilled registers, check that stored pointers types
19317 * are the same as well.
19318 * Ex: explored safe path could have stored
19319 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
19320 * but current path has stored:
19321 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
19322 * such verifier states are not equivalent.
19323 * return false to continue verification of this path
19324 */
19325 if (!regsafe(env, &old->stack[spi].spilled_ptr,
19326 &cur->stack[spi].spilled_ptr, idmap, exact))
19327 return false;
19328 break;
19329 case STACK_DYNPTR:
19330 old_reg = &old->stack[spi].spilled_ptr;
19331 cur_reg = &cur->stack[spi].spilled_ptr;
19332 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
19333 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
19334 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19335 return false;
19336 break;
19337 case STACK_ITER:
19338 old_reg = &old->stack[spi].spilled_ptr;
19339 cur_reg = &cur->stack[spi].spilled_ptr;
19340 /* iter.depth is not compared between states as it
19341 * doesn't matter for correctness and would otherwise
19342 * prevent convergence; we maintain it only to prevent
19343 * infinite loop check triggering, see
19344 * iter_active_depths_differ()
19345 */
19346 if (old_reg->iter.btf != cur_reg->iter.btf ||
19347 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
19348 old_reg->iter.state != cur_reg->iter.state ||
19349 /* ignore {old_reg,cur_reg}->iter.depth, see above */
19350 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19351 return false;
19352 break;
19353 case STACK_IRQ_FLAG:
19354 old_reg = &old->stack[spi].spilled_ptr;
19355 cur_reg = &cur->stack[spi].spilled_ptr;
19356 if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
19357 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
19358 return false;
19359 break;
19360 case STACK_MISC:
19361 case STACK_ZERO:
19362 case STACK_INVALID:
19363 continue;
19364 /* Ensure that new unhandled slot types return false by default */
19365 default:
19366 return false;
19367 }
19368 }
19369 return true;
19370 }
19371
refsafe(struct bpf_verifier_state * old,struct bpf_verifier_state * cur,struct bpf_idmap * idmap)19372 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
19373 struct bpf_idmap *idmap)
19374 {
19375 int i;
19376
19377 if (old->acquired_refs != cur->acquired_refs)
19378 return false;
19379
19380 if (old->active_locks != cur->active_locks)
19381 return false;
19382
19383 if (old->active_preempt_locks != cur->active_preempt_locks)
19384 return false;
19385
19386 if (old->active_rcu_locks != cur->active_rcu_locks)
19387 return false;
19388
19389 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
19390 return false;
19391
19392 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
19393 old->active_lock_ptr != cur->active_lock_ptr)
19394 return false;
19395
19396 for (i = 0; i < old->acquired_refs; i++) {
19397 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
19398 old->refs[i].type != cur->refs[i].type)
19399 return false;
19400 switch (old->refs[i].type) {
19401 case REF_TYPE_PTR:
19402 case REF_TYPE_IRQ:
19403 break;
19404 case REF_TYPE_LOCK:
19405 case REF_TYPE_RES_LOCK:
19406 case REF_TYPE_RES_LOCK_IRQ:
19407 if (old->refs[i].ptr != cur->refs[i].ptr)
19408 return false;
19409 break;
19410 default:
19411 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
19412 return false;
19413 }
19414 }
19415
19416 return true;
19417 }
19418
19419 /* compare two verifier states
19420 *
19421 * all states stored in state_list are known to be valid, since
19422 * verifier reached 'bpf_exit' instruction through them
19423 *
19424 * this function is called when verifier exploring different branches of
19425 * execution popped from the state stack. If it sees an old state that has
19426 * more strict register state and more strict stack state then this execution
19427 * branch doesn't need to be explored further, since verifier already
19428 * concluded that more strict state leads to valid finish.
19429 *
19430 * Therefore two states are equivalent if register state is more conservative
19431 * and explored stack state is more conservative than the current one.
19432 * Example:
19433 * explored current
19434 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19435 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19436 *
19437 * In other words if current stack state (one being explored) has more
19438 * valid slots than old one that already passed validation, it means
19439 * the verifier can stop exploring and conclude that current state is valid too
19440 *
19441 * Similarly with registers. If explored state has register type as invalid
19442 * whereas register type in current state is meaningful, it means that
19443 * the current state will reach 'bpf_exit' instruction safely
19444 */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,u32 insn_idx,enum exact_level exact)19445 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19446 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19447 {
19448 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19449 u16 i;
19450
19451 if (old->callback_depth > cur->callback_depth)
19452 return false;
19453
19454 for (i = 0; i < MAX_BPF_REG; i++)
19455 if (((1 << i) & live_regs) &&
19456 !regsafe(env, &old->regs[i], &cur->regs[i],
19457 &env->idmap_scratch, exact))
19458 return false;
19459
19460 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19461 return false;
19462
19463 return true;
19464 }
19465
reset_idmap_scratch(struct bpf_verifier_env * env)19466 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19467 {
19468 env->idmap_scratch.tmp_id_gen = env->id_gen;
19469 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19470 }
19471
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,enum exact_level exact)19472 static bool states_equal(struct bpf_verifier_env *env,
19473 struct bpf_verifier_state *old,
19474 struct bpf_verifier_state *cur,
19475 enum exact_level exact)
19476 {
19477 u32 insn_idx;
19478 int i;
19479
19480 if (old->curframe != cur->curframe)
19481 return false;
19482
19483 reset_idmap_scratch(env);
19484
19485 /* Verification state from speculative execution simulation
19486 * must never prune a non-speculative execution one.
19487 */
19488 if (old->speculative && !cur->speculative)
19489 return false;
19490
19491 if (old->in_sleepable != cur->in_sleepable)
19492 return false;
19493
19494 if (!refsafe(old, cur, &env->idmap_scratch))
19495 return false;
19496
19497 /* for states to be equal callsites have to be the same
19498 * and all frame states need to be equivalent
19499 */
19500 for (i = 0; i <= old->curframe; i++) {
19501 insn_idx = frame_insn_idx(old, i);
19502 if (old->frame[i]->callsite != cur->frame[i]->callsite)
19503 return false;
19504 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19505 return false;
19506 }
19507 return true;
19508 }
19509
19510 /* find precise scalars in the previous equivalent state and
19511 * propagate them into the current state
19512 */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool * changed)19513 static int propagate_precision(struct bpf_verifier_env *env,
19514 const struct bpf_verifier_state *old,
19515 struct bpf_verifier_state *cur,
19516 bool *changed)
19517 {
19518 struct bpf_reg_state *state_reg;
19519 struct bpf_func_state *state;
19520 int i, err = 0, fr;
19521 bool first;
19522
19523 for (fr = old->curframe; fr >= 0; fr--) {
19524 state = old->frame[fr];
19525 state_reg = state->regs;
19526 first = true;
19527 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19528 if (state_reg->type != SCALAR_VALUE ||
19529 !state_reg->precise)
19530 continue;
19531 if (env->log.level & BPF_LOG_LEVEL2) {
19532 if (first)
19533 verbose(env, "frame %d: propagating r%d", fr, i);
19534 else
19535 verbose(env, ",r%d", i);
19536 }
19537 bt_set_frame_reg(&env->bt, fr, i);
19538 first = false;
19539 }
19540
19541 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19542 if (!is_spilled_reg(&state->stack[i]))
19543 continue;
19544 state_reg = &state->stack[i].spilled_ptr;
19545 if (state_reg->type != SCALAR_VALUE ||
19546 !state_reg->precise)
19547 continue;
19548 if (env->log.level & BPF_LOG_LEVEL2) {
19549 if (first)
19550 verbose(env, "frame %d: propagating fp%d",
19551 fr, (-i - 1) * BPF_REG_SIZE);
19552 else
19553 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19554 }
19555 bt_set_frame_slot(&env->bt, fr, i);
19556 first = false;
19557 }
19558 if (!first && (env->log.level & BPF_LOG_LEVEL2))
19559 verbose(env, "\n");
19560 }
19561
19562 err = __mark_chain_precision(env, cur, -1, changed);
19563 if (err < 0)
19564 return err;
19565
19566 return 0;
19567 }
19568
19569 #define MAX_BACKEDGE_ITERS 64
19570
19571 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19572 * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19573 * then free visit->backedges.
19574 * After execution of this function incomplete_read_marks() will return false
19575 * for all states corresponding to @visit->callchain.
19576 */
propagate_backedges(struct bpf_verifier_env * env,struct bpf_scc_visit * visit)19577 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19578 {
19579 struct bpf_scc_backedge *backedge;
19580 struct bpf_verifier_state *st;
19581 bool changed;
19582 int i, err;
19583
19584 i = 0;
19585 do {
19586 if (i++ > MAX_BACKEDGE_ITERS) {
19587 if (env->log.level & BPF_LOG_LEVEL2)
19588 verbose(env, "%s: too many iterations\n", __func__);
19589 for (backedge = visit->backedges; backedge; backedge = backedge->next)
19590 mark_all_scalars_precise(env, &backedge->state);
19591 break;
19592 }
19593 changed = false;
19594 for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19595 st = &backedge->state;
19596 err = propagate_precision(env, st->equal_state, st, &changed);
19597 if (err)
19598 return err;
19599 }
19600 } while (changed);
19601
19602 free_backedges(visit);
19603 return 0;
19604 }
19605
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19606 static bool states_maybe_looping(struct bpf_verifier_state *old,
19607 struct bpf_verifier_state *cur)
19608 {
19609 struct bpf_func_state *fold, *fcur;
19610 int i, fr = cur->curframe;
19611
19612 if (old->curframe != fr)
19613 return false;
19614
19615 fold = old->frame[fr];
19616 fcur = cur->frame[fr];
19617 for (i = 0; i < MAX_BPF_REG; i++)
19618 if (memcmp(&fold->regs[i], &fcur->regs[i],
19619 offsetof(struct bpf_reg_state, frameno)))
19620 return false;
19621 return true;
19622 }
19623
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)19624 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19625 {
19626 return env->insn_aux_data[insn_idx].is_iter_next;
19627 }
19628
19629 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19630 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19631 * states to match, which otherwise would look like an infinite loop. So while
19632 * iter_next() calls are taken care of, we still need to be careful and
19633 * prevent erroneous and too eager declaration of "infinite loop", when
19634 * iterators are involved.
19635 *
19636 * Here's a situation in pseudo-BPF assembly form:
19637 *
19638 * 0: again: ; set up iter_next() call args
19639 * 1: r1 = &it ; <CHECKPOINT HERE>
19640 * 2: call bpf_iter_num_next ; this is iter_next() call
19641 * 3: if r0 == 0 goto done
19642 * 4: ... something useful here ...
19643 * 5: goto again ; another iteration
19644 * 6: done:
19645 * 7: r1 = &it
19646 * 8: call bpf_iter_num_destroy ; clean up iter state
19647 * 9: exit
19648 *
19649 * This is a typical loop. Let's assume that we have a prune point at 1:,
19650 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19651 * again`, assuming other heuristics don't get in a way).
19652 *
19653 * When we first time come to 1:, let's say we have some state X. We proceed
19654 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19655 * Now we come back to validate that forked ACTIVE state. We proceed through
19656 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19657 * are converging. But the problem is that we don't know that yet, as this
19658 * convergence has to happen at iter_next() call site only. So if nothing is
19659 * done, at 1: verifier will use bounded loop logic and declare infinite
19660 * looping (and would be *technically* correct, if not for iterator's
19661 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19662 * don't want that. So what we do in process_iter_next_call() when we go on
19663 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19664 * a different iteration. So when we suspect an infinite loop, we additionally
19665 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19666 * pretend we are not looping and wait for next iter_next() call.
19667 *
19668 * This only applies to ACTIVE state. In DRAINED state we don't expect to
19669 * loop, because that would actually mean infinite loop, as DRAINED state is
19670 * "sticky", and so we'll keep returning into the same instruction with the
19671 * same state (at least in one of possible code paths).
19672 *
19673 * This approach allows to keep infinite loop heuristic even in the face of
19674 * active iterator. E.g., C snippet below is and will be detected as
19675 * infinitely looping:
19676 *
19677 * struct bpf_iter_num it;
19678 * int *p, x;
19679 *
19680 * bpf_iter_num_new(&it, 0, 10);
19681 * while ((p = bpf_iter_num_next(&t))) {
19682 * x = p;
19683 * while (x--) {} // <<-- infinite loop here
19684 * }
19685 *
19686 */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19687 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19688 {
19689 struct bpf_reg_state *slot, *cur_slot;
19690 struct bpf_func_state *state;
19691 int i, fr;
19692
19693 for (fr = old->curframe; fr >= 0; fr--) {
19694 state = old->frame[fr];
19695 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19696 if (state->stack[i].slot_type[0] != STACK_ITER)
19697 continue;
19698
19699 slot = &state->stack[i].spilled_ptr;
19700 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19701 continue;
19702
19703 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19704 if (cur_slot->iter.depth != slot->iter.depth)
19705 return true;
19706 }
19707 }
19708 return false;
19709 }
19710
is_state_visited(struct bpf_verifier_env * env,int insn_idx)19711 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19712 {
19713 struct bpf_verifier_state_list *new_sl;
19714 struct bpf_verifier_state_list *sl;
19715 struct bpf_verifier_state *cur = env->cur_state, *new;
19716 bool force_new_state, add_new_state, loop;
19717 int n, err, states_cnt = 0;
19718 struct list_head *pos, *tmp, *head;
19719
19720 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19721 /* Avoid accumulating infinitely long jmp history */
19722 cur->jmp_history_cnt > 40;
19723
19724 /* bpf progs typically have pruning point every 4 instructions
19725 * http://vger.kernel.org/bpfconf2019.html#session-1
19726 * Do not add new state for future pruning if the verifier hasn't seen
19727 * at least 2 jumps and at least 8 instructions.
19728 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19729 * In tests that amounts to up to 50% reduction into total verifier
19730 * memory consumption and 20% verifier time speedup.
19731 */
19732 add_new_state = force_new_state;
19733 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19734 env->insn_processed - env->prev_insn_processed >= 8)
19735 add_new_state = true;
19736
19737 clean_live_states(env, insn_idx, cur);
19738
19739 loop = false;
19740 head = explored_state(env, insn_idx);
19741 list_for_each_safe(pos, tmp, head) {
19742 sl = container_of(pos, struct bpf_verifier_state_list, node);
19743 states_cnt++;
19744 if (sl->state.insn_idx != insn_idx)
19745 continue;
19746
19747 if (sl->state.branches) {
19748 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19749
19750 if (frame->in_async_callback_fn &&
19751 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19752 /* Different async_entry_cnt means that the verifier is
19753 * processing another entry into async callback.
19754 * Seeing the same state is not an indication of infinite
19755 * loop or infinite recursion.
19756 * But finding the same state doesn't mean that it's safe
19757 * to stop processing the current state. The previous state
19758 * hasn't yet reached bpf_exit, since state.branches > 0.
19759 * Checking in_async_callback_fn alone is not enough either.
19760 * Since the verifier still needs to catch infinite loops
19761 * inside async callbacks.
19762 */
19763 goto skip_inf_loop_check;
19764 }
19765 /* BPF open-coded iterators loop detection is special.
19766 * states_maybe_looping() logic is too simplistic in detecting
19767 * states that *might* be equivalent, because it doesn't know
19768 * about ID remapping, so don't even perform it.
19769 * See process_iter_next_call() and iter_active_depths_differ()
19770 * for overview of the logic. When current and one of parent
19771 * states are detected as equivalent, it's a good thing: we prove
19772 * convergence and can stop simulating further iterations.
19773 * It's safe to assume that iterator loop will finish, taking into
19774 * account iter_next() contract of eventually returning
19775 * sticky NULL result.
19776 *
19777 * Note, that states have to be compared exactly in this case because
19778 * read and precision marks might not be finalized inside the loop.
19779 * E.g. as in the program below:
19780 *
19781 * 1. r7 = -16
19782 * 2. r6 = bpf_get_prandom_u32()
19783 * 3. while (bpf_iter_num_next(&fp[-8])) {
19784 * 4. if (r6 != 42) {
19785 * 5. r7 = -32
19786 * 6. r6 = bpf_get_prandom_u32()
19787 * 7. continue
19788 * 8. }
19789 * 9. r0 = r10
19790 * 10. r0 += r7
19791 * 11. r8 = *(u64 *)(r0 + 0)
19792 * 12. r6 = bpf_get_prandom_u32()
19793 * 13. }
19794 *
19795 * Here verifier would first visit path 1-3, create a checkpoint at 3
19796 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19797 * not have read or precision mark for r7 yet, thus inexact states
19798 * comparison would discard current state with r7=-32
19799 * => unsafe memory access at 11 would not be caught.
19800 */
19801 if (is_iter_next_insn(env, insn_idx)) {
19802 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19803 struct bpf_func_state *cur_frame;
19804 struct bpf_reg_state *iter_state, *iter_reg;
19805 int spi;
19806
19807 cur_frame = cur->frame[cur->curframe];
19808 /* btf_check_iter_kfuncs() enforces that
19809 * iter state pointer is always the first arg
19810 */
19811 iter_reg = &cur_frame->regs[BPF_REG_1];
19812 /* current state is valid due to states_equal(),
19813 * so we can assume valid iter and reg state,
19814 * no need for extra (re-)validations
19815 */
19816 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19817 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19818 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19819 loop = true;
19820 goto hit;
19821 }
19822 }
19823 goto skip_inf_loop_check;
19824 }
19825 if (is_may_goto_insn_at(env, insn_idx)) {
19826 if (sl->state.may_goto_depth != cur->may_goto_depth &&
19827 states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19828 loop = true;
19829 goto hit;
19830 }
19831 }
19832 if (bpf_calls_callback(env, insn_idx)) {
19833 if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19834 goto hit;
19835 goto skip_inf_loop_check;
19836 }
19837 /* attempt to detect infinite loop to avoid unnecessary doomed work */
19838 if (states_maybe_looping(&sl->state, cur) &&
19839 states_equal(env, &sl->state, cur, EXACT) &&
19840 !iter_active_depths_differ(&sl->state, cur) &&
19841 sl->state.may_goto_depth == cur->may_goto_depth &&
19842 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19843 verbose_linfo(env, insn_idx, "; ");
19844 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19845 verbose(env, "cur state:");
19846 print_verifier_state(env, cur, cur->curframe, true);
19847 verbose(env, "old state:");
19848 print_verifier_state(env, &sl->state, cur->curframe, true);
19849 return -EINVAL;
19850 }
19851 /* if the verifier is processing a loop, avoid adding new state
19852 * too often, since different loop iterations have distinct
19853 * states and may not help future pruning.
19854 * This threshold shouldn't be too low to make sure that
19855 * a loop with large bound will be rejected quickly.
19856 * The most abusive loop will be:
19857 * r1 += 1
19858 * if r1 < 1000000 goto pc-2
19859 * 1M insn_procssed limit / 100 == 10k peak states.
19860 * This threshold shouldn't be too high either, since states
19861 * at the end of the loop are likely to be useful in pruning.
19862 */
19863 skip_inf_loop_check:
19864 if (!force_new_state &&
19865 env->jmps_processed - env->prev_jmps_processed < 20 &&
19866 env->insn_processed - env->prev_insn_processed < 100)
19867 add_new_state = false;
19868 goto miss;
19869 }
19870 /* See comments for mark_all_regs_read_and_precise() */
19871 loop = incomplete_read_marks(env, &sl->state);
19872 if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19873 hit:
19874 sl->hit_cnt++;
19875
19876 /* if previous state reached the exit with precision and
19877 * current state is equivalent to it (except precision marks)
19878 * the precision needs to be propagated back in
19879 * the current state.
19880 */
19881 err = 0;
19882 if (is_jmp_point(env, env->insn_idx))
19883 err = push_jmp_history(env, cur, 0, 0);
19884 err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19885 if (err)
19886 return err;
19887 /* When processing iterator based loops above propagate_liveness and
19888 * propagate_precision calls are not sufficient to transfer all relevant
19889 * read and precision marks. E.g. consider the following case:
19890 *
19891 * .-> A --. Assume the states are visited in the order A, B, C.
19892 * | | | Assume that state B reaches a state equivalent to state A.
19893 * | v v At this point, state C is not processed yet, so state A
19894 * '-- B C has not received any read or precision marks from C.
19895 * Thus, marks propagated from A to B are incomplete.
19896 *
19897 * The verifier mitigates this by performing the following steps:
19898 *
19899 * - Prior to the main verification pass, strongly connected components
19900 * (SCCs) are computed over the program's control flow graph,
19901 * intraprocedurally.
19902 *
19903 * - During the main verification pass, `maybe_enter_scc()` checks
19904 * whether the current verifier state is entering an SCC. If so, an
19905 * instance of a `bpf_scc_visit` object is created, and the state
19906 * entering the SCC is recorded as the entry state.
19907 *
19908 * - This instance is associated not with the SCC itself, but with a
19909 * `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19910 * the SCC and the SCC id. See `compute_scc_callchain()`.
19911 *
19912 * - When a verification path encounters a `states_equal(...,
19913 * RANGE_WITHIN)` condition, there exists a call chain describing the
19914 * current state and a corresponding `bpf_scc_visit` instance. A copy
19915 * of the current state is created and added to
19916 * `bpf_scc_visit->backedges`.
19917 *
19918 * - When a verification path terminates, `maybe_exit_scc()` is called
19919 * from `update_branch_counts()`. For states with `branches == 0`, it
19920 * checks whether the state is the entry state of any `bpf_scc_visit`
19921 * instance. If it is, this indicates that all paths originating from
19922 * this SCC visit have been explored. `propagate_backedges()` is then
19923 * called, which propagates read and precision marks through the
19924 * backedges until a fixed point is reached.
19925 * (In the earlier example, this would propagate marks from A to B,
19926 * from C to A, and then again from A to B.)
19927 *
19928 * A note on callchains
19929 * --------------------
19930 *
19931 * Consider the following example:
19932 *
19933 * void foo() { loop { ... SCC#1 ... } }
19934 * void main() {
19935 * A: foo();
19936 * B: ...
19937 * C: foo();
19938 * }
19939 *
19940 * Here, there are two distinct callchains leading to SCC#1:
19941 * - (A, SCC#1)
19942 * - (C, SCC#1)
19943 *
19944 * Each callchain identifies a separate `bpf_scc_visit` instance that
19945 * accumulates backedge states. The `propagate_{liveness,precision}()`
19946 * functions traverse the parent state of each backedge state, which
19947 * means these parent states must remain valid (i.e., not freed) while
19948 * the corresponding `bpf_scc_visit` instance exists.
19949 *
19950 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19951 * callchains would break this invariant:
19952 * - States explored during `C: foo()` would contribute backedges to
19953 * SCC#1, but SCC#1 would only be exited once the exploration of
19954 * `A: foo()` completes.
19955 * - By that time, the states explored between `A: foo()` and `C: foo()`
19956 * (i.e., `B: ...`) may have already been freed, causing the parent
19957 * links for states from `C: foo()` to become invalid.
19958 */
19959 if (loop) {
19960 struct bpf_scc_backedge *backedge;
19961
19962 backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19963 if (!backedge)
19964 return -ENOMEM;
19965 err = copy_verifier_state(&backedge->state, cur);
19966 backedge->state.equal_state = &sl->state;
19967 backedge->state.insn_idx = insn_idx;
19968 err = err ?: add_scc_backedge(env, &sl->state, backedge);
19969 if (err) {
19970 free_verifier_state(&backedge->state, false);
19971 kfree(backedge);
19972 return err;
19973 }
19974 }
19975 return 1;
19976 }
19977 miss:
19978 /* when new state is not going to be added do not increase miss count.
19979 * Otherwise several loop iterations will remove the state
19980 * recorded earlier. The goal of these heuristics is to have
19981 * states from some iterations of the loop (some in the beginning
19982 * and some at the end) to help pruning.
19983 */
19984 if (add_new_state)
19985 sl->miss_cnt++;
19986 /* heuristic to determine whether this state is beneficial
19987 * to keep checking from state equivalence point of view.
19988 * Higher numbers increase max_states_per_insn and verification time,
19989 * but do not meaningfully decrease insn_processed.
19990 * 'n' controls how many times state could miss before eviction.
19991 * Use bigger 'n' for checkpoints because evicting checkpoint states
19992 * too early would hinder iterator convergence.
19993 */
19994 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
19995 if (sl->miss_cnt > sl->hit_cnt * n + n) {
19996 /* the state is unlikely to be useful. Remove it to
19997 * speed up verification
19998 */
19999 sl->in_free_list = true;
20000 list_del(&sl->node);
20001 list_add(&sl->node, &env->free_list);
20002 env->free_list_size++;
20003 env->explored_states_size--;
20004 maybe_free_verifier_state(env, sl);
20005 }
20006 }
20007
20008 if (env->max_states_per_insn < states_cnt)
20009 env->max_states_per_insn = states_cnt;
20010
20011 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
20012 return 0;
20013
20014 if (!add_new_state)
20015 return 0;
20016
20017 /* There were no equivalent states, remember the current one.
20018 * Technically the current state is not proven to be safe yet,
20019 * but it will either reach outer most bpf_exit (which means it's safe)
20020 * or it will be rejected. When there are no loops the verifier won't be
20021 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
20022 * again on the way to bpf_exit.
20023 * When looping the sl->state.branches will be > 0 and this state
20024 * will not be considered for equivalence until branches == 0.
20025 */
20026 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
20027 if (!new_sl)
20028 return -ENOMEM;
20029 env->total_states++;
20030 env->explored_states_size++;
20031 update_peak_states(env);
20032 env->prev_jmps_processed = env->jmps_processed;
20033 env->prev_insn_processed = env->insn_processed;
20034
20035 /* forget precise markings we inherited, see __mark_chain_precision */
20036 if (env->bpf_capable)
20037 mark_all_scalars_imprecise(env, cur);
20038
20039 /* add new state to the head of linked list */
20040 new = &new_sl->state;
20041 err = copy_verifier_state(new, cur);
20042 if (err) {
20043 free_verifier_state(new, false);
20044 kfree(new_sl);
20045 return err;
20046 }
20047 new->insn_idx = insn_idx;
20048 verifier_bug_if(new->branches != 1, env,
20049 "%s:branches_to_explore=%d insn %d",
20050 __func__, new->branches, insn_idx);
20051 err = maybe_enter_scc(env, new);
20052 if (err) {
20053 free_verifier_state(new, false);
20054 kfree(new_sl);
20055 return err;
20056 }
20057
20058 cur->parent = new;
20059 cur->first_insn_idx = insn_idx;
20060 cur->dfs_depth = new->dfs_depth + 1;
20061 clear_jmp_history(cur);
20062 list_add(&new_sl->node, head);
20063 return 0;
20064 }
20065
20066 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)20067 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20068 {
20069 switch (base_type(type)) {
20070 case PTR_TO_CTX:
20071 case PTR_TO_SOCKET:
20072 case PTR_TO_SOCK_COMMON:
20073 case PTR_TO_TCP_SOCK:
20074 case PTR_TO_XDP_SOCK:
20075 case PTR_TO_BTF_ID:
20076 case PTR_TO_ARENA:
20077 return false;
20078 default:
20079 return true;
20080 }
20081 }
20082
20083 /* If an instruction was previously used with particular pointer types, then we
20084 * need to be careful to avoid cases such as the below, where it may be ok
20085 * for one branch accessing the pointer, but not ok for the other branch:
20086 *
20087 * R1 = sock_ptr
20088 * goto X;
20089 * ...
20090 * R1 = some_other_valid_ptr;
20091 * goto X;
20092 * ...
20093 * R2 = *(u32 *)(R1 + 0);
20094 */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)20095 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20096 {
20097 return src != prev && (!reg_type_mismatch_ok(src) ||
20098 !reg_type_mismatch_ok(prev));
20099 }
20100
is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)20101 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
20102 {
20103 switch (base_type(type)) {
20104 case PTR_TO_MEM:
20105 case PTR_TO_BTF_ID:
20106 return true;
20107 default:
20108 return false;
20109 }
20110 }
20111
is_ptr_to_mem(enum bpf_reg_type type)20112 static bool is_ptr_to_mem(enum bpf_reg_type type)
20113 {
20114 return base_type(type) == PTR_TO_MEM;
20115 }
20116
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_mismatch)20117 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20118 bool allow_trust_mismatch)
20119 {
20120 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20121 enum bpf_reg_type merged_type;
20122
20123 if (*prev_type == NOT_INIT) {
20124 /* Saw a valid insn
20125 * dst_reg = *(u32 *)(src_reg + off)
20126 * save type to validate intersecting paths
20127 */
20128 *prev_type = type;
20129 } else if (reg_type_mismatch(type, *prev_type)) {
20130 /* Abuser program is trying to use the same insn
20131 * dst_reg = *(u32*) (src_reg + off)
20132 * with different pointer types:
20133 * src_reg == ctx in one branch and
20134 * src_reg == stack|map in some other branch.
20135 * Reject it.
20136 */
20137 if (allow_trust_mismatch &&
20138 is_ptr_to_mem_or_btf_id(type) &&
20139 is_ptr_to_mem_or_btf_id(*prev_type)) {
20140 /*
20141 * Have to support a use case when one path through
20142 * the program yields TRUSTED pointer while another
20143 * is UNTRUSTED. Fallback to UNTRUSTED to generate
20144 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
20145 * Same behavior of MEM_RDONLY flag.
20146 */
20147 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
20148 merged_type = PTR_TO_MEM;
20149 else
20150 merged_type = PTR_TO_BTF_ID;
20151 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
20152 merged_type |= PTR_UNTRUSTED;
20153 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
20154 merged_type |= MEM_RDONLY;
20155 *prev_type = merged_type;
20156 } else {
20157 verbose(env, "same insn cannot be used with different pointers\n");
20158 return -EINVAL;
20159 }
20160 }
20161
20162 return 0;
20163 }
20164
20165 enum {
20166 PROCESS_BPF_EXIT = 1
20167 };
20168
process_bpf_exit_full(struct bpf_verifier_env * env,bool * do_print_state,bool exception_exit)20169 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20170 bool *do_print_state,
20171 bool exception_exit)
20172 {
20173 /* We must do check_reference_leak here before
20174 * prepare_func_exit to handle the case when
20175 * state->curframe > 0, it may be a callback function,
20176 * for which reference_state must match caller reference
20177 * state when it exits.
20178 */
20179 int err = check_resource_leak(env, exception_exit,
20180 !env->cur_state->curframe,
20181 "BPF_EXIT instruction in main prog");
20182 if (err)
20183 return err;
20184
20185 /* The side effect of the prepare_func_exit which is
20186 * being skipped is that it frees bpf_func_state.
20187 * Typically, process_bpf_exit will only be hit with
20188 * outermost exit. copy_verifier_state in pop_stack will
20189 * handle freeing of any extra bpf_func_state left over
20190 * from not processing all nested function exits. We
20191 * also skip return code checks as they are not needed
20192 * for exceptional exits.
20193 */
20194 if (exception_exit)
20195 return PROCESS_BPF_EXIT;
20196
20197 if (env->cur_state->curframe) {
20198 /* exit from nested function */
20199 err = prepare_func_exit(env, &env->insn_idx);
20200 if (err)
20201 return err;
20202 *do_print_state = true;
20203 return 0;
20204 }
20205
20206 err = check_return_code(env, BPF_REG_0, "R0");
20207 if (err)
20208 return err;
20209 return PROCESS_BPF_EXIT;
20210 }
20211
indirect_jump_min_max_index(struct bpf_verifier_env * env,int regno,struct bpf_map * map,u32 * pmin_index,u32 * pmax_index)20212 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20213 int regno,
20214 struct bpf_map *map,
20215 u32 *pmin_index, u32 *pmax_index)
20216 {
20217 struct bpf_reg_state *reg = reg_state(env, regno);
20218 u64 min_index, max_index;
20219 const u32 size = 8;
20220
20221 if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
20222 (min_index > (u64) U32_MAX * size)) {
20223 verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
20224 regno, reg->umin_value, reg->off);
20225 return -ERANGE;
20226 }
20227 if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
20228 (max_index > (u64) U32_MAX * size)) {
20229 verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
20230 regno, reg->umax_value, reg->off);
20231 return -ERANGE;
20232 }
20233
20234 min_index /= size;
20235 max_index /= size;
20236
20237 if (max_index >= map->max_entries) {
20238 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20239 regno, min_index, max_index, map->max_entries);
20240 return -EINVAL;
20241 }
20242
20243 *pmin_index = min_index;
20244 *pmax_index = max_index;
20245 return 0;
20246 }
20247
20248 /* gotox *dst_reg */
check_indirect_jump(struct bpf_verifier_env * env,struct bpf_insn * insn)20249 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20250 {
20251 struct bpf_verifier_state *other_branch;
20252 struct bpf_reg_state *dst_reg;
20253 struct bpf_map *map;
20254 u32 min_index, max_index;
20255 int err = 0;
20256 int n;
20257 int i;
20258
20259 dst_reg = reg_state(env, insn->dst_reg);
20260 if (dst_reg->type != PTR_TO_INSN) {
20261 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20262 insn->dst_reg, reg_type_str(env, dst_reg->type));
20263 return -EINVAL;
20264 }
20265
20266 map = dst_reg->map_ptr;
20267 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20268 return -EFAULT;
20269
20270 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20271 "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20272 return -EFAULT;
20273
20274 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20275 if (err)
20276 return err;
20277
20278 /* Ensure that the buffer is large enough */
20279 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20280 env->gotox_tmp_buf = iarray_realloc(env->gotox_tmp_buf,
20281 max_index - min_index + 1);
20282 if (!env->gotox_tmp_buf)
20283 return -ENOMEM;
20284 }
20285
20286 n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20287 if (n < 0)
20288 return n;
20289 if (n == 0) {
20290 verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20291 insn->dst_reg, map->id);
20292 return -EINVAL;
20293 }
20294
20295 for (i = 0; i < n - 1; i++) {
20296 other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20297 env->insn_idx, env->cur_state->speculative);
20298 if (IS_ERR(other_branch))
20299 return PTR_ERR(other_branch);
20300 }
20301 env->insn_idx = env->gotox_tmp_buf->items[n-1];
20302 return 0;
20303 }
20304
do_check_insn(struct bpf_verifier_env * env,bool * do_print_state)20305 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20306 {
20307 int err;
20308 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20309 u8 class = BPF_CLASS(insn->code);
20310
20311 if (class == BPF_ALU || class == BPF_ALU64) {
20312 err = check_alu_op(env, insn);
20313 if (err)
20314 return err;
20315
20316 } else if (class == BPF_LDX) {
20317 bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
20318
20319 /* Check for reserved fields is already done in
20320 * resolve_pseudo_ldimm64().
20321 */
20322 err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
20323 if (err)
20324 return err;
20325 } else if (class == BPF_STX) {
20326 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
20327 err = check_atomic(env, insn);
20328 if (err)
20329 return err;
20330 env->insn_idx++;
20331 return 0;
20332 }
20333
20334 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
20335 verbose(env, "BPF_STX uses reserved fields\n");
20336 return -EINVAL;
20337 }
20338
20339 err = check_store_reg(env, insn, false);
20340 if (err)
20341 return err;
20342 } else if (class == BPF_ST) {
20343 enum bpf_reg_type dst_reg_type;
20344
20345 if (BPF_MODE(insn->code) != BPF_MEM ||
20346 insn->src_reg != BPF_REG_0) {
20347 verbose(env, "BPF_ST uses reserved fields\n");
20348 return -EINVAL;
20349 }
20350 /* check src operand */
20351 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
20352 if (err)
20353 return err;
20354
20355 dst_reg_type = cur_regs(env)[insn->dst_reg].type;
20356
20357 /* check that memory (dst_reg + off) is writeable */
20358 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
20359 insn->off, BPF_SIZE(insn->code),
20360 BPF_WRITE, -1, false, false);
20361 if (err)
20362 return err;
20363
20364 err = save_aux_ptr_type(env, dst_reg_type, false);
20365 if (err)
20366 return err;
20367 } else if (class == BPF_JMP || class == BPF_JMP32) {
20368 u8 opcode = BPF_OP(insn->code);
20369
20370 env->jmps_processed++;
20371 if (opcode == BPF_CALL) {
20372 if (BPF_SRC(insn->code) != BPF_K ||
20373 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
20374 insn->off != 0) ||
20375 (insn->src_reg != BPF_REG_0 &&
20376 insn->src_reg != BPF_PSEUDO_CALL &&
20377 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
20378 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
20379 verbose(env, "BPF_CALL uses reserved fields\n");
20380 return -EINVAL;
20381 }
20382
20383 if (env->cur_state->active_locks) {
20384 if ((insn->src_reg == BPF_REG_0 &&
20385 insn->imm != BPF_FUNC_spin_unlock) ||
20386 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
20387 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
20388 verbose(env,
20389 "function calls are not allowed while holding a lock\n");
20390 return -EINVAL;
20391 }
20392 }
20393 if (insn->src_reg == BPF_PSEUDO_CALL) {
20394 err = check_func_call(env, insn, &env->insn_idx);
20395 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20396 err = check_kfunc_call(env, insn, &env->insn_idx);
20397 if (!err && is_bpf_throw_kfunc(insn))
20398 return process_bpf_exit_full(env, do_print_state, true);
20399 } else {
20400 err = check_helper_call(env, insn, &env->insn_idx);
20401 }
20402 if (err)
20403 return err;
20404
20405 mark_reg_scratched(env, BPF_REG_0);
20406 } else if (opcode == BPF_JA) {
20407 if (BPF_SRC(insn->code) == BPF_X) {
20408 if (insn->src_reg != BPF_REG_0 ||
20409 insn->imm != 0 || insn->off != 0) {
20410 verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
20411 return -EINVAL;
20412 }
20413 return check_indirect_jump(env, insn);
20414 }
20415
20416 if (BPF_SRC(insn->code) != BPF_K ||
20417 insn->src_reg != BPF_REG_0 ||
20418 insn->dst_reg != BPF_REG_0 ||
20419 (class == BPF_JMP && insn->imm != 0) ||
20420 (class == BPF_JMP32 && insn->off != 0)) {
20421 verbose(env, "BPF_JA uses reserved fields\n");
20422 return -EINVAL;
20423 }
20424
20425 if (class == BPF_JMP)
20426 env->insn_idx += insn->off + 1;
20427 else
20428 env->insn_idx += insn->imm + 1;
20429 return 0;
20430 } else if (opcode == BPF_EXIT) {
20431 if (BPF_SRC(insn->code) != BPF_K ||
20432 insn->imm != 0 ||
20433 insn->src_reg != BPF_REG_0 ||
20434 insn->dst_reg != BPF_REG_0 ||
20435 class == BPF_JMP32) {
20436 verbose(env, "BPF_EXIT uses reserved fields\n");
20437 return -EINVAL;
20438 }
20439 return process_bpf_exit_full(env, do_print_state, false);
20440 } else {
20441 err = check_cond_jmp_op(env, insn, &env->insn_idx);
20442 if (err)
20443 return err;
20444 }
20445 } else if (class == BPF_LD) {
20446 u8 mode = BPF_MODE(insn->code);
20447
20448 if (mode == BPF_ABS || mode == BPF_IND) {
20449 err = check_ld_abs(env, insn);
20450 if (err)
20451 return err;
20452
20453 } else if (mode == BPF_IMM) {
20454 err = check_ld_imm(env, insn);
20455 if (err)
20456 return err;
20457
20458 env->insn_idx++;
20459 sanitize_mark_insn_seen(env);
20460 } else {
20461 verbose(env, "invalid BPF_LD mode\n");
20462 return -EINVAL;
20463 }
20464 } else {
20465 verbose(env, "unknown insn class %d\n", class);
20466 return -EINVAL;
20467 }
20468
20469 env->insn_idx++;
20470 return 0;
20471 }
20472
do_check(struct bpf_verifier_env * env)20473 static int do_check(struct bpf_verifier_env *env)
20474 {
20475 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20476 struct bpf_verifier_state *state = env->cur_state;
20477 struct bpf_insn *insns = env->prog->insnsi;
20478 int insn_cnt = env->prog->len;
20479 bool do_print_state = false;
20480 int prev_insn_idx = -1;
20481
20482 for (;;) {
20483 struct bpf_insn *insn;
20484 struct bpf_insn_aux_data *insn_aux;
20485 int err, marks_err;
20486
20487 /* reset current history entry on each new instruction */
20488 env->cur_hist_ent = NULL;
20489
20490 env->prev_insn_idx = prev_insn_idx;
20491 if (env->insn_idx >= insn_cnt) {
20492 verbose(env, "invalid insn idx %d insn_cnt %d\n",
20493 env->insn_idx, insn_cnt);
20494 return -EFAULT;
20495 }
20496
20497 insn = &insns[env->insn_idx];
20498 insn_aux = &env->insn_aux_data[env->insn_idx];
20499
20500 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20501 verbose(env,
20502 "BPF program is too large. Processed %d insn\n",
20503 env->insn_processed);
20504 return -E2BIG;
20505 }
20506
20507 state->last_insn_idx = env->prev_insn_idx;
20508 state->insn_idx = env->insn_idx;
20509
20510 if (is_prune_point(env, env->insn_idx)) {
20511 err = is_state_visited(env, env->insn_idx);
20512 if (err < 0)
20513 return err;
20514 if (err == 1) {
20515 /* found equivalent state, can prune the search */
20516 if (env->log.level & BPF_LOG_LEVEL) {
20517 if (do_print_state)
20518 verbose(env, "\nfrom %d to %d%s: safe\n",
20519 env->prev_insn_idx, env->insn_idx,
20520 env->cur_state->speculative ?
20521 " (speculative execution)" : "");
20522 else
20523 verbose(env, "%d: safe\n", env->insn_idx);
20524 }
20525 goto process_bpf_exit;
20526 }
20527 }
20528
20529 if (is_jmp_point(env, env->insn_idx)) {
20530 err = push_jmp_history(env, state, 0, 0);
20531 if (err)
20532 return err;
20533 }
20534
20535 if (signal_pending(current))
20536 return -EAGAIN;
20537
20538 if (need_resched())
20539 cond_resched();
20540
20541 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20542 verbose(env, "\nfrom %d to %d%s:",
20543 env->prev_insn_idx, env->insn_idx,
20544 env->cur_state->speculative ?
20545 " (speculative execution)" : "");
20546 print_verifier_state(env, state, state->curframe, true);
20547 do_print_state = false;
20548 }
20549
20550 if (env->log.level & BPF_LOG_LEVEL) {
20551 if (verifier_state_scratched(env))
20552 print_insn_state(env, state, state->curframe);
20553
20554 verbose_linfo(env, env->insn_idx, "; ");
20555 env->prev_log_pos = env->log.end_pos;
20556 verbose(env, "%d: ", env->insn_idx);
20557 verbose_insn(env, insn);
20558 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20559 env->prev_log_pos = env->log.end_pos;
20560 }
20561
20562 if (bpf_prog_is_offloaded(env->prog->aux)) {
20563 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20564 env->prev_insn_idx);
20565 if (err)
20566 return err;
20567 }
20568
20569 sanitize_mark_insn_seen(env);
20570 prev_insn_idx = env->insn_idx;
20571
20572 /* Reduce verification complexity by stopping speculative path
20573 * verification when a nospec is encountered.
20574 */
20575 if (state->speculative && insn_aux->nospec)
20576 goto process_bpf_exit;
20577
20578 err = bpf_reset_stack_write_marks(env, env->insn_idx);
20579 if (err)
20580 return err;
20581 err = do_check_insn(env, &do_print_state);
20582 if (err >= 0 || error_recoverable_with_nospec(err)) {
20583 marks_err = bpf_commit_stack_write_marks(env);
20584 if (marks_err)
20585 return marks_err;
20586 }
20587 if (error_recoverable_with_nospec(err) && state->speculative) {
20588 /* Prevent this speculative path from ever reaching the
20589 * insn that would have been unsafe to execute.
20590 */
20591 insn_aux->nospec = true;
20592 /* If it was an ADD/SUB insn, potentially remove any
20593 * markings for alu sanitization.
20594 */
20595 insn_aux->alu_state = 0;
20596 goto process_bpf_exit;
20597 } else if (err < 0) {
20598 return err;
20599 } else if (err == PROCESS_BPF_EXIT) {
20600 goto process_bpf_exit;
20601 }
20602 WARN_ON_ONCE(err);
20603
20604 if (state->speculative && insn_aux->nospec_result) {
20605 /* If we are on a path that performed a jump-op, this
20606 * may skip a nospec patched-in after the jump. This can
20607 * currently never happen because nospec_result is only
20608 * used for the write-ops
20609 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20610 * never skip the following insn. Still, add a warning
20611 * to document this in case nospec_result is used
20612 * elsewhere in the future.
20613 *
20614 * All non-branch instructions have a single
20615 * fall-through edge. For these, nospec_result should
20616 * already work.
20617 */
20618 if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20619 BPF_CLASS(insn->code) == BPF_JMP32, env,
20620 "speculation barrier after jump instruction may not have the desired effect"))
20621 return -EFAULT;
20622 process_bpf_exit:
20623 mark_verifier_state_scratched(env);
20624 err = update_branch_counts(env, env->cur_state);
20625 if (err)
20626 return err;
20627 err = bpf_update_live_stack(env);
20628 if (err)
20629 return err;
20630 err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20631 pop_log);
20632 if (err < 0) {
20633 if (err != -ENOENT)
20634 return err;
20635 break;
20636 } else {
20637 do_print_state = true;
20638 continue;
20639 }
20640 }
20641 }
20642
20643 return 0;
20644 }
20645
find_btf_percpu_datasec(struct btf * btf)20646 static int find_btf_percpu_datasec(struct btf *btf)
20647 {
20648 const struct btf_type *t;
20649 const char *tname;
20650 int i, n;
20651
20652 /*
20653 * Both vmlinux and module each have their own ".data..percpu"
20654 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20655 * types to look at only module's own BTF types.
20656 */
20657 n = btf_nr_types(btf);
20658 if (btf_is_module(btf))
20659 i = btf_nr_types(btf_vmlinux);
20660 else
20661 i = 1;
20662
20663 for(; i < n; i++) {
20664 t = btf_type_by_id(btf, i);
20665 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20666 continue;
20667
20668 tname = btf_name_by_offset(btf, t->name_off);
20669 if (!strcmp(tname, ".data..percpu"))
20670 return i;
20671 }
20672
20673 return -ENOENT;
20674 }
20675
20676 /*
20677 * Add btf to the used_btfs array and return the index. (If the btf was
20678 * already added, then just return the index.) Upon successful insertion
20679 * increase btf refcnt, and, if present, also refcount the corresponding
20680 * kernel module.
20681 */
__add_used_btf(struct bpf_verifier_env * env,struct btf * btf)20682 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20683 {
20684 struct btf_mod_pair *btf_mod;
20685 int i;
20686
20687 /* check whether we recorded this BTF (and maybe module) already */
20688 for (i = 0; i < env->used_btf_cnt; i++)
20689 if (env->used_btfs[i].btf == btf)
20690 return i;
20691
20692 if (env->used_btf_cnt >= MAX_USED_BTFS) {
20693 verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20694 MAX_USED_BTFS);
20695 return -E2BIG;
20696 }
20697
20698 btf_get(btf);
20699
20700 btf_mod = &env->used_btfs[env->used_btf_cnt];
20701 btf_mod->btf = btf;
20702 btf_mod->module = NULL;
20703
20704 /* if we reference variables from kernel module, bump its refcount */
20705 if (btf_is_module(btf)) {
20706 btf_mod->module = btf_try_get_module(btf);
20707 if (!btf_mod->module) {
20708 btf_put(btf);
20709 return -ENXIO;
20710 }
20711 }
20712
20713 return env->used_btf_cnt++;
20714 }
20715
20716 /* replace pseudo btf_id with kernel symbol address */
__check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux,struct btf * btf)20717 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20718 struct bpf_insn *insn,
20719 struct bpf_insn_aux_data *aux,
20720 struct btf *btf)
20721 {
20722 const struct btf_var_secinfo *vsi;
20723 const struct btf_type *datasec;
20724 const struct btf_type *t;
20725 const char *sym_name;
20726 bool percpu = false;
20727 u32 type, id = insn->imm;
20728 s32 datasec_id;
20729 u64 addr;
20730 int i;
20731
20732 t = btf_type_by_id(btf, id);
20733 if (!t) {
20734 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20735 return -ENOENT;
20736 }
20737
20738 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20739 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20740 return -EINVAL;
20741 }
20742
20743 sym_name = btf_name_by_offset(btf, t->name_off);
20744 addr = kallsyms_lookup_name(sym_name);
20745 if (!addr) {
20746 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20747 sym_name);
20748 return -ENOENT;
20749 }
20750 insn[0].imm = (u32)addr;
20751 insn[1].imm = addr >> 32;
20752
20753 if (btf_type_is_func(t)) {
20754 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20755 aux->btf_var.mem_size = 0;
20756 return 0;
20757 }
20758
20759 datasec_id = find_btf_percpu_datasec(btf);
20760 if (datasec_id > 0) {
20761 datasec = btf_type_by_id(btf, datasec_id);
20762 for_each_vsi(i, datasec, vsi) {
20763 if (vsi->type == id) {
20764 percpu = true;
20765 break;
20766 }
20767 }
20768 }
20769
20770 type = t->type;
20771 t = btf_type_skip_modifiers(btf, type, NULL);
20772 if (percpu) {
20773 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20774 aux->btf_var.btf = btf;
20775 aux->btf_var.btf_id = type;
20776 } else if (!btf_type_is_struct(t)) {
20777 const struct btf_type *ret;
20778 const char *tname;
20779 u32 tsize;
20780
20781 /* resolve the type size of ksym. */
20782 ret = btf_resolve_size(btf, t, &tsize);
20783 if (IS_ERR(ret)) {
20784 tname = btf_name_by_offset(btf, t->name_off);
20785 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20786 tname, PTR_ERR(ret));
20787 return -EINVAL;
20788 }
20789 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20790 aux->btf_var.mem_size = tsize;
20791 } else {
20792 aux->btf_var.reg_type = PTR_TO_BTF_ID;
20793 aux->btf_var.btf = btf;
20794 aux->btf_var.btf_id = type;
20795 }
20796
20797 return 0;
20798 }
20799
check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux)20800 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20801 struct bpf_insn *insn,
20802 struct bpf_insn_aux_data *aux)
20803 {
20804 struct btf *btf;
20805 int btf_fd;
20806 int err;
20807
20808 btf_fd = insn[1].imm;
20809 if (btf_fd) {
20810 CLASS(fd, f)(btf_fd);
20811
20812 btf = __btf_get_by_fd(f);
20813 if (IS_ERR(btf)) {
20814 verbose(env, "invalid module BTF object FD specified.\n");
20815 return -EINVAL;
20816 }
20817 } else {
20818 if (!btf_vmlinux) {
20819 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20820 return -EINVAL;
20821 }
20822 btf = btf_vmlinux;
20823 }
20824
20825 err = __check_pseudo_btf_id(env, insn, aux, btf);
20826 if (err)
20827 return err;
20828
20829 err = __add_used_btf(env, btf);
20830 if (err < 0)
20831 return err;
20832 return 0;
20833 }
20834
is_tracing_prog_type(enum bpf_prog_type type)20835 static bool is_tracing_prog_type(enum bpf_prog_type type)
20836 {
20837 switch (type) {
20838 case BPF_PROG_TYPE_KPROBE:
20839 case BPF_PROG_TYPE_TRACEPOINT:
20840 case BPF_PROG_TYPE_PERF_EVENT:
20841 case BPF_PROG_TYPE_RAW_TRACEPOINT:
20842 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20843 return true;
20844 default:
20845 return false;
20846 }
20847 }
20848
bpf_map_is_cgroup_storage(struct bpf_map * map)20849 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20850 {
20851 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20852 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20853 }
20854
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)20855 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20856 struct bpf_map *map,
20857 struct bpf_prog *prog)
20858
20859 {
20860 enum bpf_prog_type prog_type = resolve_prog_type(prog);
20861
20862 if (map->excl_prog_sha &&
20863 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20864 verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20865 return -EACCES;
20866 }
20867
20868 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20869 btf_record_has_field(map->record, BPF_RB_ROOT)) {
20870 if (is_tracing_prog_type(prog_type)) {
20871 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20872 return -EINVAL;
20873 }
20874 }
20875
20876 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20877 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20878 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20879 return -EINVAL;
20880 }
20881
20882 if (is_tracing_prog_type(prog_type)) {
20883 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20884 return -EINVAL;
20885 }
20886 }
20887
20888 if (btf_record_has_field(map->record, BPF_TIMER)) {
20889 if (is_tracing_prog_type(prog_type)) {
20890 verbose(env, "tracing progs cannot use bpf_timer yet\n");
20891 return -EINVAL;
20892 }
20893 }
20894
20895 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20896 if (is_tracing_prog_type(prog_type)) {
20897 verbose(env, "tracing progs cannot use bpf_wq yet\n");
20898 return -EINVAL;
20899 }
20900 }
20901
20902 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20903 !bpf_offload_prog_map_match(prog, map)) {
20904 verbose(env, "offload device mismatch between prog and map\n");
20905 return -EINVAL;
20906 }
20907
20908 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20909 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20910 return -EINVAL;
20911 }
20912
20913 if (prog->sleepable)
20914 switch (map->map_type) {
20915 case BPF_MAP_TYPE_HASH:
20916 case BPF_MAP_TYPE_LRU_HASH:
20917 case BPF_MAP_TYPE_ARRAY:
20918 case BPF_MAP_TYPE_PERCPU_HASH:
20919 case BPF_MAP_TYPE_PERCPU_ARRAY:
20920 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20921 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20922 case BPF_MAP_TYPE_HASH_OF_MAPS:
20923 case BPF_MAP_TYPE_RINGBUF:
20924 case BPF_MAP_TYPE_USER_RINGBUF:
20925 case BPF_MAP_TYPE_INODE_STORAGE:
20926 case BPF_MAP_TYPE_SK_STORAGE:
20927 case BPF_MAP_TYPE_TASK_STORAGE:
20928 case BPF_MAP_TYPE_CGRP_STORAGE:
20929 case BPF_MAP_TYPE_QUEUE:
20930 case BPF_MAP_TYPE_STACK:
20931 case BPF_MAP_TYPE_ARENA:
20932 case BPF_MAP_TYPE_INSN_ARRAY:
20933 break;
20934 default:
20935 verbose(env,
20936 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20937 return -EINVAL;
20938 }
20939
20940 if (bpf_map_is_cgroup_storage(map) &&
20941 bpf_cgroup_storage_assign(env->prog->aux, map)) {
20942 verbose(env, "only one cgroup storage of each type is allowed\n");
20943 return -EBUSY;
20944 }
20945
20946 if (map->map_type == BPF_MAP_TYPE_ARENA) {
20947 if (env->prog->aux->arena) {
20948 verbose(env, "Only one arena per program\n");
20949 return -EBUSY;
20950 }
20951 if (!env->allow_ptr_leaks || !env->bpf_capable) {
20952 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20953 return -EPERM;
20954 }
20955 if (!env->prog->jit_requested) {
20956 verbose(env, "JIT is required to use arena\n");
20957 return -EOPNOTSUPP;
20958 }
20959 if (!bpf_jit_supports_arena()) {
20960 verbose(env, "JIT doesn't support arena\n");
20961 return -EOPNOTSUPP;
20962 }
20963 env->prog->aux->arena = (void *)map;
20964 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20965 verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20966 return -EINVAL;
20967 }
20968 }
20969
20970 return 0;
20971 }
20972
__add_used_map(struct bpf_verifier_env * env,struct bpf_map * map)20973 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20974 {
20975 int i, err;
20976
20977 /* check whether we recorded this map already */
20978 for (i = 0; i < env->used_map_cnt; i++)
20979 if (env->used_maps[i] == map)
20980 return i;
20981
20982 if (env->used_map_cnt >= MAX_USED_MAPS) {
20983 verbose(env, "The total number of maps per program has reached the limit of %u\n",
20984 MAX_USED_MAPS);
20985 return -E2BIG;
20986 }
20987
20988 err = check_map_prog_compatibility(env, map, env->prog);
20989 if (err)
20990 return err;
20991
20992 if (env->prog->sleepable)
20993 atomic64_inc(&map->sleepable_refcnt);
20994
20995 /* hold the map. If the program is rejected by verifier,
20996 * the map will be released by release_maps() or it
20997 * will be used by the valid program until it's unloaded
20998 * and all maps are released in bpf_free_used_maps()
20999 */
21000 bpf_map_inc(map);
21001
21002 env->used_maps[env->used_map_cnt++] = map;
21003
21004 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
21005 err = bpf_insn_array_init(map, env->prog);
21006 if (err) {
21007 verbose(env, "Failed to properly initialize insn array\n");
21008 return err;
21009 }
21010 env->insn_array_maps[env->insn_array_map_cnt++] = map;
21011 }
21012
21013 return env->used_map_cnt - 1;
21014 }
21015
21016 /* Add map behind fd to used maps list, if it's not already there, and return
21017 * its index.
21018 * Returns <0 on error, or >= 0 index, on success.
21019 */
add_used_map(struct bpf_verifier_env * env,int fd)21020 static int add_used_map(struct bpf_verifier_env *env, int fd)
21021 {
21022 struct bpf_map *map;
21023 CLASS(fd, f)(fd);
21024
21025 map = __bpf_map_get(f);
21026 if (IS_ERR(map)) {
21027 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21028 return PTR_ERR(map);
21029 }
21030
21031 return __add_used_map(env, map);
21032 }
21033
21034 /* find and rewrite pseudo imm in ld_imm64 instructions:
21035 *
21036 * 1. if it accesses map FD, replace it with actual map pointer.
21037 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21038 *
21039 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21040 */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)21041 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
21042 {
21043 struct bpf_insn *insn = env->prog->insnsi;
21044 int insn_cnt = env->prog->len;
21045 int i, err;
21046
21047 err = bpf_prog_calc_tag(env->prog);
21048 if (err)
21049 return err;
21050
21051 for (i = 0; i < insn_cnt; i++, insn++) {
21052 if (BPF_CLASS(insn->code) == BPF_LDX &&
21053 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21054 insn->imm != 0)) {
21055 verbose(env, "BPF_LDX uses reserved fields\n");
21056 return -EINVAL;
21057 }
21058
21059 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21060 struct bpf_insn_aux_data *aux;
21061 struct bpf_map *map;
21062 int map_idx;
21063 u64 addr;
21064 u32 fd;
21065
21066 if (i == insn_cnt - 1 || insn[1].code != 0 ||
21067 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21068 insn[1].off != 0) {
21069 verbose(env, "invalid bpf_ld_imm64 insn\n");
21070 return -EINVAL;
21071 }
21072
21073 if (insn[0].src_reg == 0)
21074 /* valid generic load 64-bit imm */
21075 goto next_insn;
21076
21077 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21078 aux = &env->insn_aux_data[i];
21079 err = check_pseudo_btf_id(env, insn, aux);
21080 if (err)
21081 return err;
21082 goto next_insn;
21083 }
21084
21085 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21086 aux = &env->insn_aux_data[i];
21087 aux->ptr_type = PTR_TO_FUNC;
21088 goto next_insn;
21089 }
21090
21091 /* In final convert_pseudo_ld_imm64() step, this is
21092 * converted into regular 64-bit imm load insn.
21093 */
21094 switch (insn[0].src_reg) {
21095 case BPF_PSEUDO_MAP_VALUE:
21096 case BPF_PSEUDO_MAP_IDX_VALUE:
21097 break;
21098 case BPF_PSEUDO_MAP_FD:
21099 case BPF_PSEUDO_MAP_IDX:
21100 if (insn[1].imm == 0)
21101 break;
21102 fallthrough;
21103 default:
21104 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21105 return -EINVAL;
21106 }
21107
21108 switch (insn[0].src_reg) {
21109 case BPF_PSEUDO_MAP_IDX_VALUE:
21110 case BPF_PSEUDO_MAP_IDX:
21111 if (bpfptr_is_null(env->fd_array)) {
21112 verbose(env, "fd_idx without fd_array is invalid\n");
21113 return -EPROTO;
21114 }
21115 if (copy_from_bpfptr_offset(&fd, env->fd_array,
21116 insn[0].imm * sizeof(fd),
21117 sizeof(fd)))
21118 return -EFAULT;
21119 break;
21120 default:
21121 fd = insn[0].imm;
21122 break;
21123 }
21124
21125 map_idx = add_used_map(env, fd);
21126 if (map_idx < 0)
21127 return map_idx;
21128 map = env->used_maps[map_idx];
21129
21130 aux = &env->insn_aux_data[i];
21131 aux->map_index = map_idx;
21132
21133 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21134 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21135 addr = (unsigned long)map;
21136 } else {
21137 u32 off = insn[1].imm;
21138
21139 if (off >= BPF_MAX_VAR_OFF) {
21140 verbose(env, "direct value offset of %u is not allowed\n", off);
21141 return -EINVAL;
21142 }
21143
21144 if (!map->ops->map_direct_value_addr) {
21145 verbose(env, "no direct value access support for this map type\n");
21146 return -EINVAL;
21147 }
21148
21149 err = map->ops->map_direct_value_addr(map, &addr, off);
21150 if (err) {
21151 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21152 map->value_size, off);
21153 return err;
21154 }
21155
21156 aux->map_off = off;
21157 addr += off;
21158 }
21159
21160 insn[0].imm = (u32)addr;
21161 insn[1].imm = addr >> 32;
21162
21163 next_insn:
21164 insn++;
21165 i++;
21166 continue;
21167 }
21168
21169 /* Basic sanity check before we invest more work here. */
21170 if (!bpf_opcode_in_insntable(insn->code)) {
21171 verbose(env, "unknown opcode %02x\n", insn->code);
21172 return -EINVAL;
21173 }
21174 }
21175
21176 /* now all pseudo BPF_LD_IMM64 instructions load valid
21177 * 'struct bpf_map *' into a register instead of user map_fd.
21178 * These pointers will be used later by verifier to validate map access.
21179 */
21180 return 0;
21181 }
21182
21183 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)21184 static void release_maps(struct bpf_verifier_env *env)
21185 {
21186 __bpf_free_used_maps(env->prog->aux, env->used_maps,
21187 env->used_map_cnt);
21188 }
21189
21190 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)21191 static void release_btfs(struct bpf_verifier_env *env)
21192 {
21193 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21194 }
21195
21196 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)21197 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21198 {
21199 struct bpf_insn *insn = env->prog->insnsi;
21200 int insn_cnt = env->prog->len;
21201 int i;
21202
21203 for (i = 0; i < insn_cnt; i++, insn++) {
21204 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21205 continue;
21206 if (insn->src_reg == BPF_PSEUDO_FUNC)
21207 continue;
21208 insn->src_reg = 0;
21209 }
21210 }
21211
21212 /* single env->prog->insni[off] instruction was replaced with the range
21213 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
21214 * [0, off) and [off, end) to new locations, so the patched range stays zero
21215 */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_prog * new_prog,u32 off,u32 cnt)21216 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
21217 struct bpf_prog *new_prog, u32 off, u32 cnt)
21218 {
21219 struct bpf_insn_aux_data *data = env->insn_aux_data;
21220 struct bpf_insn *insn = new_prog->insnsi;
21221 u32 old_seen = data[off].seen;
21222 u32 prog_len;
21223 int i;
21224
21225 /* aux info at OFF always needs adjustment, no matter fast path
21226 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
21227 * original insn at old prog.
21228 */
21229 data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
21230
21231 if (cnt == 1)
21232 return;
21233 prog_len = new_prog->len;
21234
21235 memmove(data + off + cnt - 1, data + off,
21236 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
21237 memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
21238 for (i = off; i < off + cnt - 1; i++) {
21239 /* Expand insni[off]'s seen count to the patched range. */
21240 data[i].seen = old_seen;
21241 data[i].zext_dst = insn_has_def32(insn + i);
21242 }
21243 }
21244
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)21245 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
21246 {
21247 int i;
21248
21249 if (len == 1)
21250 return;
21251 /* NOTE: fake 'exit' subprog should be updated as well. */
21252 for (i = 0; i <= env->subprog_cnt; i++) {
21253 if (env->subprog_info[i].start <= off)
21254 continue;
21255 env->subprog_info[i].start += len - 1;
21256 }
21257 }
21258
release_insn_arrays(struct bpf_verifier_env * env)21259 static void release_insn_arrays(struct bpf_verifier_env *env)
21260 {
21261 int i;
21262
21263 for (i = 0; i < env->insn_array_map_cnt; i++)
21264 bpf_insn_array_release(env->insn_array_maps[i]);
21265 }
21266
adjust_insn_arrays(struct bpf_verifier_env * env,u32 off,u32 len)21267 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 off, u32 len)
21268 {
21269 int i;
21270
21271 if (len == 1)
21272 return;
21273
21274 for (i = 0; i < env->insn_array_map_cnt; i++)
21275 bpf_insn_array_adjust(env->insn_array_maps[i], off, len);
21276 }
21277
adjust_insn_arrays_after_remove(struct bpf_verifier_env * env,u32 off,u32 len)21278 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
21279 {
21280 int i;
21281
21282 for (i = 0; i < env->insn_array_map_cnt; i++)
21283 bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
21284 }
21285
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)21286 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
21287 {
21288 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
21289 int i, sz = prog->aux->size_poke_tab;
21290 struct bpf_jit_poke_descriptor *desc;
21291
21292 for (i = 0; i < sz; i++) {
21293 desc = &tab[i];
21294 if (desc->insn_idx <= off)
21295 continue;
21296 desc->insn_idx += len - 1;
21297 }
21298 }
21299
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)21300 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
21301 const struct bpf_insn *patch, u32 len)
21302 {
21303 struct bpf_prog *new_prog;
21304 struct bpf_insn_aux_data *new_data = NULL;
21305
21306 if (len > 1) {
21307 new_data = vrealloc(env->insn_aux_data,
21308 array_size(env->prog->len + len - 1,
21309 sizeof(struct bpf_insn_aux_data)),
21310 GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21311 if (!new_data)
21312 return NULL;
21313
21314 env->insn_aux_data = new_data;
21315 }
21316
21317 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
21318 if (IS_ERR(new_prog)) {
21319 if (PTR_ERR(new_prog) == -ERANGE)
21320 verbose(env,
21321 "insn %d cannot be patched due to 16-bit range\n",
21322 env->insn_aux_data[off].orig_idx);
21323 return NULL;
21324 }
21325 adjust_insn_aux_data(env, new_prog, off, len);
21326 adjust_subprog_starts(env, off, len);
21327 adjust_insn_arrays(env, off, len);
21328 adjust_poke_descs(new_prog, off, len);
21329 return new_prog;
21330 }
21331
21332 /*
21333 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
21334 * jump offset by 'delta'.
21335 */
adjust_jmp_off(struct bpf_prog * prog,u32 tgt_idx,u32 delta)21336 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
21337 {
21338 struct bpf_insn *insn = prog->insnsi;
21339 u32 insn_cnt = prog->len, i;
21340 s32 imm;
21341 s16 off;
21342
21343 for (i = 0; i < insn_cnt; i++, insn++) {
21344 u8 code = insn->code;
21345
21346 if (tgt_idx <= i && i < tgt_idx + delta)
21347 continue;
21348
21349 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
21350 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
21351 continue;
21352
21353 if (insn->code == (BPF_JMP32 | BPF_JA)) {
21354 if (i + 1 + insn->imm != tgt_idx)
21355 continue;
21356 if (check_add_overflow(insn->imm, delta, &imm))
21357 return -ERANGE;
21358 insn->imm = imm;
21359 } else {
21360 if (i + 1 + insn->off != tgt_idx)
21361 continue;
21362 if (check_add_overflow(insn->off, delta, &off))
21363 return -ERANGE;
21364 insn->off = off;
21365 }
21366 }
21367 return 0;
21368 }
21369
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)21370 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
21371 u32 off, u32 cnt)
21372 {
21373 int i, j;
21374
21375 /* find first prog starting at or after off (first to remove) */
21376 for (i = 0; i < env->subprog_cnt; i++)
21377 if (env->subprog_info[i].start >= off)
21378 break;
21379 /* find first prog starting at or after off + cnt (first to stay) */
21380 for (j = i; j < env->subprog_cnt; j++)
21381 if (env->subprog_info[j].start >= off + cnt)
21382 break;
21383 /* if j doesn't start exactly at off + cnt, we are just removing
21384 * the front of previous prog
21385 */
21386 if (env->subprog_info[j].start != off + cnt)
21387 j--;
21388
21389 if (j > i) {
21390 struct bpf_prog_aux *aux = env->prog->aux;
21391 int move;
21392
21393 /* move fake 'exit' subprog as well */
21394 move = env->subprog_cnt + 1 - j;
21395
21396 memmove(env->subprog_info + i,
21397 env->subprog_info + j,
21398 sizeof(*env->subprog_info) * move);
21399 env->subprog_cnt -= j - i;
21400
21401 /* remove func_info */
21402 if (aux->func_info) {
21403 move = aux->func_info_cnt - j;
21404
21405 memmove(aux->func_info + i,
21406 aux->func_info + j,
21407 sizeof(*aux->func_info) * move);
21408 aux->func_info_cnt -= j - i;
21409 /* func_info->insn_off is set after all code rewrites,
21410 * in adjust_btf_func() - no need to adjust
21411 */
21412 }
21413 } else {
21414 /* convert i from "first prog to remove" to "first to adjust" */
21415 if (env->subprog_info[i].start == off)
21416 i++;
21417 }
21418
21419 /* update fake 'exit' subprog as well */
21420 for (; i <= env->subprog_cnt; i++)
21421 env->subprog_info[i].start -= cnt;
21422
21423 return 0;
21424 }
21425
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)21426 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
21427 u32 cnt)
21428 {
21429 struct bpf_prog *prog = env->prog;
21430 u32 i, l_off, l_cnt, nr_linfo;
21431 struct bpf_line_info *linfo;
21432
21433 nr_linfo = prog->aux->nr_linfo;
21434 if (!nr_linfo)
21435 return 0;
21436
21437 linfo = prog->aux->linfo;
21438
21439 /* find first line info to remove, count lines to be removed */
21440 for (i = 0; i < nr_linfo; i++)
21441 if (linfo[i].insn_off >= off)
21442 break;
21443
21444 l_off = i;
21445 l_cnt = 0;
21446 for (; i < nr_linfo; i++)
21447 if (linfo[i].insn_off < off + cnt)
21448 l_cnt++;
21449 else
21450 break;
21451
21452 /* First live insn doesn't match first live linfo, it needs to "inherit"
21453 * last removed linfo. prog is already modified, so prog->len == off
21454 * means no live instructions after (tail of the program was removed).
21455 */
21456 if (prog->len != off && l_cnt &&
21457 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
21458 l_cnt--;
21459 linfo[--i].insn_off = off + cnt;
21460 }
21461
21462 /* remove the line info which refer to the removed instructions */
21463 if (l_cnt) {
21464 memmove(linfo + l_off, linfo + i,
21465 sizeof(*linfo) * (nr_linfo - i));
21466
21467 prog->aux->nr_linfo -= l_cnt;
21468 nr_linfo = prog->aux->nr_linfo;
21469 }
21470
21471 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
21472 for (i = l_off; i < nr_linfo; i++)
21473 linfo[i].insn_off -= cnt;
21474
21475 /* fix up all subprogs (incl. 'exit') which start >= off */
21476 for (i = 0; i <= env->subprog_cnt; i++)
21477 if (env->subprog_info[i].linfo_idx > l_off) {
21478 /* program may have started in the removed region but
21479 * may not be fully removed
21480 */
21481 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
21482 env->subprog_info[i].linfo_idx -= l_cnt;
21483 else
21484 env->subprog_info[i].linfo_idx = l_off;
21485 }
21486
21487 return 0;
21488 }
21489
21490 /*
21491 * Clean up dynamically allocated fields of aux data for instructions [start, ...]
21492 */
clear_insn_aux_data(struct bpf_verifier_env * env,int start,int len)21493 static void clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
21494 {
21495 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21496 struct bpf_insn *insns = env->prog->insnsi;
21497 int end = start + len;
21498 int i;
21499
21500 for (i = start; i < end; i++) {
21501 if (aux_data[i].jt) {
21502 kvfree(aux_data[i].jt);
21503 aux_data[i].jt = NULL;
21504 }
21505
21506 if (bpf_is_ldimm64(&insns[i]))
21507 i++;
21508 }
21509 }
21510
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)21511 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
21512 {
21513 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21514 unsigned int orig_prog_len = env->prog->len;
21515 int err;
21516
21517 if (bpf_prog_is_offloaded(env->prog->aux))
21518 bpf_prog_offload_remove_insns(env, off, cnt);
21519
21520 /* Should be called before bpf_remove_insns, as it uses prog->insnsi */
21521 clear_insn_aux_data(env, off, cnt);
21522
21523 err = bpf_remove_insns(env->prog, off, cnt);
21524 if (err)
21525 return err;
21526
21527 err = adjust_subprog_starts_after_remove(env, off, cnt);
21528 if (err)
21529 return err;
21530
21531 err = bpf_adj_linfo_after_remove(env, off, cnt);
21532 if (err)
21533 return err;
21534
21535 adjust_insn_arrays_after_remove(env, off, cnt);
21536
21537 memmove(aux_data + off, aux_data + off + cnt,
21538 sizeof(*aux_data) * (orig_prog_len - off - cnt));
21539
21540 return 0;
21541 }
21542
21543 /* The verifier does more data flow analysis than llvm and will not
21544 * explore branches that are dead at run time. Malicious programs can
21545 * have dead code too. Therefore replace all dead at-run-time code
21546 * with 'ja -1'.
21547 *
21548 * Just nops are not optimal, e.g. if they would sit at the end of the
21549 * program and through another bug we would manage to jump there, then
21550 * we'd execute beyond program memory otherwise. Returning exception
21551 * code also wouldn't work since we can have subprogs where the dead
21552 * code could be located.
21553 */
sanitize_dead_code(struct bpf_verifier_env * env)21554 static void sanitize_dead_code(struct bpf_verifier_env *env)
21555 {
21556 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21557 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21558 struct bpf_insn *insn = env->prog->insnsi;
21559 const int insn_cnt = env->prog->len;
21560 int i;
21561
21562 for (i = 0; i < insn_cnt; i++) {
21563 if (aux_data[i].seen)
21564 continue;
21565 memcpy(insn + i, &trap, sizeof(trap));
21566 aux_data[i].zext_dst = false;
21567 }
21568 }
21569
insn_is_cond_jump(u8 code)21570 static bool insn_is_cond_jump(u8 code)
21571 {
21572 u8 op;
21573
21574 op = BPF_OP(code);
21575 if (BPF_CLASS(code) == BPF_JMP32)
21576 return op != BPF_JA;
21577
21578 if (BPF_CLASS(code) != BPF_JMP)
21579 return false;
21580
21581 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21582 }
21583
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)21584 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21585 {
21586 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21587 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21588 struct bpf_insn *insn = env->prog->insnsi;
21589 const int insn_cnt = env->prog->len;
21590 int i;
21591
21592 for (i = 0; i < insn_cnt; i++, insn++) {
21593 if (!insn_is_cond_jump(insn->code))
21594 continue;
21595
21596 if (!aux_data[i + 1].seen)
21597 ja.off = insn->off;
21598 else if (!aux_data[i + 1 + insn->off].seen)
21599 ja.off = 0;
21600 else
21601 continue;
21602
21603 if (bpf_prog_is_offloaded(env->prog->aux))
21604 bpf_prog_offload_replace_insn(env, i, &ja);
21605
21606 memcpy(insn, &ja, sizeof(ja));
21607 }
21608 }
21609
opt_remove_dead_code(struct bpf_verifier_env * env)21610 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21611 {
21612 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21613 int insn_cnt = env->prog->len;
21614 int i, err;
21615
21616 for (i = 0; i < insn_cnt; i++) {
21617 int j;
21618
21619 j = 0;
21620 while (i + j < insn_cnt && !aux_data[i + j].seen)
21621 j++;
21622 if (!j)
21623 continue;
21624
21625 err = verifier_remove_insns(env, i, j);
21626 if (err)
21627 return err;
21628 insn_cnt = env->prog->len;
21629 }
21630
21631 return 0;
21632 }
21633
21634 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21635 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21636
opt_remove_nops(struct bpf_verifier_env * env)21637 static int opt_remove_nops(struct bpf_verifier_env *env)
21638 {
21639 struct bpf_insn *insn = env->prog->insnsi;
21640 int insn_cnt = env->prog->len;
21641 bool is_may_goto_0, is_ja;
21642 int i, err;
21643
21644 for (i = 0; i < insn_cnt; i++) {
21645 is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21646 is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21647
21648 if (!is_may_goto_0 && !is_ja)
21649 continue;
21650
21651 err = verifier_remove_insns(env, i, 1);
21652 if (err)
21653 return err;
21654 insn_cnt--;
21655 /* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21656 i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21657 }
21658
21659 return 0;
21660 }
21661
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)21662 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21663 const union bpf_attr *attr)
21664 {
21665 struct bpf_insn *patch;
21666 /* use env->insn_buf as two independent buffers */
21667 struct bpf_insn *zext_patch = env->insn_buf;
21668 struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21669 struct bpf_insn_aux_data *aux = env->insn_aux_data;
21670 int i, patch_len, delta = 0, len = env->prog->len;
21671 struct bpf_insn *insns = env->prog->insnsi;
21672 struct bpf_prog *new_prog;
21673 bool rnd_hi32;
21674
21675 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21676 zext_patch[1] = BPF_ZEXT_REG(0);
21677 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21678 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21679 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21680 for (i = 0; i < len; i++) {
21681 int adj_idx = i + delta;
21682 struct bpf_insn insn;
21683 int load_reg;
21684
21685 insn = insns[adj_idx];
21686 load_reg = insn_def_regno(&insn);
21687 if (!aux[adj_idx].zext_dst) {
21688 u8 code, class;
21689 u32 imm_rnd;
21690
21691 if (!rnd_hi32)
21692 continue;
21693
21694 code = insn.code;
21695 class = BPF_CLASS(code);
21696 if (load_reg == -1)
21697 continue;
21698
21699 /* NOTE: arg "reg" (the fourth one) is only used for
21700 * BPF_STX + SRC_OP, so it is safe to pass NULL
21701 * here.
21702 */
21703 if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21704 if (class == BPF_LD &&
21705 BPF_MODE(code) == BPF_IMM)
21706 i++;
21707 continue;
21708 }
21709
21710 /* ctx load could be transformed into wider load. */
21711 if (class == BPF_LDX &&
21712 aux[adj_idx].ptr_type == PTR_TO_CTX)
21713 continue;
21714
21715 imm_rnd = get_random_u32();
21716 rnd_hi32_patch[0] = insn;
21717 rnd_hi32_patch[1].imm = imm_rnd;
21718 rnd_hi32_patch[3].dst_reg = load_reg;
21719 patch = rnd_hi32_patch;
21720 patch_len = 4;
21721 goto apply_patch_buffer;
21722 }
21723
21724 /* Add in an zero-extend instruction if a) the JIT has requested
21725 * it or b) it's a CMPXCHG.
21726 *
21727 * The latter is because: BPF_CMPXCHG always loads a value into
21728 * R0, therefore always zero-extends. However some archs'
21729 * equivalent instruction only does this load when the
21730 * comparison is successful. This detail of CMPXCHG is
21731 * orthogonal to the general zero-extension behaviour of the
21732 * CPU, so it's treated independently of bpf_jit_needs_zext.
21733 */
21734 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21735 continue;
21736
21737 /* Zero-extension is done by the caller. */
21738 if (bpf_pseudo_kfunc_call(&insn))
21739 continue;
21740
21741 if (verifier_bug_if(load_reg == -1, env,
21742 "zext_dst is set, but no reg is defined"))
21743 return -EFAULT;
21744
21745 zext_patch[0] = insn;
21746 zext_patch[1].dst_reg = load_reg;
21747 zext_patch[1].src_reg = load_reg;
21748 patch = zext_patch;
21749 patch_len = 2;
21750 apply_patch_buffer:
21751 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21752 if (!new_prog)
21753 return -ENOMEM;
21754 env->prog = new_prog;
21755 insns = new_prog->insnsi;
21756 aux = env->insn_aux_data;
21757 delta += patch_len - 1;
21758 }
21759
21760 return 0;
21761 }
21762
21763 /* convert load instructions that access fields of a context type into a
21764 * sequence of instructions that access fields of the underlying structure:
21765 * struct __sk_buff -> struct sk_buff
21766 * struct bpf_sock_ops -> struct sock
21767 */
convert_ctx_accesses(struct bpf_verifier_env * env)21768 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21769 {
21770 struct bpf_subprog_info *subprogs = env->subprog_info;
21771 const struct bpf_verifier_ops *ops = env->ops;
21772 int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21773 const int insn_cnt = env->prog->len;
21774 struct bpf_insn *epilogue_buf = env->epilogue_buf;
21775 struct bpf_insn *insn_buf = env->insn_buf;
21776 struct bpf_insn *insn;
21777 u32 target_size, size_default, off;
21778 struct bpf_prog *new_prog;
21779 enum bpf_access_type type;
21780 bool is_narrower_load;
21781 int epilogue_idx = 0;
21782
21783 if (ops->gen_epilogue) {
21784 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21785 -(subprogs[0].stack_depth + 8));
21786 if (epilogue_cnt >= INSN_BUF_SIZE) {
21787 verifier_bug(env, "epilogue is too long");
21788 return -EFAULT;
21789 } else if (epilogue_cnt) {
21790 /* Save the ARG_PTR_TO_CTX for the epilogue to use */
21791 cnt = 0;
21792 subprogs[0].stack_depth += 8;
21793 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21794 -subprogs[0].stack_depth);
21795 insn_buf[cnt++] = env->prog->insnsi[0];
21796 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21797 if (!new_prog)
21798 return -ENOMEM;
21799 env->prog = new_prog;
21800 delta += cnt - 1;
21801
21802 ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21803 if (ret < 0)
21804 return ret;
21805 }
21806 }
21807
21808 if (ops->gen_prologue || env->seen_direct_write) {
21809 if (!ops->gen_prologue) {
21810 verifier_bug(env, "gen_prologue is null");
21811 return -EFAULT;
21812 }
21813 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21814 env->prog);
21815 if (cnt >= INSN_BUF_SIZE) {
21816 verifier_bug(env, "prologue is too long");
21817 return -EFAULT;
21818 } else if (cnt) {
21819 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21820 if (!new_prog)
21821 return -ENOMEM;
21822
21823 env->prog = new_prog;
21824 delta += cnt - 1;
21825
21826 ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21827 if (ret < 0)
21828 return ret;
21829 }
21830 }
21831
21832 if (delta)
21833 WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21834
21835 if (bpf_prog_is_offloaded(env->prog->aux))
21836 return 0;
21837
21838 insn = env->prog->insnsi + delta;
21839
21840 for (i = 0; i < insn_cnt; i++, insn++) {
21841 bpf_convert_ctx_access_t convert_ctx_access;
21842 u8 mode;
21843
21844 if (env->insn_aux_data[i + delta].nospec) {
21845 WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21846 struct bpf_insn *patch = insn_buf;
21847
21848 *patch++ = BPF_ST_NOSPEC();
21849 *patch++ = *insn;
21850 cnt = patch - insn_buf;
21851 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21852 if (!new_prog)
21853 return -ENOMEM;
21854
21855 delta += cnt - 1;
21856 env->prog = new_prog;
21857 insn = new_prog->insnsi + i + delta;
21858 /* This can not be easily merged with the
21859 * nospec_result-case, because an insn may require a
21860 * nospec before and after itself. Therefore also do not
21861 * 'continue' here but potentially apply further
21862 * patching to insn. *insn should equal patch[1] now.
21863 */
21864 }
21865
21866 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21867 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21868 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21869 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21870 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21871 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21872 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21873 type = BPF_READ;
21874 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21875 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21876 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21877 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21878 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21879 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21880 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21881 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21882 type = BPF_WRITE;
21883 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21884 insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21885 insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21886 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21887 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21888 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21889 env->prog->aux->num_exentries++;
21890 continue;
21891 } else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21892 epilogue_cnt &&
21893 i + delta < subprogs[1].start) {
21894 /* Generate epilogue for the main prog */
21895 if (epilogue_idx) {
21896 /* jump back to the earlier generated epilogue */
21897 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21898 cnt = 1;
21899 } else {
21900 memcpy(insn_buf, epilogue_buf,
21901 epilogue_cnt * sizeof(*epilogue_buf));
21902 cnt = epilogue_cnt;
21903 /* epilogue_idx cannot be 0. It must have at
21904 * least one ctx ptr saving insn before the
21905 * epilogue.
21906 */
21907 epilogue_idx = i + delta;
21908 }
21909 goto patch_insn_buf;
21910 } else {
21911 continue;
21912 }
21913
21914 if (type == BPF_WRITE &&
21915 env->insn_aux_data[i + delta].nospec_result) {
21916 /* nospec_result is only used to mitigate Spectre v4 and
21917 * to limit verification-time for Spectre v1.
21918 */
21919 struct bpf_insn *patch = insn_buf;
21920
21921 *patch++ = *insn;
21922 *patch++ = BPF_ST_NOSPEC();
21923 cnt = patch - insn_buf;
21924 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21925 if (!new_prog)
21926 return -ENOMEM;
21927
21928 delta += cnt - 1;
21929 env->prog = new_prog;
21930 insn = new_prog->insnsi + i + delta;
21931 continue;
21932 }
21933
21934 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21935 case PTR_TO_CTX:
21936 if (!ops->convert_ctx_access)
21937 continue;
21938 convert_ctx_access = ops->convert_ctx_access;
21939 break;
21940 case PTR_TO_SOCKET:
21941 case PTR_TO_SOCK_COMMON:
21942 convert_ctx_access = bpf_sock_convert_ctx_access;
21943 break;
21944 case PTR_TO_TCP_SOCK:
21945 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21946 break;
21947 case PTR_TO_XDP_SOCK:
21948 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21949 break;
21950 case PTR_TO_BTF_ID:
21951 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21952 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21953 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21954 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21955 * any faults for loads into such types. BPF_WRITE is disallowed
21956 * for this case.
21957 */
21958 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21959 case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21960 if (type == BPF_READ) {
21961 if (BPF_MODE(insn->code) == BPF_MEM)
21962 insn->code = BPF_LDX | BPF_PROBE_MEM |
21963 BPF_SIZE((insn)->code);
21964 else
21965 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21966 BPF_SIZE((insn)->code);
21967 env->prog->aux->num_exentries++;
21968 }
21969 continue;
21970 case PTR_TO_ARENA:
21971 if (BPF_MODE(insn->code) == BPF_MEMSX) {
21972 if (!bpf_jit_supports_insn(insn, true)) {
21973 verbose(env, "sign extending loads from arena are not supported yet\n");
21974 return -EOPNOTSUPP;
21975 }
21976 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
21977 } else {
21978 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21979 }
21980 env->prog->aux->num_exentries++;
21981 continue;
21982 default:
21983 continue;
21984 }
21985
21986 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21987 size = BPF_LDST_BYTES(insn);
21988 mode = BPF_MODE(insn->code);
21989
21990 /* If the read access is a narrower load of the field,
21991 * convert to a 4/8-byte load, to minimum program type specific
21992 * convert_ctx_access changes. If conversion is successful,
21993 * we will apply proper mask to the result.
21994 */
21995 is_narrower_load = size < ctx_field_size;
21996 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
21997 off = insn->off;
21998 if (is_narrower_load) {
21999 u8 size_code;
22000
22001 if (type == BPF_WRITE) {
22002 verifier_bug(env, "narrow ctx access misconfigured");
22003 return -EFAULT;
22004 }
22005
22006 size_code = BPF_H;
22007 if (ctx_field_size == 4)
22008 size_code = BPF_W;
22009 else if (ctx_field_size == 8)
22010 size_code = BPF_DW;
22011
22012 insn->off = off & ~(size_default - 1);
22013 insn->code = BPF_LDX | BPF_MEM | size_code;
22014 }
22015
22016 target_size = 0;
22017 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
22018 &target_size);
22019 if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
22020 (ctx_field_size && !target_size)) {
22021 verifier_bug(env, "error during ctx access conversion (%d)", cnt);
22022 return -EFAULT;
22023 }
22024
22025 if (is_narrower_load && size < target_size) {
22026 u8 shift = bpf_ctx_narrow_access_offset(
22027 off, size, size_default) * 8;
22028 if (shift && cnt + 1 >= INSN_BUF_SIZE) {
22029 verifier_bug(env, "narrow ctx load misconfigured");
22030 return -EFAULT;
22031 }
22032 if (ctx_field_size <= 4) {
22033 if (shift)
22034 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
22035 insn->dst_reg,
22036 shift);
22037 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22038 (1 << size * 8) - 1);
22039 } else {
22040 if (shift)
22041 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
22042 insn->dst_reg,
22043 shift);
22044 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22045 (1ULL << size * 8) - 1);
22046 }
22047 }
22048 if (mode == BPF_MEMSX)
22049 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
22050 insn->dst_reg, insn->dst_reg,
22051 size * 8, 0);
22052
22053 patch_insn_buf:
22054 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22055 if (!new_prog)
22056 return -ENOMEM;
22057
22058 delta += cnt - 1;
22059
22060 /* keep walking new program and skip insns we just inserted */
22061 env->prog = new_prog;
22062 insn = new_prog->insnsi + i + delta;
22063 }
22064
22065 return 0;
22066 }
22067
jit_subprogs(struct bpf_verifier_env * env)22068 static int jit_subprogs(struct bpf_verifier_env *env)
22069 {
22070 struct bpf_prog *prog = env->prog, **func, *tmp;
22071 int i, j, subprog_start, subprog_end = 0, len, subprog;
22072 struct bpf_map *map_ptr;
22073 struct bpf_insn *insn;
22074 void *old_bpf_func;
22075 int err, num_exentries;
22076 int old_len, subprog_start_adjustment = 0;
22077
22078 if (env->subprog_cnt <= 1)
22079 return 0;
22080
22081 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22082 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
22083 continue;
22084
22085 /* Upon error here we cannot fall back to interpreter but
22086 * need a hard reject of the program. Thus -EFAULT is
22087 * propagated in any case.
22088 */
22089 subprog = find_subprog(env, i + insn->imm + 1);
22090 if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
22091 i + insn->imm + 1))
22092 return -EFAULT;
22093 /* temporarily remember subprog id inside insn instead of
22094 * aux_data, since next loop will split up all insns into funcs
22095 */
22096 insn->off = subprog;
22097 /* remember original imm in case JIT fails and fallback
22098 * to interpreter will be needed
22099 */
22100 env->insn_aux_data[i].call_imm = insn->imm;
22101 /* point imm to __bpf_call_base+1 from JITs point of view */
22102 insn->imm = 1;
22103 if (bpf_pseudo_func(insn)) {
22104 #if defined(MODULES_VADDR)
22105 u64 addr = MODULES_VADDR;
22106 #else
22107 u64 addr = VMALLOC_START;
22108 #endif
22109 /* jit (e.g. x86_64) may emit fewer instructions
22110 * if it learns a u32 imm is the same as a u64 imm.
22111 * Set close enough to possible prog address.
22112 */
22113 insn[0].imm = (u32)addr;
22114 insn[1].imm = addr >> 32;
22115 }
22116 }
22117
22118 err = bpf_prog_alloc_jited_linfo(prog);
22119 if (err)
22120 goto out_undo_insn;
22121
22122 err = -ENOMEM;
22123 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
22124 if (!func)
22125 goto out_undo_insn;
22126
22127 for (i = 0; i < env->subprog_cnt; i++) {
22128 subprog_start = subprog_end;
22129 subprog_end = env->subprog_info[i + 1].start;
22130
22131 len = subprog_end - subprog_start;
22132 /* bpf_prog_run() doesn't call subprogs directly,
22133 * hence main prog stats include the runtime of subprogs.
22134 * subprogs don't have IDs and not reachable via prog_get_next_id
22135 * func[i]->stats will never be accessed and stays NULL
22136 */
22137 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
22138 if (!func[i])
22139 goto out_free;
22140 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
22141 len * sizeof(struct bpf_insn));
22142 func[i]->type = prog->type;
22143 func[i]->len = len;
22144 if (bpf_prog_calc_tag(func[i]))
22145 goto out_free;
22146 func[i]->is_func = 1;
22147 func[i]->sleepable = prog->sleepable;
22148 func[i]->aux->func_idx = i;
22149 /* Below members will be freed only at prog->aux */
22150 func[i]->aux->btf = prog->aux->btf;
22151 func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
22152 func[i]->aux->func_info = prog->aux->func_info;
22153 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
22154 func[i]->aux->poke_tab = prog->aux->poke_tab;
22155 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
22156 func[i]->aux->main_prog_aux = prog->aux;
22157
22158 for (j = 0; j < prog->aux->size_poke_tab; j++) {
22159 struct bpf_jit_poke_descriptor *poke;
22160
22161 poke = &prog->aux->poke_tab[j];
22162 if (poke->insn_idx < subprog_end &&
22163 poke->insn_idx >= subprog_start)
22164 poke->aux = func[i]->aux;
22165 }
22166
22167 func[i]->aux->name[0] = 'F';
22168 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
22169 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
22170 func[i]->aux->jits_use_priv_stack = true;
22171
22172 func[i]->jit_requested = 1;
22173 func[i]->blinding_requested = prog->blinding_requested;
22174 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
22175 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
22176 func[i]->aux->linfo = prog->aux->linfo;
22177 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
22178 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
22179 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
22180 func[i]->aux->arena = prog->aux->arena;
22181 func[i]->aux->used_maps = env->used_maps;
22182 func[i]->aux->used_map_cnt = env->used_map_cnt;
22183 num_exentries = 0;
22184 insn = func[i]->insnsi;
22185 for (j = 0; j < func[i]->len; j++, insn++) {
22186 if (BPF_CLASS(insn->code) == BPF_LDX &&
22187 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22188 BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
22189 BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
22190 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
22191 num_exentries++;
22192 if ((BPF_CLASS(insn->code) == BPF_STX ||
22193 BPF_CLASS(insn->code) == BPF_ST) &&
22194 BPF_MODE(insn->code) == BPF_PROBE_MEM32)
22195 num_exentries++;
22196 if (BPF_CLASS(insn->code) == BPF_STX &&
22197 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
22198 num_exentries++;
22199 }
22200 func[i]->aux->num_exentries = num_exentries;
22201 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
22202 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
22203 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
22204 func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
22205 if (!i)
22206 func[i]->aux->exception_boundary = env->seen_exception;
22207
22208 /*
22209 * To properly pass the absolute subprog start to jit
22210 * all instruction adjustments should be accumulated
22211 */
22212 old_len = func[i]->len;
22213 func[i] = bpf_int_jit_compile(func[i]);
22214 subprog_start_adjustment += func[i]->len - old_len;
22215
22216 if (!func[i]->jited) {
22217 err = -ENOTSUPP;
22218 goto out_free;
22219 }
22220 cond_resched();
22221 }
22222
22223 /* at this point all bpf functions were successfully JITed
22224 * now populate all bpf_calls with correct addresses and
22225 * run last pass of JIT
22226 */
22227 for (i = 0; i < env->subprog_cnt; i++) {
22228 insn = func[i]->insnsi;
22229 for (j = 0; j < func[i]->len; j++, insn++) {
22230 if (bpf_pseudo_func(insn)) {
22231 subprog = insn->off;
22232 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
22233 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
22234 continue;
22235 }
22236 if (!bpf_pseudo_call(insn))
22237 continue;
22238 subprog = insn->off;
22239 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
22240 }
22241
22242 /* we use the aux data to keep a list of the start addresses
22243 * of the JITed images for each function in the program
22244 *
22245 * for some architectures, such as powerpc64, the imm field
22246 * might not be large enough to hold the offset of the start
22247 * address of the callee's JITed image from __bpf_call_base
22248 *
22249 * in such cases, we can lookup the start address of a callee
22250 * by using its subprog id, available from the off field of
22251 * the call instruction, as an index for this list
22252 */
22253 func[i]->aux->func = func;
22254 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22255 func[i]->aux->real_func_cnt = env->subprog_cnt;
22256 }
22257 for (i = 0; i < env->subprog_cnt; i++) {
22258 old_bpf_func = func[i]->bpf_func;
22259 tmp = bpf_int_jit_compile(func[i]);
22260 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
22261 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
22262 err = -ENOTSUPP;
22263 goto out_free;
22264 }
22265 cond_resched();
22266 }
22267
22268 /*
22269 * Cleanup func[i]->aux fields which aren't required
22270 * or can become invalid in future
22271 */
22272 for (i = 0; i < env->subprog_cnt; i++) {
22273 func[i]->aux->used_maps = NULL;
22274 func[i]->aux->used_map_cnt = 0;
22275 }
22276
22277 /* finally lock prog and jit images for all functions and
22278 * populate kallsysm. Begin at the first subprogram, since
22279 * bpf_prog_load will add the kallsyms for the main program.
22280 */
22281 for (i = 1; i < env->subprog_cnt; i++) {
22282 err = bpf_prog_lock_ro(func[i]);
22283 if (err)
22284 goto out_free;
22285 }
22286
22287 for (i = 1; i < env->subprog_cnt; i++)
22288 bpf_prog_kallsyms_add(func[i]);
22289
22290 /* Last step: make now unused interpreter insns from main
22291 * prog consistent for later dump requests, so they can
22292 * later look the same as if they were interpreted only.
22293 */
22294 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22295 if (bpf_pseudo_func(insn)) {
22296 insn[0].imm = env->insn_aux_data[i].call_imm;
22297 insn[1].imm = insn->off;
22298 insn->off = 0;
22299 continue;
22300 }
22301 if (!bpf_pseudo_call(insn))
22302 continue;
22303 insn->off = env->insn_aux_data[i].call_imm;
22304 subprog = find_subprog(env, i + insn->off + 1);
22305 insn->imm = subprog;
22306 }
22307
22308 prog->jited = 1;
22309 prog->bpf_func = func[0]->bpf_func;
22310 prog->jited_len = func[0]->jited_len;
22311 prog->aux->extable = func[0]->aux->extable;
22312 prog->aux->num_exentries = func[0]->aux->num_exentries;
22313 prog->aux->func = func;
22314 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22315 prog->aux->real_func_cnt = env->subprog_cnt;
22316 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
22317 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
22318 bpf_prog_jit_attempt_done(prog);
22319 return 0;
22320 out_free:
22321 /* We failed JIT'ing, so at this point we need to unregister poke
22322 * descriptors from subprogs, so that kernel is not attempting to
22323 * patch it anymore as we're freeing the subprog JIT memory.
22324 */
22325 for (i = 0; i < prog->aux->size_poke_tab; i++) {
22326 map_ptr = prog->aux->poke_tab[i].tail_call.map;
22327 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
22328 }
22329 /* At this point we're guaranteed that poke descriptors are not
22330 * live anymore. We can just unlink its descriptor table as it's
22331 * released with the main prog.
22332 */
22333 for (i = 0; i < env->subprog_cnt; i++) {
22334 if (!func[i])
22335 continue;
22336 func[i]->aux->poke_tab = NULL;
22337 bpf_jit_free(func[i]);
22338 }
22339 kfree(func);
22340 out_undo_insn:
22341 /* cleanup main prog to be interpreted */
22342 prog->jit_requested = 0;
22343 prog->blinding_requested = 0;
22344 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22345 if (!bpf_pseudo_call(insn))
22346 continue;
22347 insn->off = 0;
22348 insn->imm = env->insn_aux_data[i].call_imm;
22349 }
22350 bpf_prog_jit_attempt_done(prog);
22351 return err;
22352 }
22353
fixup_call_args(struct bpf_verifier_env * env)22354 static int fixup_call_args(struct bpf_verifier_env *env)
22355 {
22356 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22357 struct bpf_prog *prog = env->prog;
22358 struct bpf_insn *insn = prog->insnsi;
22359 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
22360 int i, depth;
22361 #endif
22362 int err = 0;
22363
22364 if (env->prog->jit_requested &&
22365 !bpf_prog_is_offloaded(env->prog->aux)) {
22366 err = jit_subprogs(env);
22367 if (err == 0)
22368 return 0;
22369 if (err == -EFAULT)
22370 return err;
22371 }
22372 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22373 if (has_kfunc_call) {
22374 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
22375 return -EINVAL;
22376 }
22377 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
22378 /* When JIT fails the progs with bpf2bpf calls and tail_calls
22379 * have to be rejected, since interpreter doesn't support them yet.
22380 */
22381 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
22382 return -EINVAL;
22383 }
22384 for (i = 0; i < prog->len; i++, insn++) {
22385 if (bpf_pseudo_func(insn)) {
22386 /* When JIT fails the progs with callback calls
22387 * have to be rejected, since interpreter doesn't support them yet.
22388 */
22389 verbose(env, "callbacks are not allowed in non-JITed programs\n");
22390 return -EINVAL;
22391 }
22392
22393 if (!bpf_pseudo_call(insn))
22394 continue;
22395 depth = get_callee_stack_depth(env, insn, i);
22396 if (depth < 0)
22397 return depth;
22398 bpf_patch_call_args(insn, depth);
22399 }
22400 err = 0;
22401 #endif
22402 return err;
22403 }
22404
22405 /* replace a generic kfunc with a specialized version if necessary */
specialize_kfunc(struct bpf_verifier_env * env,struct bpf_kfunc_desc * desc,int insn_idx)22406 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
22407 {
22408 struct bpf_prog *prog = env->prog;
22409 bool seen_direct_write;
22410 void *xdp_kfunc;
22411 bool is_rdonly;
22412 u32 func_id = desc->func_id;
22413 u16 offset = desc->offset;
22414 unsigned long addr = desc->addr;
22415
22416 if (offset) /* return if module BTF is used */
22417 return 0;
22418
22419 if (bpf_dev_bound_kfunc_id(func_id)) {
22420 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
22421 if (xdp_kfunc)
22422 addr = (unsigned long)xdp_kfunc;
22423 /* fallback to default kfunc when not supported by netdev */
22424 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
22425 seen_direct_write = env->seen_direct_write;
22426 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
22427
22428 if (is_rdonly)
22429 addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
22430
22431 /* restore env->seen_direct_write to its original value, since
22432 * may_access_direct_pkt_data mutates it
22433 */
22434 env->seen_direct_write = seen_direct_write;
22435 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
22436 if (bpf_lsm_has_d_inode_locked(prog))
22437 addr = (unsigned long)bpf_set_dentry_xattr_locked;
22438 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
22439 if (bpf_lsm_has_d_inode_locked(prog))
22440 addr = (unsigned long)bpf_remove_dentry_xattr_locked;
22441 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
22442 if (!env->insn_aux_data[insn_idx].non_sleepable)
22443 addr = (unsigned long)bpf_dynptr_from_file_sleepable;
22444 }
22445 desc->addr = addr;
22446 return 0;
22447 }
22448
__fixup_collection_insert_kfunc(struct bpf_insn_aux_data * insn_aux,u16 struct_meta_reg,u16 node_offset_reg,struct bpf_insn * insn,struct bpf_insn * insn_buf,int * cnt)22449 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
22450 u16 struct_meta_reg,
22451 u16 node_offset_reg,
22452 struct bpf_insn *insn,
22453 struct bpf_insn *insn_buf,
22454 int *cnt)
22455 {
22456 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
22457 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
22458
22459 insn_buf[0] = addr[0];
22460 insn_buf[1] = addr[1];
22461 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
22462 insn_buf[3] = *insn;
22463 *cnt = 4;
22464 }
22465
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)22466 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
22467 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
22468 {
22469 struct bpf_kfunc_desc *desc;
22470 int err;
22471
22472 if (!insn->imm) {
22473 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
22474 return -EINVAL;
22475 }
22476
22477 *cnt = 0;
22478
22479 /* insn->imm has the btf func_id. Replace it with an offset relative to
22480 * __bpf_call_base, unless the JIT needs to call functions that are
22481 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
22482 */
22483 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
22484 if (!desc) {
22485 verifier_bug(env, "kernel function descriptor not found for func_id %u",
22486 insn->imm);
22487 return -EFAULT;
22488 }
22489
22490 err = specialize_kfunc(env, desc, insn_idx);
22491 if (err)
22492 return err;
22493
22494 if (!bpf_jit_supports_far_kfunc_call())
22495 insn->imm = BPF_CALL_IMM(desc->addr);
22496 if (insn->off)
22497 return 0;
22498 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
22499 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
22500 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22501 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22502 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
22503
22504 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
22505 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22506 insn_idx);
22507 return -EFAULT;
22508 }
22509
22510 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
22511 insn_buf[1] = addr[0];
22512 insn_buf[2] = addr[1];
22513 insn_buf[3] = *insn;
22514 *cnt = 4;
22515 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
22516 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
22517 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
22518 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22519 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22520
22521 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
22522 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22523 insn_idx);
22524 return -EFAULT;
22525 }
22526
22527 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
22528 !kptr_struct_meta) {
22529 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22530 insn_idx);
22531 return -EFAULT;
22532 }
22533
22534 insn_buf[0] = addr[0];
22535 insn_buf[1] = addr[1];
22536 insn_buf[2] = *insn;
22537 *cnt = 3;
22538 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
22539 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
22540 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22541 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22542 int struct_meta_reg = BPF_REG_3;
22543 int node_offset_reg = BPF_REG_4;
22544
22545 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
22546 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22547 struct_meta_reg = BPF_REG_4;
22548 node_offset_reg = BPF_REG_5;
22549 }
22550
22551 if (!kptr_struct_meta) {
22552 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22553 insn_idx);
22554 return -EFAULT;
22555 }
22556
22557 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
22558 node_offset_reg, insn, insn_buf, cnt);
22559 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
22560 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
22561 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22562 *cnt = 1;
22563 }
22564
22565 if (env->insn_aux_data[insn_idx].arg_prog) {
22566 u32 regno = env->insn_aux_data[insn_idx].arg_prog;
22567 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
22568 int idx = *cnt;
22569
22570 insn_buf[idx++] = ld_addrs[0];
22571 insn_buf[idx++] = ld_addrs[1];
22572 insn_buf[idx++] = *insn;
22573 *cnt = idx;
22574 }
22575 return 0;
22576 }
22577
22578 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
add_hidden_subprog(struct bpf_verifier_env * env,struct bpf_insn * patch,int len)22579 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
22580 {
22581 struct bpf_subprog_info *info = env->subprog_info;
22582 int cnt = env->subprog_cnt;
22583 struct bpf_prog *prog;
22584
22585 /* We only reserve one slot for hidden subprogs in subprog_info. */
22586 if (env->hidden_subprog_cnt) {
22587 verifier_bug(env, "only one hidden subprog supported");
22588 return -EFAULT;
22589 }
22590 /* We're not patching any existing instruction, just appending the new
22591 * ones for the hidden subprog. Hence all of the adjustment operations
22592 * in bpf_patch_insn_data are no-ops.
22593 */
22594 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
22595 if (!prog)
22596 return -ENOMEM;
22597 env->prog = prog;
22598 info[cnt + 1].start = info[cnt].start;
22599 info[cnt].start = prog->len - len + 1;
22600 env->subprog_cnt++;
22601 env->hidden_subprog_cnt++;
22602 return 0;
22603 }
22604
22605 /* Do various post-verification rewrites in a single program pass.
22606 * These rewrites simplify JIT and interpreter implementations.
22607 */
do_misc_fixups(struct bpf_verifier_env * env)22608 static int do_misc_fixups(struct bpf_verifier_env *env)
22609 {
22610 struct bpf_prog *prog = env->prog;
22611 enum bpf_attach_type eatype = prog->expected_attach_type;
22612 enum bpf_prog_type prog_type = resolve_prog_type(prog);
22613 struct bpf_insn *insn = prog->insnsi;
22614 const struct bpf_func_proto *fn;
22615 const int insn_cnt = prog->len;
22616 const struct bpf_map_ops *ops;
22617 struct bpf_insn_aux_data *aux;
22618 struct bpf_insn *insn_buf = env->insn_buf;
22619 struct bpf_prog *new_prog;
22620 struct bpf_map *map_ptr;
22621 int i, ret, cnt, delta = 0, cur_subprog = 0;
22622 struct bpf_subprog_info *subprogs = env->subprog_info;
22623 u16 stack_depth = subprogs[cur_subprog].stack_depth;
22624 u16 stack_depth_extra = 0;
22625
22626 if (env->seen_exception && !env->exception_callback_subprog) {
22627 struct bpf_insn *patch = insn_buf;
22628
22629 *patch++ = env->prog->insnsi[insn_cnt - 1];
22630 *patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22631 *patch++ = BPF_EXIT_INSN();
22632 ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22633 if (ret < 0)
22634 return ret;
22635 prog = env->prog;
22636 insn = prog->insnsi;
22637
22638 env->exception_callback_subprog = env->subprog_cnt - 1;
22639 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22640 mark_subprog_exc_cb(env, env->exception_callback_subprog);
22641 }
22642
22643 for (i = 0; i < insn_cnt;) {
22644 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22645 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22646 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22647 /* convert to 32-bit mov that clears upper 32-bit */
22648 insn->code = BPF_ALU | BPF_MOV | BPF_X;
22649 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22650 insn->off = 0;
22651 insn->imm = 0;
22652 } /* cast from as(0) to as(1) should be handled by JIT */
22653 goto next_insn;
22654 }
22655
22656 if (env->insn_aux_data[i + delta].needs_zext)
22657 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22658 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22659
22660 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22661 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22662 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22663 insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22664 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22665 insn->off == 1 && insn->imm == -1) {
22666 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22667 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22668 struct bpf_insn *patch = insn_buf;
22669
22670 if (isdiv)
22671 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22672 BPF_NEG | BPF_K, insn->dst_reg,
22673 0, 0, 0);
22674 else
22675 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22676
22677 cnt = patch - insn_buf;
22678
22679 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22680 if (!new_prog)
22681 return -ENOMEM;
22682
22683 delta += cnt - 1;
22684 env->prog = prog = new_prog;
22685 insn = new_prog->insnsi + i + delta;
22686 goto next_insn;
22687 }
22688
22689 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22690 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22691 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22692 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22693 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22694 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22695 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22696 bool is_sdiv = isdiv && insn->off == 1;
22697 bool is_smod = !isdiv && insn->off == 1;
22698 struct bpf_insn *patch = insn_buf;
22699
22700 if (is_sdiv) {
22701 /* [R,W]x sdiv 0 -> 0
22702 * LLONG_MIN sdiv -1 -> LLONG_MIN
22703 * INT_MIN sdiv -1 -> INT_MIN
22704 */
22705 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22706 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22707 BPF_ADD | BPF_K, BPF_REG_AX,
22708 0, 0, 1);
22709 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22710 BPF_JGT | BPF_K, BPF_REG_AX,
22711 0, 4, 1);
22712 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22713 BPF_JEQ | BPF_K, BPF_REG_AX,
22714 0, 1, 0);
22715 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22716 BPF_MOV | BPF_K, insn->dst_reg,
22717 0, 0, 0);
22718 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22719 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22720 BPF_NEG | BPF_K, insn->dst_reg,
22721 0, 0, 0);
22722 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22723 *patch++ = *insn;
22724 cnt = patch - insn_buf;
22725 } else if (is_smod) {
22726 /* [R,W]x mod 0 -> [R,W]x */
22727 /* [R,W]x mod -1 -> 0 */
22728 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22729 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22730 BPF_ADD | BPF_K, BPF_REG_AX,
22731 0, 0, 1);
22732 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22733 BPF_JGT | BPF_K, BPF_REG_AX,
22734 0, 3, 1);
22735 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22736 BPF_JEQ | BPF_K, BPF_REG_AX,
22737 0, 3 + (is64 ? 0 : 1), 1);
22738 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22739 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22740 *patch++ = *insn;
22741
22742 if (!is64) {
22743 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22744 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22745 }
22746 cnt = patch - insn_buf;
22747 } else if (isdiv) {
22748 /* [R,W]x div 0 -> 0 */
22749 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22750 BPF_JNE | BPF_K, insn->src_reg,
22751 0, 2, 0);
22752 *patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22753 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22754 *patch++ = *insn;
22755 cnt = patch - insn_buf;
22756 } else {
22757 /* [R,W]x mod 0 -> [R,W]x */
22758 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22759 BPF_JEQ | BPF_K, insn->src_reg,
22760 0, 1 + (is64 ? 0 : 1), 0);
22761 *patch++ = *insn;
22762
22763 if (!is64) {
22764 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22765 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22766 }
22767 cnt = patch - insn_buf;
22768 }
22769
22770 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22771 if (!new_prog)
22772 return -ENOMEM;
22773
22774 delta += cnt - 1;
22775 env->prog = prog = new_prog;
22776 insn = new_prog->insnsi + i + delta;
22777 goto next_insn;
22778 }
22779
22780 /* Make it impossible to de-reference a userspace address */
22781 if (BPF_CLASS(insn->code) == BPF_LDX &&
22782 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22783 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22784 struct bpf_insn *patch = insn_buf;
22785 u64 uaddress_limit = bpf_arch_uaddress_limit();
22786
22787 if (!uaddress_limit)
22788 goto next_insn;
22789
22790 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22791 if (insn->off)
22792 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22793 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22794 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22795 *patch++ = *insn;
22796 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22797 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22798
22799 cnt = patch - insn_buf;
22800 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22801 if (!new_prog)
22802 return -ENOMEM;
22803
22804 delta += cnt - 1;
22805 env->prog = prog = new_prog;
22806 insn = new_prog->insnsi + i + delta;
22807 goto next_insn;
22808 }
22809
22810 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22811 if (BPF_CLASS(insn->code) == BPF_LD &&
22812 (BPF_MODE(insn->code) == BPF_ABS ||
22813 BPF_MODE(insn->code) == BPF_IND)) {
22814 cnt = env->ops->gen_ld_abs(insn, insn_buf);
22815 if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22816 verifier_bug(env, "%d insns generated for ld_abs", cnt);
22817 return -EFAULT;
22818 }
22819
22820 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22821 if (!new_prog)
22822 return -ENOMEM;
22823
22824 delta += cnt - 1;
22825 env->prog = prog = new_prog;
22826 insn = new_prog->insnsi + i + delta;
22827 goto next_insn;
22828 }
22829
22830 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
22831 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22832 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22833 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22834 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22835 struct bpf_insn *patch = insn_buf;
22836 bool issrc, isneg, isimm;
22837 u32 off_reg;
22838
22839 aux = &env->insn_aux_data[i + delta];
22840 if (!aux->alu_state ||
22841 aux->alu_state == BPF_ALU_NON_POINTER)
22842 goto next_insn;
22843
22844 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22845 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22846 BPF_ALU_SANITIZE_SRC;
22847 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22848
22849 off_reg = issrc ? insn->src_reg : insn->dst_reg;
22850 if (isimm) {
22851 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22852 } else {
22853 if (isneg)
22854 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22855 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22856 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22857 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22858 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22859 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22860 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22861 }
22862 if (!issrc)
22863 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22864 insn->src_reg = BPF_REG_AX;
22865 if (isneg)
22866 insn->code = insn->code == code_add ?
22867 code_sub : code_add;
22868 *patch++ = *insn;
22869 if (issrc && isneg && !isimm)
22870 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22871 cnt = patch - insn_buf;
22872
22873 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22874 if (!new_prog)
22875 return -ENOMEM;
22876
22877 delta += cnt - 1;
22878 env->prog = prog = new_prog;
22879 insn = new_prog->insnsi + i + delta;
22880 goto next_insn;
22881 }
22882
22883 if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22884 int stack_off_cnt = -stack_depth - 16;
22885
22886 /*
22887 * Two 8 byte slots, depth-16 stores the count, and
22888 * depth-8 stores the start timestamp of the loop.
22889 *
22890 * The starting value of count is BPF_MAX_TIMED_LOOPS
22891 * (0xffff). Every iteration loads it and subs it by 1,
22892 * until the value becomes 0 in AX (thus, 1 in stack),
22893 * after which we call arch_bpf_timed_may_goto, which
22894 * either sets AX to 0xffff to keep looping, or to 0
22895 * upon timeout. AX is then stored into the stack. In
22896 * the next iteration, we either see 0 and break out, or
22897 * continue iterating until the next time value is 0
22898 * after subtraction, rinse and repeat.
22899 */
22900 stack_depth_extra = 16;
22901 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22902 if (insn->off >= 0)
22903 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22904 else
22905 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22906 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22907 insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22908 /*
22909 * AX is used as an argument to pass in stack_off_cnt
22910 * (to add to r10/fp), and also as the return value of
22911 * the call to arch_bpf_timed_may_goto.
22912 */
22913 insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22914 insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22915 insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22916 cnt = 7;
22917
22918 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22919 if (!new_prog)
22920 return -ENOMEM;
22921
22922 delta += cnt - 1;
22923 env->prog = prog = new_prog;
22924 insn = new_prog->insnsi + i + delta;
22925 goto next_insn;
22926 } else if (is_may_goto_insn(insn)) {
22927 int stack_off = -stack_depth - 8;
22928
22929 stack_depth_extra = 8;
22930 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22931 if (insn->off >= 0)
22932 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22933 else
22934 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22935 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22936 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22937 cnt = 4;
22938
22939 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22940 if (!new_prog)
22941 return -ENOMEM;
22942
22943 delta += cnt - 1;
22944 env->prog = prog = new_prog;
22945 insn = new_prog->insnsi + i + delta;
22946 goto next_insn;
22947 }
22948
22949 if (insn->code != (BPF_JMP | BPF_CALL))
22950 goto next_insn;
22951 if (insn->src_reg == BPF_PSEUDO_CALL)
22952 goto next_insn;
22953 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22954 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22955 if (ret)
22956 return ret;
22957 if (cnt == 0)
22958 goto next_insn;
22959
22960 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22961 if (!new_prog)
22962 return -ENOMEM;
22963
22964 delta += cnt - 1;
22965 env->prog = prog = new_prog;
22966 insn = new_prog->insnsi + i + delta;
22967 goto next_insn;
22968 }
22969
22970 /* Skip inlining the helper call if the JIT does it. */
22971 if (bpf_jit_inlines_helper_call(insn->imm))
22972 goto next_insn;
22973
22974 if (insn->imm == BPF_FUNC_get_route_realm)
22975 prog->dst_needed = 1;
22976 if (insn->imm == BPF_FUNC_get_prandom_u32)
22977 bpf_user_rnd_init_once();
22978 if (insn->imm == BPF_FUNC_override_return)
22979 prog->kprobe_override = 1;
22980 if (insn->imm == BPF_FUNC_tail_call) {
22981 /* If we tail call into other programs, we
22982 * cannot make any assumptions since they can
22983 * be replaced dynamically during runtime in
22984 * the program array.
22985 */
22986 prog->cb_access = 1;
22987 if (!allow_tail_call_in_subprogs(env))
22988 prog->aux->stack_depth = MAX_BPF_STACK;
22989 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22990
22991 /* mark bpf_tail_call as different opcode to avoid
22992 * conditional branch in the interpreter for every normal
22993 * call and to prevent accidental JITing by JIT compiler
22994 * that doesn't support bpf_tail_call yet
22995 */
22996 insn->imm = 0;
22997 insn->code = BPF_JMP | BPF_TAIL_CALL;
22998
22999 aux = &env->insn_aux_data[i + delta];
23000 if (env->bpf_capable && !prog->blinding_requested &&
23001 prog->jit_requested &&
23002 !bpf_map_key_poisoned(aux) &&
23003 !bpf_map_ptr_poisoned(aux) &&
23004 !bpf_map_ptr_unpriv(aux)) {
23005 struct bpf_jit_poke_descriptor desc = {
23006 .reason = BPF_POKE_REASON_TAIL_CALL,
23007 .tail_call.map = aux->map_ptr_state.map_ptr,
23008 .tail_call.key = bpf_map_key_immediate(aux),
23009 .insn_idx = i + delta,
23010 };
23011
23012 ret = bpf_jit_add_poke_descriptor(prog, &desc);
23013 if (ret < 0) {
23014 verbose(env, "adding tail call poke descriptor failed\n");
23015 return ret;
23016 }
23017
23018 insn->imm = ret + 1;
23019 goto next_insn;
23020 }
23021
23022 if (!bpf_map_ptr_unpriv(aux))
23023 goto next_insn;
23024
23025 /* instead of changing every JIT dealing with tail_call
23026 * emit two extra insns:
23027 * if (index >= max_entries) goto out;
23028 * index &= array->index_mask;
23029 * to avoid out-of-bounds cpu speculation
23030 */
23031 if (bpf_map_ptr_poisoned(aux)) {
23032 verbose(env, "tail_call abusing map_ptr\n");
23033 return -EINVAL;
23034 }
23035
23036 map_ptr = aux->map_ptr_state.map_ptr;
23037 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
23038 map_ptr->max_entries, 2);
23039 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
23040 container_of(map_ptr,
23041 struct bpf_array,
23042 map)->index_mask);
23043 insn_buf[2] = *insn;
23044 cnt = 3;
23045 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23046 if (!new_prog)
23047 return -ENOMEM;
23048
23049 delta += cnt - 1;
23050 env->prog = prog = new_prog;
23051 insn = new_prog->insnsi + i + delta;
23052 goto next_insn;
23053 }
23054
23055 if (insn->imm == BPF_FUNC_timer_set_callback) {
23056 /* The verifier will process callback_fn as many times as necessary
23057 * with different maps and the register states prepared by
23058 * set_timer_callback_state will be accurate.
23059 *
23060 * The following use case is valid:
23061 * map1 is shared by prog1, prog2, prog3.
23062 * prog1 calls bpf_timer_init for some map1 elements
23063 * prog2 calls bpf_timer_set_callback for some map1 elements.
23064 * Those that were not bpf_timer_init-ed will return -EINVAL.
23065 * prog3 calls bpf_timer_start for some map1 elements.
23066 * Those that were not both bpf_timer_init-ed and
23067 * bpf_timer_set_callback-ed will return -EINVAL.
23068 */
23069 struct bpf_insn ld_addrs[2] = {
23070 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
23071 };
23072
23073 insn_buf[0] = ld_addrs[0];
23074 insn_buf[1] = ld_addrs[1];
23075 insn_buf[2] = *insn;
23076 cnt = 3;
23077
23078 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23079 if (!new_prog)
23080 return -ENOMEM;
23081
23082 delta += cnt - 1;
23083 env->prog = prog = new_prog;
23084 insn = new_prog->insnsi + i + delta;
23085 goto patch_call_imm;
23086 }
23087
23088 if (is_storage_get_function(insn->imm)) {
23089 if (env->insn_aux_data[i + delta].non_sleepable)
23090 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
23091 else
23092 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
23093 insn_buf[1] = *insn;
23094 cnt = 2;
23095
23096 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23097 if (!new_prog)
23098 return -ENOMEM;
23099
23100 delta += cnt - 1;
23101 env->prog = prog = new_prog;
23102 insn = new_prog->insnsi + i + delta;
23103 goto patch_call_imm;
23104 }
23105
23106 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
23107 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
23108 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
23109 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
23110 */
23111 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
23112 insn_buf[1] = *insn;
23113 cnt = 2;
23114
23115 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23116 if (!new_prog)
23117 return -ENOMEM;
23118
23119 delta += cnt - 1;
23120 env->prog = prog = new_prog;
23121 insn = new_prog->insnsi + i + delta;
23122 goto patch_call_imm;
23123 }
23124
23125 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
23126 * and other inlining handlers are currently limited to 64 bit
23127 * only.
23128 */
23129 if (prog->jit_requested && BITS_PER_LONG == 64 &&
23130 (insn->imm == BPF_FUNC_map_lookup_elem ||
23131 insn->imm == BPF_FUNC_map_update_elem ||
23132 insn->imm == BPF_FUNC_map_delete_elem ||
23133 insn->imm == BPF_FUNC_map_push_elem ||
23134 insn->imm == BPF_FUNC_map_pop_elem ||
23135 insn->imm == BPF_FUNC_map_peek_elem ||
23136 insn->imm == BPF_FUNC_redirect_map ||
23137 insn->imm == BPF_FUNC_for_each_map_elem ||
23138 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
23139 aux = &env->insn_aux_data[i + delta];
23140 if (bpf_map_ptr_poisoned(aux))
23141 goto patch_call_imm;
23142
23143 map_ptr = aux->map_ptr_state.map_ptr;
23144 ops = map_ptr->ops;
23145 if (insn->imm == BPF_FUNC_map_lookup_elem &&
23146 ops->map_gen_lookup) {
23147 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
23148 if (cnt == -EOPNOTSUPP)
23149 goto patch_map_ops_generic;
23150 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
23151 verifier_bug(env, "%d insns generated for map lookup", cnt);
23152 return -EFAULT;
23153 }
23154
23155 new_prog = bpf_patch_insn_data(env, i + delta,
23156 insn_buf, cnt);
23157 if (!new_prog)
23158 return -ENOMEM;
23159
23160 delta += cnt - 1;
23161 env->prog = prog = new_prog;
23162 insn = new_prog->insnsi + i + delta;
23163 goto next_insn;
23164 }
23165
23166 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
23167 (void *(*)(struct bpf_map *map, void *key))NULL));
23168 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
23169 (long (*)(struct bpf_map *map, void *key))NULL));
23170 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
23171 (long (*)(struct bpf_map *map, void *key, void *value,
23172 u64 flags))NULL));
23173 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
23174 (long (*)(struct bpf_map *map, void *value,
23175 u64 flags))NULL));
23176 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
23177 (long (*)(struct bpf_map *map, void *value))NULL));
23178 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
23179 (long (*)(struct bpf_map *map, void *value))NULL));
23180 BUILD_BUG_ON(!__same_type(ops->map_redirect,
23181 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
23182 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
23183 (long (*)(struct bpf_map *map,
23184 bpf_callback_t callback_fn,
23185 void *callback_ctx,
23186 u64 flags))NULL));
23187 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
23188 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
23189
23190 patch_map_ops_generic:
23191 switch (insn->imm) {
23192 case BPF_FUNC_map_lookup_elem:
23193 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
23194 goto next_insn;
23195 case BPF_FUNC_map_update_elem:
23196 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
23197 goto next_insn;
23198 case BPF_FUNC_map_delete_elem:
23199 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
23200 goto next_insn;
23201 case BPF_FUNC_map_push_elem:
23202 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
23203 goto next_insn;
23204 case BPF_FUNC_map_pop_elem:
23205 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
23206 goto next_insn;
23207 case BPF_FUNC_map_peek_elem:
23208 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
23209 goto next_insn;
23210 case BPF_FUNC_redirect_map:
23211 insn->imm = BPF_CALL_IMM(ops->map_redirect);
23212 goto next_insn;
23213 case BPF_FUNC_for_each_map_elem:
23214 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
23215 goto next_insn;
23216 case BPF_FUNC_map_lookup_percpu_elem:
23217 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
23218 goto next_insn;
23219 }
23220
23221 goto patch_call_imm;
23222 }
23223
23224 /* Implement bpf_jiffies64 inline. */
23225 if (prog->jit_requested && BITS_PER_LONG == 64 &&
23226 insn->imm == BPF_FUNC_jiffies64) {
23227 struct bpf_insn ld_jiffies_addr[2] = {
23228 BPF_LD_IMM64(BPF_REG_0,
23229 (unsigned long)&jiffies),
23230 };
23231
23232 insn_buf[0] = ld_jiffies_addr[0];
23233 insn_buf[1] = ld_jiffies_addr[1];
23234 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
23235 BPF_REG_0, 0);
23236 cnt = 3;
23237
23238 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
23239 cnt);
23240 if (!new_prog)
23241 return -ENOMEM;
23242
23243 delta += cnt - 1;
23244 env->prog = prog = new_prog;
23245 insn = new_prog->insnsi + i + delta;
23246 goto next_insn;
23247 }
23248
23249 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
23250 /* Implement bpf_get_smp_processor_id() inline. */
23251 if (insn->imm == BPF_FUNC_get_smp_processor_id &&
23252 verifier_inlines_helper_call(env, insn->imm)) {
23253 /* BPF_FUNC_get_smp_processor_id inlining is an
23254 * optimization, so if cpu_number is ever
23255 * changed in some incompatible and hard to support
23256 * way, it's fine to back out this inlining logic
23257 */
23258 #ifdef CONFIG_SMP
23259 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
23260 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23261 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
23262 cnt = 3;
23263 #else
23264 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
23265 cnt = 1;
23266 #endif
23267 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23268 if (!new_prog)
23269 return -ENOMEM;
23270
23271 delta += cnt - 1;
23272 env->prog = prog = new_prog;
23273 insn = new_prog->insnsi + i + delta;
23274 goto next_insn;
23275 }
23276 #endif
23277 /* Implement bpf_get_func_arg inline. */
23278 if (prog_type == BPF_PROG_TYPE_TRACING &&
23279 insn->imm == BPF_FUNC_get_func_arg) {
23280 /* Load nr_args from ctx - 8 */
23281 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23282 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
23283 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
23284 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
23285 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
23286 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23287 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
23288 insn_buf[7] = BPF_JMP_A(1);
23289 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23290 cnt = 9;
23291
23292 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23293 if (!new_prog)
23294 return -ENOMEM;
23295
23296 delta += cnt - 1;
23297 env->prog = prog = new_prog;
23298 insn = new_prog->insnsi + i + delta;
23299 goto next_insn;
23300 }
23301
23302 /* Implement bpf_get_func_ret inline. */
23303 if (prog_type == BPF_PROG_TYPE_TRACING &&
23304 insn->imm == BPF_FUNC_get_func_ret) {
23305 if (eatype == BPF_TRACE_FEXIT ||
23306 eatype == BPF_MODIFY_RETURN) {
23307 /* Load nr_args from ctx - 8 */
23308 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23309 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23310 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
23311 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23312 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
23313 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
23314 cnt = 6;
23315 } else {
23316 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
23317 cnt = 1;
23318 }
23319
23320 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23321 if (!new_prog)
23322 return -ENOMEM;
23323
23324 delta += cnt - 1;
23325 env->prog = prog = new_prog;
23326 insn = new_prog->insnsi + i + delta;
23327 goto next_insn;
23328 }
23329
23330 /* Implement get_func_arg_cnt inline. */
23331 if (prog_type == BPF_PROG_TYPE_TRACING &&
23332 insn->imm == BPF_FUNC_get_func_arg_cnt) {
23333 /* Load nr_args from ctx - 8 */
23334 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23335
23336 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23337 if (!new_prog)
23338 return -ENOMEM;
23339
23340 env->prog = prog = new_prog;
23341 insn = new_prog->insnsi + i + delta;
23342 goto next_insn;
23343 }
23344
23345 /* Implement bpf_get_func_ip inline. */
23346 if (prog_type == BPF_PROG_TYPE_TRACING &&
23347 insn->imm == BPF_FUNC_get_func_ip) {
23348 /* Load IP address from ctx - 16 */
23349 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
23350
23351 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23352 if (!new_prog)
23353 return -ENOMEM;
23354
23355 env->prog = prog = new_prog;
23356 insn = new_prog->insnsi + i + delta;
23357 goto next_insn;
23358 }
23359
23360 /* Implement bpf_get_branch_snapshot inline. */
23361 if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
23362 prog->jit_requested && BITS_PER_LONG == 64 &&
23363 insn->imm == BPF_FUNC_get_branch_snapshot) {
23364 /* We are dealing with the following func protos:
23365 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
23366 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
23367 */
23368 const u32 br_entry_size = sizeof(struct perf_branch_entry);
23369
23370 /* struct perf_branch_entry is part of UAPI and is
23371 * used as an array element, so extremely unlikely to
23372 * ever grow or shrink
23373 */
23374 BUILD_BUG_ON(br_entry_size != 24);
23375
23376 /* if (unlikely(flags)) return -EINVAL */
23377 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
23378
23379 /* Transform size (bytes) into number of entries (cnt = size / 24).
23380 * But to avoid expensive division instruction, we implement
23381 * divide-by-3 through multiplication, followed by further
23382 * division by 8 through 3-bit right shift.
23383 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
23384 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
23385 *
23386 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
23387 */
23388 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
23389 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
23390 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
23391
23392 /* call perf_snapshot_branch_stack implementation */
23393 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
23394 /* if (entry_cnt == 0) return -ENOENT */
23395 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
23396 /* return entry_cnt * sizeof(struct perf_branch_entry) */
23397 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
23398 insn_buf[7] = BPF_JMP_A(3);
23399 /* return -EINVAL; */
23400 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23401 insn_buf[9] = BPF_JMP_A(1);
23402 /* return -ENOENT; */
23403 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
23404 cnt = 11;
23405
23406 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23407 if (!new_prog)
23408 return -ENOMEM;
23409
23410 delta += cnt - 1;
23411 env->prog = prog = new_prog;
23412 insn = new_prog->insnsi + i + delta;
23413 goto next_insn;
23414 }
23415
23416 /* Implement bpf_kptr_xchg inline */
23417 if (prog->jit_requested && BITS_PER_LONG == 64 &&
23418 insn->imm == BPF_FUNC_kptr_xchg &&
23419 bpf_jit_supports_ptr_xchg()) {
23420 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
23421 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
23422 cnt = 2;
23423
23424 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23425 if (!new_prog)
23426 return -ENOMEM;
23427
23428 delta += cnt - 1;
23429 env->prog = prog = new_prog;
23430 insn = new_prog->insnsi + i + delta;
23431 goto next_insn;
23432 }
23433 patch_call_imm:
23434 fn = env->ops->get_func_proto(insn->imm, env->prog);
23435 /* all functions that have prototype and verifier allowed
23436 * programs to call them, must be real in-kernel functions
23437 */
23438 if (!fn->func) {
23439 verifier_bug(env,
23440 "not inlined functions %s#%d is missing func",
23441 func_id_name(insn->imm), insn->imm);
23442 return -EFAULT;
23443 }
23444 insn->imm = fn->func - __bpf_call_base;
23445 next_insn:
23446 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23447 subprogs[cur_subprog].stack_depth += stack_depth_extra;
23448 subprogs[cur_subprog].stack_extra = stack_depth_extra;
23449
23450 stack_depth = subprogs[cur_subprog].stack_depth;
23451 if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
23452 verbose(env, "stack size %d(extra %d) is too large\n",
23453 stack_depth, stack_depth_extra);
23454 return -EINVAL;
23455 }
23456 cur_subprog++;
23457 stack_depth = subprogs[cur_subprog].stack_depth;
23458 stack_depth_extra = 0;
23459 }
23460 i++;
23461 insn++;
23462 }
23463
23464 env->prog->aux->stack_depth = subprogs[0].stack_depth;
23465 for (i = 0; i < env->subprog_cnt; i++) {
23466 int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
23467 int subprog_start = subprogs[i].start;
23468 int stack_slots = subprogs[i].stack_extra / 8;
23469 int slots = delta, cnt = 0;
23470
23471 if (!stack_slots)
23472 continue;
23473 /* We need two slots in case timed may_goto is supported. */
23474 if (stack_slots > slots) {
23475 verifier_bug(env, "stack_slots supports may_goto only");
23476 return -EFAULT;
23477 }
23478
23479 stack_depth = subprogs[i].stack_depth;
23480 if (bpf_jit_supports_timed_may_goto()) {
23481 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23482 BPF_MAX_TIMED_LOOPS);
23483 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
23484 } else {
23485 /* Add ST insn to subprog prologue to init extra stack */
23486 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23487 BPF_MAX_LOOPS);
23488 }
23489 /* Copy first actual insn to preserve it */
23490 insn_buf[cnt++] = env->prog->insnsi[subprog_start];
23491
23492 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
23493 if (!new_prog)
23494 return -ENOMEM;
23495 env->prog = prog = new_prog;
23496 /*
23497 * If may_goto is a first insn of a prog there could be a jmp
23498 * insn that points to it, hence adjust all such jmps to point
23499 * to insn after BPF_ST that inits may_goto count.
23500 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
23501 */
23502 WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
23503 }
23504
23505 /* Since poke tab is now finalized, publish aux to tracker. */
23506 for (i = 0; i < prog->aux->size_poke_tab; i++) {
23507 map_ptr = prog->aux->poke_tab[i].tail_call.map;
23508 if (!map_ptr->ops->map_poke_track ||
23509 !map_ptr->ops->map_poke_untrack ||
23510 !map_ptr->ops->map_poke_run) {
23511 verifier_bug(env, "poke tab is misconfigured");
23512 return -EFAULT;
23513 }
23514
23515 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
23516 if (ret < 0) {
23517 verbose(env, "tracking tail call prog failed\n");
23518 return ret;
23519 }
23520 }
23521
23522 ret = sort_kfunc_descs_by_imm_off(env);
23523 if (ret)
23524 return ret;
23525
23526 return 0;
23527 }
23528
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * total_cnt)23529 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
23530 int position,
23531 s32 stack_base,
23532 u32 callback_subprogno,
23533 u32 *total_cnt)
23534 {
23535 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
23536 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
23537 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
23538 int reg_loop_max = BPF_REG_6;
23539 int reg_loop_cnt = BPF_REG_7;
23540 int reg_loop_ctx = BPF_REG_8;
23541
23542 struct bpf_insn *insn_buf = env->insn_buf;
23543 struct bpf_prog *new_prog;
23544 u32 callback_start;
23545 u32 call_insn_offset;
23546 s32 callback_offset;
23547 u32 cnt = 0;
23548
23549 /* This represents an inlined version of bpf_iter.c:bpf_loop,
23550 * be careful to modify this code in sync.
23551 */
23552
23553 /* Return error and jump to the end of the patch if
23554 * expected number of iterations is too big.
23555 */
23556 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
23557 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
23558 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
23559 /* spill R6, R7, R8 to use these as loop vars */
23560 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
23561 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
23562 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
23563 /* initialize loop vars */
23564 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
23565 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
23566 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
23567 /* loop header,
23568 * if reg_loop_cnt >= reg_loop_max skip the loop body
23569 */
23570 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
23571 /* callback call,
23572 * correct callback offset would be set after patching
23573 */
23574 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
23575 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
23576 insn_buf[cnt++] = BPF_CALL_REL(0);
23577 /* increment loop counter */
23578 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
23579 /* jump to loop header if callback returned 0 */
23580 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
23581 /* return value of bpf_loop,
23582 * set R0 to the number of iterations
23583 */
23584 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
23585 /* restore original values of R6, R7, R8 */
23586 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
23587 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
23588 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
23589
23590 *total_cnt = cnt;
23591 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
23592 if (!new_prog)
23593 return new_prog;
23594
23595 /* callback start is known only after patching */
23596 callback_start = env->subprog_info[callback_subprogno].start;
23597 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
23598 call_insn_offset = position + 12;
23599 callback_offset = callback_start - call_insn_offset - 1;
23600 new_prog->insnsi[call_insn_offset].imm = callback_offset;
23601
23602 return new_prog;
23603 }
23604
is_bpf_loop_call(struct bpf_insn * insn)23605 static bool is_bpf_loop_call(struct bpf_insn *insn)
23606 {
23607 return insn->code == (BPF_JMP | BPF_CALL) &&
23608 insn->src_reg == 0 &&
23609 insn->imm == BPF_FUNC_loop;
23610 }
23611
23612 /* For all sub-programs in the program (including main) check
23613 * insn_aux_data to see if there are bpf_loop calls that require
23614 * inlining. If such calls are found the calls are replaced with a
23615 * sequence of instructions produced by `inline_bpf_loop` function and
23616 * subprog stack_depth is increased by the size of 3 registers.
23617 * This stack space is used to spill values of the R6, R7, R8. These
23618 * registers are used to store the loop bound, counter and context
23619 * variables.
23620 */
optimize_bpf_loop(struct bpf_verifier_env * env)23621 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23622 {
23623 struct bpf_subprog_info *subprogs = env->subprog_info;
23624 int i, cur_subprog = 0, cnt, delta = 0;
23625 struct bpf_insn *insn = env->prog->insnsi;
23626 int insn_cnt = env->prog->len;
23627 u16 stack_depth = subprogs[cur_subprog].stack_depth;
23628 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23629 u16 stack_depth_extra = 0;
23630
23631 for (i = 0; i < insn_cnt; i++, insn++) {
23632 struct bpf_loop_inline_state *inline_state =
23633 &env->insn_aux_data[i + delta].loop_inline_state;
23634
23635 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23636 struct bpf_prog *new_prog;
23637
23638 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23639 new_prog = inline_bpf_loop(env,
23640 i + delta,
23641 -(stack_depth + stack_depth_extra),
23642 inline_state->callback_subprogno,
23643 &cnt);
23644 if (!new_prog)
23645 return -ENOMEM;
23646
23647 delta += cnt - 1;
23648 env->prog = new_prog;
23649 insn = new_prog->insnsi + i + delta;
23650 }
23651
23652 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23653 subprogs[cur_subprog].stack_depth += stack_depth_extra;
23654 cur_subprog++;
23655 stack_depth = subprogs[cur_subprog].stack_depth;
23656 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23657 stack_depth_extra = 0;
23658 }
23659 }
23660
23661 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23662
23663 return 0;
23664 }
23665
23666 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23667 * adjust subprograms stack depth when possible.
23668 */
remove_fastcall_spills_fills(struct bpf_verifier_env * env)23669 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23670 {
23671 struct bpf_subprog_info *subprog = env->subprog_info;
23672 struct bpf_insn_aux_data *aux = env->insn_aux_data;
23673 struct bpf_insn *insn = env->prog->insnsi;
23674 int insn_cnt = env->prog->len;
23675 u32 spills_num;
23676 bool modified = false;
23677 int i, j;
23678
23679 for (i = 0; i < insn_cnt; i++, insn++) {
23680 if (aux[i].fastcall_spills_num > 0) {
23681 spills_num = aux[i].fastcall_spills_num;
23682 /* NOPs would be removed by opt_remove_nops() */
23683 for (j = 1; j <= spills_num; ++j) {
23684 *(insn - j) = NOP;
23685 *(insn + j) = NOP;
23686 }
23687 modified = true;
23688 }
23689 if ((subprog + 1)->start == i + 1) {
23690 if (modified && !subprog->keep_fastcall_stack)
23691 subprog->stack_depth = -subprog->fastcall_stack_off;
23692 subprog++;
23693 modified = false;
23694 }
23695 }
23696
23697 return 0;
23698 }
23699
free_states(struct bpf_verifier_env * env)23700 static void free_states(struct bpf_verifier_env *env)
23701 {
23702 struct bpf_verifier_state_list *sl;
23703 struct list_head *head, *pos, *tmp;
23704 struct bpf_scc_info *info;
23705 int i, j;
23706
23707 free_verifier_state(env->cur_state, true);
23708 env->cur_state = NULL;
23709 while (!pop_stack(env, NULL, NULL, false));
23710
23711 list_for_each_safe(pos, tmp, &env->free_list) {
23712 sl = container_of(pos, struct bpf_verifier_state_list, node);
23713 free_verifier_state(&sl->state, false);
23714 kfree(sl);
23715 }
23716 INIT_LIST_HEAD(&env->free_list);
23717
23718 for (i = 0; i < env->scc_cnt; ++i) {
23719 info = env->scc_info[i];
23720 if (!info)
23721 continue;
23722 for (j = 0; j < info->num_visits; j++)
23723 free_backedges(&info->visits[j]);
23724 kvfree(info);
23725 env->scc_info[i] = NULL;
23726 }
23727
23728 if (!env->explored_states)
23729 return;
23730
23731 for (i = 0; i < state_htab_size(env); i++) {
23732 head = &env->explored_states[i];
23733
23734 list_for_each_safe(pos, tmp, head) {
23735 sl = container_of(pos, struct bpf_verifier_state_list, node);
23736 free_verifier_state(&sl->state, false);
23737 kfree(sl);
23738 }
23739 INIT_LIST_HEAD(&env->explored_states[i]);
23740 }
23741 }
23742
do_check_common(struct bpf_verifier_env * env,int subprog)23743 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23744 {
23745 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23746 struct bpf_subprog_info *sub = subprog_info(env, subprog);
23747 struct bpf_prog_aux *aux = env->prog->aux;
23748 struct bpf_verifier_state *state;
23749 struct bpf_reg_state *regs;
23750 int ret, i;
23751
23752 env->prev_linfo = NULL;
23753 env->pass_cnt++;
23754
23755 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23756 if (!state)
23757 return -ENOMEM;
23758 state->curframe = 0;
23759 state->speculative = false;
23760 state->branches = 1;
23761 state->in_sleepable = env->prog->sleepable;
23762 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23763 if (!state->frame[0]) {
23764 kfree(state);
23765 return -ENOMEM;
23766 }
23767 env->cur_state = state;
23768 init_func_state(env, state->frame[0],
23769 BPF_MAIN_FUNC /* callsite */,
23770 0 /* frameno */,
23771 subprog);
23772 state->first_insn_idx = env->subprog_info[subprog].start;
23773 state->last_insn_idx = -1;
23774
23775 regs = state->frame[state->curframe]->regs;
23776 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23777 const char *sub_name = subprog_name(env, subprog);
23778 struct bpf_subprog_arg_info *arg;
23779 struct bpf_reg_state *reg;
23780
23781 if (env->log.level & BPF_LOG_LEVEL)
23782 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23783 ret = btf_prepare_func_args(env, subprog);
23784 if (ret)
23785 goto out;
23786
23787 if (subprog_is_exc_cb(env, subprog)) {
23788 state->frame[0]->in_exception_callback_fn = true;
23789 /* We have already ensured that the callback returns an integer, just
23790 * like all global subprogs. We need to determine it only has a single
23791 * scalar argument.
23792 */
23793 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23794 verbose(env, "exception cb only supports single integer argument\n");
23795 ret = -EINVAL;
23796 goto out;
23797 }
23798 }
23799 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23800 arg = &sub->args[i - BPF_REG_1];
23801 reg = ®s[i];
23802
23803 if (arg->arg_type == ARG_PTR_TO_CTX) {
23804 reg->type = PTR_TO_CTX;
23805 mark_reg_known_zero(env, regs, i);
23806 } else if (arg->arg_type == ARG_ANYTHING) {
23807 reg->type = SCALAR_VALUE;
23808 mark_reg_unknown(env, regs, i);
23809 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23810 /* assume unspecial LOCAL dynptr type */
23811 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23812 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23813 reg->type = PTR_TO_MEM;
23814 reg->type |= arg->arg_type &
23815 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23816 mark_reg_known_zero(env, regs, i);
23817 reg->mem_size = arg->mem_size;
23818 if (arg->arg_type & PTR_MAYBE_NULL)
23819 reg->id = ++env->id_gen;
23820 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23821 reg->type = PTR_TO_BTF_ID;
23822 if (arg->arg_type & PTR_MAYBE_NULL)
23823 reg->type |= PTR_MAYBE_NULL;
23824 if (arg->arg_type & PTR_UNTRUSTED)
23825 reg->type |= PTR_UNTRUSTED;
23826 if (arg->arg_type & PTR_TRUSTED)
23827 reg->type |= PTR_TRUSTED;
23828 mark_reg_known_zero(env, regs, i);
23829 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23830 reg->btf_id = arg->btf_id;
23831 reg->id = ++env->id_gen;
23832 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23833 /* caller can pass either PTR_TO_ARENA or SCALAR */
23834 mark_reg_unknown(env, regs, i);
23835 } else {
23836 verifier_bug(env, "unhandled arg#%d type %d",
23837 i - BPF_REG_1, arg->arg_type);
23838 ret = -EFAULT;
23839 goto out;
23840 }
23841 }
23842 } else {
23843 /* if main BPF program has associated BTF info, validate that
23844 * it's matching expected signature, and otherwise mark BTF
23845 * info for main program as unreliable
23846 */
23847 if (env->prog->aux->func_info_aux) {
23848 ret = btf_prepare_func_args(env, 0);
23849 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23850 env->prog->aux->func_info_aux[0].unreliable = true;
23851 }
23852
23853 /* 1st arg to a function */
23854 regs[BPF_REG_1].type = PTR_TO_CTX;
23855 mark_reg_known_zero(env, regs, BPF_REG_1);
23856 }
23857
23858 /* Acquire references for struct_ops program arguments tagged with "__ref" */
23859 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23860 for (i = 0; i < aux->ctx_arg_info_size; i++)
23861 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23862 acquire_reference(env, 0) : 0;
23863 }
23864
23865 ret = do_check(env);
23866 out:
23867 if (!ret && pop_log)
23868 bpf_vlog_reset(&env->log, 0);
23869 free_states(env);
23870 return ret;
23871 }
23872
23873 /* Lazily verify all global functions based on their BTF, if they are called
23874 * from main BPF program or any of subprograms transitively.
23875 * BPF global subprogs called from dead code are not validated.
23876 * All callable global functions must pass verification.
23877 * Otherwise the whole program is rejected.
23878 * Consider:
23879 * int bar(int);
23880 * int foo(int f)
23881 * {
23882 * return bar(f);
23883 * }
23884 * int bar(int b)
23885 * {
23886 * ...
23887 * }
23888 * foo() will be verified first for R1=any_scalar_value. During verification it
23889 * will be assumed that bar() already verified successfully and call to bar()
23890 * from foo() will be checked for type match only. Later bar() will be verified
23891 * independently to check that it's safe for R1=any_scalar_value.
23892 */
do_check_subprogs(struct bpf_verifier_env * env)23893 static int do_check_subprogs(struct bpf_verifier_env *env)
23894 {
23895 struct bpf_prog_aux *aux = env->prog->aux;
23896 struct bpf_func_info_aux *sub_aux;
23897 int i, ret, new_cnt;
23898
23899 if (!aux->func_info)
23900 return 0;
23901
23902 /* exception callback is presumed to be always called */
23903 if (env->exception_callback_subprog)
23904 subprog_aux(env, env->exception_callback_subprog)->called = true;
23905
23906 again:
23907 new_cnt = 0;
23908 for (i = 1; i < env->subprog_cnt; i++) {
23909 if (!subprog_is_global(env, i))
23910 continue;
23911
23912 sub_aux = subprog_aux(env, i);
23913 if (!sub_aux->called || sub_aux->verified)
23914 continue;
23915
23916 env->insn_idx = env->subprog_info[i].start;
23917 WARN_ON_ONCE(env->insn_idx == 0);
23918 ret = do_check_common(env, i);
23919 if (ret) {
23920 return ret;
23921 } else if (env->log.level & BPF_LOG_LEVEL) {
23922 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23923 i, subprog_name(env, i));
23924 }
23925
23926 /* We verified new global subprog, it might have called some
23927 * more global subprogs that we haven't verified yet, so we
23928 * need to do another pass over subprogs to verify those.
23929 */
23930 sub_aux->verified = true;
23931 new_cnt++;
23932 }
23933
23934 /* We can't loop forever as we verify at least one global subprog on
23935 * each pass.
23936 */
23937 if (new_cnt)
23938 goto again;
23939
23940 return 0;
23941 }
23942
do_check_main(struct bpf_verifier_env * env)23943 static int do_check_main(struct bpf_verifier_env *env)
23944 {
23945 int ret;
23946
23947 env->insn_idx = 0;
23948 ret = do_check_common(env, 0);
23949 if (!ret)
23950 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23951 return ret;
23952 }
23953
23954
print_verification_stats(struct bpf_verifier_env * env)23955 static void print_verification_stats(struct bpf_verifier_env *env)
23956 {
23957 int i;
23958
23959 if (env->log.level & BPF_LOG_STATS) {
23960 verbose(env, "verification time %lld usec\n",
23961 div_u64(env->verification_time, 1000));
23962 verbose(env, "stack depth ");
23963 for (i = 0; i < env->subprog_cnt; i++) {
23964 u32 depth = env->subprog_info[i].stack_depth;
23965
23966 verbose(env, "%d", depth);
23967 if (i + 1 < env->subprog_cnt)
23968 verbose(env, "+");
23969 }
23970 verbose(env, "\n");
23971 }
23972 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23973 "total_states %d peak_states %d mark_read %d\n",
23974 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23975 env->max_states_per_insn, env->total_states,
23976 env->peak_states, env->longest_mark_read_walk);
23977 }
23978
bpf_prog_ctx_arg_info_init(struct bpf_prog * prog,const struct bpf_ctx_arg_aux * info,u32 cnt)23979 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23980 const struct bpf_ctx_arg_aux *info, u32 cnt)
23981 {
23982 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23983 prog->aux->ctx_arg_info_size = cnt;
23984
23985 return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23986 }
23987
check_struct_ops_btf_id(struct bpf_verifier_env * env)23988 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23989 {
23990 const struct btf_type *t, *func_proto;
23991 const struct bpf_struct_ops_desc *st_ops_desc;
23992 const struct bpf_struct_ops *st_ops;
23993 const struct btf_member *member;
23994 struct bpf_prog *prog = env->prog;
23995 bool has_refcounted_arg = false;
23996 u32 btf_id, member_idx, member_off;
23997 struct btf *btf;
23998 const char *mname;
23999 int i, err;
24000
24001 if (!prog->gpl_compatible) {
24002 verbose(env, "struct ops programs must have a GPL compatible license\n");
24003 return -EINVAL;
24004 }
24005
24006 if (!prog->aux->attach_btf_id)
24007 return -ENOTSUPP;
24008
24009 btf = prog->aux->attach_btf;
24010 if (btf_is_module(btf)) {
24011 /* Make sure st_ops is valid through the lifetime of env */
24012 env->attach_btf_mod = btf_try_get_module(btf);
24013 if (!env->attach_btf_mod) {
24014 verbose(env, "struct_ops module %s is not found\n",
24015 btf_get_name(btf));
24016 return -ENOTSUPP;
24017 }
24018 }
24019
24020 btf_id = prog->aux->attach_btf_id;
24021 st_ops_desc = bpf_struct_ops_find(btf, btf_id);
24022 if (!st_ops_desc) {
24023 verbose(env, "attach_btf_id %u is not a supported struct\n",
24024 btf_id);
24025 return -ENOTSUPP;
24026 }
24027 st_ops = st_ops_desc->st_ops;
24028
24029 t = st_ops_desc->type;
24030 member_idx = prog->expected_attach_type;
24031 if (member_idx >= btf_type_vlen(t)) {
24032 verbose(env, "attach to invalid member idx %u of struct %s\n",
24033 member_idx, st_ops->name);
24034 return -EINVAL;
24035 }
24036
24037 member = &btf_type_member(t)[member_idx];
24038 mname = btf_name_by_offset(btf, member->name_off);
24039 func_proto = btf_type_resolve_func_ptr(btf, member->type,
24040 NULL);
24041 if (!func_proto) {
24042 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
24043 mname, member_idx, st_ops->name);
24044 return -EINVAL;
24045 }
24046
24047 member_off = __btf_member_bit_offset(t, member) / 8;
24048 err = bpf_struct_ops_supported(st_ops, member_off);
24049 if (err) {
24050 verbose(env, "attach to unsupported member %s of struct %s\n",
24051 mname, st_ops->name);
24052 return err;
24053 }
24054
24055 if (st_ops->check_member) {
24056 err = st_ops->check_member(t, member, prog);
24057
24058 if (err) {
24059 verbose(env, "attach to unsupported member %s of struct %s\n",
24060 mname, st_ops->name);
24061 return err;
24062 }
24063 }
24064
24065 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
24066 verbose(env, "Private stack not supported by jit\n");
24067 return -EACCES;
24068 }
24069
24070 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
24071 if (st_ops_desc->arg_info[member_idx].info->refcounted) {
24072 has_refcounted_arg = true;
24073 break;
24074 }
24075 }
24076
24077 /* Tail call is not allowed for programs with refcounted arguments since we
24078 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
24079 */
24080 for (i = 0; i < env->subprog_cnt; i++) {
24081 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
24082 verbose(env, "program with __ref argument cannot tail call\n");
24083 return -EINVAL;
24084 }
24085 }
24086
24087 prog->aux->st_ops = st_ops;
24088 prog->aux->attach_st_ops_member_off = member_off;
24089
24090 prog->aux->attach_func_proto = func_proto;
24091 prog->aux->attach_func_name = mname;
24092 env->ops = st_ops->verifier_ops;
24093
24094 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
24095 st_ops_desc->arg_info[member_idx].cnt);
24096 }
24097 #define SECURITY_PREFIX "security_"
24098
check_attach_modify_return(unsigned long addr,const char * func_name)24099 static int check_attach_modify_return(unsigned long addr, const char *func_name)
24100 {
24101 if (within_error_injection_list(addr) ||
24102 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
24103 return 0;
24104
24105 return -EINVAL;
24106 }
24107
24108 /* list of non-sleepable functions that are otherwise on
24109 * ALLOW_ERROR_INJECTION list
24110 */
24111 BTF_SET_START(btf_non_sleepable_error_inject)
24112 /* Three functions below can be called from sleepable and non-sleepable context.
24113 * Assume non-sleepable from bpf safety point of view.
24114 */
BTF_ID(func,__filemap_add_folio)24115 BTF_ID(func, __filemap_add_folio)
24116 #ifdef CONFIG_FAIL_PAGE_ALLOC
24117 BTF_ID(func, should_fail_alloc_page)
24118 #endif
24119 #ifdef CONFIG_FAILSLAB
24120 BTF_ID(func, should_failslab)
24121 #endif
24122 BTF_SET_END(btf_non_sleepable_error_inject)
24123
24124 static int check_non_sleepable_error_inject(u32 btf_id)
24125 {
24126 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
24127 }
24128
bpf_check_attach_target(struct bpf_verifier_log * log,const struct bpf_prog * prog,const struct bpf_prog * tgt_prog,u32 btf_id,struct bpf_attach_target_info * tgt_info)24129 int bpf_check_attach_target(struct bpf_verifier_log *log,
24130 const struct bpf_prog *prog,
24131 const struct bpf_prog *tgt_prog,
24132 u32 btf_id,
24133 struct bpf_attach_target_info *tgt_info)
24134 {
24135 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
24136 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
24137 char trace_symbol[KSYM_SYMBOL_LEN];
24138 const char prefix[] = "btf_trace_";
24139 struct bpf_raw_event_map *btp;
24140 int ret = 0, subprog = -1, i;
24141 const struct btf_type *t;
24142 bool conservative = true;
24143 const char *tname, *fname;
24144 struct btf *btf;
24145 long addr = 0;
24146 struct module *mod = NULL;
24147
24148 if (!btf_id) {
24149 bpf_log(log, "Tracing programs must provide btf_id\n");
24150 return -EINVAL;
24151 }
24152 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
24153 if (!btf) {
24154 bpf_log(log,
24155 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
24156 return -EINVAL;
24157 }
24158 t = btf_type_by_id(btf, btf_id);
24159 if (!t) {
24160 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
24161 return -EINVAL;
24162 }
24163 tname = btf_name_by_offset(btf, t->name_off);
24164 if (!tname) {
24165 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
24166 return -EINVAL;
24167 }
24168 if (tgt_prog) {
24169 struct bpf_prog_aux *aux = tgt_prog->aux;
24170 bool tgt_changes_pkt_data;
24171 bool tgt_might_sleep;
24172
24173 if (bpf_prog_is_dev_bound(prog->aux) &&
24174 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
24175 bpf_log(log, "Target program bound device mismatch");
24176 return -EINVAL;
24177 }
24178
24179 for (i = 0; i < aux->func_info_cnt; i++)
24180 if (aux->func_info[i].type_id == btf_id) {
24181 subprog = i;
24182 break;
24183 }
24184 if (subprog == -1) {
24185 bpf_log(log, "Subprog %s doesn't exist\n", tname);
24186 return -EINVAL;
24187 }
24188 if (aux->func && aux->func[subprog]->aux->exception_cb) {
24189 bpf_log(log,
24190 "%s programs cannot attach to exception callback\n",
24191 prog_extension ? "Extension" : "FENTRY/FEXIT");
24192 return -EINVAL;
24193 }
24194 conservative = aux->func_info_aux[subprog].unreliable;
24195 if (prog_extension) {
24196 if (conservative) {
24197 bpf_log(log,
24198 "Cannot replace static functions\n");
24199 return -EINVAL;
24200 }
24201 if (!prog->jit_requested) {
24202 bpf_log(log,
24203 "Extension programs should be JITed\n");
24204 return -EINVAL;
24205 }
24206 tgt_changes_pkt_data = aux->func
24207 ? aux->func[subprog]->aux->changes_pkt_data
24208 : aux->changes_pkt_data;
24209 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
24210 bpf_log(log,
24211 "Extension program changes packet data, while original does not\n");
24212 return -EINVAL;
24213 }
24214
24215 tgt_might_sleep = aux->func
24216 ? aux->func[subprog]->aux->might_sleep
24217 : aux->might_sleep;
24218 if (prog->aux->might_sleep && !tgt_might_sleep) {
24219 bpf_log(log,
24220 "Extension program may sleep, while original does not\n");
24221 return -EINVAL;
24222 }
24223 }
24224 if (!tgt_prog->jited) {
24225 bpf_log(log, "Can attach to only JITed progs\n");
24226 return -EINVAL;
24227 }
24228 if (prog_tracing) {
24229 if (aux->attach_tracing_prog) {
24230 /*
24231 * Target program is an fentry/fexit which is already attached
24232 * to another tracing program. More levels of nesting
24233 * attachment are not allowed.
24234 */
24235 bpf_log(log, "Cannot nest tracing program attach more than once\n");
24236 return -EINVAL;
24237 }
24238 } else if (tgt_prog->type == prog->type) {
24239 /*
24240 * To avoid potential call chain cycles, prevent attaching of a
24241 * program extension to another extension. It's ok to attach
24242 * fentry/fexit to extension program.
24243 */
24244 bpf_log(log, "Cannot recursively attach\n");
24245 return -EINVAL;
24246 }
24247 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
24248 prog_extension &&
24249 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
24250 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
24251 /* Program extensions can extend all program types
24252 * except fentry/fexit. The reason is the following.
24253 * The fentry/fexit programs are used for performance
24254 * analysis, stats and can be attached to any program
24255 * type. When extension program is replacing XDP function
24256 * it is necessary to allow performance analysis of all
24257 * functions. Both original XDP program and its program
24258 * extension. Hence attaching fentry/fexit to
24259 * BPF_PROG_TYPE_EXT is allowed. If extending of
24260 * fentry/fexit was allowed it would be possible to create
24261 * long call chain fentry->extension->fentry->extension
24262 * beyond reasonable stack size. Hence extending fentry
24263 * is not allowed.
24264 */
24265 bpf_log(log, "Cannot extend fentry/fexit\n");
24266 return -EINVAL;
24267 }
24268 } else {
24269 if (prog_extension) {
24270 bpf_log(log, "Cannot replace kernel functions\n");
24271 return -EINVAL;
24272 }
24273 }
24274
24275 switch (prog->expected_attach_type) {
24276 case BPF_TRACE_RAW_TP:
24277 if (tgt_prog) {
24278 bpf_log(log,
24279 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
24280 return -EINVAL;
24281 }
24282 if (!btf_type_is_typedef(t)) {
24283 bpf_log(log, "attach_btf_id %u is not a typedef\n",
24284 btf_id);
24285 return -EINVAL;
24286 }
24287 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
24288 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
24289 btf_id, tname);
24290 return -EINVAL;
24291 }
24292 tname += sizeof(prefix) - 1;
24293
24294 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument
24295 * names. Thus using bpf_raw_event_map to get argument names.
24296 */
24297 btp = bpf_get_raw_tracepoint(tname);
24298 if (!btp)
24299 return -EINVAL;
24300 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
24301 trace_symbol);
24302 bpf_put_raw_tracepoint(btp);
24303
24304 if (fname)
24305 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
24306
24307 if (!fname || ret < 0) {
24308 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
24309 prefix, tname);
24310 t = btf_type_by_id(btf, t->type);
24311 if (!btf_type_is_ptr(t))
24312 /* should never happen in valid vmlinux build */
24313 return -EINVAL;
24314 } else {
24315 t = btf_type_by_id(btf, ret);
24316 if (!btf_type_is_func(t))
24317 /* should never happen in valid vmlinux build */
24318 return -EINVAL;
24319 }
24320
24321 t = btf_type_by_id(btf, t->type);
24322 if (!btf_type_is_func_proto(t))
24323 /* should never happen in valid vmlinux build */
24324 return -EINVAL;
24325
24326 break;
24327 case BPF_TRACE_ITER:
24328 if (!btf_type_is_func(t)) {
24329 bpf_log(log, "attach_btf_id %u is not a function\n",
24330 btf_id);
24331 return -EINVAL;
24332 }
24333 t = btf_type_by_id(btf, t->type);
24334 if (!btf_type_is_func_proto(t))
24335 return -EINVAL;
24336 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24337 if (ret)
24338 return ret;
24339 break;
24340 default:
24341 if (!prog_extension)
24342 return -EINVAL;
24343 fallthrough;
24344 case BPF_MODIFY_RETURN:
24345 case BPF_LSM_MAC:
24346 case BPF_LSM_CGROUP:
24347 case BPF_TRACE_FENTRY:
24348 case BPF_TRACE_FEXIT:
24349 if (!btf_type_is_func(t)) {
24350 bpf_log(log, "attach_btf_id %u is not a function\n",
24351 btf_id);
24352 return -EINVAL;
24353 }
24354 if (prog_extension &&
24355 btf_check_type_match(log, prog, btf, t))
24356 return -EINVAL;
24357 t = btf_type_by_id(btf, t->type);
24358 if (!btf_type_is_func_proto(t))
24359 return -EINVAL;
24360
24361 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
24362 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
24363 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
24364 return -EINVAL;
24365
24366 if (tgt_prog && conservative)
24367 t = NULL;
24368
24369 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24370 if (ret < 0)
24371 return ret;
24372
24373 if (tgt_prog) {
24374 if (subprog == 0)
24375 addr = (long) tgt_prog->bpf_func;
24376 else
24377 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
24378 } else {
24379 if (btf_is_module(btf)) {
24380 mod = btf_try_get_module(btf);
24381 if (mod)
24382 addr = find_kallsyms_symbol_value(mod, tname);
24383 else
24384 addr = 0;
24385 } else {
24386 addr = kallsyms_lookup_name(tname);
24387 }
24388 if (!addr) {
24389 module_put(mod);
24390 bpf_log(log,
24391 "The address of function %s cannot be found\n",
24392 tname);
24393 return -ENOENT;
24394 }
24395 }
24396
24397 if (prog->sleepable) {
24398 ret = -EINVAL;
24399 switch (prog->type) {
24400 case BPF_PROG_TYPE_TRACING:
24401
24402 /* fentry/fexit/fmod_ret progs can be sleepable if they are
24403 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
24404 */
24405 if (!check_non_sleepable_error_inject(btf_id) &&
24406 within_error_injection_list(addr))
24407 ret = 0;
24408 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
24409 * in the fmodret id set with the KF_SLEEPABLE flag.
24410 */
24411 else {
24412 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
24413 prog);
24414
24415 if (flags && (*flags & KF_SLEEPABLE))
24416 ret = 0;
24417 }
24418 break;
24419 case BPF_PROG_TYPE_LSM:
24420 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
24421 * Only some of them are sleepable.
24422 */
24423 if (bpf_lsm_is_sleepable_hook(btf_id))
24424 ret = 0;
24425 break;
24426 default:
24427 break;
24428 }
24429 if (ret) {
24430 module_put(mod);
24431 bpf_log(log, "%s is not sleepable\n", tname);
24432 return ret;
24433 }
24434 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
24435 if (tgt_prog) {
24436 module_put(mod);
24437 bpf_log(log, "can't modify return codes of BPF programs\n");
24438 return -EINVAL;
24439 }
24440 ret = -EINVAL;
24441 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
24442 !check_attach_modify_return(addr, tname))
24443 ret = 0;
24444 if (ret) {
24445 module_put(mod);
24446 bpf_log(log, "%s() is not modifiable\n", tname);
24447 return ret;
24448 }
24449 }
24450
24451 break;
24452 }
24453 tgt_info->tgt_addr = addr;
24454 tgt_info->tgt_name = tname;
24455 tgt_info->tgt_type = t;
24456 tgt_info->tgt_mod = mod;
24457 return 0;
24458 }
24459
BTF_SET_START(btf_id_deny)24460 BTF_SET_START(btf_id_deny)
24461 BTF_ID_UNUSED
24462 #ifdef CONFIG_SMP
24463 BTF_ID(func, ___migrate_enable)
24464 BTF_ID(func, migrate_disable)
24465 BTF_ID(func, migrate_enable)
24466 #endif
24467 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
24468 BTF_ID(func, rcu_read_unlock_strict)
24469 #endif
24470 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
24471 BTF_ID(func, preempt_count_add)
24472 BTF_ID(func, preempt_count_sub)
24473 #endif
24474 #ifdef CONFIG_PREEMPT_RCU
24475 BTF_ID(func, __rcu_read_lock)
24476 BTF_ID(func, __rcu_read_unlock)
24477 #endif
24478 BTF_SET_END(btf_id_deny)
24479
24480 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
24481 * Currently, we must manually list all __noreturn functions here. Once a more
24482 * robust solution is implemented, this workaround can be removed.
24483 */
24484 BTF_SET_START(noreturn_deny)
24485 #ifdef CONFIG_IA32_EMULATION
24486 BTF_ID(func, __ia32_sys_exit)
24487 BTF_ID(func, __ia32_sys_exit_group)
24488 #endif
24489 #ifdef CONFIG_KUNIT
24490 BTF_ID(func, __kunit_abort)
24491 BTF_ID(func, kunit_try_catch_throw)
24492 #endif
24493 #ifdef CONFIG_MODULES
24494 BTF_ID(func, __module_put_and_kthread_exit)
24495 #endif
24496 #ifdef CONFIG_X86_64
24497 BTF_ID(func, __x64_sys_exit)
24498 BTF_ID(func, __x64_sys_exit_group)
24499 #endif
24500 BTF_ID(func, do_exit)
24501 BTF_ID(func, do_group_exit)
24502 BTF_ID(func, kthread_complete_and_exit)
24503 BTF_ID(func, kthread_exit)
24504 BTF_ID(func, make_task_dead)
24505 BTF_SET_END(noreturn_deny)
24506
24507 static bool can_be_sleepable(struct bpf_prog *prog)
24508 {
24509 if (prog->type == BPF_PROG_TYPE_TRACING) {
24510 switch (prog->expected_attach_type) {
24511 case BPF_TRACE_FENTRY:
24512 case BPF_TRACE_FEXIT:
24513 case BPF_MODIFY_RETURN:
24514 case BPF_TRACE_ITER:
24515 return true;
24516 default:
24517 return false;
24518 }
24519 }
24520 return prog->type == BPF_PROG_TYPE_LSM ||
24521 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
24522 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
24523 }
24524
check_attach_btf_id(struct bpf_verifier_env * env)24525 static int check_attach_btf_id(struct bpf_verifier_env *env)
24526 {
24527 struct bpf_prog *prog = env->prog;
24528 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
24529 struct bpf_attach_target_info tgt_info = {};
24530 u32 btf_id = prog->aux->attach_btf_id;
24531 struct bpf_trampoline *tr;
24532 int ret;
24533 u64 key;
24534
24535 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
24536 if (prog->sleepable)
24537 /* attach_btf_id checked to be zero already */
24538 return 0;
24539 verbose(env, "Syscall programs can only be sleepable\n");
24540 return -EINVAL;
24541 }
24542
24543 if (prog->sleepable && !can_be_sleepable(prog)) {
24544 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
24545 return -EINVAL;
24546 }
24547
24548 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
24549 return check_struct_ops_btf_id(env);
24550
24551 if (prog->type != BPF_PROG_TYPE_TRACING &&
24552 prog->type != BPF_PROG_TYPE_LSM &&
24553 prog->type != BPF_PROG_TYPE_EXT)
24554 return 0;
24555
24556 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
24557 if (ret)
24558 return ret;
24559
24560 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
24561 /* to make freplace equivalent to their targets, they need to
24562 * inherit env->ops and expected_attach_type for the rest of the
24563 * verification
24564 */
24565 env->ops = bpf_verifier_ops[tgt_prog->type];
24566 prog->expected_attach_type = tgt_prog->expected_attach_type;
24567 }
24568
24569 /* store info about the attachment target that will be used later */
24570 prog->aux->attach_func_proto = tgt_info.tgt_type;
24571 prog->aux->attach_func_name = tgt_info.tgt_name;
24572 prog->aux->mod = tgt_info.tgt_mod;
24573
24574 if (tgt_prog) {
24575 prog->aux->saved_dst_prog_type = tgt_prog->type;
24576 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
24577 }
24578
24579 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
24580 prog->aux->attach_btf_trace = true;
24581 return 0;
24582 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
24583 return bpf_iter_prog_supported(prog);
24584 }
24585
24586 if (prog->type == BPF_PROG_TYPE_LSM) {
24587 ret = bpf_lsm_verify_prog(&env->log, prog);
24588 if (ret < 0)
24589 return ret;
24590 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
24591 btf_id_set_contains(&btf_id_deny, btf_id)) {
24592 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
24593 tgt_info.tgt_name);
24594 return -EINVAL;
24595 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
24596 prog->expected_attach_type == BPF_MODIFY_RETURN) &&
24597 btf_id_set_contains(&noreturn_deny, btf_id)) {
24598 verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
24599 tgt_info.tgt_name);
24600 return -EINVAL;
24601 }
24602
24603 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
24604 tr = bpf_trampoline_get(key, &tgt_info);
24605 if (!tr)
24606 return -ENOMEM;
24607
24608 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24609 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24610
24611 prog->aux->dst_trampoline = tr;
24612 return 0;
24613 }
24614
bpf_get_btf_vmlinux(void)24615 struct btf *bpf_get_btf_vmlinux(void)
24616 {
24617 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24618 mutex_lock(&bpf_verifier_lock);
24619 if (!btf_vmlinux)
24620 btf_vmlinux = btf_parse_vmlinux();
24621 mutex_unlock(&bpf_verifier_lock);
24622 }
24623 return btf_vmlinux;
24624 }
24625
24626 /*
24627 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24628 * this case expect that every file descriptor in the array is either a map or
24629 * a BTF. Everything else is considered to be trash.
24630 */
add_fd_from_fd_array(struct bpf_verifier_env * env,int fd)24631 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24632 {
24633 struct bpf_map *map;
24634 struct btf *btf;
24635 CLASS(fd, f)(fd);
24636 int err;
24637
24638 map = __bpf_map_get(f);
24639 if (!IS_ERR(map)) {
24640 err = __add_used_map(env, map);
24641 if (err < 0)
24642 return err;
24643 return 0;
24644 }
24645
24646 btf = __btf_get_by_fd(f);
24647 if (!IS_ERR(btf)) {
24648 err = __add_used_btf(env, btf);
24649 if (err < 0)
24650 return err;
24651 return 0;
24652 }
24653
24654 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24655 return PTR_ERR(map);
24656 }
24657
process_fd_array(struct bpf_verifier_env * env,union bpf_attr * attr,bpfptr_t uattr)24658 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24659 {
24660 size_t size = sizeof(int);
24661 int ret;
24662 int fd;
24663 u32 i;
24664
24665 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24666
24667 /*
24668 * The only difference between old (no fd_array_cnt is given) and new
24669 * APIs is that in the latter case the fd_array is expected to be
24670 * continuous and is scanned for map fds right away
24671 */
24672 if (!attr->fd_array_cnt)
24673 return 0;
24674
24675 /* Check for integer overflow */
24676 if (attr->fd_array_cnt >= (U32_MAX / size)) {
24677 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24678 return -EINVAL;
24679 }
24680
24681 for (i = 0; i < attr->fd_array_cnt; i++) {
24682 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24683 return -EFAULT;
24684
24685 ret = add_fd_from_fd_array(env, fd);
24686 if (ret)
24687 return ret;
24688 }
24689
24690 return 0;
24691 }
24692
24693 /* Each field is a register bitmask */
24694 struct insn_live_regs {
24695 u16 use; /* registers read by instruction */
24696 u16 def; /* registers written by instruction */
24697 u16 in; /* registers that may be alive before instruction */
24698 u16 out; /* registers that may be alive after instruction */
24699 };
24700
24701 /* Bitmask with 1s for all caller saved registers */
24702 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24703
24704 /* Compute info->{use,def} fields for the instruction */
compute_insn_live_regs(struct bpf_verifier_env * env,struct bpf_insn * insn,struct insn_live_regs * info)24705 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24706 struct bpf_insn *insn,
24707 struct insn_live_regs *info)
24708 {
24709 struct call_summary cs;
24710 u8 class = BPF_CLASS(insn->code);
24711 u8 code = BPF_OP(insn->code);
24712 u8 mode = BPF_MODE(insn->code);
24713 u16 src = BIT(insn->src_reg);
24714 u16 dst = BIT(insn->dst_reg);
24715 u16 r0 = BIT(0);
24716 u16 def = 0;
24717 u16 use = 0xffff;
24718
24719 switch (class) {
24720 case BPF_LD:
24721 switch (mode) {
24722 case BPF_IMM:
24723 if (BPF_SIZE(insn->code) == BPF_DW) {
24724 def = dst;
24725 use = 0;
24726 }
24727 break;
24728 case BPF_LD | BPF_ABS:
24729 case BPF_LD | BPF_IND:
24730 /* stick with defaults */
24731 break;
24732 }
24733 break;
24734 case BPF_LDX:
24735 switch (mode) {
24736 case BPF_MEM:
24737 case BPF_MEMSX:
24738 def = dst;
24739 use = src;
24740 break;
24741 }
24742 break;
24743 case BPF_ST:
24744 switch (mode) {
24745 case BPF_MEM:
24746 def = 0;
24747 use = dst;
24748 break;
24749 }
24750 break;
24751 case BPF_STX:
24752 switch (mode) {
24753 case BPF_MEM:
24754 def = 0;
24755 use = dst | src;
24756 break;
24757 case BPF_ATOMIC:
24758 switch (insn->imm) {
24759 case BPF_CMPXCHG:
24760 use = r0 | dst | src;
24761 def = r0;
24762 break;
24763 case BPF_LOAD_ACQ:
24764 def = dst;
24765 use = src;
24766 break;
24767 case BPF_STORE_REL:
24768 def = 0;
24769 use = dst | src;
24770 break;
24771 default:
24772 use = dst | src;
24773 if (insn->imm & BPF_FETCH)
24774 def = src;
24775 else
24776 def = 0;
24777 }
24778 break;
24779 }
24780 break;
24781 case BPF_ALU:
24782 case BPF_ALU64:
24783 switch (code) {
24784 case BPF_END:
24785 use = dst;
24786 def = dst;
24787 break;
24788 case BPF_MOV:
24789 def = dst;
24790 if (BPF_SRC(insn->code) == BPF_K)
24791 use = 0;
24792 else
24793 use = src;
24794 break;
24795 default:
24796 def = dst;
24797 if (BPF_SRC(insn->code) == BPF_K)
24798 use = dst;
24799 else
24800 use = dst | src;
24801 }
24802 break;
24803 case BPF_JMP:
24804 case BPF_JMP32:
24805 switch (code) {
24806 case BPF_JA:
24807 case BPF_JCOND:
24808 def = 0;
24809 use = 0;
24810 break;
24811 case BPF_EXIT:
24812 def = 0;
24813 use = r0;
24814 break;
24815 case BPF_CALL:
24816 def = ALL_CALLER_SAVED_REGS;
24817 use = def & ~BIT(BPF_REG_0);
24818 if (get_call_summary(env, insn, &cs))
24819 use = GENMASK(cs.num_params, 1);
24820 break;
24821 default:
24822 def = 0;
24823 if (BPF_SRC(insn->code) == BPF_K)
24824 use = dst;
24825 else
24826 use = dst | src;
24827 }
24828 break;
24829 }
24830
24831 info->def = def;
24832 info->use = use;
24833 }
24834
24835 /* Compute may-live registers after each instruction in the program.
24836 * The register is live after the instruction I if it is read by some
24837 * instruction S following I during program execution and is not
24838 * overwritten between I and S.
24839 *
24840 * Store result in env->insn_aux_data[i].live_regs.
24841 */
compute_live_registers(struct bpf_verifier_env * env)24842 static int compute_live_registers(struct bpf_verifier_env *env)
24843 {
24844 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24845 struct bpf_insn *insns = env->prog->insnsi;
24846 struct insn_live_regs *state;
24847 int insn_cnt = env->prog->len;
24848 int err = 0, i, j;
24849 bool changed;
24850
24851 /* Use the following algorithm:
24852 * - define the following:
24853 * - I.use : a set of all registers read by instruction I;
24854 * - I.def : a set of all registers written by instruction I;
24855 * - I.in : a set of all registers that may be alive before I execution;
24856 * - I.out : a set of all registers that may be alive after I execution;
24857 * - insn_successors(I): a set of instructions S that might immediately
24858 * follow I for some program execution;
24859 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24860 * - visit each instruction in a postorder and update
24861 * state[i].in, state[i].out as follows:
24862 *
24863 * state[i].out = U [state[s].in for S in insn_successors(i)]
24864 * state[i].in = (state[i].out / state[i].def) U state[i].use
24865 *
24866 * (where U stands for set union, / stands for set difference)
24867 * - repeat the computation while {in,out} fields changes for
24868 * any instruction.
24869 */
24870 state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24871 if (!state) {
24872 err = -ENOMEM;
24873 goto out;
24874 }
24875
24876 for (i = 0; i < insn_cnt; ++i)
24877 compute_insn_live_regs(env, &insns[i], &state[i]);
24878
24879 changed = true;
24880 while (changed) {
24881 changed = false;
24882 for (i = 0; i < env->cfg.cur_postorder; ++i) {
24883 int insn_idx = env->cfg.insn_postorder[i];
24884 struct insn_live_regs *live = &state[insn_idx];
24885 struct bpf_iarray *succ;
24886 u16 new_out = 0;
24887 u16 new_in = 0;
24888
24889 succ = bpf_insn_successors(env, insn_idx);
24890 for (int s = 0; s < succ->cnt; ++s)
24891 new_out |= state[succ->items[s]].in;
24892 new_in = (new_out & ~live->def) | live->use;
24893 if (new_out != live->out || new_in != live->in) {
24894 live->in = new_in;
24895 live->out = new_out;
24896 changed = true;
24897 }
24898 }
24899 }
24900
24901 for (i = 0; i < insn_cnt; ++i)
24902 insn_aux[i].live_regs_before = state[i].in;
24903
24904 if (env->log.level & BPF_LOG_LEVEL2) {
24905 verbose(env, "Live regs before insn:\n");
24906 for (i = 0; i < insn_cnt; ++i) {
24907 if (env->insn_aux_data[i].scc)
24908 verbose(env, "%3d ", env->insn_aux_data[i].scc);
24909 else
24910 verbose(env, " ");
24911 verbose(env, "%3d: ", i);
24912 for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24913 if (insn_aux[i].live_regs_before & BIT(j))
24914 verbose(env, "%d", j);
24915 else
24916 verbose(env, ".");
24917 verbose(env, " ");
24918 verbose_insn(env, &insns[i]);
24919 if (bpf_is_ldimm64(&insns[i]))
24920 i++;
24921 }
24922 }
24923
24924 out:
24925 kvfree(state);
24926 return err;
24927 }
24928
24929 /*
24930 * Compute strongly connected components (SCCs) on the CFG.
24931 * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24932 * If instruction is a sole member of its SCC and there are no self edges,
24933 * assign it SCC number of zero.
24934 * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24935 */
compute_scc(struct bpf_verifier_env * env)24936 static int compute_scc(struct bpf_verifier_env *env)
24937 {
24938 const u32 NOT_ON_STACK = U32_MAX;
24939
24940 struct bpf_insn_aux_data *aux = env->insn_aux_data;
24941 const u32 insn_cnt = env->prog->len;
24942 int stack_sz, dfs_sz, err = 0;
24943 u32 *stack, *pre, *low, *dfs;
24944 u32 i, j, t, w;
24945 u32 next_preorder_num;
24946 u32 next_scc_id;
24947 bool assign_scc;
24948 struct bpf_iarray *succ;
24949
24950 next_preorder_num = 1;
24951 next_scc_id = 1;
24952 /*
24953 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24954 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24955 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24956 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24957 */
24958 stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24959 pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24960 low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24961 dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24962 if (!stack || !pre || !low || !dfs) {
24963 err = -ENOMEM;
24964 goto exit;
24965 }
24966 /*
24967 * References:
24968 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24969 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24970 *
24971 * The algorithm maintains the following invariant:
24972 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24973 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24974 *
24975 * Consequently:
24976 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24977 * such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24978 * and thus there is an SCC (loop) containing both 'u' and 'v'.
24979 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24980 * and 'v' can be considered the root of some SCC.
24981 *
24982 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24983 *
24984 * NOT_ON_STACK = insn_cnt + 1
24985 * pre = [0] * insn_cnt
24986 * low = [0] * insn_cnt
24987 * scc = [0] * insn_cnt
24988 * stack = []
24989 *
24990 * next_preorder_num = 1
24991 * next_scc_id = 1
24992 *
24993 * def recur(w):
24994 * nonlocal next_preorder_num
24995 * nonlocal next_scc_id
24996 *
24997 * pre[w] = next_preorder_num
24998 * low[w] = next_preorder_num
24999 * next_preorder_num += 1
25000 * stack.append(w)
25001 * for s in successors(w):
25002 * # Note: for classic algorithm the block below should look as:
25003 * #
25004 * # if pre[s] == 0:
25005 * # recur(s)
25006 * # low[w] = min(low[w], low[s])
25007 * # elif low[s] != NOT_ON_STACK:
25008 * # low[w] = min(low[w], pre[s])
25009 * #
25010 * # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
25011 * # does not break the invariant and makes itartive version of the algorithm
25012 * # simpler. See 'Algorithm #3' from [2].
25013 *
25014 * # 's' not yet visited
25015 * if pre[s] == 0:
25016 * recur(s)
25017 * # if 's' is on stack, pick lowest reachable preorder number from it;
25018 * # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
25019 * # so 'min' would be a noop.
25020 * low[w] = min(low[w], low[s])
25021 *
25022 * if low[w] == pre[w]:
25023 * # 'w' is the root of an SCC, pop all vertices
25024 * # below 'w' on stack and assign same SCC to them.
25025 * while True:
25026 * t = stack.pop()
25027 * low[t] = NOT_ON_STACK
25028 * scc[t] = next_scc_id
25029 * if t == w:
25030 * break
25031 * next_scc_id += 1
25032 *
25033 * for i in range(0, insn_cnt):
25034 * if pre[i] == 0:
25035 * recur(i)
25036 *
25037 * Below implementation replaces explicit recursion with array 'dfs'.
25038 */
25039 for (i = 0; i < insn_cnt; i++) {
25040 if (pre[i])
25041 continue;
25042 stack_sz = 0;
25043 dfs_sz = 1;
25044 dfs[0] = i;
25045 dfs_continue:
25046 while (dfs_sz) {
25047 w = dfs[dfs_sz - 1];
25048 if (pre[w] == 0) {
25049 low[w] = next_preorder_num;
25050 pre[w] = next_preorder_num;
25051 next_preorder_num++;
25052 stack[stack_sz++] = w;
25053 }
25054 /* Visit 'w' successors */
25055 succ = bpf_insn_successors(env, w);
25056 for (j = 0; j < succ->cnt; ++j) {
25057 if (pre[succ->items[j]]) {
25058 low[w] = min(low[w], low[succ->items[j]]);
25059 } else {
25060 dfs[dfs_sz++] = succ->items[j];
25061 goto dfs_continue;
25062 }
25063 }
25064 /*
25065 * Preserve the invariant: if some vertex above in the stack
25066 * is reachable from 'w', keep 'w' on the stack.
25067 */
25068 if (low[w] < pre[w]) {
25069 dfs_sz--;
25070 goto dfs_continue;
25071 }
25072 /*
25073 * Assign SCC number only if component has two or more elements,
25074 * or if component has a self reference.
25075 */
25076 assign_scc = stack[stack_sz - 1] != w;
25077 for (j = 0; j < succ->cnt; ++j) {
25078 if (succ->items[j] == w) {
25079 assign_scc = true;
25080 break;
25081 }
25082 }
25083 /* Pop component elements from stack */
25084 do {
25085 t = stack[--stack_sz];
25086 low[t] = NOT_ON_STACK;
25087 if (assign_scc)
25088 aux[t].scc = next_scc_id;
25089 } while (t != w);
25090 if (assign_scc)
25091 next_scc_id++;
25092 dfs_sz--;
25093 }
25094 }
25095 env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
25096 if (!env->scc_info) {
25097 err = -ENOMEM;
25098 goto exit;
25099 }
25100 env->scc_cnt = next_scc_id;
25101 exit:
25102 kvfree(stack);
25103 kvfree(pre);
25104 kvfree(low);
25105 kvfree(dfs);
25106 return err;
25107 }
25108
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)25109 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
25110 {
25111 u64 start_time = ktime_get_ns();
25112 struct bpf_verifier_env *env;
25113 int i, len, ret = -EINVAL, err;
25114 u32 log_true_size;
25115 bool is_priv;
25116
25117 BTF_TYPE_EMIT(enum bpf_features);
25118
25119 /* no program is valid */
25120 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
25121 return -EINVAL;
25122
25123 /* 'struct bpf_verifier_env' can be global, but since it's not small,
25124 * allocate/free it every time bpf_check() is called
25125 */
25126 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
25127 if (!env)
25128 return -ENOMEM;
25129
25130 env->bt.env = env;
25131
25132 len = (*prog)->len;
25133 env->insn_aux_data =
25134 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
25135 ret = -ENOMEM;
25136 if (!env->insn_aux_data)
25137 goto err_free_env;
25138 for (i = 0; i < len; i++)
25139 env->insn_aux_data[i].orig_idx = i;
25140 env->succ = iarray_realloc(NULL, 2);
25141 if (!env->succ)
25142 goto err_free_env;
25143 env->prog = *prog;
25144 env->ops = bpf_verifier_ops[env->prog->type];
25145
25146 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
25147 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
25148 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
25149 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
25150 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
25151
25152 bpf_get_btf_vmlinux();
25153
25154 /* grab the mutex to protect few globals used by verifier */
25155 if (!is_priv)
25156 mutex_lock(&bpf_verifier_lock);
25157
25158 /* user could have requested verbose verifier output
25159 * and supplied buffer to store the verification trace
25160 */
25161 ret = bpf_vlog_init(&env->log, attr->log_level,
25162 (char __user *) (unsigned long) attr->log_buf,
25163 attr->log_size);
25164 if (ret)
25165 goto err_unlock;
25166
25167 ret = process_fd_array(env, attr, uattr);
25168 if (ret)
25169 goto skip_full_check;
25170
25171 mark_verifier_state_clean(env);
25172
25173 if (IS_ERR(btf_vmlinux)) {
25174 /* Either gcc or pahole or kernel are broken. */
25175 verbose(env, "in-kernel BTF is malformed\n");
25176 ret = PTR_ERR(btf_vmlinux);
25177 goto skip_full_check;
25178 }
25179
25180 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
25181 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
25182 env->strict_alignment = true;
25183 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
25184 env->strict_alignment = false;
25185
25186 if (is_priv)
25187 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
25188 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
25189
25190 env->explored_states = kvcalloc(state_htab_size(env),
25191 sizeof(struct list_head),
25192 GFP_KERNEL_ACCOUNT);
25193 ret = -ENOMEM;
25194 if (!env->explored_states)
25195 goto skip_full_check;
25196
25197 for (i = 0; i < state_htab_size(env); i++)
25198 INIT_LIST_HEAD(&env->explored_states[i]);
25199 INIT_LIST_HEAD(&env->free_list);
25200
25201 ret = check_btf_info_early(env, attr, uattr);
25202 if (ret < 0)
25203 goto skip_full_check;
25204
25205 ret = add_subprog_and_kfunc(env);
25206 if (ret < 0)
25207 goto skip_full_check;
25208
25209 ret = check_subprogs(env);
25210 if (ret < 0)
25211 goto skip_full_check;
25212
25213 ret = check_btf_info(env, attr, uattr);
25214 if (ret < 0)
25215 goto skip_full_check;
25216
25217 ret = resolve_pseudo_ldimm64(env);
25218 if (ret < 0)
25219 goto skip_full_check;
25220
25221 if (bpf_prog_is_offloaded(env->prog->aux)) {
25222 ret = bpf_prog_offload_verifier_prep(env->prog);
25223 if (ret)
25224 goto skip_full_check;
25225 }
25226
25227 ret = check_cfg(env);
25228 if (ret < 0)
25229 goto skip_full_check;
25230
25231 ret = compute_postorder(env);
25232 if (ret < 0)
25233 goto skip_full_check;
25234
25235 ret = bpf_stack_liveness_init(env);
25236 if (ret)
25237 goto skip_full_check;
25238
25239 ret = check_attach_btf_id(env);
25240 if (ret)
25241 goto skip_full_check;
25242
25243 ret = compute_scc(env);
25244 if (ret < 0)
25245 goto skip_full_check;
25246
25247 ret = compute_live_registers(env);
25248 if (ret < 0)
25249 goto skip_full_check;
25250
25251 ret = mark_fastcall_patterns(env);
25252 if (ret < 0)
25253 goto skip_full_check;
25254
25255 ret = do_check_main(env);
25256 ret = ret ?: do_check_subprogs(env);
25257
25258 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
25259 ret = bpf_prog_offload_finalize(env);
25260
25261 skip_full_check:
25262 kvfree(env->explored_states);
25263
25264 /* might decrease stack depth, keep it before passes that
25265 * allocate additional slots.
25266 */
25267 if (ret == 0)
25268 ret = remove_fastcall_spills_fills(env);
25269
25270 if (ret == 0)
25271 ret = check_max_stack_depth(env);
25272
25273 /* instruction rewrites happen after this point */
25274 if (ret == 0)
25275 ret = optimize_bpf_loop(env);
25276
25277 if (is_priv) {
25278 if (ret == 0)
25279 opt_hard_wire_dead_code_branches(env);
25280 if (ret == 0)
25281 ret = opt_remove_dead_code(env);
25282 if (ret == 0)
25283 ret = opt_remove_nops(env);
25284 } else {
25285 if (ret == 0)
25286 sanitize_dead_code(env);
25287 }
25288
25289 if (ret == 0)
25290 /* program is valid, convert *(u32*)(ctx + off) accesses */
25291 ret = convert_ctx_accesses(env);
25292
25293 if (ret == 0)
25294 ret = do_misc_fixups(env);
25295
25296 /* do 32-bit optimization after insn patching has done so those patched
25297 * insns could be handled correctly.
25298 */
25299 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
25300 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
25301 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
25302 : false;
25303 }
25304
25305 if (ret == 0)
25306 ret = fixup_call_args(env);
25307
25308 env->verification_time = ktime_get_ns() - start_time;
25309 print_verification_stats(env);
25310 env->prog->aux->verified_insns = env->insn_processed;
25311
25312 /* preserve original error even if log finalization is successful */
25313 err = bpf_vlog_finalize(&env->log, &log_true_size);
25314 if (err)
25315 ret = err;
25316
25317 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
25318 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
25319 &log_true_size, sizeof(log_true_size))) {
25320 ret = -EFAULT;
25321 goto err_release_maps;
25322 }
25323
25324 if (ret)
25325 goto err_release_maps;
25326
25327 if (env->used_map_cnt) {
25328 /* if program passed verifier, update used_maps in bpf_prog_info */
25329 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
25330 sizeof(env->used_maps[0]),
25331 GFP_KERNEL_ACCOUNT);
25332
25333 if (!env->prog->aux->used_maps) {
25334 ret = -ENOMEM;
25335 goto err_release_maps;
25336 }
25337
25338 memcpy(env->prog->aux->used_maps, env->used_maps,
25339 sizeof(env->used_maps[0]) * env->used_map_cnt);
25340 env->prog->aux->used_map_cnt = env->used_map_cnt;
25341 }
25342 if (env->used_btf_cnt) {
25343 /* if program passed verifier, update used_btfs in bpf_prog_aux */
25344 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
25345 sizeof(env->used_btfs[0]),
25346 GFP_KERNEL_ACCOUNT);
25347 if (!env->prog->aux->used_btfs) {
25348 ret = -ENOMEM;
25349 goto err_release_maps;
25350 }
25351
25352 memcpy(env->prog->aux->used_btfs, env->used_btfs,
25353 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
25354 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
25355 }
25356 if (env->used_map_cnt || env->used_btf_cnt) {
25357 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
25358 * bpf_ld_imm64 instructions
25359 */
25360 convert_pseudo_ld_imm64(env);
25361 }
25362
25363 adjust_btf_func(env);
25364
25365 err_release_maps:
25366 if (ret)
25367 release_insn_arrays(env);
25368 if (!env->prog->aux->used_maps)
25369 /* if we didn't copy map pointers into bpf_prog_info, release
25370 * them now. Otherwise free_used_maps() will release them.
25371 */
25372 release_maps(env);
25373 if (!env->prog->aux->used_btfs)
25374 release_btfs(env);
25375
25376 /* extension progs temporarily inherit the attach_type of their targets
25377 for verification purposes, so set it back to zero before returning
25378 */
25379 if (env->prog->type == BPF_PROG_TYPE_EXT)
25380 env->prog->expected_attach_type = 0;
25381
25382 *prog = env->prog;
25383
25384 module_put(env->attach_btf_mod);
25385 err_unlock:
25386 if (!is_priv)
25387 mutex_unlock(&bpf_verifier_lock);
25388 clear_insn_aux_data(env, 0, env->prog->len);
25389 vfree(env->insn_aux_data);
25390 err_free_env:
25391 bpf_stack_liveness_free(env);
25392 kvfree(env->cfg.insn_postorder);
25393 kvfree(env->scc_info);
25394 kvfree(env->succ);
25395 kvfree(env->gotox_tmp_buf);
25396 kvfree(env);
25397 return ret;
25398 }
25399