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 (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
9613 verbose(env, "R%d points to insn_array map which cannot be used as const string\n", regno);
9614 return -EACCES;
9615 }
9616
9617 if (!bpf_map_is_rdonly(map)) {
9618 verbose(env, "R%d does not point to a readonly map'\n", regno);
9619 return -EACCES;
9620 }
9621
9622 if (!tnum_is_const(reg->var_off)) {
9623 verbose(env, "R%d is not a constant address'\n", regno);
9624 return -EACCES;
9625 }
9626
9627 if (!map->ops->map_direct_value_addr) {
9628 verbose(env, "no direct value access support for this map type\n");
9629 return -EACCES;
9630 }
9631
9632 err = check_map_access(env, regno, reg->off,
9633 map->value_size - reg->off, false,
9634 ACCESS_HELPER);
9635 if (err)
9636 return err;
9637
9638 map_off = reg->off + reg->var_off.value;
9639 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
9640 if (err) {
9641 verbose(env, "direct value access on string failed\n");
9642 return err;
9643 }
9644
9645 str_ptr = (char *)(long)(map_addr);
9646 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
9647 verbose(env, "string is not zero-terminated\n");
9648 return -EINVAL;
9649 }
9650 return 0;
9651 }
9652
9653 /* 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)9654 static int get_constant_map_key(struct bpf_verifier_env *env,
9655 struct bpf_reg_state *key,
9656 u32 key_size,
9657 s64 *value)
9658 {
9659 struct bpf_func_state *state = func(env, key);
9660 struct bpf_reg_state *reg;
9661 int slot, spi, off;
9662 int spill_size = 0;
9663 int zero_size = 0;
9664 int stack_off;
9665 int i, err;
9666 u8 *stype;
9667
9668 if (!env->bpf_capable)
9669 return -EOPNOTSUPP;
9670 if (key->type != PTR_TO_STACK)
9671 return -EOPNOTSUPP;
9672 if (!tnum_is_const(key->var_off))
9673 return -EOPNOTSUPP;
9674
9675 stack_off = key->off + key->var_off.value;
9676 slot = -stack_off - 1;
9677 spi = slot / BPF_REG_SIZE;
9678 off = slot % BPF_REG_SIZE;
9679 stype = state->stack[spi].slot_type;
9680
9681 /* First handle precisely tracked STACK_ZERO */
9682 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--)
9683 zero_size++;
9684 if (zero_size >= key_size) {
9685 *value = 0;
9686 return 0;
9687 }
9688
9689 /* Check that stack contains a scalar spill of expected size */
9690 if (!is_spilled_scalar_reg(&state->stack[spi]))
9691 return -EOPNOTSUPP;
9692 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--)
9693 spill_size++;
9694 if (spill_size != key_size)
9695 return -EOPNOTSUPP;
9696
9697 reg = &state->stack[spi].spilled_ptr;
9698 if (!tnum_is_const(reg->var_off))
9699 /* Stack value not statically known */
9700 return -EOPNOTSUPP;
9701
9702 /* We are relying on a constant value. So mark as precise
9703 * to prevent pruning on it.
9704 */
9705 bt_set_frame_slot(&env->bt, key->frameno, spi);
9706 err = mark_chain_precision_batch(env, env->cur_state);
9707 if (err < 0)
9708 return err;
9709
9710 *value = reg->var_off.value;
9711 return 0;
9712 }
9713
9714 static bool can_elide_value_nullness(enum bpf_map_type type);
9715
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)9716 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
9717 struct bpf_call_arg_meta *meta,
9718 const struct bpf_func_proto *fn,
9719 int insn_idx)
9720 {
9721 u32 regno = BPF_REG_1 + arg;
9722 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
9723 enum bpf_arg_type arg_type = fn->arg_type[arg];
9724 enum bpf_reg_type type = reg->type;
9725 u32 *arg_btf_id = NULL;
9726 u32 key_size;
9727 int err = 0;
9728
9729 if (arg_type == ARG_DONTCARE)
9730 return 0;
9731
9732 err = check_reg_arg(env, regno, SRC_OP);
9733 if (err)
9734 return err;
9735
9736 if (arg_type == ARG_ANYTHING) {
9737 if (is_pointer_value(env, regno)) {
9738 verbose(env, "R%d leaks addr into helper function\n",
9739 regno);
9740 return -EACCES;
9741 }
9742 return 0;
9743 }
9744
9745 if (type_is_pkt_pointer(type) &&
9746 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
9747 verbose(env, "helper access to the packet is not allowed\n");
9748 return -EACCES;
9749 }
9750
9751 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
9752 err = resolve_map_arg_type(env, meta, &arg_type);
9753 if (err)
9754 return err;
9755 }
9756
9757 if (register_is_null(reg) && type_may_be_null(arg_type))
9758 /* A NULL register has a SCALAR_VALUE type, so skip
9759 * type checking.
9760 */
9761 goto skip_type_check;
9762
9763 /* arg_btf_id and arg_size are in a union. */
9764 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
9765 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
9766 arg_btf_id = fn->arg_btf_id[arg];
9767
9768 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
9769 if (err)
9770 return err;
9771
9772 err = check_func_arg_reg_off(env, reg, regno, arg_type);
9773 if (err)
9774 return err;
9775
9776 skip_type_check:
9777 if (arg_type_is_release(arg_type)) {
9778 if (arg_type_is_dynptr(arg_type)) {
9779 struct bpf_func_state *state = func(env, reg);
9780 int spi;
9781
9782 /* Only dynptr created on stack can be released, thus
9783 * the get_spi and stack state checks for spilled_ptr
9784 * should only be done before process_dynptr_func for
9785 * PTR_TO_STACK.
9786 */
9787 if (reg->type == PTR_TO_STACK) {
9788 spi = dynptr_get_spi(env, reg);
9789 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
9790 verbose(env, "arg %d is an unacquired reference\n", regno);
9791 return -EINVAL;
9792 }
9793 } else {
9794 verbose(env, "cannot release unowned const bpf_dynptr\n");
9795 return -EINVAL;
9796 }
9797 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
9798 verbose(env, "R%d must be referenced when passed to release function\n",
9799 regno);
9800 return -EINVAL;
9801 }
9802 if (meta->release_regno) {
9803 verifier_bug(env, "more than one release argument");
9804 return -EFAULT;
9805 }
9806 meta->release_regno = regno;
9807 }
9808
9809 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) {
9810 if (meta->ref_obj_id) {
9811 verbose(env, "more than one arg with ref_obj_id R%d %u %u",
9812 regno, reg->ref_obj_id,
9813 meta->ref_obj_id);
9814 return -EACCES;
9815 }
9816 meta->ref_obj_id = reg->ref_obj_id;
9817 }
9818
9819 switch (base_type(arg_type)) {
9820 case ARG_CONST_MAP_PTR:
9821 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
9822 if (meta->map_ptr) {
9823 /* Use map_uid (which is unique id of inner map) to reject:
9824 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
9825 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
9826 * if (inner_map1 && inner_map2) {
9827 * timer = bpf_map_lookup_elem(inner_map1);
9828 * if (timer)
9829 * // mismatch would have been allowed
9830 * bpf_timer_init(timer, inner_map2);
9831 * }
9832 *
9833 * Comparing map_ptr is enough to distinguish normal and outer maps.
9834 */
9835 if (meta->map_ptr != reg->map_ptr ||
9836 meta->map_uid != reg->map_uid) {
9837 verbose(env,
9838 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
9839 meta->map_uid, reg->map_uid);
9840 return -EINVAL;
9841 }
9842 }
9843 meta->map_ptr = reg->map_ptr;
9844 meta->map_uid = reg->map_uid;
9845 break;
9846 case ARG_PTR_TO_MAP_KEY:
9847 /* bpf_map_xxx(..., map_ptr, ..., key) call:
9848 * check that [key, key + map->key_size) are within
9849 * stack limits and initialized
9850 */
9851 if (!meta->map_ptr) {
9852 /* in function declaration map_ptr must come before
9853 * map_key, so that it's verified and known before
9854 * we have to check map_key here. Otherwise it means
9855 * that kernel subsystem misconfigured verifier
9856 */
9857 verifier_bug(env, "invalid map_ptr to access map->key");
9858 return -EFAULT;
9859 }
9860 key_size = meta->map_ptr->key_size;
9861 err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL);
9862 if (err)
9863 return err;
9864 if (can_elide_value_nullness(meta->map_ptr->map_type)) {
9865 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key);
9866 if (err < 0) {
9867 meta->const_map_key = -1;
9868 if (err == -EOPNOTSUPP)
9869 err = 0;
9870 else
9871 return err;
9872 }
9873 }
9874 break;
9875 case ARG_PTR_TO_MAP_VALUE:
9876 if (type_may_be_null(arg_type) && register_is_null(reg))
9877 return 0;
9878
9879 /* bpf_map_xxx(..., map_ptr, ..., value) call:
9880 * check [value, value + map->value_size) validity
9881 */
9882 if (!meta->map_ptr) {
9883 /* kernel subsystem misconfigured verifier */
9884 verifier_bug(env, "invalid map_ptr to access map->value");
9885 return -EFAULT;
9886 }
9887 meta->raw_mode = arg_type & MEM_UNINIT;
9888 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size,
9889 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9890 false, meta);
9891 break;
9892 case ARG_PTR_TO_PERCPU_BTF_ID:
9893 if (!reg->btf_id) {
9894 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
9895 return -EACCES;
9896 }
9897 meta->ret_btf = reg->btf;
9898 meta->ret_btf_id = reg->btf_id;
9899 break;
9900 case ARG_PTR_TO_SPIN_LOCK:
9901 if (in_rbtree_lock_required_cb(env)) {
9902 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
9903 return -EACCES;
9904 }
9905 if (meta->func_id == BPF_FUNC_spin_lock) {
9906 err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK);
9907 if (err)
9908 return err;
9909 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
9910 err = process_spin_lock(env, regno, 0);
9911 if (err)
9912 return err;
9913 } else {
9914 verifier_bug(env, "spin lock arg on unexpected helper");
9915 return -EFAULT;
9916 }
9917 break;
9918 case ARG_PTR_TO_TIMER:
9919 err = process_timer_func(env, regno, meta);
9920 if (err)
9921 return err;
9922 break;
9923 case ARG_PTR_TO_FUNC:
9924 meta->subprogno = reg->subprogno;
9925 break;
9926 case ARG_PTR_TO_MEM:
9927 /* The access to this pointer is only checked when we hit the
9928 * next is_mem_size argument below.
9929 */
9930 meta->raw_mode = arg_type & MEM_UNINIT;
9931 if (arg_type & MEM_FIXED_SIZE) {
9932 err = check_helper_mem_access(env, regno, fn->arg_size[arg],
9933 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ,
9934 false, meta);
9935 if (err)
9936 return err;
9937 if (arg_type & MEM_ALIGNED)
9938 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true);
9939 }
9940 break;
9941 case ARG_CONST_SIZE:
9942 err = check_mem_size_reg(env, reg, regno,
9943 fn->arg_type[arg - 1] & MEM_WRITE ?
9944 BPF_WRITE : BPF_READ,
9945 false, meta);
9946 break;
9947 case ARG_CONST_SIZE_OR_ZERO:
9948 err = check_mem_size_reg(env, reg, regno,
9949 fn->arg_type[arg - 1] & MEM_WRITE ?
9950 BPF_WRITE : BPF_READ,
9951 true, meta);
9952 break;
9953 case ARG_PTR_TO_DYNPTR:
9954 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
9955 if (err)
9956 return err;
9957 break;
9958 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
9959 if (!tnum_is_const(reg->var_off)) {
9960 verbose(env, "R%d is not a known constant'\n",
9961 regno);
9962 return -EACCES;
9963 }
9964 meta->mem_size = reg->var_off.value;
9965 err = mark_chain_precision(env, regno);
9966 if (err)
9967 return err;
9968 break;
9969 case ARG_PTR_TO_CONST_STR:
9970 {
9971 err = check_reg_const_str(env, reg, regno);
9972 if (err)
9973 return err;
9974 break;
9975 }
9976 case ARG_KPTR_XCHG_DEST:
9977 err = process_kptr_func(env, regno, meta);
9978 if (err)
9979 return err;
9980 break;
9981 }
9982
9983 return err;
9984 }
9985
may_update_sockmap(struct bpf_verifier_env * env,int func_id)9986 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
9987 {
9988 enum bpf_attach_type eatype = env->prog->expected_attach_type;
9989 enum bpf_prog_type type = resolve_prog_type(env->prog);
9990
9991 if (func_id != BPF_FUNC_map_update_elem &&
9992 func_id != BPF_FUNC_map_delete_elem)
9993 return false;
9994
9995 /* It's not possible to get access to a locked struct sock in these
9996 * contexts, so updating is safe.
9997 */
9998 switch (type) {
9999 case BPF_PROG_TYPE_TRACING:
10000 if (eatype == BPF_TRACE_ITER)
10001 return true;
10002 break;
10003 case BPF_PROG_TYPE_SOCK_OPS:
10004 /* map_update allowed only via dedicated helpers with event type checks */
10005 if (func_id == BPF_FUNC_map_delete_elem)
10006 return true;
10007 break;
10008 case BPF_PROG_TYPE_SOCKET_FILTER:
10009 case BPF_PROG_TYPE_SCHED_CLS:
10010 case BPF_PROG_TYPE_SCHED_ACT:
10011 case BPF_PROG_TYPE_XDP:
10012 case BPF_PROG_TYPE_SK_REUSEPORT:
10013 case BPF_PROG_TYPE_FLOW_DISSECTOR:
10014 case BPF_PROG_TYPE_SK_LOOKUP:
10015 return true;
10016 default:
10017 break;
10018 }
10019
10020 verbose(env, "cannot update sockmap in this context\n");
10021 return false;
10022 }
10023
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)10024 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
10025 {
10026 return env->prog->jit_requested &&
10027 bpf_jit_supports_subprog_tailcalls();
10028 }
10029
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)10030 static int check_map_func_compatibility(struct bpf_verifier_env *env,
10031 struct bpf_map *map, int func_id)
10032 {
10033 if (!map)
10034 return 0;
10035
10036 /* We need a two way check, first is from map perspective ... */
10037 switch (map->map_type) {
10038 case BPF_MAP_TYPE_PROG_ARRAY:
10039 if (func_id != BPF_FUNC_tail_call)
10040 goto error;
10041 break;
10042 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
10043 if (func_id != BPF_FUNC_perf_event_read &&
10044 func_id != BPF_FUNC_perf_event_output &&
10045 func_id != BPF_FUNC_skb_output &&
10046 func_id != BPF_FUNC_perf_event_read_value &&
10047 func_id != BPF_FUNC_xdp_output)
10048 goto error;
10049 break;
10050 case BPF_MAP_TYPE_RINGBUF:
10051 if (func_id != BPF_FUNC_ringbuf_output &&
10052 func_id != BPF_FUNC_ringbuf_reserve &&
10053 func_id != BPF_FUNC_ringbuf_query &&
10054 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
10055 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
10056 func_id != BPF_FUNC_ringbuf_discard_dynptr)
10057 goto error;
10058 break;
10059 case BPF_MAP_TYPE_USER_RINGBUF:
10060 if (func_id != BPF_FUNC_user_ringbuf_drain)
10061 goto error;
10062 break;
10063 case BPF_MAP_TYPE_STACK_TRACE:
10064 if (func_id != BPF_FUNC_get_stackid)
10065 goto error;
10066 break;
10067 case BPF_MAP_TYPE_CGROUP_ARRAY:
10068 if (func_id != BPF_FUNC_skb_under_cgroup &&
10069 func_id != BPF_FUNC_current_task_under_cgroup)
10070 goto error;
10071 break;
10072 case BPF_MAP_TYPE_CGROUP_STORAGE:
10073 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
10074 if (func_id != BPF_FUNC_get_local_storage)
10075 goto error;
10076 break;
10077 case BPF_MAP_TYPE_DEVMAP:
10078 case BPF_MAP_TYPE_DEVMAP_HASH:
10079 if (func_id != BPF_FUNC_redirect_map &&
10080 func_id != BPF_FUNC_map_lookup_elem)
10081 goto error;
10082 break;
10083 /* Restrict bpf side of cpumap and xskmap, open when use-cases
10084 * appear.
10085 */
10086 case BPF_MAP_TYPE_CPUMAP:
10087 if (func_id != BPF_FUNC_redirect_map)
10088 goto error;
10089 break;
10090 case BPF_MAP_TYPE_XSKMAP:
10091 if (func_id != BPF_FUNC_redirect_map &&
10092 func_id != BPF_FUNC_map_lookup_elem)
10093 goto error;
10094 break;
10095 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10096 case BPF_MAP_TYPE_HASH_OF_MAPS:
10097 if (func_id != BPF_FUNC_map_lookup_elem)
10098 goto error;
10099 break;
10100 case BPF_MAP_TYPE_SOCKMAP:
10101 if (func_id != BPF_FUNC_sk_redirect_map &&
10102 func_id != BPF_FUNC_sock_map_update &&
10103 func_id != BPF_FUNC_msg_redirect_map &&
10104 func_id != BPF_FUNC_sk_select_reuseport &&
10105 func_id != BPF_FUNC_map_lookup_elem &&
10106 !may_update_sockmap(env, func_id))
10107 goto error;
10108 break;
10109 case BPF_MAP_TYPE_SOCKHASH:
10110 if (func_id != BPF_FUNC_sk_redirect_hash &&
10111 func_id != BPF_FUNC_sock_hash_update &&
10112 func_id != BPF_FUNC_msg_redirect_hash &&
10113 func_id != BPF_FUNC_sk_select_reuseport &&
10114 func_id != BPF_FUNC_map_lookup_elem &&
10115 !may_update_sockmap(env, func_id))
10116 goto error;
10117 break;
10118 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
10119 if (func_id != BPF_FUNC_sk_select_reuseport)
10120 goto error;
10121 break;
10122 case BPF_MAP_TYPE_QUEUE:
10123 case BPF_MAP_TYPE_STACK:
10124 if (func_id != BPF_FUNC_map_peek_elem &&
10125 func_id != BPF_FUNC_map_pop_elem &&
10126 func_id != BPF_FUNC_map_push_elem)
10127 goto error;
10128 break;
10129 case BPF_MAP_TYPE_SK_STORAGE:
10130 if (func_id != BPF_FUNC_sk_storage_get &&
10131 func_id != BPF_FUNC_sk_storage_delete &&
10132 func_id != BPF_FUNC_kptr_xchg)
10133 goto error;
10134 break;
10135 case BPF_MAP_TYPE_INODE_STORAGE:
10136 if (func_id != BPF_FUNC_inode_storage_get &&
10137 func_id != BPF_FUNC_inode_storage_delete &&
10138 func_id != BPF_FUNC_kptr_xchg)
10139 goto error;
10140 break;
10141 case BPF_MAP_TYPE_TASK_STORAGE:
10142 if (func_id != BPF_FUNC_task_storage_get &&
10143 func_id != BPF_FUNC_task_storage_delete &&
10144 func_id != BPF_FUNC_kptr_xchg)
10145 goto error;
10146 break;
10147 case BPF_MAP_TYPE_CGRP_STORAGE:
10148 if (func_id != BPF_FUNC_cgrp_storage_get &&
10149 func_id != BPF_FUNC_cgrp_storage_delete &&
10150 func_id != BPF_FUNC_kptr_xchg)
10151 goto error;
10152 break;
10153 case BPF_MAP_TYPE_BLOOM_FILTER:
10154 if (func_id != BPF_FUNC_map_peek_elem &&
10155 func_id != BPF_FUNC_map_push_elem)
10156 goto error;
10157 break;
10158 case BPF_MAP_TYPE_INSN_ARRAY:
10159 goto error;
10160 default:
10161 break;
10162 }
10163
10164 /* ... and second from the function itself. */
10165 switch (func_id) {
10166 case BPF_FUNC_tail_call:
10167 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
10168 goto error;
10169 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
10170 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n");
10171 return -EINVAL;
10172 }
10173 break;
10174 case BPF_FUNC_perf_event_read:
10175 case BPF_FUNC_perf_event_output:
10176 case BPF_FUNC_perf_event_read_value:
10177 case BPF_FUNC_skb_output:
10178 case BPF_FUNC_xdp_output:
10179 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
10180 goto error;
10181 break;
10182 case BPF_FUNC_ringbuf_output:
10183 case BPF_FUNC_ringbuf_reserve:
10184 case BPF_FUNC_ringbuf_query:
10185 case BPF_FUNC_ringbuf_reserve_dynptr:
10186 case BPF_FUNC_ringbuf_submit_dynptr:
10187 case BPF_FUNC_ringbuf_discard_dynptr:
10188 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
10189 goto error;
10190 break;
10191 case BPF_FUNC_user_ringbuf_drain:
10192 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
10193 goto error;
10194 break;
10195 case BPF_FUNC_get_stackid:
10196 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
10197 goto error;
10198 break;
10199 case BPF_FUNC_current_task_under_cgroup:
10200 case BPF_FUNC_skb_under_cgroup:
10201 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
10202 goto error;
10203 break;
10204 case BPF_FUNC_redirect_map:
10205 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
10206 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
10207 map->map_type != BPF_MAP_TYPE_CPUMAP &&
10208 map->map_type != BPF_MAP_TYPE_XSKMAP)
10209 goto error;
10210 break;
10211 case BPF_FUNC_sk_redirect_map:
10212 case BPF_FUNC_msg_redirect_map:
10213 case BPF_FUNC_sock_map_update:
10214 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
10215 goto error;
10216 break;
10217 case BPF_FUNC_sk_redirect_hash:
10218 case BPF_FUNC_msg_redirect_hash:
10219 case BPF_FUNC_sock_hash_update:
10220 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
10221 goto error;
10222 break;
10223 case BPF_FUNC_get_local_storage:
10224 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
10225 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
10226 goto error;
10227 break;
10228 case BPF_FUNC_sk_select_reuseport:
10229 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
10230 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
10231 map->map_type != BPF_MAP_TYPE_SOCKHASH)
10232 goto error;
10233 break;
10234 case BPF_FUNC_map_pop_elem:
10235 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10236 map->map_type != BPF_MAP_TYPE_STACK)
10237 goto error;
10238 break;
10239 case BPF_FUNC_map_peek_elem:
10240 case BPF_FUNC_map_push_elem:
10241 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
10242 map->map_type != BPF_MAP_TYPE_STACK &&
10243 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
10244 goto error;
10245 break;
10246 case BPF_FUNC_map_lookup_percpu_elem:
10247 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
10248 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10249 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
10250 goto error;
10251 break;
10252 case BPF_FUNC_sk_storage_get:
10253 case BPF_FUNC_sk_storage_delete:
10254 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
10255 goto error;
10256 break;
10257 case BPF_FUNC_inode_storage_get:
10258 case BPF_FUNC_inode_storage_delete:
10259 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
10260 goto error;
10261 break;
10262 case BPF_FUNC_task_storage_get:
10263 case BPF_FUNC_task_storage_delete:
10264 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
10265 goto error;
10266 break;
10267 case BPF_FUNC_cgrp_storage_get:
10268 case BPF_FUNC_cgrp_storage_delete:
10269 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
10270 goto error;
10271 break;
10272 default:
10273 break;
10274 }
10275
10276 return 0;
10277 error:
10278 verbose(env, "cannot pass map_type %d into func %s#%d\n",
10279 map->map_type, func_id_name(func_id), func_id);
10280 return -EINVAL;
10281 }
10282
check_raw_mode_ok(const struct bpf_func_proto * fn)10283 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
10284 {
10285 int count = 0;
10286
10287 if (arg_type_is_raw_mem(fn->arg1_type))
10288 count++;
10289 if (arg_type_is_raw_mem(fn->arg2_type))
10290 count++;
10291 if (arg_type_is_raw_mem(fn->arg3_type))
10292 count++;
10293 if (arg_type_is_raw_mem(fn->arg4_type))
10294 count++;
10295 if (arg_type_is_raw_mem(fn->arg5_type))
10296 count++;
10297
10298 /* We only support one arg being in raw mode at the moment,
10299 * which is sufficient for the helper functions we have
10300 * right now.
10301 */
10302 return count <= 1;
10303 }
10304
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)10305 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
10306 {
10307 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
10308 bool has_size = fn->arg_size[arg] != 0;
10309 bool is_next_size = false;
10310
10311 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
10312 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
10313
10314 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
10315 return is_next_size;
10316
10317 return has_size == is_next_size || is_next_size == is_fixed;
10318 }
10319
check_arg_pair_ok(const struct bpf_func_proto * fn)10320 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
10321 {
10322 /* bpf_xxx(..., buf, len) call will access 'len'
10323 * bytes from memory 'buf'. Both arg types need
10324 * to be paired, so make sure there's no buggy
10325 * helper function specification.
10326 */
10327 if (arg_type_is_mem_size(fn->arg1_type) ||
10328 check_args_pair_invalid(fn, 0) ||
10329 check_args_pair_invalid(fn, 1) ||
10330 check_args_pair_invalid(fn, 2) ||
10331 check_args_pair_invalid(fn, 3) ||
10332 check_args_pair_invalid(fn, 4))
10333 return false;
10334
10335 return true;
10336 }
10337
check_btf_id_ok(const struct bpf_func_proto * fn)10338 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
10339 {
10340 int i;
10341
10342 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
10343 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
10344 return !!fn->arg_btf_id[i];
10345 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
10346 return fn->arg_btf_id[i] == BPF_PTR_POISON;
10347 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
10348 /* arg_btf_id and arg_size are in a union. */
10349 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
10350 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
10351 return false;
10352 }
10353
10354 return true;
10355 }
10356
check_func_proto(const struct bpf_func_proto * fn,int func_id)10357 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
10358 {
10359 return check_raw_mode_ok(fn) &&
10360 check_arg_pair_ok(fn) &&
10361 check_btf_id_ok(fn) ? 0 : -EINVAL;
10362 }
10363
10364 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
10365 * are now invalid, so turn them into unknown SCALAR_VALUE.
10366 *
10367 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
10368 * since these slices point to packet data.
10369 */
clear_all_pkt_pointers(struct bpf_verifier_env * env)10370 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
10371 {
10372 struct bpf_func_state *state;
10373 struct bpf_reg_state *reg;
10374
10375 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10376 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
10377 mark_reg_invalid(env, reg);
10378 }));
10379 }
10380
10381 enum {
10382 AT_PKT_END = -1,
10383 BEYOND_PKT_END = -2,
10384 };
10385
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)10386 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
10387 {
10388 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10389 struct bpf_reg_state *reg = &state->regs[regn];
10390
10391 if (reg->type != PTR_TO_PACKET)
10392 /* PTR_TO_PACKET_META is not supported yet */
10393 return;
10394
10395 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
10396 * How far beyond pkt_end it goes is unknown.
10397 * if (!range_open) it's the case of pkt >= pkt_end
10398 * if (range_open) it's the case of pkt > pkt_end
10399 * hence this pointer is at least 1 byte bigger than pkt_end
10400 */
10401 if (range_open)
10402 reg->range = BEYOND_PKT_END;
10403 else
10404 reg->range = AT_PKT_END;
10405 }
10406
release_reference_nomark(struct bpf_verifier_state * state,int ref_obj_id)10407 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id)
10408 {
10409 int i;
10410
10411 for (i = 0; i < state->acquired_refs; i++) {
10412 if (state->refs[i].type != REF_TYPE_PTR)
10413 continue;
10414 if (state->refs[i].id == ref_obj_id) {
10415 release_reference_state(state, i);
10416 return 0;
10417 }
10418 }
10419 return -EINVAL;
10420 }
10421
10422 /* The pointer with the specified id has released its reference to kernel
10423 * resources. Identify all copies of the same pointer and clear the reference.
10424 *
10425 * This is the release function corresponding to acquire_reference(). Idempotent.
10426 */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)10427 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id)
10428 {
10429 struct bpf_verifier_state *vstate = env->cur_state;
10430 struct bpf_func_state *state;
10431 struct bpf_reg_state *reg;
10432 int err;
10433
10434 err = release_reference_nomark(vstate, ref_obj_id);
10435 if (err)
10436 return err;
10437
10438 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10439 if (reg->ref_obj_id == ref_obj_id)
10440 mark_reg_invalid(env, reg);
10441 }));
10442
10443 return 0;
10444 }
10445
invalidate_non_owning_refs(struct bpf_verifier_env * env)10446 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
10447 {
10448 struct bpf_func_state *unused;
10449 struct bpf_reg_state *reg;
10450
10451 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10452 if (type_is_non_owning_ref(reg->type))
10453 mark_reg_invalid(env, reg);
10454 }));
10455 }
10456
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)10457 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
10458 struct bpf_reg_state *regs)
10459 {
10460 int i;
10461
10462 /* after the call registers r0 - r5 were scratched */
10463 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10464 mark_reg_not_init(env, regs, caller_saved[i]);
10465 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
10466 }
10467 }
10468
10469 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
10470 struct bpf_func_state *caller,
10471 struct bpf_func_state *callee,
10472 int insn_idx);
10473
10474 static int set_callee_state(struct bpf_verifier_env *env,
10475 struct bpf_func_state *caller,
10476 struct bpf_func_state *callee, int insn_idx);
10477
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)10478 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
10479 set_callee_state_fn set_callee_state_cb,
10480 struct bpf_verifier_state *state)
10481 {
10482 struct bpf_func_state *caller, *callee;
10483 int err;
10484
10485 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
10486 verbose(env, "the call stack of %d frames is too deep\n",
10487 state->curframe + 2);
10488 return -E2BIG;
10489 }
10490
10491 if (state->frame[state->curframe + 1]) {
10492 verifier_bug(env, "Frame %d already allocated", state->curframe + 1);
10493 return -EFAULT;
10494 }
10495
10496 caller = state->frame[state->curframe];
10497 callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT);
10498 if (!callee)
10499 return -ENOMEM;
10500 state->frame[state->curframe + 1] = callee;
10501
10502 /* callee cannot access r0, r6 - r9 for reading and has to write
10503 * into its own stack before reading from it.
10504 * callee can read/write into caller's stack
10505 */
10506 init_func_state(env, callee,
10507 /* remember the callsite, it will be used by bpf_exit */
10508 callsite,
10509 state->curframe + 1 /* frameno within this callchain */,
10510 subprog /* subprog number within this prog */);
10511 err = set_callee_state_cb(env, caller, callee, callsite);
10512 if (err)
10513 goto err_out;
10514
10515 /* only increment it after check_reg_arg() finished */
10516 state->curframe++;
10517
10518 return 0;
10519
10520 err_out:
10521 free_func_state(callee);
10522 state->frame[state->curframe + 1] = NULL;
10523 return err;
10524 }
10525
btf_check_func_arg_match(struct bpf_verifier_env * env,int subprog,const struct btf * btf,struct bpf_reg_state * regs)10526 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
10527 const struct btf *btf,
10528 struct bpf_reg_state *regs)
10529 {
10530 struct bpf_subprog_info *sub = subprog_info(env, subprog);
10531 struct bpf_verifier_log *log = &env->log;
10532 u32 i;
10533 int ret;
10534
10535 ret = btf_prepare_func_args(env, subprog);
10536 if (ret)
10537 return ret;
10538
10539 /* check that BTF function arguments match actual types that the
10540 * verifier sees.
10541 */
10542 for (i = 0; i < sub->arg_cnt; i++) {
10543 u32 regno = i + 1;
10544 struct bpf_reg_state *reg = ®s[regno];
10545 struct bpf_subprog_arg_info *arg = &sub->args[i];
10546
10547 if (arg->arg_type == ARG_ANYTHING) {
10548 if (reg->type != SCALAR_VALUE) {
10549 bpf_log(log, "R%d is not a scalar\n", regno);
10550 return -EINVAL;
10551 }
10552 } else if (arg->arg_type & PTR_UNTRUSTED) {
10553 /*
10554 * Anything is allowed for untrusted arguments, as these are
10555 * read-only and probe read instructions would protect against
10556 * invalid memory access.
10557 */
10558 } else if (arg->arg_type == ARG_PTR_TO_CTX) {
10559 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10560 if (ret < 0)
10561 return ret;
10562 /* If function expects ctx type in BTF check that caller
10563 * is passing PTR_TO_CTX.
10564 */
10565 if (reg->type != PTR_TO_CTX) {
10566 bpf_log(log, "arg#%d expects pointer to ctx\n", i);
10567 return -EINVAL;
10568 }
10569 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
10570 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE);
10571 if (ret < 0)
10572 return ret;
10573 if (check_mem_reg(env, reg, regno, arg->mem_size))
10574 return -EINVAL;
10575 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) {
10576 bpf_log(log, "arg#%d is expected to be non-NULL\n", i);
10577 return -EINVAL;
10578 }
10579 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
10580 /*
10581 * Can pass any value and the kernel won't crash, but
10582 * only PTR_TO_ARENA or SCALAR make sense. Everything
10583 * else is a bug in the bpf program. Point it out to
10584 * the user at the verification time instead of
10585 * run-time debug nightmare.
10586 */
10587 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) {
10588 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno);
10589 return -EINVAL;
10590 }
10591 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
10592 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR);
10593 if (ret)
10594 return ret;
10595
10596 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0);
10597 if (ret)
10598 return ret;
10599 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
10600 struct bpf_call_arg_meta meta;
10601 int err;
10602
10603 if (register_is_null(reg) && type_may_be_null(arg->arg_type))
10604 continue;
10605
10606 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */
10607 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta);
10608 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type);
10609 if (err)
10610 return err;
10611 } else {
10612 verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type);
10613 return -EFAULT;
10614 }
10615 }
10616
10617 return 0;
10618 }
10619
10620 /* Compare BTF of a function call with given bpf_reg_state.
10621 * Returns:
10622 * EFAULT - there is a verifier bug. Abort verification.
10623 * EINVAL - there is a type mismatch or BTF is not available.
10624 * 0 - BTF matches with what bpf_reg_state expects.
10625 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
10626 */
btf_check_subprog_call(struct bpf_verifier_env * env,int subprog,struct bpf_reg_state * regs)10627 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
10628 struct bpf_reg_state *regs)
10629 {
10630 struct bpf_prog *prog = env->prog;
10631 struct btf *btf = prog->aux->btf;
10632 u32 btf_id;
10633 int err;
10634
10635 if (!prog->aux->func_info)
10636 return -EINVAL;
10637
10638 btf_id = prog->aux->func_info[subprog].type_id;
10639 if (!btf_id)
10640 return -EFAULT;
10641
10642 if (prog->aux->func_info_aux[subprog].unreliable)
10643 return -EINVAL;
10644
10645 err = btf_check_func_arg_match(env, subprog, btf, regs);
10646 /* Compiler optimizations can remove arguments from static functions
10647 * or mismatched type can be passed into a global function.
10648 * In such cases mark the function as unreliable from BTF point of view.
10649 */
10650 if (err)
10651 prog->aux->func_info_aux[subprog].unreliable = true;
10652 return err;
10653 }
10654
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)10655 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10656 int insn_idx, int subprog,
10657 set_callee_state_fn set_callee_state_cb)
10658 {
10659 struct bpf_verifier_state *state = env->cur_state, *callback_state;
10660 struct bpf_func_state *caller, *callee;
10661 int err;
10662
10663 caller = state->frame[state->curframe];
10664 err = btf_check_subprog_call(env, subprog, caller->regs);
10665 if (err == -EFAULT)
10666 return err;
10667
10668 /* set_callee_state is used for direct subprog calls, but we are
10669 * interested in validating only BPF helpers that can call subprogs as
10670 * callbacks
10671 */
10672 env->subprog_info[subprog].is_cb = true;
10673 if (bpf_pseudo_kfunc_call(insn) &&
10674 !is_callback_calling_kfunc(insn->imm)) {
10675 verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
10676 func_id_name(insn->imm), insn->imm);
10677 return -EFAULT;
10678 } else if (!bpf_pseudo_kfunc_call(insn) &&
10679 !is_callback_calling_function(insn->imm)) { /* helper */
10680 verifier_bug(env, "helper %s#%d not marked as callback-calling",
10681 func_id_name(insn->imm), insn->imm);
10682 return -EFAULT;
10683 }
10684
10685 if (is_async_callback_calling_insn(insn)) {
10686 struct bpf_verifier_state *async_cb;
10687
10688 /* there is no real recursion here. timer and workqueue callbacks are async */
10689 env->subprog_info[subprog].is_async_cb = true;
10690 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
10691 insn_idx, subprog,
10692 is_async_cb_sleepable(env, insn));
10693 if (IS_ERR(async_cb))
10694 return PTR_ERR(async_cb);
10695 callee = async_cb->frame[0];
10696 callee->async_entry_cnt = caller->async_entry_cnt + 1;
10697
10698 /* Convert bpf_timer_set_callback() args into timer callback args */
10699 err = set_callee_state_cb(env, caller, callee, insn_idx);
10700 if (err)
10701 return err;
10702
10703 return 0;
10704 }
10705
10706 /* for callback functions enqueue entry to callback and
10707 * proceed with next instruction within current frame.
10708 */
10709 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
10710 if (IS_ERR(callback_state))
10711 return PTR_ERR(callback_state);
10712
10713 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
10714 callback_state);
10715 if (err)
10716 return err;
10717
10718 callback_state->callback_unroll_depth++;
10719 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
10720 caller->callback_depth = 0;
10721 return 0;
10722 }
10723
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)10724 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10725 int *insn_idx)
10726 {
10727 struct bpf_verifier_state *state = env->cur_state;
10728 struct bpf_func_state *caller;
10729 int err, subprog, target_insn;
10730
10731 target_insn = *insn_idx + insn->imm + 1;
10732 subprog = find_subprog(env, target_insn);
10733 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program",
10734 target_insn))
10735 return -EFAULT;
10736
10737 caller = state->frame[state->curframe];
10738 err = btf_check_subprog_call(env, subprog, caller->regs);
10739 if (err == -EFAULT)
10740 return err;
10741 if (subprog_is_global(env, subprog)) {
10742 const char *sub_name = subprog_name(env, subprog);
10743
10744 if (env->cur_state->active_locks) {
10745 verbose(env, "global function calls are not allowed while holding a lock,\n"
10746 "use static function instead\n");
10747 return -EINVAL;
10748 }
10749
10750 if (env->subprog_info[subprog].might_sleep &&
10751 (env->cur_state->active_rcu_locks || env->cur_state->active_preempt_locks ||
10752 env->cur_state->active_irq_id || !in_sleepable(env))) {
10753 verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n"
10754 "i.e., in a RCU/IRQ/preempt-disabled section, or in\n"
10755 "a non-sleepable BPF program context\n");
10756 return -EINVAL;
10757 }
10758
10759 if (err) {
10760 verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
10761 subprog, sub_name);
10762 return err;
10763 }
10764
10765 if (env->log.level & BPF_LOG_LEVEL)
10766 verbose(env, "Func#%d ('%s') is global and assumed valid.\n",
10767 subprog, sub_name);
10768 if (env->subprog_info[subprog].changes_pkt_data)
10769 clear_all_pkt_pointers(env);
10770 /* mark global subprog for verifying after main prog */
10771 subprog_aux(env, subprog)->called = true;
10772 clear_caller_saved_regs(env, caller->regs);
10773
10774 /* All global functions return a 64-bit SCALAR_VALUE */
10775 mark_reg_unknown(env, caller->regs, BPF_REG_0);
10776 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10777
10778 /* continue with next insn after call */
10779 return 0;
10780 }
10781
10782 /* for regular function entry setup new frame and continue
10783 * from that frame.
10784 */
10785 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
10786 if (err)
10787 return err;
10788
10789 clear_caller_saved_regs(env, caller->regs);
10790
10791 /* and go analyze first insn of the callee */
10792 *insn_idx = env->subprog_info[subprog].start - 1;
10793
10794 bpf_reset_live_stack_callchain(env);
10795
10796 if (env->log.level & BPF_LOG_LEVEL) {
10797 verbose(env, "caller:\n");
10798 print_verifier_state(env, state, caller->frameno, true);
10799 verbose(env, "callee:\n");
10800 print_verifier_state(env, state, state->curframe, true);
10801 }
10802
10803 return 0;
10804 }
10805
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)10806 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
10807 struct bpf_func_state *caller,
10808 struct bpf_func_state *callee)
10809 {
10810 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
10811 * void *callback_ctx, u64 flags);
10812 * callback_fn(struct bpf_map *map, void *key, void *value,
10813 * void *callback_ctx);
10814 */
10815 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10816
10817 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10818 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10819 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10820
10821 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10822 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10823 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
10824
10825 /* pointer to stack or null */
10826 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
10827
10828 /* unused */
10829 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10830 return 0;
10831 }
10832
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10833 static int set_callee_state(struct bpf_verifier_env *env,
10834 struct bpf_func_state *caller,
10835 struct bpf_func_state *callee, int insn_idx)
10836 {
10837 int i;
10838
10839 /* copy r1 - r5 args that callee can access. The copy includes parent
10840 * pointers, which connects us up to the liveness chain
10841 */
10842 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
10843 callee->regs[i] = caller->regs[i];
10844 return 0;
10845 }
10846
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10847 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
10848 struct bpf_func_state *caller,
10849 struct bpf_func_state *callee,
10850 int insn_idx)
10851 {
10852 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
10853 struct bpf_map *map;
10854 int err;
10855
10856 /* valid map_ptr and poison value does not matter */
10857 map = insn_aux->map_ptr_state.map_ptr;
10858 if (!map->ops->map_set_for_each_callback_args ||
10859 !map->ops->map_for_each_callback) {
10860 verbose(env, "callback function not allowed for map\n");
10861 return -ENOTSUPP;
10862 }
10863
10864 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
10865 if (err)
10866 return err;
10867
10868 callee->in_callback_fn = true;
10869 callee->callback_ret_range = retval_range(0, 1);
10870 return 0;
10871 }
10872
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10873 static int set_loop_callback_state(struct bpf_verifier_env *env,
10874 struct bpf_func_state *caller,
10875 struct bpf_func_state *callee,
10876 int insn_idx)
10877 {
10878 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
10879 * u64 flags);
10880 * callback_fn(u64 index, void *callback_ctx);
10881 */
10882 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
10883 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10884
10885 /* unused */
10886 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10887 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10888 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10889
10890 callee->in_callback_fn = true;
10891 callee->callback_ret_range = retval_range(0, 1);
10892 return 0;
10893 }
10894
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10895 static int set_timer_callback_state(struct bpf_verifier_env *env,
10896 struct bpf_func_state *caller,
10897 struct bpf_func_state *callee,
10898 int insn_idx)
10899 {
10900 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
10901
10902 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
10903 * callback_fn(struct bpf_map *map, void *key, void *value);
10904 */
10905 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
10906 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
10907 callee->regs[BPF_REG_1].map_ptr = map_ptr;
10908
10909 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
10910 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10911 callee->regs[BPF_REG_2].map_ptr = map_ptr;
10912
10913 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
10914 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
10915 callee->regs[BPF_REG_3].map_ptr = map_ptr;
10916
10917 /* unused */
10918 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10919 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10920 callee->in_async_callback_fn = true;
10921 callee->callback_ret_range = retval_range(0, 0);
10922 return 0;
10923 }
10924
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10925 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
10926 struct bpf_func_state *caller,
10927 struct bpf_func_state *callee,
10928 int insn_idx)
10929 {
10930 /* bpf_find_vma(struct task_struct *task, u64 addr,
10931 * void *callback_fn, void *callback_ctx, u64 flags)
10932 * (callback_fn)(struct task_struct *task,
10933 * struct vm_area_struct *vma, void *callback_ctx);
10934 */
10935 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
10936
10937 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
10938 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
10939 callee->regs[BPF_REG_2].btf = btf_vmlinux;
10940 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
10941
10942 /* pointer to stack or null */
10943 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
10944
10945 /* unused */
10946 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10947 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10948 callee->in_callback_fn = true;
10949 callee->callback_ret_range = retval_range(0, 1);
10950 return 0;
10951 }
10952
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10953 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
10954 struct bpf_func_state *caller,
10955 struct bpf_func_state *callee,
10956 int insn_idx)
10957 {
10958 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
10959 * callback_ctx, u64 flags);
10960 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
10961 */
10962 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
10963 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
10964 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
10965
10966 /* unused */
10967 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
10968 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
10969 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
10970
10971 callee->in_callback_fn = true;
10972 callee->callback_ret_range = retval_range(0, 1);
10973 return 0;
10974 }
10975
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)10976 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
10977 struct bpf_func_state *caller,
10978 struct bpf_func_state *callee,
10979 int insn_idx)
10980 {
10981 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
10982 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
10983 *
10984 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
10985 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
10986 * by this point, so look at 'root'
10987 */
10988 struct btf_field *field;
10989
10990 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
10991 BPF_RB_ROOT);
10992 if (!field || !field->graph_root.value_btf_id)
10993 return -EFAULT;
10994
10995 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
10996 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
10997 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
10998 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
10999
11000 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
11001 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11002 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11003 callee->in_callback_fn = true;
11004 callee->callback_ret_range = retval_range(0, 1);
11005 return 0;
11006 }
11007
set_task_work_schedule_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)11008 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env,
11009 struct bpf_func_state *caller,
11010 struct bpf_func_state *callee,
11011 int insn_idx)
11012 {
11013 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr;
11014
11015 /*
11016 * callback_fn(struct bpf_map *map, void *key, void *value);
11017 */
11018 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
11019 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
11020 callee->regs[BPF_REG_1].map_ptr = map_ptr;
11021
11022 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
11023 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
11024 callee->regs[BPF_REG_2].map_ptr = map_ptr;
11025
11026 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
11027 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
11028 callee->regs[BPF_REG_3].map_ptr = map_ptr;
11029
11030 /* unused */
11031 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
11032 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
11033 callee->in_async_callback_fn = true;
11034 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX);
11035 return 0;
11036 }
11037
11038 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
11039
11040 /* Are we currently verifying the callback for a rbtree helper that must
11041 * be called with lock held? If so, no need to complain about unreleased
11042 * lock
11043 */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)11044 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
11045 {
11046 struct bpf_verifier_state *state = env->cur_state;
11047 struct bpf_insn *insn = env->prog->insnsi;
11048 struct bpf_func_state *callee;
11049 int kfunc_btf_id;
11050
11051 if (!state->curframe)
11052 return false;
11053
11054 callee = state->frame[state->curframe];
11055
11056 if (!callee->in_callback_fn)
11057 return false;
11058
11059 kfunc_btf_id = insn[callee->callsite].imm;
11060 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
11061 }
11062
retval_range_within(struct bpf_retval_range range,const struct bpf_reg_state * reg,bool return_32bit)11063 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg,
11064 bool return_32bit)
11065 {
11066 if (return_32bit)
11067 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval;
11068 else
11069 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval;
11070 }
11071
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)11072 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
11073 {
11074 struct bpf_verifier_state *state = env->cur_state, *prev_st;
11075 struct bpf_func_state *caller, *callee;
11076 struct bpf_reg_state *r0;
11077 bool in_callback_fn;
11078 int err;
11079
11080 err = bpf_update_live_stack(env);
11081 if (err)
11082 return err;
11083
11084 callee = state->frame[state->curframe];
11085 r0 = &callee->regs[BPF_REG_0];
11086 if (r0->type == PTR_TO_STACK) {
11087 /* technically it's ok to return caller's stack pointer
11088 * (or caller's caller's pointer) back to the caller,
11089 * since these pointers are valid. Only current stack
11090 * pointer will be invalid as soon as function exits,
11091 * but let's be conservative
11092 */
11093 verbose(env, "cannot return stack pointer to the caller\n");
11094 return -EINVAL;
11095 }
11096
11097 caller = state->frame[state->curframe - 1];
11098 if (callee->in_callback_fn) {
11099 if (r0->type != SCALAR_VALUE) {
11100 verbose(env, "R0 not a scalar value\n");
11101 return -EACCES;
11102 }
11103
11104 /* we are going to rely on register's precise value */
11105 err = mark_chain_precision(env, BPF_REG_0);
11106 if (err)
11107 return err;
11108
11109 /* enforce R0 return value range, and bpf_callback_t returns 64bit */
11110 if (!retval_range_within(callee->callback_ret_range, r0, false)) {
11111 verbose_invalid_scalar(env, r0, callee->callback_ret_range,
11112 "At callback return", "R0");
11113 return -EINVAL;
11114 }
11115 if (!bpf_calls_callback(env, callee->callsite)) {
11116 verifier_bug(env, "in callback at %d, callsite %d !calls_callback",
11117 *insn_idx, callee->callsite);
11118 return -EFAULT;
11119 }
11120 } else {
11121 /* return to the caller whatever r0 had in the callee */
11122 caller->regs[BPF_REG_0] = *r0;
11123 }
11124
11125 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
11126 * there function call logic would reschedule callback visit. If iteration
11127 * converges is_state_visited() would prune that visit eventually.
11128 */
11129 in_callback_fn = callee->in_callback_fn;
11130 if (in_callback_fn)
11131 *insn_idx = callee->callsite;
11132 else
11133 *insn_idx = callee->callsite + 1;
11134
11135 if (env->log.level & BPF_LOG_LEVEL) {
11136 verbose(env, "returning from callee:\n");
11137 print_verifier_state(env, state, callee->frameno, true);
11138 verbose(env, "to caller at %d:\n", *insn_idx);
11139 print_verifier_state(env, state, caller->frameno, true);
11140 }
11141 /* clear everything in the callee. In case of exceptional exits using
11142 * bpf_throw, this will be done by copy_verifier_state for extra frames. */
11143 free_func_state(callee);
11144 state->frame[state->curframe--] = NULL;
11145
11146 /* for callbacks widen imprecise scalars to make programs like below verify:
11147 *
11148 * struct ctx { int i; }
11149 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
11150 * ...
11151 * struct ctx = { .i = 0; }
11152 * bpf_loop(100, cb, &ctx, 0);
11153 *
11154 * This is similar to what is done in process_iter_next_call() for open
11155 * coded iterators.
11156 */
11157 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
11158 if (prev_st) {
11159 err = widen_imprecise_scalars(env, prev_st, state);
11160 if (err)
11161 return err;
11162 }
11163 return 0;
11164 }
11165
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)11166 static int do_refine_retval_range(struct bpf_verifier_env *env,
11167 struct bpf_reg_state *regs, int ret_type,
11168 int func_id,
11169 struct bpf_call_arg_meta *meta)
11170 {
11171 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
11172
11173 if (ret_type != RET_INTEGER)
11174 return 0;
11175
11176 switch (func_id) {
11177 case BPF_FUNC_get_stack:
11178 case BPF_FUNC_get_task_stack:
11179 case BPF_FUNC_probe_read_str:
11180 case BPF_FUNC_probe_read_kernel_str:
11181 case BPF_FUNC_probe_read_user_str:
11182 ret_reg->smax_value = meta->msize_max_value;
11183 ret_reg->s32_max_value = meta->msize_max_value;
11184 ret_reg->smin_value = -MAX_ERRNO;
11185 ret_reg->s32_min_value = -MAX_ERRNO;
11186 reg_bounds_sync(ret_reg);
11187 break;
11188 case BPF_FUNC_get_smp_processor_id:
11189 ret_reg->umax_value = nr_cpu_ids - 1;
11190 ret_reg->u32_max_value = nr_cpu_ids - 1;
11191 ret_reg->smax_value = nr_cpu_ids - 1;
11192 ret_reg->s32_max_value = nr_cpu_ids - 1;
11193 ret_reg->umin_value = 0;
11194 ret_reg->u32_min_value = 0;
11195 ret_reg->smin_value = 0;
11196 ret_reg->s32_min_value = 0;
11197 reg_bounds_sync(ret_reg);
11198 break;
11199 }
11200
11201 return reg_bounds_sanity_check(env, ret_reg, "retval");
11202 }
11203
11204 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11205 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11206 int func_id, int insn_idx)
11207 {
11208 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11209 struct bpf_map *map = meta->map_ptr;
11210
11211 if (func_id != BPF_FUNC_tail_call &&
11212 func_id != BPF_FUNC_map_lookup_elem &&
11213 func_id != BPF_FUNC_map_update_elem &&
11214 func_id != BPF_FUNC_map_delete_elem &&
11215 func_id != BPF_FUNC_map_push_elem &&
11216 func_id != BPF_FUNC_map_pop_elem &&
11217 func_id != BPF_FUNC_map_peek_elem &&
11218 func_id != BPF_FUNC_for_each_map_elem &&
11219 func_id != BPF_FUNC_redirect_map &&
11220 func_id != BPF_FUNC_map_lookup_percpu_elem)
11221 return 0;
11222
11223 if (map == NULL) {
11224 verifier_bug(env, "expected map for helper call");
11225 return -EFAULT;
11226 }
11227
11228 /* In case of read-only, some additional restrictions
11229 * need to be applied in order to prevent altering the
11230 * state of the map from program side.
11231 */
11232 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
11233 (func_id == BPF_FUNC_map_delete_elem ||
11234 func_id == BPF_FUNC_map_update_elem ||
11235 func_id == BPF_FUNC_map_push_elem ||
11236 func_id == BPF_FUNC_map_pop_elem)) {
11237 verbose(env, "write into map forbidden\n");
11238 return -EACCES;
11239 }
11240
11241 if (!aux->map_ptr_state.map_ptr)
11242 bpf_map_ptr_store(aux, meta->map_ptr,
11243 !meta->map_ptr->bypass_spec_v1, false);
11244 else if (aux->map_ptr_state.map_ptr != meta->map_ptr)
11245 bpf_map_ptr_store(aux, meta->map_ptr,
11246 !meta->map_ptr->bypass_spec_v1, true);
11247 return 0;
11248 }
11249
11250 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)11251 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
11252 int func_id, int insn_idx)
11253 {
11254 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
11255 struct bpf_reg_state *regs = cur_regs(env), *reg;
11256 struct bpf_map *map = meta->map_ptr;
11257 u64 val, max;
11258 int err;
11259
11260 if (func_id != BPF_FUNC_tail_call)
11261 return 0;
11262 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
11263 verbose(env, "expected prog array map for tail call");
11264 return -EINVAL;
11265 }
11266
11267 reg = ®s[BPF_REG_3];
11268 val = reg->var_off.value;
11269 max = map->max_entries;
11270
11271 if (!(is_reg_const(reg, false) && val < max)) {
11272 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11273 return 0;
11274 }
11275
11276 err = mark_chain_precision(env, BPF_REG_3);
11277 if (err)
11278 return err;
11279 if (bpf_map_key_unseen(aux))
11280 bpf_map_key_store(aux, val);
11281 else if (!bpf_map_key_poisoned(aux) &&
11282 bpf_map_key_immediate(aux) != val)
11283 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
11284 return 0;
11285 }
11286
check_reference_leak(struct bpf_verifier_env * env,bool exception_exit)11287 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
11288 {
11289 struct bpf_verifier_state *state = env->cur_state;
11290 enum bpf_prog_type type = resolve_prog_type(env->prog);
11291 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
11292 bool refs_lingering = false;
11293 int i;
11294
11295 if (!exception_exit && cur_func(env)->frameno)
11296 return 0;
11297
11298 for (i = 0; i < state->acquired_refs; i++) {
11299 if (state->refs[i].type != REF_TYPE_PTR)
11300 continue;
11301 /* Allow struct_ops programs to return a referenced kptr back to
11302 * kernel. Type checks are performed later in check_return_code.
11303 */
11304 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit &&
11305 reg->ref_obj_id == state->refs[i].id)
11306 continue;
11307 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
11308 state->refs[i].id, state->refs[i].insn_idx);
11309 refs_lingering = true;
11310 }
11311 return refs_lingering ? -EINVAL : 0;
11312 }
11313
check_resource_leak(struct bpf_verifier_env * env,bool exception_exit,bool check_lock,const char * prefix)11314 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
11315 {
11316 int err;
11317
11318 if (check_lock && env->cur_state->active_locks) {
11319 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix);
11320 return -EINVAL;
11321 }
11322
11323 err = check_reference_leak(env, exception_exit);
11324 if (err) {
11325 verbose(env, "%s would lead to reference leak\n", prefix);
11326 return err;
11327 }
11328
11329 if (check_lock && env->cur_state->active_irq_id) {
11330 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix);
11331 return -EINVAL;
11332 }
11333
11334 if (check_lock && env->cur_state->active_rcu_locks) {
11335 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix);
11336 return -EINVAL;
11337 }
11338
11339 if (check_lock && env->cur_state->active_preempt_locks) {
11340 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix);
11341 return -EINVAL;
11342 }
11343
11344 return 0;
11345 }
11346
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)11347 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
11348 struct bpf_reg_state *regs)
11349 {
11350 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
11351 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
11352 struct bpf_map *fmt_map = fmt_reg->map_ptr;
11353 struct bpf_bprintf_data data = {};
11354 int err, fmt_map_off, num_args;
11355 u64 fmt_addr;
11356 char *fmt;
11357
11358 /* data must be an array of u64 */
11359 if (data_len_reg->var_off.value % 8)
11360 return -EINVAL;
11361 num_args = data_len_reg->var_off.value / 8;
11362
11363 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
11364 * and map_direct_value_addr is set.
11365 */
11366 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
11367 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
11368 fmt_map_off);
11369 if (err) {
11370 verbose(env, "failed to retrieve map value address\n");
11371 return -EFAULT;
11372 }
11373 fmt = (char *)(long)fmt_addr + fmt_map_off;
11374
11375 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
11376 * can focus on validating the format specifiers.
11377 */
11378 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
11379 if (err < 0)
11380 verbose(env, "Invalid format string\n");
11381
11382 return err;
11383 }
11384
check_get_func_ip(struct bpf_verifier_env * env)11385 static int check_get_func_ip(struct bpf_verifier_env *env)
11386 {
11387 enum bpf_prog_type type = resolve_prog_type(env->prog);
11388 int func_id = BPF_FUNC_get_func_ip;
11389
11390 if (type == BPF_PROG_TYPE_TRACING) {
11391 if (!bpf_prog_has_trampoline(env->prog)) {
11392 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
11393 func_id_name(func_id), func_id);
11394 return -ENOTSUPP;
11395 }
11396 return 0;
11397 } else if (type == BPF_PROG_TYPE_KPROBE) {
11398 return 0;
11399 }
11400
11401 verbose(env, "func %s#%d not supported for program type %d\n",
11402 func_id_name(func_id), func_id, type);
11403 return -ENOTSUPP;
11404 }
11405
cur_aux(const struct bpf_verifier_env * env)11406 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env)
11407 {
11408 return &env->insn_aux_data[env->insn_idx];
11409 }
11410
loop_flag_is_zero(struct bpf_verifier_env * env)11411 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
11412 {
11413 struct bpf_reg_state *regs = cur_regs(env);
11414 struct bpf_reg_state *reg = ®s[BPF_REG_4];
11415 bool reg_is_null = register_is_null(reg);
11416
11417 if (reg_is_null)
11418 mark_chain_precision(env, BPF_REG_4);
11419
11420 return reg_is_null;
11421 }
11422
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)11423 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
11424 {
11425 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
11426
11427 if (!state->initialized) {
11428 state->initialized = 1;
11429 state->fit_for_inline = loop_flag_is_zero(env);
11430 state->callback_subprogno = subprogno;
11431 return;
11432 }
11433
11434 if (!state->fit_for_inline)
11435 return;
11436
11437 state->fit_for_inline = (loop_flag_is_zero(env) &&
11438 state->callback_subprogno == subprogno);
11439 }
11440
11441 /* Returns whether or not the given map type can potentially elide
11442 * lookup return value nullness check. This is possible if the key
11443 * is statically known.
11444 */
can_elide_value_nullness(enum bpf_map_type type)11445 static bool can_elide_value_nullness(enum bpf_map_type type)
11446 {
11447 switch (type) {
11448 case BPF_MAP_TYPE_ARRAY:
11449 case BPF_MAP_TYPE_PERCPU_ARRAY:
11450 return true;
11451 default:
11452 return false;
11453 }
11454 }
11455
get_helper_proto(struct bpf_verifier_env * env,int func_id,const struct bpf_func_proto ** ptr)11456 static int get_helper_proto(struct bpf_verifier_env *env, int func_id,
11457 const struct bpf_func_proto **ptr)
11458 {
11459 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID)
11460 return -ERANGE;
11461
11462 if (!env->ops->get_func_proto)
11463 return -EINVAL;
11464
11465 *ptr = env->ops->get_func_proto(func_id, env->prog);
11466 return *ptr && (*ptr)->func ? 0 : -EINVAL;
11467 }
11468
11469 /* Check if we're in a sleepable context. */
in_sleepable_context(struct bpf_verifier_env * env)11470 static inline bool in_sleepable_context(struct bpf_verifier_env *env)
11471 {
11472 return !env->cur_state->active_rcu_locks &&
11473 !env->cur_state->active_preempt_locks &&
11474 !env->cur_state->active_irq_id &&
11475 in_sleepable(env);
11476 }
11477
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11478 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11479 int *insn_idx_p)
11480 {
11481 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11482 bool returns_cpu_specific_alloc_ptr = false;
11483 const struct bpf_func_proto *fn = NULL;
11484 enum bpf_return_type ret_type;
11485 enum bpf_type_flag ret_flag;
11486 struct bpf_reg_state *regs;
11487 struct bpf_call_arg_meta meta;
11488 int insn_idx = *insn_idx_p;
11489 bool changes_data;
11490 int i, err, func_id;
11491
11492 /* find function prototype */
11493 func_id = insn->imm;
11494 err = get_helper_proto(env, insn->imm, &fn);
11495 if (err == -ERANGE) {
11496 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id);
11497 return -EINVAL;
11498 }
11499
11500 if (err) {
11501 verbose(env, "program of this type cannot use helper %s#%d\n",
11502 func_id_name(func_id), func_id);
11503 return err;
11504 }
11505
11506 /* eBPF programs must be GPL compatible to use GPL-ed functions */
11507 if (!env->prog->gpl_compatible && fn->gpl_only) {
11508 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
11509 return -EINVAL;
11510 }
11511
11512 if (fn->allowed && !fn->allowed(env->prog)) {
11513 verbose(env, "helper call is not allowed in probe\n");
11514 return -EINVAL;
11515 }
11516
11517 if (!in_sleepable(env) && fn->might_sleep) {
11518 verbose(env, "helper call might sleep in a non-sleepable prog\n");
11519 return -EINVAL;
11520 }
11521
11522 /* With LD_ABS/IND some JITs save/restore skb from r1. */
11523 changes_data = bpf_helper_changes_pkt_data(func_id);
11524 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
11525 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id);
11526 return -EFAULT;
11527 }
11528
11529 memset(&meta, 0, sizeof(meta));
11530 meta.pkt_access = fn->pkt_access;
11531
11532 err = check_func_proto(fn, func_id);
11533 if (err) {
11534 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id);
11535 return err;
11536 }
11537
11538 if (env->cur_state->active_rcu_locks) {
11539 if (fn->might_sleep) {
11540 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
11541 func_id_name(func_id), func_id);
11542 return -EINVAL;
11543 }
11544 }
11545
11546 if (env->cur_state->active_preempt_locks) {
11547 if (fn->might_sleep) {
11548 verbose(env, "sleepable helper %s#%d in non-preemptible region\n",
11549 func_id_name(func_id), func_id);
11550 return -EINVAL;
11551 }
11552 }
11553
11554 if (env->cur_state->active_irq_id) {
11555 if (fn->might_sleep) {
11556 verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n",
11557 func_id_name(func_id), func_id);
11558 return -EINVAL;
11559 }
11560 }
11561
11562 /* Track non-sleepable context for helpers. */
11563 if (!in_sleepable_context(env))
11564 env->insn_aux_data[insn_idx].non_sleepable = true;
11565
11566 meta.func_id = func_id;
11567 /* check args */
11568 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
11569 err = check_func_arg(env, i, &meta, fn, insn_idx);
11570 if (err)
11571 return err;
11572 }
11573
11574 err = record_func_map(env, &meta, func_id, insn_idx);
11575 if (err)
11576 return err;
11577
11578 err = record_func_key(env, &meta, func_id, insn_idx);
11579 if (err)
11580 return err;
11581
11582 /* Mark slots with STACK_MISC in case of raw mode, stack offset
11583 * is inferred from register state.
11584 */
11585 for (i = 0; i < meta.access_size; i++) {
11586 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
11587 BPF_WRITE, -1, false, false);
11588 if (err)
11589 return err;
11590 }
11591
11592 regs = cur_regs(env);
11593
11594 if (meta.release_regno) {
11595 err = -EINVAL;
11596 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
11597 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
11598 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
11599 u32 ref_obj_id = meta.ref_obj_id;
11600 bool in_rcu = in_rcu_cs(env);
11601 struct bpf_func_state *state;
11602 struct bpf_reg_state *reg;
11603
11604 err = release_reference_nomark(env->cur_state, ref_obj_id);
11605 if (!err) {
11606 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11607 if (reg->ref_obj_id == ref_obj_id) {
11608 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
11609 reg->ref_obj_id = 0;
11610 reg->type &= ~MEM_ALLOC;
11611 reg->type |= MEM_RCU;
11612 } else {
11613 mark_reg_invalid(env, reg);
11614 }
11615 }
11616 }));
11617 }
11618 } else if (meta.ref_obj_id) {
11619 err = release_reference(env, meta.ref_obj_id);
11620 } else if (register_is_null(®s[meta.release_regno])) {
11621 /* meta.ref_obj_id can only be 0 if register that is meant to be
11622 * released is NULL, which must be > R0.
11623 */
11624 err = 0;
11625 }
11626 if (err) {
11627 verbose(env, "func %s#%d reference has not been acquired before\n",
11628 func_id_name(func_id), func_id);
11629 return err;
11630 }
11631 }
11632
11633 switch (func_id) {
11634 case BPF_FUNC_tail_call:
11635 err = check_resource_leak(env, false, true, "tail_call");
11636 if (err)
11637 return err;
11638 break;
11639 case BPF_FUNC_get_local_storage:
11640 /* check that flags argument in get_local_storage(map, flags) is 0,
11641 * this is required because get_local_storage() can't return an error.
11642 */
11643 if (!register_is_null(®s[BPF_REG_2])) {
11644 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
11645 return -EINVAL;
11646 }
11647 break;
11648 case BPF_FUNC_for_each_map_elem:
11649 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11650 set_map_elem_callback_state);
11651 break;
11652 case BPF_FUNC_timer_set_callback:
11653 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11654 set_timer_callback_state);
11655 break;
11656 case BPF_FUNC_find_vma:
11657 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11658 set_find_vma_callback_state);
11659 break;
11660 case BPF_FUNC_snprintf:
11661 err = check_bpf_snprintf_call(env, regs);
11662 break;
11663 case BPF_FUNC_loop:
11664 update_loop_inline_state(env, meta.subprogno);
11665 /* Verifier relies on R1 value to determine if bpf_loop() iteration
11666 * is finished, thus mark it precise.
11667 */
11668 err = mark_chain_precision(env, BPF_REG_1);
11669 if (err)
11670 return err;
11671 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
11672 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11673 set_loop_callback_state);
11674 } else {
11675 cur_func(env)->callback_depth = 0;
11676 if (env->log.level & BPF_LOG_LEVEL2)
11677 verbose(env, "frame%d bpf_loop iteration limit reached\n",
11678 env->cur_state->curframe);
11679 }
11680 break;
11681 case BPF_FUNC_dynptr_from_mem:
11682 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
11683 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
11684 reg_type_str(env, regs[BPF_REG_1].type));
11685 return -EACCES;
11686 }
11687 break;
11688 case BPF_FUNC_set_retval:
11689 if (prog_type == BPF_PROG_TYPE_LSM &&
11690 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
11691 if (!env->prog->aux->attach_func_proto->type) {
11692 /* Make sure programs that attach to void
11693 * hooks don't try to modify return value.
11694 */
11695 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
11696 return -EINVAL;
11697 }
11698 }
11699 break;
11700 case BPF_FUNC_dynptr_data:
11701 {
11702 struct bpf_reg_state *reg;
11703 int id, ref_obj_id;
11704
11705 reg = get_dynptr_arg_reg(env, fn, regs);
11706 if (!reg)
11707 return -EFAULT;
11708
11709
11710 if (meta.dynptr_id) {
11711 verifier_bug(env, "meta.dynptr_id already set");
11712 return -EFAULT;
11713 }
11714 if (meta.ref_obj_id) {
11715 verifier_bug(env, "meta.ref_obj_id already set");
11716 return -EFAULT;
11717 }
11718
11719 id = dynptr_id(env, reg);
11720 if (id < 0) {
11721 verifier_bug(env, "failed to obtain dynptr id");
11722 return id;
11723 }
11724
11725 ref_obj_id = dynptr_ref_obj_id(env, reg);
11726 if (ref_obj_id < 0) {
11727 verifier_bug(env, "failed to obtain dynptr ref_obj_id");
11728 return ref_obj_id;
11729 }
11730
11731 meta.dynptr_id = id;
11732 meta.ref_obj_id = ref_obj_id;
11733
11734 break;
11735 }
11736 case BPF_FUNC_dynptr_write:
11737 {
11738 enum bpf_dynptr_type dynptr_type;
11739 struct bpf_reg_state *reg;
11740
11741 reg = get_dynptr_arg_reg(env, fn, regs);
11742 if (!reg)
11743 return -EFAULT;
11744
11745 dynptr_type = dynptr_get_type(env, reg);
11746 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
11747 return -EFAULT;
11748
11749 if (dynptr_type == BPF_DYNPTR_TYPE_SKB ||
11750 dynptr_type == BPF_DYNPTR_TYPE_SKB_META)
11751 /* this will trigger clear_all_pkt_pointers(), which will
11752 * invalidate all dynptr slices associated with the skb
11753 */
11754 changes_data = true;
11755
11756 break;
11757 }
11758 case BPF_FUNC_per_cpu_ptr:
11759 case BPF_FUNC_this_cpu_ptr:
11760 {
11761 struct bpf_reg_state *reg = ®s[BPF_REG_1];
11762 const struct btf_type *type;
11763
11764 if (reg->type & MEM_RCU) {
11765 type = btf_type_by_id(reg->btf, reg->btf_id);
11766 if (!type || !btf_type_is_struct(type)) {
11767 verbose(env, "Helper has invalid btf/btf_id in R1\n");
11768 return -EFAULT;
11769 }
11770 returns_cpu_specific_alloc_ptr = true;
11771 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
11772 }
11773 break;
11774 }
11775 case BPF_FUNC_user_ringbuf_drain:
11776 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11777 set_user_ringbuf_callback_state);
11778 break;
11779 }
11780
11781 if (err)
11782 return err;
11783
11784 /* reset caller saved regs */
11785 for (i = 0; i < CALLER_SAVED_REGS; i++) {
11786 mark_reg_not_init(env, regs, caller_saved[i]);
11787 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
11788 }
11789
11790 /* helper call returns 64-bit value. */
11791 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
11792
11793 /* update return register (already marked as written above) */
11794 ret_type = fn->ret_type;
11795 ret_flag = type_flag(ret_type);
11796
11797 switch (base_type(ret_type)) {
11798 case RET_INTEGER:
11799 /* sets type to SCALAR_VALUE */
11800 mark_reg_unknown(env, regs, BPF_REG_0);
11801 break;
11802 case RET_VOID:
11803 regs[BPF_REG_0].type = NOT_INIT;
11804 break;
11805 case RET_PTR_TO_MAP_VALUE:
11806 /* There is no offset yet applied, variable or fixed */
11807 mark_reg_known_zero(env, regs, BPF_REG_0);
11808 /* remember map_ptr, so that check_map_access()
11809 * can check 'value_size' boundary of memory access
11810 * to map element returned from bpf_map_lookup_elem()
11811 */
11812 if (meta.map_ptr == NULL) {
11813 verifier_bug(env, "unexpected null map_ptr");
11814 return -EFAULT;
11815 }
11816
11817 if (func_id == BPF_FUNC_map_lookup_elem &&
11818 can_elide_value_nullness(meta.map_ptr->map_type) &&
11819 meta.const_map_key >= 0 &&
11820 meta.const_map_key < meta.map_ptr->max_entries)
11821 ret_flag &= ~PTR_MAYBE_NULL;
11822
11823 regs[BPF_REG_0].map_ptr = meta.map_ptr;
11824 regs[BPF_REG_0].map_uid = meta.map_uid;
11825 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
11826 if (!type_may_be_null(ret_flag) &&
11827 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
11828 regs[BPF_REG_0].id = ++env->id_gen;
11829 }
11830 break;
11831 case RET_PTR_TO_SOCKET:
11832 mark_reg_known_zero(env, regs, BPF_REG_0);
11833 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
11834 break;
11835 case RET_PTR_TO_SOCK_COMMON:
11836 mark_reg_known_zero(env, regs, BPF_REG_0);
11837 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
11838 break;
11839 case RET_PTR_TO_TCP_SOCK:
11840 mark_reg_known_zero(env, regs, BPF_REG_0);
11841 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
11842 break;
11843 case RET_PTR_TO_MEM:
11844 mark_reg_known_zero(env, regs, BPF_REG_0);
11845 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11846 regs[BPF_REG_0].mem_size = meta.mem_size;
11847 break;
11848 case RET_PTR_TO_MEM_OR_BTF_ID:
11849 {
11850 const struct btf_type *t;
11851
11852 mark_reg_known_zero(env, regs, BPF_REG_0);
11853 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
11854 if (!btf_type_is_struct(t)) {
11855 u32 tsize;
11856 const struct btf_type *ret;
11857 const char *tname;
11858
11859 /* resolve the type size of ksym. */
11860 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
11861 if (IS_ERR(ret)) {
11862 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
11863 verbose(env, "unable to resolve the size of type '%s': %ld\n",
11864 tname, PTR_ERR(ret));
11865 return -EINVAL;
11866 }
11867 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
11868 regs[BPF_REG_0].mem_size = tsize;
11869 } else {
11870 if (returns_cpu_specific_alloc_ptr) {
11871 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
11872 } else {
11873 /* MEM_RDONLY may be carried from ret_flag, but it
11874 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
11875 * it will confuse the check of PTR_TO_BTF_ID in
11876 * check_mem_access().
11877 */
11878 ret_flag &= ~MEM_RDONLY;
11879 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11880 }
11881
11882 regs[BPF_REG_0].btf = meta.ret_btf;
11883 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11884 }
11885 break;
11886 }
11887 case RET_PTR_TO_BTF_ID:
11888 {
11889 struct btf *ret_btf;
11890 int ret_btf_id;
11891
11892 mark_reg_known_zero(env, regs, BPF_REG_0);
11893 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
11894 if (func_id == BPF_FUNC_kptr_xchg) {
11895 ret_btf = meta.kptr_field->kptr.btf;
11896 ret_btf_id = meta.kptr_field->kptr.btf_id;
11897 if (!btf_is_kernel(ret_btf)) {
11898 regs[BPF_REG_0].type |= MEM_ALLOC;
11899 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
11900 regs[BPF_REG_0].type |= MEM_PERCPU;
11901 }
11902 } else {
11903 if (fn->ret_btf_id == BPF_PTR_POISON) {
11904 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type",
11905 func_id_name(func_id));
11906 return -EFAULT;
11907 }
11908 ret_btf = btf_vmlinux;
11909 ret_btf_id = *fn->ret_btf_id;
11910 }
11911 if (ret_btf_id == 0) {
11912 verbose(env, "invalid return type %u of func %s#%d\n",
11913 base_type(ret_type), func_id_name(func_id),
11914 func_id);
11915 return -EINVAL;
11916 }
11917 regs[BPF_REG_0].btf = ret_btf;
11918 regs[BPF_REG_0].btf_id = ret_btf_id;
11919 break;
11920 }
11921 default:
11922 verbose(env, "unknown return type %u of func %s#%d\n",
11923 base_type(ret_type), func_id_name(func_id), func_id);
11924 return -EINVAL;
11925 }
11926
11927 if (type_may_be_null(regs[BPF_REG_0].type))
11928 regs[BPF_REG_0].id = ++env->id_gen;
11929
11930 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
11931 verifier_bug(env, "func %s#%d sets ref_obj_id more than once",
11932 func_id_name(func_id), func_id);
11933 return -EFAULT;
11934 }
11935
11936 if (is_dynptr_ref_function(func_id))
11937 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
11938
11939 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
11940 /* For release_reference() */
11941 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11942 } else if (is_acquire_function(func_id, meta.map_ptr)) {
11943 int id = acquire_reference(env, insn_idx);
11944
11945 if (id < 0)
11946 return id;
11947 /* For mark_ptr_or_null_reg() */
11948 regs[BPF_REG_0].id = id;
11949 /* For release_reference() */
11950 regs[BPF_REG_0].ref_obj_id = id;
11951 }
11952
11953 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
11954 if (err)
11955 return err;
11956
11957 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
11958 if (err)
11959 return err;
11960
11961 if ((func_id == BPF_FUNC_get_stack ||
11962 func_id == BPF_FUNC_get_task_stack) &&
11963 !env->prog->has_callchain_buf) {
11964 const char *err_str;
11965
11966 #ifdef CONFIG_PERF_EVENTS
11967 err = get_callchain_buffers(sysctl_perf_event_max_stack);
11968 err_str = "cannot get callchain buffer for func %s#%d\n";
11969 #else
11970 err = -ENOTSUPP;
11971 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
11972 #endif
11973 if (err) {
11974 verbose(env, err_str, func_id_name(func_id), func_id);
11975 return err;
11976 }
11977
11978 env->prog->has_callchain_buf = true;
11979 }
11980
11981 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
11982 env->prog->call_get_stack = true;
11983
11984 if (func_id == BPF_FUNC_get_func_ip) {
11985 if (check_get_func_ip(env))
11986 return -ENOTSUPP;
11987 env->prog->call_get_func_ip = true;
11988 }
11989
11990 if (func_id == BPF_FUNC_tail_call) {
11991 if (env->cur_state->curframe) {
11992 struct bpf_verifier_state *branch;
11993
11994 mark_reg_scratched(env, BPF_REG_0);
11995 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
11996 if (IS_ERR(branch))
11997 return PTR_ERR(branch);
11998 clear_all_pkt_pointers(env);
11999 mark_reg_unknown(env, regs, BPF_REG_0);
12000 err = prepare_func_exit(env, &env->insn_idx);
12001 if (err)
12002 return err;
12003 env->insn_idx--;
12004 } else {
12005 changes_data = false;
12006 }
12007 }
12008
12009 if (changes_data)
12010 clear_all_pkt_pointers(env);
12011 return 0;
12012 }
12013
12014 /* mark_btf_func_reg_size() is used when the reg size is determined by
12015 * the BTF func_proto's return value size and argument.
12016 */
__mark_btf_func_reg_size(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,size_t reg_size)12017 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs,
12018 u32 regno, size_t reg_size)
12019 {
12020 struct bpf_reg_state *reg = ®s[regno];
12021
12022 if (regno == BPF_REG_0) {
12023 /* Function return value */
12024 reg->subreg_def = reg_size == sizeof(u64) ?
12025 DEF_NOT_SUBREG : env->insn_idx + 1;
12026 } else if (reg_size == sizeof(u64)) {
12027 /* Function argument */
12028 mark_insn_zext(env, reg);
12029 }
12030 }
12031
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)12032 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
12033 size_t reg_size)
12034 {
12035 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size);
12036 }
12037
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)12038 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
12039 {
12040 return meta->kfunc_flags & KF_ACQUIRE;
12041 }
12042
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)12043 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
12044 {
12045 return meta->kfunc_flags & KF_RELEASE;
12046 }
12047
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)12048 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
12049 {
12050 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
12051 }
12052
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)12053 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
12054 {
12055 return meta->kfunc_flags & KF_SLEEPABLE;
12056 }
12057
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)12058 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
12059 {
12060 return meta->kfunc_flags & KF_DESTRUCTIVE;
12061 }
12062
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)12063 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
12064 {
12065 return meta->kfunc_flags & KF_RCU;
12066 }
12067
is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta * meta)12068 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
12069 {
12070 return meta->kfunc_flags & KF_RCU_PROTECTED;
12071 }
12072
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)12073 static bool is_kfunc_arg_mem_size(const struct btf *btf,
12074 const struct btf_param *arg,
12075 const struct bpf_reg_state *reg)
12076 {
12077 const struct btf_type *t;
12078
12079 t = btf_type_skip_modifiers(btf, arg->type, NULL);
12080 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12081 return false;
12082
12083 return btf_param_match_suffix(btf, arg, "__sz");
12084 }
12085
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)12086 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
12087 const struct btf_param *arg,
12088 const struct bpf_reg_state *reg)
12089 {
12090 const struct btf_type *t;
12091
12092 t = btf_type_skip_modifiers(btf, arg->type, NULL);
12093 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
12094 return false;
12095
12096 return btf_param_match_suffix(btf, arg, "__szk");
12097 }
12098
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)12099 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
12100 {
12101 return btf_param_match_suffix(btf, arg, "__opt");
12102 }
12103
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)12104 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
12105 {
12106 return btf_param_match_suffix(btf, arg, "__k");
12107 }
12108
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)12109 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
12110 {
12111 return btf_param_match_suffix(btf, arg, "__ign");
12112 }
12113
is_kfunc_arg_map(const struct btf * btf,const struct btf_param * arg)12114 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg)
12115 {
12116 return btf_param_match_suffix(btf, arg, "__map");
12117 }
12118
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)12119 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
12120 {
12121 return btf_param_match_suffix(btf, arg, "__alloc");
12122 }
12123
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)12124 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
12125 {
12126 return btf_param_match_suffix(btf, arg, "__uninit");
12127 }
12128
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)12129 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
12130 {
12131 return btf_param_match_suffix(btf, arg, "__refcounted_kptr");
12132 }
12133
is_kfunc_arg_nullable(const struct btf * btf,const struct btf_param * arg)12134 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
12135 {
12136 return btf_param_match_suffix(btf, arg, "__nullable");
12137 }
12138
is_kfunc_arg_const_str(const struct btf * btf,const struct btf_param * arg)12139 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg)
12140 {
12141 return btf_param_match_suffix(btf, arg, "__str");
12142 }
12143
is_kfunc_arg_irq_flag(const struct btf * btf,const struct btf_param * arg)12144 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg)
12145 {
12146 return btf_param_match_suffix(btf, arg, "__irq_flag");
12147 }
12148
is_kfunc_arg_prog(const struct btf * btf,const struct btf_param * arg)12149 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg)
12150 {
12151 return btf_param_match_suffix(btf, arg, "__prog");
12152 }
12153
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)12154 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
12155 const struct btf_param *arg,
12156 const char *name)
12157 {
12158 int len, target_len = strlen(name);
12159 const char *param_name;
12160
12161 param_name = btf_name_by_offset(btf, arg->name_off);
12162 if (str_is_empty(param_name))
12163 return false;
12164 len = strlen(param_name);
12165 if (len != target_len)
12166 return false;
12167 if (strcmp(param_name, name))
12168 return false;
12169
12170 return true;
12171 }
12172
12173 enum {
12174 KF_ARG_DYNPTR_ID,
12175 KF_ARG_LIST_HEAD_ID,
12176 KF_ARG_LIST_NODE_ID,
12177 KF_ARG_RB_ROOT_ID,
12178 KF_ARG_RB_NODE_ID,
12179 KF_ARG_WORKQUEUE_ID,
12180 KF_ARG_RES_SPIN_LOCK_ID,
12181 KF_ARG_TASK_WORK_ID,
12182 };
12183
12184 BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr)12185 BTF_ID(struct, bpf_dynptr)
12186 BTF_ID(struct, bpf_list_head)
12187 BTF_ID(struct, bpf_list_node)
12188 BTF_ID(struct, bpf_rb_root)
12189 BTF_ID(struct, bpf_rb_node)
12190 BTF_ID(struct, bpf_wq)
12191 BTF_ID(struct, bpf_res_spin_lock)
12192 BTF_ID(struct, bpf_task_work)
12193
12194 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
12195 const struct btf_param *arg, int type)
12196 {
12197 const struct btf_type *t;
12198 u32 res_id;
12199
12200 t = btf_type_skip_modifiers(btf, arg->type, NULL);
12201 if (!t)
12202 return false;
12203 if (!btf_type_is_ptr(t))
12204 return false;
12205 t = btf_type_skip_modifiers(btf, t->type, &res_id);
12206 if (!t)
12207 return false;
12208 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
12209 }
12210
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)12211 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
12212 {
12213 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
12214 }
12215
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)12216 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
12217 {
12218 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
12219 }
12220
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)12221 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
12222 {
12223 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
12224 }
12225
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)12226 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
12227 {
12228 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
12229 }
12230
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)12231 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
12232 {
12233 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
12234 }
12235
is_kfunc_arg_wq(const struct btf * btf,const struct btf_param * arg)12236 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg)
12237 {
12238 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID);
12239 }
12240
is_kfunc_arg_task_work(const struct btf * btf,const struct btf_param * arg)12241 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg)
12242 {
12243 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID);
12244 }
12245
is_kfunc_arg_res_spin_lock(const struct btf * btf,const struct btf_param * arg)12246 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg)
12247 {
12248 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID);
12249 }
12250
is_rbtree_node_type(const struct btf_type * t)12251 static bool is_rbtree_node_type(const struct btf_type *t)
12252 {
12253 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]);
12254 }
12255
is_list_node_type(const struct btf_type * t)12256 static bool is_list_node_type(const struct btf_type *t)
12257 {
12258 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]);
12259 }
12260
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)12261 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
12262 const struct btf_param *arg)
12263 {
12264 const struct btf_type *t;
12265
12266 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
12267 if (!t)
12268 return false;
12269
12270 return true;
12271 }
12272
12273 /* 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)12274 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
12275 const struct btf *btf,
12276 const struct btf_type *t, int rec)
12277 {
12278 const struct btf_type *member_type;
12279 const struct btf_member *member;
12280 u32 i;
12281
12282 if (!btf_type_is_struct(t))
12283 return false;
12284
12285 for_each_member(i, t, member) {
12286 const struct btf_array *array;
12287
12288 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
12289 if (btf_type_is_struct(member_type)) {
12290 if (rec >= 3) {
12291 verbose(env, "max struct nesting depth exceeded\n");
12292 return false;
12293 }
12294 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
12295 return false;
12296 continue;
12297 }
12298 if (btf_type_is_array(member_type)) {
12299 array = btf_array(member_type);
12300 if (!array->nelems)
12301 return false;
12302 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
12303 if (!btf_type_is_scalar(member_type))
12304 return false;
12305 continue;
12306 }
12307 if (!btf_type_is_scalar(member_type))
12308 return false;
12309 }
12310 return true;
12311 }
12312
12313 enum kfunc_ptr_arg_type {
12314 KF_ARG_PTR_TO_CTX,
12315 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
12316 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
12317 KF_ARG_PTR_TO_DYNPTR,
12318 KF_ARG_PTR_TO_ITER,
12319 KF_ARG_PTR_TO_LIST_HEAD,
12320 KF_ARG_PTR_TO_LIST_NODE,
12321 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
12322 KF_ARG_PTR_TO_MEM,
12323 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
12324 KF_ARG_PTR_TO_CALLBACK,
12325 KF_ARG_PTR_TO_RB_ROOT,
12326 KF_ARG_PTR_TO_RB_NODE,
12327 KF_ARG_PTR_TO_NULL,
12328 KF_ARG_PTR_TO_CONST_STR,
12329 KF_ARG_PTR_TO_MAP,
12330 KF_ARG_PTR_TO_WORKQUEUE,
12331 KF_ARG_PTR_TO_IRQ_FLAG,
12332 KF_ARG_PTR_TO_RES_SPIN_LOCK,
12333 KF_ARG_PTR_TO_TASK_WORK,
12334 };
12335
12336 enum special_kfunc_type {
12337 KF_bpf_obj_new_impl,
12338 KF_bpf_obj_drop_impl,
12339 KF_bpf_refcount_acquire_impl,
12340 KF_bpf_list_push_front_impl,
12341 KF_bpf_list_push_back_impl,
12342 KF_bpf_list_pop_front,
12343 KF_bpf_list_pop_back,
12344 KF_bpf_list_front,
12345 KF_bpf_list_back,
12346 KF_bpf_cast_to_kern_ctx,
12347 KF_bpf_rdonly_cast,
12348 KF_bpf_rcu_read_lock,
12349 KF_bpf_rcu_read_unlock,
12350 KF_bpf_rbtree_remove,
12351 KF_bpf_rbtree_add_impl,
12352 KF_bpf_rbtree_first,
12353 KF_bpf_rbtree_root,
12354 KF_bpf_rbtree_left,
12355 KF_bpf_rbtree_right,
12356 KF_bpf_dynptr_from_skb,
12357 KF_bpf_dynptr_from_xdp,
12358 KF_bpf_dynptr_from_skb_meta,
12359 KF_bpf_xdp_pull_data,
12360 KF_bpf_dynptr_slice,
12361 KF_bpf_dynptr_slice_rdwr,
12362 KF_bpf_dynptr_clone,
12363 KF_bpf_percpu_obj_new_impl,
12364 KF_bpf_percpu_obj_drop_impl,
12365 KF_bpf_throw,
12366 KF_bpf_wq_set_callback_impl,
12367 KF_bpf_preempt_disable,
12368 KF_bpf_preempt_enable,
12369 KF_bpf_iter_css_task_new,
12370 KF_bpf_session_cookie,
12371 KF_bpf_get_kmem_cache,
12372 KF_bpf_local_irq_save,
12373 KF_bpf_local_irq_restore,
12374 KF_bpf_iter_num_new,
12375 KF_bpf_iter_num_next,
12376 KF_bpf_iter_num_destroy,
12377 KF_bpf_set_dentry_xattr,
12378 KF_bpf_remove_dentry_xattr,
12379 KF_bpf_res_spin_lock,
12380 KF_bpf_res_spin_unlock,
12381 KF_bpf_res_spin_lock_irqsave,
12382 KF_bpf_res_spin_unlock_irqrestore,
12383 KF_bpf_dynptr_from_file,
12384 KF_bpf_dynptr_file_discard,
12385 KF___bpf_trap,
12386 KF_bpf_task_work_schedule_signal_impl,
12387 KF_bpf_task_work_schedule_resume_impl,
12388 };
12389
12390 BTF_ID_LIST(special_kfunc_list)
BTF_ID(func,bpf_obj_new_impl)12391 BTF_ID(func, bpf_obj_new_impl)
12392 BTF_ID(func, bpf_obj_drop_impl)
12393 BTF_ID(func, bpf_refcount_acquire_impl)
12394 BTF_ID(func, bpf_list_push_front_impl)
12395 BTF_ID(func, bpf_list_push_back_impl)
12396 BTF_ID(func, bpf_list_pop_front)
12397 BTF_ID(func, bpf_list_pop_back)
12398 BTF_ID(func, bpf_list_front)
12399 BTF_ID(func, bpf_list_back)
12400 BTF_ID(func, bpf_cast_to_kern_ctx)
12401 BTF_ID(func, bpf_rdonly_cast)
12402 BTF_ID(func, bpf_rcu_read_lock)
12403 BTF_ID(func, bpf_rcu_read_unlock)
12404 BTF_ID(func, bpf_rbtree_remove)
12405 BTF_ID(func, bpf_rbtree_add_impl)
12406 BTF_ID(func, bpf_rbtree_first)
12407 BTF_ID(func, bpf_rbtree_root)
12408 BTF_ID(func, bpf_rbtree_left)
12409 BTF_ID(func, bpf_rbtree_right)
12410 #ifdef CONFIG_NET
12411 BTF_ID(func, bpf_dynptr_from_skb)
12412 BTF_ID(func, bpf_dynptr_from_xdp)
12413 BTF_ID(func, bpf_dynptr_from_skb_meta)
12414 BTF_ID(func, bpf_xdp_pull_data)
12415 #else
12416 BTF_ID_UNUSED
12417 BTF_ID_UNUSED
12418 BTF_ID_UNUSED
12419 BTF_ID_UNUSED
12420 #endif
12421 BTF_ID(func, bpf_dynptr_slice)
12422 BTF_ID(func, bpf_dynptr_slice_rdwr)
12423 BTF_ID(func, bpf_dynptr_clone)
12424 BTF_ID(func, bpf_percpu_obj_new_impl)
12425 BTF_ID(func, bpf_percpu_obj_drop_impl)
12426 BTF_ID(func, bpf_throw)
12427 BTF_ID(func, bpf_wq_set_callback_impl)
12428 BTF_ID(func, bpf_preempt_disable)
12429 BTF_ID(func, bpf_preempt_enable)
12430 #ifdef CONFIG_CGROUPS
12431 BTF_ID(func, bpf_iter_css_task_new)
12432 #else
12433 BTF_ID_UNUSED
12434 #endif
12435 #ifdef CONFIG_BPF_EVENTS
12436 BTF_ID(func, bpf_session_cookie)
12437 #else
12438 BTF_ID_UNUSED
12439 #endif
12440 BTF_ID(func, bpf_get_kmem_cache)
12441 BTF_ID(func, bpf_local_irq_save)
12442 BTF_ID(func, bpf_local_irq_restore)
12443 BTF_ID(func, bpf_iter_num_new)
12444 BTF_ID(func, bpf_iter_num_next)
12445 BTF_ID(func, bpf_iter_num_destroy)
12446 #ifdef CONFIG_BPF_LSM
12447 BTF_ID(func, bpf_set_dentry_xattr)
12448 BTF_ID(func, bpf_remove_dentry_xattr)
12449 #else
12450 BTF_ID_UNUSED
12451 BTF_ID_UNUSED
12452 #endif
12453 BTF_ID(func, bpf_res_spin_lock)
12454 BTF_ID(func, bpf_res_spin_unlock)
12455 BTF_ID(func, bpf_res_spin_lock_irqsave)
12456 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
12457 BTF_ID(func, bpf_dynptr_from_file)
12458 BTF_ID(func, bpf_dynptr_file_discard)
12459 BTF_ID(func, __bpf_trap)
12460 BTF_ID(func, bpf_task_work_schedule_signal_impl)
12461 BTF_ID(func, bpf_task_work_schedule_resume_impl)
12462
12463 static bool is_task_work_add_kfunc(u32 func_id)
12464 {
12465 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal_impl] ||
12466 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume_impl];
12467 }
12468
is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta * meta)12469 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
12470 {
12471 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
12472 meta->arg_owning_ref) {
12473 return false;
12474 }
12475
12476 return meta->kfunc_flags & KF_RET_NULL;
12477 }
12478
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)12479 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
12480 {
12481 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
12482 }
12483
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)12484 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
12485 {
12486 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
12487 }
12488
is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta * meta)12489 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta)
12490 {
12491 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable];
12492 }
12493
is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta * meta)12494 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta)
12495 {
12496 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable];
12497 }
12498
is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta * meta)12499 static bool is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta)
12500 {
12501 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data];
12502 }
12503
12504 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)12505 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
12506 struct bpf_kfunc_call_arg_meta *meta,
12507 const struct btf_type *t, const struct btf_type *ref_t,
12508 const char *ref_tname, const struct btf_param *args,
12509 int argno, int nargs)
12510 {
12511 u32 regno = argno + 1;
12512 struct bpf_reg_state *regs = cur_regs(env);
12513 struct bpf_reg_state *reg = ®s[regno];
12514 bool arg_mem_size = false;
12515
12516 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
12517 return KF_ARG_PTR_TO_CTX;
12518
12519 /* In this function, we verify the kfunc's BTF as per the argument type,
12520 * leaving the rest of the verification with respect to the register
12521 * type to our caller. When a set of conditions hold in the BTF type of
12522 * arguments, we resolve it to a known kfunc_ptr_arg_type.
12523 */
12524 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
12525 return KF_ARG_PTR_TO_CTX;
12526
12527 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
12528 return KF_ARG_PTR_TO_NULL;
12529
12530 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
12531 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
12532
12533 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
12534 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
12535
12536 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
12537 return KF_ARG_PTR_TO_DYNPTR;
12538
12539 if (is_kfunc_arg_iter(meta, argno, &args[argno]))
12540 return KF_ARG_PTR_TO_ITER;
12541
12542 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
12543 return KF_ARG_PTR_TO_LIST_HEAD;
12544
12545 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
12546 return KF_ARG_PTR_TO_LIST_NODE;
12547
12548 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
12549 return KF_ARG_PTR_TO_RB_ROOT;
12550
12551 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
12552 return KF_ARG_PTR_TO_RB_NODE;
12553
12554 if (is_kfunc_arg_const_str(meta->btf, &args[argno]))
12555 return KF_ARG_PTR_TO_CONST_STR;
12556
12557 if (is_kfunc_arg_map(meta->btf, &args[argno]))
12558 return KF_ARG_PTR_TO_MAP;
12559
12560 if (is_kfunc_arg_wq(meta->btf, &args[argno]))
12561 return KF_ARG_PTR_TO_WORKQUEUE;
12562
12563 if (is_kfunc_arg_task_work(meta->btf, &args[argno]))
12564 return KF_ARG_PTR_TO_TASK_WORK;
12565
12566 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno]))
12567 return KF_ARG_PTR_TO_IRQ_FLAG;
12568
12569 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno]))
12570 return KF_ARG_PTR_TO_RES_SPIN_LOCK;
12571
12572 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
12573 if (!btf_type_is_struct(ref_t)) {
12574 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
12575 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
12576 return -EINVAL;
12577 }
12578 return KF_ARG_PTR_TO_BTF_ID;
12579 }
12580
12581 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
12582 return KF_ARG_PTR_TO_CALLBACK;
12583
12584 if (argno + 1 < nargs &&
12585 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
12586 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
12587 arg_mem_size = true;
12588
12589 /* This is the catch all argument type of register types supported by
12590 * check_helper_mem_access. However, we only allow when argument type is
12591 * pointer to scalar, or struct composed (recursively) of scalars. When
12592 * arg_mem_size is true, the pointer can be void *.
12593 */
12594 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
12595 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
12596 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
12597 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
12598 return -EINVAL;
12599 }
12600 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
12601 }
12602
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)12603 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
12604 struct bpf_reg_state *reg,
12605 const struct btf_type *ref_t,
12606 const char *ref_tname, u32 ref_id,
12607 struct bpf_kfunc_call_arg_meta *meta,
12608 int argno)
12609 {
12610 const struct btf_type *reg_ref_t;
12611 bool strict_type_match = false;
12612 const struct btf *reg_btf;
12613 const char *reg_ref_tname;
12614 bool taking_projection;
12615 bool struct_same;
12616 u32 reg_ref_id;
12617
12618 if (base_type(reg->type) == PTR_TO_BTF_ID) {
12619 reg_btf = reg->btf;
12620 reg_ref_id = reg->btf_id;
12621 } else {
12622 reg_btf = btf_vmlinux;
12623 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
12624 }
12625
12626 /* Enforce strict type matching for calls to kfuncs that are acquiring
12627 * or releasing a reference, or are no-cast aliases. We do _not_
12628 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
12629 * as we want to enable BPF programs to pass types that are bitwise
12630 * equivalent without forcing them to explicitly cast with something
12631 * like bpf_cast_to_kern_ctx().
12632 *
12633 * For example, say we had a type like the following:
12634 *
12635 * struct bpf_cpumask {
12636 * cpumask_t cpumask;
12637 * refcount_t usage;
12638 * };
12639 *
12640 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
12641 * to a struct cpumask, so it would be safe to pass a struct
12642 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
12643 *
12644 * The philosophy here is similar to how we allow scalars of different
12645 * types to be passed to kfuncs as long as the size is the same. The
12646 * only difference here is that we're simply allowing
12647 * btf_struct_ids_match() to walk the struct at the 0th offset, and
12648 * resolve types.
12649 */
12650 if ((is_kfunc_release(meta) && reg->ref_obj_id) ||
12651 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
12652 strict_type_match = true;
12653
12654 WARN_ON_ONCE(is_kfunc_release(meta) &&
12655 (reg->off || !tnum_is_const(reg->var_off) ||
12656 reg->var_off.value));
12657
12658 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
12659 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
12660 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match);
12661 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot
12662 * actually use it -- it must cast to the underlying type. So we allow
12663 * caller to pass in the underlying type.
12664 */
12665 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname);
12666 if (!taking_projection && !struct_same) {
12667 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
12668 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
12669 btf_type_str(reg_ref_t), reg_ref_tname);
12670 return -EINVAL;
12671 }
12672 return 0;
12673 }
12674
process_irq_flag(struct bpf_verifier_env * env,int regno,struct bpf_kfunc_call_arg_meta * meta)12675 static int process_irq_flag(struct bpf_verifier_env *env, int regno,
12676 struct bpf_kfunc_call_arg_meta *meta)
12677 {
12678 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
12679 int err, kfunc_class = IRQ_NATIVE_KFUNC;
12680 bool irq_save;
12681
12682 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] ||
12683 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) {
12684 irq_save = true;
12685 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
12686 kfunc_class = IRQ_LOCK_KFUNC;
12687 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] ||
12688 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) {
12689 irq_save = false;
12690 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
12691 kfunc_class = IRQ_LOCK_KFUNC;
12692 } else {
12693 verifier_bug(env, "unknown irq flags kfunc");
12694 return -EFAULT;
12695 }
12696
12697 if (irq_save) {
12698 if (!is_irq_flag_reg_valid_uninit(env, reg)) {
12699 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1);
12700 return -EINVAL;
12701 }
12702
12703 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false);
12704 if (err)
12705 return err;
12706
12707 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class);
12708 if (err)
12709 return err;
12710 } else {
12711 err = is_irq_flag_reg_valid_init(env, reg);
12712 if (err) {
12713 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1);
12714 return err;
12715 }
12716
12717 err = mark_irq_flag_read(env, reg);
12718 if (err)
12719 return err;
12720
12721 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class);
12722 if (err)
12723 return err;
12724 }
12725 return 0;
12726 }
12727
12728
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12729 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12730 {
12731 struct btf_record *rec = reg_btf_record(reg);
12732
12733 if (!env->cur_state->active_locks) {
12734 verifier_bug(env, "%s w/o active lock", __func__);
12735 return -EFAULT;
12736 }
12737
12738 if (type_flag(reg->type) & NON_OWN_REF) {
12739 verifier_bug(env, "NON_OWN_REF already set");
12740 return -EFAULT;
12741 }
12742
12743 reg->type |= NON_OWN_REF;
12744 if (rec->refcount_off >= 0)
12745 reg->type |= MEM_RCU;
12746
12747 return 0;
12748 }
12749
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)12750 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
12751 {
12752 struct bpf_verifier_state *state = env->cur_state;
12753 struct bpf_func_state *unused;
12754 struct bpf_reg_state *reg;
12755 int i;
12756
12757 if (!ref_obj_id) {
12758 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion");
12759 return -EFAULT;
12760 }
12761
12762 for (i = 0; i < state->acquired_refs; i++) {
12763 if (state->refs[i].id != ref_obj_id)
12764 continue;
12765
12766 /* Clear ref_obj_id here so release_reference doesn't clobber
12767 * the whole reg
12768 */
12769 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
12770 if (reg->ref_obj_id == ref_obj_id) {
12771 reg->ref_obj_id = 0;
12772 ref_set_non_owning(env, reg);
12773 }
12774 }));
12775 return 0;
12776 }
12777
12778 verifier_bug(env, "ref state missing for ref_obj_id");
12779 return -EFAULT;
12780 }
12781
12782 /* Implementation details:
12783 *
12784 * Each register points to some region of memory, which we define as an
12785 * allocation. Each allocation may embed a bpf_spin_lock which protects any
12786 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
12787 * allocation. The lock and the data it protects are colocated in the same
12788 * memory region.
12789 *
12790 * Hence, everytime a register holds a pointer value pointing to such
12791 * allocation, the verifier preserves a unique reg->id for it.
12792 *
12793 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
12794 * bpf_spin_lock is called.
12795 *
12796 * To enable this, lock state in the verifier captures two values:
12797 * active_lock.ptr = Register's type specific pointer
12798 * active_lock.id = A unique ID for each register pointer value
12799 *
12800 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
12801 * supported register types.
12802 *
12803 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
12804 * allocated objects is the reg->btf pointer.
12805 *
12806 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
12807 * can establish the provenance of the map value statically for each distinct
12808 * lookup into such maps. They always contain a single map value hence unique
12809 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
12810 *
12811 * So, in case of global variables, they use array maps with max_entries = 1,
12812 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
12813 * into the same map value as max_entries is 1, as described above).
12814 *
12815 * In case of inner map lookups, the inner map pointer has same map_ptr as the
12816 * outer map pointer (in verifier context), but each lookup into an inner map
12817 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
12818 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
12819 * will get different reg->id assigned to each lookup, hence different
12820 * active_lock.id.
12821 *
12822 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
12823 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
12824 * returned from bpf_obj_new. Each allocation receives a new reg->id.
12825 */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)12826 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
12827 {
12828 struct bpf_reference_state *s;
12829 void *ptr;
12830 u32 id;
12831
12832 switch ((int)reg->type) {
12833 case PTR_TO_MAP_VALUE:
12834 ptr = reg->map_ptr;
12835 break;
12836 case PTR_TO_BTF_ID | MEM_ALLOC:
12837 ptr = reg->btf;
12838 break;
12839 default:
12840 verifier_bug(env, "unknown reg type for lock check");
12841 return -EFAULT;
12842 }
12843 id = reg->id;
12844
12845 if (!env->cur_state->active_locks)
12846 return -EINVAL;
12847 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr);
12848 if (!s) {
12849 verbose(env, "held lock and object are not in the same allocation\n");
12850 return -EINVAL;
12851 }
12852 return 0;
12853 }
12854
is_bpf_list_api_kfunc(u32 btf_id)12855 static bool is_bpf_list_api_kfunc(u32 btf_id)
12856 {
12857 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12858 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
12859 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12860 btf_id == special_kfunc_list[KF_bpf_list_pop_back] ||
12861 btf_id == special_kfunc_list[KF_bpf_list_front] ||
12862 btf_id == special_kfunc_list[KF_bpf_list_back];
12863 }
12864
is_bpf_rbtree_api_kfunc(u32 btf_id)12865 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
12866 {
12867 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12868 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12869 btf_id == special_kfunc_list[KF_bpf_rbtree_first] ||
12870 btf_id == special_kfunc_list[KF_bpf_rbtree_root] ||
12871 btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12872 btf_id == special_kfunc_list[KF_bpf_rbtree_right];
12873 }
12874
is_bpf_iter_num_api_kfunc(u32 btf_id)12875 static bool is_bpf_iter_num_api_kfunc(u32 btf_id)
12876 {
12877 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] ||
12878 btf_id == special_kfunc_list[KF_bpf_iter_num_next] ||
12879 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy];
12880 }
12881
is_bpf_graph_api_kfunc(u32 btf_id)12882 static bool is_bpf_graph_api_kfunc(u32 btf_id)
12883 {
12884 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
12885 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
12886 }
12887
is_bpf_res_spin_lock_kfunc(u32 btf_id)12888 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id)
12889 {
12890 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
12891 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] ||
12892 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
12893 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore];
12894 }
12895
kfunc_spin_allowed(u32 btf_id)12896 static bool kfunc_spin_allowed(u32 btf_id)
12897 {
12898 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) ||
12899 is_bpf_res_spin_lock_kfunc(btf_id);
12900 }
12901
is_sync_callback_calling_kfunc(u32 btf_id)12902 static bool is_sync_callback_calling_kfunc(u32 btf_id)
12903 {
12904 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
12905 }
12906
is_async_callback_calling_kfunc(u32 btf_id)12907 static bool is_async_callback_calling_kfunc(u32 btf_id)
12908 {
12909 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl] ||
12910 is_task_work_add_kfunc(btf_id);
12911 }
12912
is_bpf_throw_kfunc(struct bpf_insn * insn)12913 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
12914 {
12915 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
12916 insn->imm == special_kfunc_list[KF_bpf_throw];
12917 }
12918
is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)12919 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id)
12920 {
12921 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl];
12922 }
12923
is_callback_calling_kfunc(u32 btf_id)12924 static bool is_callback_calling_kfunc(u32 btf_id)
12925 {
12926 return is_sync_callback_calling_kfunc(btf_id) ||
12927 is_async_callback_calling_kfunc(btf_id);
12928 }
12929
is_rbtree_lock_required_kfunc(u32 btf_id)12930 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
12931 {
12932 return is_bpf_rbtree_api_kfunc(btf_id);
12933 }
12934
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)12935 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
12936 enum btf_field_type head_field_type,
12937 u32 kfunc_btf_id)
12938 {
12939 bool ret;
12940
12941 switch (head_field_type) {
12942 case BPF_LIST_HEAD:
12943 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
12944 break;
12945 case BPF_RB_ROOT:
12946 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
12947 break;
12948 default:
12949 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
12950 btf_field_type_name(head_field_type));
12951 return false;
12952 }
12953
12954 if (!ret)
12955 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
12956 btf_field_type_name(head_field_type));
12957 return ret;
12958 }
12959
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)12960 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
12961 enum btf_field_type node_field_type,
12962 u32 kfunc_btf_id)
12963 {
12964 bool ret;
12965
12966 switch (node_field_type) {
12967 case BPF_LIST_NODE:
12968 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
12969 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
12970 break;
12971 case BPF_RB_NODE:
12972 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12973 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
12974 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] ||
12975 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
12976 break;
12977 default:
12978 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
12979 btf_field_type_name(node_field_type));
12980 return false;
12981 }
12982
12983 if (!ret)
12984 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
12985 btf_field_type_name(node_field_type));
12986 return ret;
12987 }
12988
12989 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)12990 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
12991 struct bpf_reg_state *reg, u32 regno,
12992 struct bpf_kfunc_call_arg_meta *meta,
12993 enum btf_field_type head_field_type,
12994 struct btf_field **head_field)
12995 {
12996 const char *head_type_name;
12997 struct btf_field *field;
12998 struct btf_record *rec;
12999 u32 head_off;
13000
13001 if (meta->btf != btf_vmlinux) {
13002 verifier_bug(env, "unexpected btf mismatch in kfunc call");
13003 return -EFAULT;
13004 }
13005
13006 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
13007 return -EFAULT;
13008
13009 head_type_name = btf_field_type_name(head_field_type);
13010 if (!tnum_is_const(reg->var_off)) {
13011 verbose(env,
13012 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
13013 regno, head_type_name);
13014 return -EINVAL;
13015 }
13016
13017 rec = reg_btf_record(reg);
13018 head_off = reg->off + reg->var_off.value;
13019 field = btf_record_find(rec, head_off, head_field_type);
13020 if (!field) {
13021 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
13022 return -EINVAL;
13023 }
13024
13025 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
13026 if (check_reg_allocation_locked(env, reg)) {
13027 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
13028 rec->spin_lock_off, head_type_name);
13029 return -EINVAL;
13030 }
13031
13032 if (*head_field) {
13033 verifier_bug(env, "repeating %s arg", head_type_name);
13034 return -EFAULT;
13035 }
13036 *head_field = field;
13037 return 0;
13038 }
13039
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)13040 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
13041 struct bpf_reg_state *reg, u32 regno,
13042 struct bpf_kfunc_call_arg_meta *meta)
13043 {
13044 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
13045 &meta->arg_list_head.field);
13046 }
13047
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)13048 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
13049 struct bpf_reg_state *reg, u32 regno,
13050 struct bpf_kfunc_call_arg_meta *meta)
13051 {
13052 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
13053 &meta->arg_rbtree_root.field);
13054 }
13055
13056 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)13057 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
13058 struct bpf_reg_state *reg, u32 regno,
13059 struct bpf_kfunc_call_arg_meta *meta,
13060 enum btf_field_type head_field_type,
13061 enum btf_field_type node_field_type,
13062 struct btf_field **node_field)
13063 {
13064 const char *node_type_name;
13065 const struct btf_type *et, *t;
13066 struct btf_field *field;
13067 u32 node_off;
13068
13069 if (meta->btf != btf_vmlinux) {
13070 verifier_bug(env, "unexpected btf mismatch in kfunc call");
13071 return -EFAULT;
13072 }
13073
13074 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
13075 return -EFAULT;
13076
13077 node_type_name = btf_field_type_name(node_field_type);
13078 if (!tnum_is_const(reg->var_off)) {
13079 verbose(env,
13080 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
13081 regno, node_type_name);
13082 return -EINVAL;
13083 }
13084
13085 node_off = reg->off + reg->var_off.value;
13086 field = reg_find_field_offset(reg, node_off, node_field_type);
13087 if (!field) {
13088 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
13089 return -EINVAL;
13090 }
13091
13092 field = *node_field;
13093
13094 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
13095 t = btf_type_by_id(reg->btf, reg->btf_id);
13096 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
13097 field->graph_root.value_btf_id, true)) {
13098 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
13099 "in struct %s, but arg is at offset=%d in struct %s\n",
13100 btf_field_type_name(head_field_type),
13101 btf_field_type_name(node_field_type),
13102 field->graph_root.node_offset,
13103 btf_name_by_offset(field->graph_root.btf, et->name_off),
13104 node_off, btf_name_by_offset(reg->btf, t->name_off));
13105 return -EINVAL;
13106 }
13107 meta->arg_btf = reg->btf;
13108 meta->arg_btf_id = reg->btf_id;
13109
13110 if (node_off != field->graph_root.node_offset) {
13111 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
13112 node_off, btf_field_type_name(node_field_type),
13113 field->graph_root.node_offset,
13114 btf_name_by_offset(field->graph_root.btf, et->name_off));
13115 return -EINVAL;
13116 }
13117
13118 return 0;
13119 }
13120
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)13121 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
13122 struct bpf_reg_state *reg, u32 regno,
13123 struct bpf_kfunc_call_arg_meta *meta)
13124 {
13125 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13126 BPF_LIST_HEAD, BPF_LIST_NODE,
13127 &meta->arg_list_head.field);
13128 }
13129
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)13130 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
13131 struct bpf_reg_state *reg, u32 regno,
13132 struct bpf_kfunc_call_arg_meta *meta)
13133 {
13134 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
13135 BPF_RB_ROOT, BPF_RB_NODE,
13136 &meta->arg_rbtree_root.field);
13137 }
13138
13139 /*
13140 * css_task iter allowlist is needed to avoid dead locking on css_set_lock.
13141 * LSM hooks and iters (both sleepable and non-sleepable) are safe.
13142 * Any sleepable progs are also safe since bpf_check_attach_target() enforce
13143 * them can only be attached to some specific hook points.
13144 */
check_css_task_iter_allowlist(struct bpf_verifier_env * env)13145 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
13146 {
13147 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
13148
13149 switch (prog_type) {
13150 case BPF_PROG_TYPE_LSM:
13151 return true;
13152 case BPF_PROG_TYPE_TRACING:
13153 if (env->prog->expected_attach_type == BPF_TRACE_ITER)
13154 return true;
13155 fallthrough;
13156 default:
13157 return in_sleepable(env);
13158 }
13159 }
13160
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)13161 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13162 int insn_idx)
13163 {
13164 const char *func_name = meta->func_name, *ref_tname;
13165 const struct btf *btf = meta->btf;
13166 const struct btf_param *args;
13167 struct btf_record *rec;
13168 u32 i, nargs;
13169 int ret;
13170
13171 args = (const struct btf_param *)(meta->func_proto + 1);
13172 nargs = btf_type_vlen(meta->func_proto);
13173 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
13174 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
13175 MAX_BPF_FUNC_REG_ARGS);
13176 return -EINVAL;
13177 }
13178
13179 /* Check that BTF function arguments match actual types that the
13180 * verifier sees.
13181 */
13182 for (i = 0; i < nargs; i++) {
13183 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
13184 const struct btf_type *t, *ref_t, *resolve_ret;
13185 enum bpf_arg_type arg_type = ARG_DONTCARE;
13186 u32 regno = i + 1, ref_id, type_size;
13187 bool is_ret_buf_sz = false;
13188 int kf_arg_type;
13189
13190 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
13191
13192 if (is_kfunc_arg_ignore(btf, &args[i]))
13193 continue;
13194
13195 if (is_kfunc_arg_prog(btf, &args[i])) {
13196 /* Used to reject repeated use of __prog. */
13197 if (meta->arg_prog) {
13198 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc");
13199 return -EFAULT;
13200 }
13201 meta->arg_prog = true;
13202 cur_aux(env)->arg_prog = regno;
13203 continue;
13204 }
13205
13206 if (btf_type_is_scalar(t)) {
13207 if (reg->type != SCALAR_VALUE) {
13208 verbose(env, "R%d is not a scalar\n", regno);
13209 return -EINVAL;
13210 }
13211
13212 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
13213 if (meta->arg_constant.found) {
13214 verifier_bug(env, "only one constant argument permitted");
13215 return -EFAULT;
13216 }
13217 if (!tnum_is_const(reg->var_off)) {
13218 verbose(env, "R%d must be a known constant\n", regno);
13219 return -EINVAL;
13220 }
13221 ret = mark_chain_precision(env, regno);
13222 if (ret < 0)
13223 return ret;
13224 meta->arg_constant.found = true;
13225 meta->arg_constant.value = reg->var_off.value;
13226 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
13227 meta->r0_rdonly = true;
13228 is_ret_buf_sz = true;
13229 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
13230 is_ret_buf_sz = true;
13231 }
13232
13233 if (is_ret_buf_sz) {
13234 if (meta->r0_size) {
13235 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
13236 return -EINVAL;
13237 }
13238
13239 if (!tnum_is_const(reg->var_off)) {
13240 verbose(env, "R%d is not a const\n", regno);
13241 return -EINVAL;
13242 }
13243
13244 meta->r0_size = reg->var_off.value;
13245 ret = mark_chain_precision(env, regno);
13246 if (ret)
13247 return ret;
13248 }
13249 continue;
13250 }
13251
13252 if (!btf_type_is_ptr(t)) {
13253 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
13254 return -EINVAL;
13255 }
13256
13257 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
13258 (register_is_null(reg) || type_may_be_null(reg->type)) &&
13259 !is_kfunc_arg_nullable(meta->btf, &args[i])) {
13260 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
13261 return -EACCES;
13262 }
13263
13264 if (reg->ref_obj_id) {
13265 if (is_kfunc_release(meta) && meta->ref_obj_id) {
13266 verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u",
13267 regno, reg->ref_obj_id,
13268 meta->ref_obj_id);
13269 return -EFAULT;
13270 }
13271 meta->ref_obj_id = reg->ref_obj_id;
13272 if (is_kfunc_release(meta))
13273 meta->release_regno = regno;
13274 }
13275
13276 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
13277 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13278
13279 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
13280 if (kf_arg_type < 0)
13281 return kf_arg_type;
13282
13283 switch (kf_arg_type) {
13284 case KF_ARG_PTR_TO_NULL:
13285 continue;
13286 case KF_ARG_PTR_TO_MAP:
13287 if (!reg->map_ptr) {
13288 verbose(env, "pointer in R%d isn't map pointer\n", regno);
13289 return -EINVAL;
13290 }
13291 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 ||
13292 reg->map_ptr->record->task_work_off >= 0)) {
13293 /* Use map_uid (which is unique id of inner map) to reject:
13294 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
13295 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
13296 * if (inner_map1 && inner_map2) {
13297 * wq = bpf_map_lookup_elem(inner_map1);
13298 * if (wq)
13299 * // mismatch would have been allowed
13300 * bpf_wq_init(wq, inner_map2);
13301 * }
13302 *
13303 * Comparing map_ptr is enough to distinguish normal and outer maps.
13304 */
13305 if (meta->map.ptr != reg->map_ptr ||
13306 meta->map.uid != reg->map_uid) {
13307 if (reg->map_ptr->record->task_work_off >= 0) {
13308 verbose(env,
13309 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n",
13310 meta->map.uid, reg->map_uid);
13311 return -EINVAL;
13312 }
13313 verbose(env,
13314 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
13315 meta->map.uid, reg->map_uid);
13316 return -EINVAL;
13317 }
13318 }
13319 meta->map.ptr = reg->map_ptr;
13320 meta->map.uid = reg->map_uid;
13321 fallthrough;
13322 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13323 case KF_ARG_PTR_TO_BTF_ID:
13324 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
13325 break;
13326
13327 if (!is_trusted_reg(reg)) {
13328 if (!is_kfunc_rcu(meta)) {
13329 verbose(env, "R%d must be referenced or trusted\n", regno);
13330 return -EINVAL;
13331 }
13332 if (!is_rcu_reg(reg)) {
13333 verbose(env, "R%d must be a rcu pointer\n", regno);
13334 return -EINVAL;
13335 }
13336 }
13337 fallthrough;
13338 case KF_ARG_PTR_TO_CTX:
13339 case KF_ARG_PTR_TO_DYNPTR:
13340 case KF_ARG_PTR_TO_ITER:
13341 case KF_ARG_PTR_TO_LIST_HEAD:
13342 case KF_ARG_PTR_TO_LIST_NODE:
13343 case KF_ARG_PTR_TO_RB_ROOT:
13344 case KF_ARG_PTR_TO_RB_NODE:
13345 case KF_ARG_PTR_TO_MEM:
13346 case KF_ARG_PTR_TO_MEM_SIZE:
13347 case KF_ARG_PTR_TO_CALLBACK:
13348 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13349 case KF_ARG_PTR_TO_CONST_STR:
13350 case KF_ARG_PTR_TO_WORKQUEUE:
13351 case KF_ARG_PTR_TO_TASK_WORK:
13352 case KF_ARG_PTR_TO_IRQ_FLAG:
13353 case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13354 break;
13355 default:
13356 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type);
13357 return -EFAULT;
13358 }
13359
13360 if (is_kfunc_release(meta) && reg->ref_obj_id)
13361 arg_type |= OBJ_RELEASE;
13362 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
13363 if (ret < 0)
13364 return ret;
13365
13366 switch (kf_arg_type) {
13367 case KF_ARG_PTR_TO_CTX:
13368 if (reg->type != PTR_TO_CTX) {
13369 verbose(env, "arg#%d expected pointer to ctx, but got %s\n",
13370 i, reg_type_str(env, reg->type));
13371 return -EINVAL;
13372 }
13373
13374 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13375 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
13376 if (ret < 0)
13377 return -EINVAL;
13378 meta->ret_btf_id = ret;
13379 }
13380 break;
13381 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
13382 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
13383 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
13384 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
13385 return -EINVAL;
13386 }
13387 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
13388 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
13389 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
13390 return -EINVAL;
13391 }
13392 } else {
13393 verbose(env, "arg#%d expected pointer to allocated object\n", i);
13394 return -EINVAL;
13395 }
13396 if (!reg->ref_obj_id) {
13397 verbose(env, "allocated object must be referenced\n");
13398 return -EINVAL;
13399 }
13400 if (meta->btf == btf_vmlinux) {
13401 meta->arg_btf = reg->btf;
13402 meta->arg_btf_id = reg->btf_id;
13403 }
13404 break;
13405 case KF_ARG_PTR_TO_DYNPTR:
13406 {
13407 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
13408 int clone_ref_obj_id = 0;
13409
13410 if (reg->type == CONST_PTR_TO_DYNPTR)
13411 dynptr_arg_type |= MEM_RDONLY;
13412
13413 if (is_kfunc_arg_uninit(btf, &args[i]))
13414 dynptr_arg_type |= MEM_UNINIT;
13415
13416 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
13417 dynptr_arg_type |= DYNPTR_TYPE_SKB;
13418 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
13419 dynptr_arg_type |= DYNPTR_TYPE_XDP;
13420 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
13421 dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
13422 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
13423 dynptr_arg_type |= DYNPTR_TYPE_FILE;
13424 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
13425 dynptr_arg_type |= DYNPTR_TYPE_FILE;
13426 meta->release_regno = regno;
13427 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
13428 (dynptr_arg_type & MEM_UNINIT)) {
13429 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
13430
13431 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
13432 verifier_bug(env, "no dynptr type for parent of clone");
13433 return -EFAULT;
13434 }
13435
13436 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
13437 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
13438 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
13439 verifier_bug(env, "missing ref obj id for parent of clone");
13440 return -EFAULT;
13441 }
13442 }
13443
13444 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
13445 if (ret < 0)
13446 return ret;
13447
13448 if (!(dynptr_arg_type & MEM_UNINIT)) {
13449 int id = dynptr_id(env, reg);
13450
13451 if (id < 0) {
13452 verifier_bug(env, "failed to obtain dynptr id");
13453 return id;
13454 }
13455 meta->initialized_dynptr.id = id;
13456 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
13457 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
13458 }
13459
13460 break;
13461 }
13462 case KF_ARG_PTR_TO_ITER:
13463 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
13464 if (!check_css_task_iter_allowlist(env)) {
13465 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n");
13466 return -EINVAL;
13467 }
13468 }
13469 ret = process_iter_arg(env, regno, insn_idx, meta);
13470 if (ret < 0)
13471 return ret;
13472 break;
13473 case KF_ARG_PTR_TO_LIST_HEAD:
13474 if (reg->type != PTR_TO_MAP_VALUE &&
13475 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13476 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13477 return -EINVAL;
13478 }
13479 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13480 verbose(env, "allocated object must be referenced\n");
13481 return -EINVAL;
13482 }
13483 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
13484 if (ret < 0)
13485 return ret;
13486 break;
13487 case KF_ARG_PTR_TO_RB_ROOT:
13488 if (reg->type != PTR_TO_MAP_VALUE &&
13489 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13490 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
13491 return -EINVAL;
13492 }
13493 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
13494 verbose(env, "allocated object must be referenced\n");
13495 return -EINVAL;
13496 }
13497 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
13498 if (ret < 0)
13499 return ret;
13500 break;
13501 case KF_ARG_PTR_TO_LIST_NODE:
13502 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13503 verbose(env, "arg#%d expected pointer to allocated object\n", i);
13504 return -EINVAL;
13505 }
13506 if (!reg->ref_obj_id) {
13507 verbose(env, "allocated object must be referenced\n");
13508 return -EINVAL;
13509 }
13510 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
13511 if (ret < 0)
13512 return ret;
13513 break;
13514 case KF_ARG_PTR_TO_RB_NODE:
13515 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
13516 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13517 verbose(env, "arg#%d expected pointer to allocated object\n", i);
13518 return -EINVAL;
13519 }
13520 if (!reg->ref_obj_id) {
13521 verbose(env, "allocated object must be referenced\n");
13522 return -EINVAL;
13523 }
13524 } else {
13525 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) {
13526 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name);
13527 return -EINVAL;
13528 }
13529 if (in_rbtree_lock_required_cb(env)) {
13530 verbose(env, "%s not allowed in rbtree cb\n", func_name);
13531 return -EINVAL;
13532 }
13533 }
13534
13535 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
13536 if (ret < 0)
13537 return ret;
13538 break;
13539 case KF_ARG_PTR_TO_MAP:
13540 /* If argument has '__map' suffix expect 'struct bpf_map *' */
13541 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP];
13542 ref_t = btf_type_by_id(btf_vmlinux, ref_id);
13543 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
13544 fallthrough;
13545 case KF_ARG_PTR_TO_BTF_ID:
13546 /* Only base_type is checked, further checks are done here */
13547 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
13548 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
13549 !reg2btf_ids[base_type(reg->type)]) {
13550 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
13551 verbose(env, "expected %s or socket\n",
13552 reg_type_str(env, base_type(reg->type) |
13553 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
13554 return -EINVAL;
13555 }
13556 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
13557 if (ret < 0)
13558 return ret;
13559 break;
13560 case KF_ARG_PTR_TO_MEM:
13561 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
13562 if (IS_ERR(resolve_ret)) {
13563 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
13564 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
13565 return -EINVAL;
13566 }
13567 ret = check_mem_reg(env, reg, regno, type_size);
13568 if (ret < 0)
13569 return ret;
13570 break;
13571 case KF_ARG_PTR_TO_MEM_SIZE:
13572 {
13573 struct bpf_reg_state *buff_reg = ®s[regno];
13574 const struct btf_param *buff_arg = &args[i];
13575 struct bpf_reg_state *size_reg = ®s[regno + 1];
13576 const struct btf_param *size_arg = &args[i + 1];
13577
13578 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
13579 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
13580 if (ret < 0) {
13581 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
13582 return ret;
13583 }
13584 }
13585
13586 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
13587 if (meta->arg_constant.found) {
13588 verifier_bug(env, "only one constant argument permitted");
13589 return -EFAULT;
13590 }
13591 if (!tnum_is_const(size_reg->var_off)) {
13592 verbose(env, "R%d must be a known constant\n", regno + 1);
13593 return -EINVAL;
13594 }
13595 meta->arg_constant.found = true;
13596 meta->arg_constant.value = size_reg->var_off.value;
13597 }
13598
13599 /* Skip next '__sz' or '__szk' argument */
13600 i++;
13601 break;
13602 }
13603 case KF_ARG_PTR_TO_CALLBACK:
13604 if (reg->type != PTR_TO_FUNC) {
13605 verbose(env, "arg%d expected pointer to func\n", i);
13606 return -EINVAL;
13607 }
13608 meta->subprogno = reg->subprogno;
13609 break;
13610 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
13611 if (!type_is_ptr_alloc_obj(reg->type)) {
13612 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
13613 return -EINVAL;
13614 }
13615 if (!type_is_non_owning_ref(reg->type))
13616 meta->arg_owning_ref = true;
13617
13618 rec = reg_btf_record(reg);
13619 if (!rec) {
13620 verifier_bug(env, "Couldn't find btf_record");
13621 return -EFAULT;
13622 }
13623
13624 if (rec->refcount_off < 0) {
13625 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
13626 return -EINVAL;
13627 }
13628
13629 meta->arg_btf = reg->btf;
13630 meta->arg_btf_id = reg->btf_id;
13631 break;
13632 case KF_ARG_PTR_TO_CONST_STR:
13633 if (reg->type != PTR_TO_MAP_VALUE) {
13634 verbose(env, "arg#%d doesn't point to a const string\n", i);
13635 return -EINVAL;
13636 }
13637 ret = check_reg_const_str(env, reg, regno);
13638 if (ret)
13639 return ret;
13640 break;
13641 case KF_ARG_PTR_TO_WORKQUEUE:
13642 if (reg->type != PTR_TO_MAP_VALUE) {
13643 verbose(env, "arg#%d doesn't point to a map value\n", i);
13644 return -EINVAL;
13645 }
13646 ret = process_wq_func(env, regno, meta);
13647 if (ret < 0)
13648 return ret;
13649 break;
13650 case KF_ARG_PTR_TO_TASK_WORK:
13651 if (reg->type != PTR_TO_MAP_VALUE) {
13652 verbose(env, "arg#%d doesn't point to a map value\n", i);
13653 return -EINVAL;
13654 }
13655 ret = process_task_work_func(env, regno, meta);
13656 if (ret < 0)
13657 return ret;
13658 break;
13659 case KF_ARG_PTR_TO_IRQ_FLAG:
13660 if (reg->type != PTR_TO_STACK) {
13661 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i);
13662 return -EINVAL;
13663 }
13664 ret = process_irq_flag(env, regno, meta);
13665 if (ret < 0)
13666 return ret;
13667 break;
13668 case KF_ARG_PTR_TO_RES_SPIN_LOCK:
13669 {
13670 int flags = PROCESS_RES_LOCK;
13671
13672 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
13673 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i);
13674 return -EINVAL;
13675 }
13676
13677 if (!is_bpf_res_spin_lock_kfunc(meta->func_id))
13678 return -EFAULT;
13679 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
13680 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])
13681 flags |= PROCESS_SPIN_LOCK;
13682 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] ||
13683 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore])
13684 flags |= PROCESS_LOCK_IRQ;
13685 ret = process_spin_lock(env, regno, flags);
13686 if (ret < 0)
13687 return ret;
13688 break;
13689 }
13690 }
13691 }
13692
13693 if (is_kfunc_release(meta) && !meta->release_regno) {
13694 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
13695 func_name);
13696 return -EINVAL;
13697 }
13698
13699 return 0;
13700 }
13701
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)13702 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
13703 struct bpf_insn *insn,
13704 struct bpf_kfunc_call_arg_meta *meta,
13705 const char **kfunc_name)
13706 {
13707 const struct btf_type *func, *func_proto;
13708 u32 func_id, *kfunc_flags;
13709 const char *func_name;
13710 struct btf *desc_btf;
13711
13712 if (kfunc_name)
13713 *kfunc_name = NULL;
13714
13715 if (!insn->imm)
13716 return -EINVAL;
13717
13718 desc_btf = find_kfunc_desc_btf(env, insn->off);
13719 if (IS_ERR(desc_btf))
13720 return PTR_ERR(desc_btf);
13721
13722 func_id = insn->imm;
13723 func = btf_type_by_id(desc_btf, func_id);
13724 func_name = btf_name_by_offset(desc_btf, func->name_off);
13725 if (kfunc_name)
13726 *kfunc_name = func_name;
13727 func_proto = btf_type_by_id(desc_btf, func->type);
13728
13729 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
13730 if (!kfunc_flags) {
13731 return -EACCES;
13732 }
13733
13734 memset(meta, 0, sizeof(*meta));
13735 meta->btf = desc_btf;
13736 meta->func_id = func_id;
13737 meta->kfunc_flags = *kfunc_flags;
13738 meta->func_proto = func_proto;
13739 meta->func_name = func_name;
13740
13741 return 0;
13742 }
13743
13744 /* check special kfuncs and return:
13745 * 1 - not fall-through to 'else' branch, continue verification
13746 * 0 - fall-through to 'else' branch
13747 * < 0 - not fall-through to 'else' branch, return error
13748 */
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)13749 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
13750 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux,
13751 const struct btf_type *ptr_type, struct btf *desc_btf)
13752 {
13753 const struct btf_type *ret_t;
13754 int err = 0;
13755
13756 if (meta->btf != btf_vmlinux)
13757 return 0;
13758
13759 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
13760 meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13761 struct btf_struct_meta *struct_meta;
13762 struct btf *ret_btf;
13763 u32 ret_btf_id;
13764
13765 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
13766 return -ENOMEM;
13767
13768 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) {
13769 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
13770 return -EINVAL;
13771 }
13772
13773 ret_btf = env->prog->aux->btf;
13774 ret_btf_id = meta->arg_constant.value;
13775
13776 /* This may be NULL due to user not supplying a BTF */
13777 if (!ret_btf) {
13778 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
13779 return -EINVAL;
13780 }
13781
13782 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
13783 if (!ret_t || !__btf_type_is_struct(ret_t)) {
13784 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
13785 return -EINVAL;
13786 }
13787
13788 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13789 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) {
13790 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n",
13791 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE);
13792 return -EINVAL;
13793 }
13794
13795 if (!bpf_global_percpu_ma_set) {
13796 mutex_lock(&bpf_percpu_ma_lock);
13797 if (!bpf_global_percpu_ma_set) {
13798 /* Charge memory allocated with bpf_global_percpu_ma to
13799 * root memcg. The obj_cgroup for root memcg is NULL.
13800 */
13801 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL);
13802 if (!err)
13803 bpf_global_percpu_ma_set = true;
13804 }
13805 mutex_unlock(&bpf_percpu_ma_lock);
13806 if (err)
13807 return err;
13808 }
13809
13810 mutex_lock(&bpf_percpu_ma_lock);
13811 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size);
13812 mutex_unlock(&bpf_percpu_ma_lock);
13813 if (err)
13814 return err;
13815 }
13816
13817 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
13818 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
13819 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
13820 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
13821 return -EINVAL;
13822 }
13823
13824 if (struct_meta) {
13825 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
13826 return -EINVAL;
13827 }
13828 }
13829
13830 mark_reg_known_zero(env, regs, BPF_REG_0);
13831 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13832 regs[BPF_REG_0].btf = ret_btf;
13833 regs[BPF_REG_0].btf_id = ret_btf_id;
13834 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
13835 regs[BPF_REG_0].type |= MEM_PERCPU;
13836
13837 insn_aux->obj_new_size = ret_t->size;
13838 insn_aux->kptr_struct_meta = struct_meta;
13839 } else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
13840 mark_reg_known_zero(env, regs, BPF_REG_0);
13841 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
13842 regs[BPF_REG_0].btf = meta->arg_btf;
13843 regs[BPF_REG_0].btf_id = meta->arg_btf_id;
13844
13845 insn_aux->kptr_struct_meta =
13846 btf_find_struct_meta(meta->arg_btf,
13847 meta->arg_btf_id);
13848 } else if (is_list_node_type(ptr_type)) {
13849 struct btf_field *field = meta->arg_list_head.field;
13850
13851 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13852 } else if (is_rbtree_node_type(ptr_type)) {
13853 struct btf_field *field = meta->arg_rbtree_root.field;
13854
13855 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
13856 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
13857 mark_reg_known_zero(env, regs, BPF_REG_0);
13858 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
13859 regs[BPF_REG_0].btf = desc_btf;
13860 regs[BPF_REG_0].btf_id = meta->ret_btf_id;
13861 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
13862 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value);
13863 if (!ret_t) {
13864 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n",
13865 meta->arg_constant.value);
13866 return -EINVAL;
13867 } else if (btf_type_is_struct(ret_t)) {
13868 mark_reg_known_zero(env, regs, BPF_REG_0);
13869 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
13870 regs[BPF_REG_0].btf = desc_btf;
13871 regs[BPF_REG_0].btf_id = meta->arg_constant.value;
13872 } else if (btf_type_is_void(ret_t)) {
13873 mark_reg_known_zero(env, regs, BPF_REG_0);
13874 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED;
13875 regs[BPF_REG_0].mem_size = 0;
13876 } else {
13877 verbose(env,
13878 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n");
13879 return -EINVAL;
13880 }
13881 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
13882 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
13883 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type);
13884
13885 mark_reg_known_zero(env, regs, BPF_REG_0);
13886
13887 if (!meta->arg_constant.found) {
13888 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size");
13889 return -EFAULT;
13890 }
13891
13892 regs[BPF_REG_0].mem_size = meta->arg_constant.value;
13893
13894 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
13895 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
13896
13897 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
13898 regs[BPF_REG_0].type |= MEM_RDONLY;
13899 } else {
13900 /* this will set env->seen_direct_write to true */
13901 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
13902 verbose(env, "the prog does not allow writes to packet data\n");
13903 return -EINVAL;
13904 }
13905 }
13906
13907 if (!meta->initialized_dynptr.id) {
13908 verifier_bug(env, "no dynptr id");
13909 return -EFAULT;
13910 }
13911 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id;
13912
13913 /* we don't need to set BPF_REG_0's ref obj id
13914 * because packet slices are not refcounted (see
13915 * dynptr_type_refcounted)
13916 */
13917 } else {
13918 return 0;
13919 }
13920
13921 return 1;
13922 }
13923
13924 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
13925
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)13926 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
13927 int *insn_idx_p)
13928 {
13929 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
13930 u32 i, nargs, ptr_type_id, release_ref_obj_id;
13931 struct bpf_reg_state *regs = cur_regs(env);
13932 const char *func_name, *ptr_type_name;
13933 const struct btf_type *t, *ptr_type;
13934 struct bpf_kfunc_call_arg_meta meta;
13935 struct bpf_insn_aux_data *insn_aux;
13936 int err, insn_idx = *insn_idx_p;
13937 const struct btf_param *args;
13938 struct btf *desc_btf;
13939
13940 /* skip for now, but return error when we find this in fixup_kfunc_call */
13941 if (!insn->imm)
13942 return 0;
13943
13944 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
13945 if (err == -EACCES && func_name)
13946 verbose(env, "calling kernel function %s is not allowed\n", func_name);
13947 if (err)
13948 return err;
13949 desc_btf = meta.btf;
13950 insn_aux = &env->insn_aux_data[insn_idx];
13951
13952 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
13953
13954 if (!insn->off &&
13955 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] ||
13956 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) {
13957 struct bpf_verifier_state *branch;
13958 struct bpf_reg_state *regs;
13959
13960 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
13961 if (IS_ERR(branch)) {
13962 verbose(env, "failed to push state for failed lock acquisition\n");
13963 return PTR_ERR(branch);
13964 }
13965
13966 regs = branch->frame[branch->curframe]->regs;
13967
13968 /* Clear r0-r5 registers in forked state */
13969 for (i = 0; i < CALLER_SAVED_REGS; i++)
13970 mark_reg_not_init(env, regs, caller_saved[i]);
13971
13972 mark_reg_unknown(env, regs, BPF_REG_0);
13973 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1);
13974 if (err) {
13975 verbose(env, "failed to mark s32 range for retval in forked state for lock\n");
13976 return err;
13977 }
13978 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32));
13979 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
13980 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
13981 return -EFAULT;
13982 }
13983
13984 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
13985 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
13986 return -EACCES;
13987 }
13988
13989 sleepable = is_kfunc_sleepable(&meta);
13990 if (sleepable && !in_sleepable(env)) {
13991 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
13992 return -EACCES;
13993 }
13994
13995 /* Track non-sleepable context for kfuncs, same as for helpers. */
13996 if (!in_sleepable_context(env))
13997 insn_aux->non_sleepable = true;
13998
13999 /* Check the arguments */
14000 err = check_kfunc_args(env, &meta, insn_idx);
14001 if (err < 0)
14002 return err;
14003
14004 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14005 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14006 set_rbtree_add_callback_state);
14007 if (err) {
14008 verbose(env, "kfunc %s#%d failed callback verification\n",
14009 func_name, meta.func_id);
14010 return err;
14011 }
14012 }
14013
14014 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) {
14015 meta.r0_size = sizeof(u64);
14016 meta.r0_rdonly = false;
14017 }
14018
14019 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) {
14020 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14021 set_timer_callback_state);
14022 if (err) {
14023 verbose(env, "kfunc %s#%d failed callback verification\n",
14024 func_name, meta.func_id);
14025 return err;
14026 }
14027 }
14028
14029 if (is_task_work_add_kfunc(meta.func_id)) {
14030 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
14031 set_task_work_schedule_callback_state);
14032 if (err) {
14033 verbose(env, "kfunc %s#%d failed callback verification\n",
14034 func_name, meta.func_id);
14035 return err;
14036 }
14037 }
14038
14039 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
14040 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
14041
14042 preempt_disable = is_kfunc_bpf_preempt_disable(&meta);
14043 preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
14044
14045 if (rcu_lock) {
14046 env->cur_state->active_rcu_locks++;
14047 } else if (rcu_unlock) {
14048 struct bpf_func_state *state;
14049 struct bpf_reg_state *reg;
14050 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
14051
14052 if (env->cur_state->active_rcu_locks == 0) {
14053 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
14054 return -EINVAL;
14055 }
14056 if (--env->cur_state->active_rcu_locks == 0) {
14057 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
14058 if (reg->type & MEM_RCU) {
14059 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
14060 reg->type |= PTR_UNTRUSTED;
14061 }
14062 }));
14063 }
14064 } else if (sleepable && env->cur_state->active_rcu_locks) {
14065 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
14066 return -EACCES;
14067 }
14068
14069 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
14070 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
14071 return -EACCES;
14072 }
14073
14074 if (env->cur_state->active_preempt_locks) {
14075 if (preempt_disable) {
14076 env->cur_state->active_preempt_locks++;
14077 } else if (preempt_enable) {
14078 env->cur_state->active_preempt_locks--;
14079 } else if (sleepable) {
14080 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name);
14081 return -EACCES;
14082 }
14083 } else if (preempt_disable) {
14084 env->cur_state->active_preempt_locks++;
14085 } else if (preempt_enable) {
14086 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
14087 return -EINVAL;
14088 }
14089
14090 if (env->cur_state->active_irq_id && sleepable) {
14091 verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name);
14092 return -EACCES;
14093 }
14094
14095 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) {
14096 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name);
14097 return -EACCES;
14098 }
14099
14100 /* In case of release function, we get register number of refcounted
14101 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
14102 */
14103 if (meta.release_regno) {
14104 struct bpf_reg_state *reg = ®s[meta.release_regno];
14105
14106 if (meta.initialized_dynptr.ref_obj_id) {
14107 err = unmark_stack_slots_dynptr(env, reg);
14108 } else {
14109 err = release_reference(env, reg->ref_obj_id);
14110 if (err)
14111 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14112 func_name, meta.func_id);
14113 }
14114 if (err)
14115 return err;
14116 }
14117
14118 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
14119 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
14120 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
14121 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
14122 insn_aux->insert_off = regs[BPF_REG_2].off;
14123 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
14124 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
14125 if (err) {
14126 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
14127 func_name, meta.func_id);
14128 return err;
14129 }
14130
14131 err = release_reference(env, release_ref_obj_id);
14132 if (err) {
14133 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
14134 func_name, meta.func_id);
14135 return err;
14136 }
14137 }
14138
14139 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
14140 if (!bpf_jit_supports_exceptions()) {
14141 verbose(env, "JIT does not support calling kfunc %s#%d\n",
14142 func_name, meta.func_id);
14143 return -ENOTSUPP;
14144 }
14145 env->seen_exception = true;
14146
14147 /* In the case of the default callback, the cookie value passed
14148 * to bpf_throw becomes the return value of the program.
14149 */
14150 if (!env->exception_callback_subprog) {
14151 err = check_return_code(env, BPF_REG_1, "R1");
14152 if (err < 0)
14153 return err;
14154 }
14155 }
14156
14157 for (i = 0; i < CALLER_SAVED_REGS; i++)
14158 mark_reg_not_init(env, regs, caller_saved[i]);
14159
14160 /* Check return type */
14161 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
14162
14163 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
14164 /* Only exception is bpf_obj_new_impl */
14165 if (meta.btf != btf_vmlinux ||
14166 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
14167 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
14168 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
14169 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
14170 return -EINVAL;
14171 }
14172 }
14173
14174 if (btf_type_is_scalar(t)) {
14175 mark_reg_unknown(env, regs, BPF_REG_0);
14176 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] ||
14177 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]))
14178 __mark_reg_const_zero(env, ®s[BPF_REG_0]);
14179 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
14180 } else if (btf_type_is_ptr(t)) {
14181 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
14182 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf);
14183 if (err) {
14184 if (err < 0)
14185 return err;
14186 } else if (btf_type_is_void(ptr_type)) {
14187 /* kfunc returning 'void *' is equivalent to returning scalar */
14188 mark_reg_unknown(env, regs, BPF_REG_0);
14189 } else if (!__btf_type_is_struct(ptr_type)) {
14190 if (!meta.r0_size) {
14191 __u32 sz;
14192
14193 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
14194 meta.r0_size = sz;
14195 meta.r0_rdonly = true;
14196 }
14197 }
14198 if (!meta.r0_size) {
14199 ptr_type_name = btf_name_by_offset(desc_btf,
14200 ptr_type->name_off);
14201 verbose(env,
14202 "kernel function %s returns pointer type %s %s is not supported\n",
14203 func_name,
14204 btf_type_str(ptr_type),
14205 ptr_type_name);
14206 return -EINVAL;
14207 }
14208
14209 mark_reg_known_zero(env, regs, BPF_REG_0);
14210 regs[BPF_REG_0].type = PTR_TO_MEM;
14211 regs[BPF_REG_0].mem_size = meta.r0_size;
14212
14213 if (meta.r0_rdonly)
14214 regs[BPF_REG_0].type |= MEM_RDONLY;
14215
14216 /* Ensures we don't access the memory after a release_reference() */
14217 if (meta.ref_obj_id)
14218 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
14219
14220 if (is_kfunc_rcu_protected(&meta))
14221 regs[BPF_REG_0].type |= MEM_RCU;
14222 } else {
14223 mark_reg_known_zero(env, regs, BPF_REG_0);
14224 regs[BPF_REG_0].btf = desc_btf;
14225 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
14226 regs[BPF_REG_0].btf_id = ptr_type_id;
14227
14228 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache])
14229 regs[BPF_REG_0].type |= PTR_UNTRUSTED;
14230 else if (is_kfunc_rcu_protected(&meta))
14231 regs[BPF_REG_0].type |= MEM_RCU;
14232
14233 if (is_iter_next_kfunc(&meta)) {
14234 struct bpf_reg_state *cur_iter;
14235
14236 cur_iter = get_iter_from_state(env->cur_state, &meta);
14237
14238 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */
14239 regs[BPF_REG_0].type |= MEM_RCU;
14240 else
14241 regs[BPF_REG_0].type |= PTR_TRUSTED;
14242 }
14243 }
14244
14245 if (is_kfunc_ret_null(&meta)) {
14246 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
14247 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
14248 regs[BPF_REG_0].id = ++env->id_gen;
14249 }
14250 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
14251 if (is_kfunc_acquire(&meta)) {
14252 int id = acquire_reference(env, insn_idx);
14253
14254 if (id < 0)
14255 return id;
14256 if (is_kfunc_ret_null(&meta))
14257 regs[BPF_REG_0].id = id;
14258 regs[BPF_REG_0].ref_obj_id = id;
14259 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
14260 ref_set_non_owning(env, ®s[BPF_REG_0]);
14261 }
14262
14263 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
14264 regs[BPF_REG_0].id = ++env->id_gen;
14265 } else if (btf_type_is_void(t)) {
14266 if (meta.btf == btf_vmlinux) {
14267 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
14268 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
14269 insn_aux->kptr_struct_meta =
14270 btf_find_struct_meta(meta.arg_btf,
14271 meta.arg_btf_id);
14272 }
14273 }
14274 }
14275
14276 if (is_kfunc_pkt_changing(&meta))
14277 clear_all_pkt_pointers(env);
14278
14279 nargs = btf_type_vlen(meta.func_proto);
14280 args = (const struct btf_param *)(meta.func_proto + 1);
14281 for (i = 0; i < nargs; i++) {
14282 u32 regno = i + 1;
14283
14284 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
14285 if (btf_type_is_ptr(t))
14286 mark_btf_func_reg_size(env, regno, sizeof(void *));
14287 else
14288 /* scalar. ensured by btf_check_kfunc_arg_match() */
14289 mark_btf_func_reg_size(env, regno, t->size);
14290 }
14291
14292 if (is_iter_next_kfunc(&meta)) {
14293 err = process_iter_next_call(env, insn_idx, &meta);
14294 if (err)
14295 return err;
14296 }
14297
14298 return 0;
14299 }
14300
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)14301 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
14302 const struct bpf_reg_state *reg,
14303 enum bpf_reg_type type)
14304 {
14305 bool known = tnum_is_const(reg->var_off);
14306 s64 val = reg->var_off.value;
14307 s64 smin = reg->smin_value;
14308
14309 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
14310 verbose(env, "math between %s pointer and %lld is not allowed\n",
14311 reg_type_str(env, type), val);
14312 return false;
14313 }
14314
14315 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
14316 verbose(env, "%s pointer offset %d is not allowed\n",
14317 reg_type_str(env, type), reg->off);
14318 return false;
14319 }
14320
14321 if (smin == S64_MIN) {
14322 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
14323 reg_type_str(env, type));
14324 return false;
14325 }
14326
14327 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
14328 verbose(env, "value %lld makes %s pointer be out of bounds\n",
14329 smin, reg_type_str(env, type));
14330 return false;
14331 }
14332
14333 return true;
14334 }
14335
14336 enum {
14337 REASON_BOUNDS = -1,
14338 REASON_TYPE = -2,
14339 REASON_PATHS = -3,
14340 REASON_LIMIT = -4,
14341 REASON_STACK = -5,
14342 };
14343
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)14344 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
14345 u32 *alu_limit, bool mask_to_left)
14346 {
14347 u32 max = 0, ptr_limit = 0;
14348
14349 switch (ptr_reg->type) {
14350 case PTR_TO_STACK:
14351 /* Offset 0 is out-of-bounds, but acceptable start for the
14352 * left direction, see BPF_REG_FP. Also, unknown scalar
14353 * offset where we would need to deal with min/max bounds is
14354 * currently prohibited for unprivileged.
14355 */
14356 max = MAX_BPF_STACK + mask_to_left;
14357 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
14358 break;
14359 case PTR_TO_MAP_VALUE:
14360 max = ptr_reg->map_ptr->value_size;
14361 ptr_limit = (mask_to_left ?
14362 ptr_reg->smin_value :
14363 ptr_reg->umax_value) + ptr_reg->off;
14364 break;
14365 default:
14366 return REASON_TYPE;
14367 }
14368
14369 if (ptr_limit >= max)
14370 return REASON_LIMIT;
14371 *alu_limit = ptr_limit;
14372 return 0;
14373 }
14374
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)14375 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
14376 const struct bpf_insn *insn)
14377 {
14378 return env->bypass_spec_v1 ||
14379 BPF_SRC(insn->code) == BPF_K ||
14380 cur_aux(env)->nospec;
14381 }
14382
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)14383 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
14384 u32 alu_state, u32 alu_limit)
14385 {
14386 /* If we arrived here from different branches with different
14387 * state or limits to sanitize, then this won't work.
14388 */
14389 if (aux->alu_state &&
14390 (aux->alu_state != alu_state ||
14391 aux->alu_limit != alu_limit))
14392 return REASON_PATHS;
14393
14394 /* Corresponding fixup done in do_misc_fixups(). */
14395 aux->alu_state = alu_state;
14396 aux->alu_limit = alu_limit;
14397 return 0;
14398 }
14399
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)14400 static int sanitize_val_alu(struct bpf_verifier_env *env,
14401 struct bpf_insn *insn)
14402 {
14403 struct bpf_insn_aux_data *aux = cur_aux(env);
14404
14405 if (can_skip_alu_sanitation(env, insn))
14406 return 0;
14407
14408 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
14409 }
14410
sanitize_needed(u8 opcode)14411 static bool sanitize_needed(u8 opcode)
14412 {
14413 return opcode == BPF_ADD || opcode == BPF_SUB;
14414 }
14415
14416 struct bpf_sanitize_info {
14417 struct bpf_insn_aux_data aux;
14418 bool mask_to_left;
14419 };
14420
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)14421 static int sanitize_speculative_path(struct bpf_verifier_env *env,
14422 const struct bpf_insn *insn,
14423 u32 next_idx, u32 curr_idx)
14424 {
14425 struct bpf_verifier_state *branch;
14426 struct bpf_reg_state *regs;
14427
14428 branch = push_stack(env, next_idx, curr_idx, true);
14429 if (!IS_ERR(branch) && insn) {
14430 regs = branch->frame[branch->curframe]->regs;
14431 if (BPF_SRC(insn->code) == BPF_K) {
14432 mark_reg_unknown(env, regs, insn->dst_reg);
14433 } else if (BPF_SRC(insn->code) == BPF_X) {
14434 mark_reg_unknown(env, regs, insn->dst_reg);
14435 mark_reg_unknown(env, regs, insn->src_reg);
14436 }
14437 }
14438 return PTR_ERR_OR_ZERO(branch);
14439 }
14440
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)14441 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
14442 struct bpf_insn *insn,
14443 const struct bpf_reg_state *ptr_reg,
14444 const struct bpf_reg_state *off_reg,
14445 struct bpf_reg_state *dst_reg,
14446 struct bpf_sanitize_info *info,
14447 const bool commit_window)
14448 {
14449 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
14450 struct bpf_verifier_state *vstate = env->cur_state;
14451 bool off_is_imm = tnum_is_const(off_reg->var_off);
14452 bool off_is_neg = off_reg->smin_value < 0;
14453 bool ptr_is_dst_reg = ptr_reg == dst_reg;
14454 u8 opcode = BPF_OP(insn->code);
14455 u32 alu_state, alu_limit;
14456 struct bpf_reg_state tmp;
14457 int err;
14458
14459 if (can_skip_alu_sanitation(env, insn))
14460 return 0;
14461
14462 /* We already marked aux for masking from non-speculative
14463 * paths, thus we got here in the first place. We only care
14464 * to explore bad access from here.
14465 */
14466 if (vstate->speculative)
14467 goto do_sim;
14468
14469 if (!commit_window) {
14470 if (!tnum_is_const(off_reg->var_off) &&
14471 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
14472 return REASON_BOUNDS;
14473
14474 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
14475 (opcode == BPF_SUB && !off_is_neg);
14476 }
14477
14478 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
14479 if (err < 0)
14480 return err;
14481
14482 if (commit_window) {
14483 /* In commit phase we narrow the masking window based on
14484 * the observed pointer move after the simulated operation.
14485 */
14486 alu_state = info->aux.alu_state;
14487 alu_limit = abs(info->aux.alu_limit - alu_limit);
14488 } else {
14489 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
14490 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
14491 alu_state |= ptr_is_dst_reg ?
14492 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
14493
14494 /* Limit pruning on unknown scalars to enable deep search for
14495 * potential masking differences from other program paths.
14496 */
14497 if (!off_is_imm)
14498 env->explore_alu_limits = true;
14499 }
14500
14501 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
14502 if (err < 0)
14503 return err;
14504 do_sim:
14505 /* If we're in commit phase, we're done here given we already
14506 * pushed the truncated dst_reg into the speculative verification
14507 * stack.
14508 *
14509 * Also, when register is a known constant, we rewrite register-based
14510 * operation to immediate-based, and thus do not need masking (and as
14511 * a consequence, do not need to simulate the zero-truncation either).
14512 */
14513 if (commit_window || off_is_imm)
14514 return 0;
14515
14516 /* Simulate and find potential out-of-bounds access under
14517 * speculative execution from truncation as a result of
14518 * masking when off was not within expected range. If off
14519 * sits in dst, then we temporarily need to move ptr there
14520 * to simulate dst (== 0) +/-= ptr. Needed, for example,
14521 * for cases where we use K-based arithmetic in one direction
14522 * and truncated reg-based in the other in order to explore
14523 * bad access.
14524 */
14525 if (!ptr_is_dst_reg) {
14526 tmp = *dst_reg;
14527 copy_register_state(dst_reg, ptr_reg);
14528 }
14529 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx);
14530 if (err < 0)
14531 return REASON_STACK;
14532 if (!ptr_is_dst_reg)
14533 *dst_reg = tmp;
14534 return 0;
14535 }
14536
sanitize_mark_insn_seen(struct bpf_verifier_env * env)14537 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
14538 {
14539 struct bpf_verifier_state *vstate = env->cur_state;
14540
14541 /* If we simulate paths under speculation, we don't update the
14542 * insn as 'seen' such that when we verify unreachable paths in
14543 * the non-speculative domain, sanitize_dead_code() can still
14544 * rewrite/sanitize them.
14545 */
14546 if (!vstate->speculative)
14547 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
14548 }
14549
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)14550 static int sanitize_err(struct bpf_verifier_env *env,
14551 const struct bpf_insn *insn, int reason,
14552 const struct bpf_reg_state *off_reg,
14553 const struct bpf_reg_state *dst_reg)
14554 {
14555 static const char *err = "pointer arithmetic with it prohibited for !root";
14556 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
14557 u32 dst = insn->dst_reg, src = insn->src_reg;
14558
14559 switch (reason) {
14560 case REASON_BOUNDS:
14561 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
14562 off_reg == dst_reg ? dst : src, err);
14563 break;
14564 case REASON_TYPE:
14565 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
14566 off_reg == dst_reg ? src : dst, err);
14567 break;
14568 case REASON_PATHS:
14569 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
14570 dst, op, err);
14571 break;
14572 case REASON_LIMIT:
14573 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
14574 dst, op, err);
14575 break;
14576 case REASON_STACK:
14577 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
14578 dst, err);
14579 return -ENOMEM;
14580 default:
14581 verifier_bug(env, "unknown reason (%d)", reason);
14582 break;
14583 }
14584
14585 return -EACCES;
14586 }
14587
14588 /* check that stack access falls within stack limits and that 'reg' doesn't
14589 * have a variable offset.
14590 *
14591 * Variable offset is prohibited for unprivileged mode for simplicity since it
14592 * requires corresponding support in Spectre masking for stack ALU. See also
14593 * retrieve_ptr_limit().
14594 *
14595 *
14596 * 'off' includes 'reg->off'.
14597 */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)14598 static int check_stack_access_for_ptr_arithmetic(
14599 struct bpf_verifier_env *env,
14600 int regno,
14601 const struct bpf_reg_state *reg,
14602 int off)
14603 {
14604 if (!tnum_is_const(reg->var_off)) {
14605 char tn_buf[48];
14606
14607 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
14608 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
14609 regno, tn_buf, off);
14610 return -EACCES;
14611 }
14612
14613 if (off >= 0 || off < -MAX_BPF_STACK) {
14614 verbose(env, "R%d stack pointer arithmetic goes out of range, "
14615 "prohibited for !root; off=%d\n", regno, off);
14616 return -EACCES;
14617 }
14618
14619 return 0;
14620 }
14621
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)14622 static int sanitize_check_bounds(struct bpf_verifier_env *env,
14623 const struct bpf_insn *insn,
14624 const struct bpf_reg_state *dst_reg)
14625 {
14626 u32 dst = insn->dst_reg;
14627
14628 /* For unprivileged we require that resulting offset must be in bounds
14629 * in order to be able to sanitize access later on.
14630 */
14631 if (env->bypass_spec_v1)
14632 return 0;
14633
14634 switch (dst_reg->type) {
14635 case PTR_TO_STACK:
14636 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
14637 dst_reg->off + dst_reg->var_off.value))
14638 return -EACCES;
14639 break;
14640 case PTR_TO_MAP_VALUE:
14641 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
14642 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
14643 "prohibited for !root\n", dst);
14644 return -EACCES;
14645 }
14646 break;
14647 default:
14648 return -EOPNOTSUPP;
14649 }
14650
14651 return 0;
14652 }
14653
14654 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
14655 * Caller should also handle BPF_MOV case separately.
14656 * If we return -EACCES, caller may want to try again treating pointer as a
14657 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
14658 */
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)14659 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
14660 struct bpf_insn *insn,
14661 const struct bpf_reg_state *ptr_reg,
14662 const struct bpf_reg_state *off_reg)
14663 {
14664 struct bpf_verifier_state *vstate = env->cur_state;
14665 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14666 struct bpf_reg_state *regs = state->regs, *dst_reg;
14667 bool known = tnum_is_const(off_reg->var_off);
14668 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
14669 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
14670 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
14671 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
14672 struct bpf_sanitize_info info = {};
14673 u8 opcode = BPF_OP(insn->code);
14674 u32 dst = insn->dst_reg;
14675 int ret, bounds_ret;
14676
14677 dst_reg = ®s[dst];
14678
14679 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
14680 smin_val > smax_val || umin_val > umax_val) {
14681 /* Taint dst register if offset had invalid bounds derived from
14682 * e.g. dead branches.
14683 */
14684 __mark_reg_unknown(env, dst_reg);
14685 return 0;
14686 }
14687
14688 if (BPF_CLASS(insn->code) != BPF_ALU64) {
14689 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
14690 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
14691 __mark_reg_unknown(env, dst_reg);
14692 return 0;
14693 }
14694
14695 verbose(env,
14696 "R%d 32-bit pointer arithmetic prohibited\n",
14697 dst);
14698 return -EACCES;
14699 }
14700
14701 if (ptr_reg->type & PTR_MAYBE_NULL) {
14702 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
14703 dst, reg_type_str(env, ptr_reg->type));
14704 return -EACCES;
14705 }
14706
14707 /*
14708 * Accesses to untrusted PTR_TO_MEM are done through probe
14709 * instructions, hence no need to track offsets.
14710 */
14711 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED))
14712 return 0;
14713
14714 switch (base_type(ptr_reg->type)) {
14715 case PTR_TO_CTX:
14716 case PTR_TO_MAP_VALUE:
14717 case PTR_TO_MAP_KEY:
14718 case PTR_TO_STACK:
14719 case PTR_TO_PACKET_META:
14720 case PTR_TO_PACKET:
14721 case PTR_TO_TP_BUFFER:
14722 case PTR_TO_BTF_ID:
14723 case PTR_TO_MEM:
14724 case PTR_TO_BUF:
14725 case PTR_TO_FUNC:
14726 case CONST_PTR_TO_DYNPTR:
14727 break;
14728 case PTR_TO_FLOW_KEYS:
14729 if (known)
14730 break;
14731 fallthrough;
14732 case CONST_PTR_TO_MAP:
14733 /* smin_val represents the known value */
14734 if (known && smin_val == 0 && opcode == BPF_ADD)
14735 break;
14736 fallthrough;
14737 default:
14738 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
14739 dst, reg_type_str(env, ptr_reg->type));
14740 return -EACCES;
14741 }
14742
14743 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
14744 * The id may be overwritten later if we create a new variable offset.
14745 */
14746 dst_reg->type = ptr_reg->type;
14747 dst_reg->id = ptr_reg->id;
14748
14749 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
14750 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
14751 return -EINVAL;
14752
14753 /* pointer types do not carry 32-bit bounds at the moment. */
14754 __mark_reg32_unbounded(dst_reg);
14755
14756 if (sanitize_needed(opcode)) {
14757 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
14758 &info, false);
14759 if (ret < 0)
14760 return sanitize_err(env, insn, ret, off_reg, dst_reg);
14761 }
14762
14763 switch (opcode) {
14764 case BPF_ADD:
14765 /* We can take a fixed offset as long as it doesn't overflow
14766 * the s32 'off' field
14767 */
14768 if (known && (ptr_reg->off + smin_val ==
14769 (s64)(s32)(ptr_reg->off + smin_val))) {
14770 /* pointer += K. Accumulate it into fixed offset */
14771 dst_reg->smin_value = smin_ptr;
14772 dst_reg->smax_value = smax_ptr;
14773 dst_reg->umin_value = umin_ptr;
14774 dst_reg->umax_value = umax_ptr;
14775 dst_reg->var_off = ptr_reg->var_off;
14776 dst_reg->off = ptr_reg->off + smin_val;
14777 dst_reg->raw = ptr_reg->raw;
14778 break;
14779 }
14780 /* A new variable offset is created. Note that off_reg->off
14781 * == 0, since it's a scalar.
14782 * dst_reg gets the pointer type and since some positive
14783 * integer value was added to the pointer, give it a new 'id'
14784 * if it's a PTR_TO_PACKET.
14785 * this creates a new 'base' pointer, off_reg (variable) gets
14786 * added into the variable offset, and we copy the fixed offset
14787 * from ptr_reg.
14788 */
14789 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) ||
14790 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) {
14791 dst_reg->smin_value = S64_MIN;
14792 dst_reg->smax_value = S64_MAX;
14793 }
14794 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) ||
14795 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) {
14796 dst_reg->umin_value = 0;
14797 dst_reg->umax_value = U64_MAX;
14798 }
14799 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
14800 dst_reg->off = ptr_reg->off;
14801 dst_reg->raw = ptr_reg->raw;
14802 if (reg_is_pkt_pointer(ptr_reg)) {
14803 dst_reg->id = ++env->id_gen;
14804 /* something was added to pkt_ptr, set range to zero */
14805 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14806 }
14807 break;
14808 case BPF_SUB:
14809 if (dst_reg == off_reg) {
14810 /* scalar -= pointer. Creates an unknown scalar */
14811 verbose(env, "R%d tried to subtract pointer from scalar\n",
14812 dst);
14813 return -EACCES;
14814 }
14815 /* We don't allow subtraction from FP, because (according to
14816 * test_verifier.c test "invalid fp arithmetic", JITs might not
14817 * be able to deal with it.
14818 */
14819 if (ptr_reg->type == PTR_TO_STACK) {
14820 verbose(env, "R%d subtraction from stack pointer prohibited\n",
14821 dst);
14822 return -EACCES;
14823 }
14824 if (known && (ptr_reg->off - smin_val ==
14825 (s64)(s32)(ptr_reg->off - smin_val))) {
14826 /* pointer -= K. Subtract it from fixed offset */
14827 dst_reg->smin_value = smin_ptr;
14828 dst_reg->smax_value = smax_ptr;
14829 dst_reg->umin_value = umin_ptr;
14830 dst_reg->umax_value = umax_ptr;
14831 dst_reg->var_off = ptr_reg->var_off;
14832 dst_reg->id = ptr_reg->id;
14833 dst_reg->off = ptr_reg->off - smin_val;
14834 dst_reg->raw = ptr_reg->raw;
14835 break;
14836 }
14837 /* A new variable offset is created. If the subtrahend is known
14838 * nonnegative, then any reg->range we had before is still good.
14839 */
14840 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) ||
14841 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) {
14842 /* Overflow possible, we know nothing */
14843 dst_reg->smin_value = S64_MIN;
14844 dst_reg->smax_value = S64_MAX;
14845 }
14846 if (umin_ptr < umax_val) {
14847 /* Overflow possible, we know nothing */
14848 dst_reg->umin_value = 0;
14849 dst_reg->umax_value = U64_MAX;
14850 } else {
14851 /* Cannot overflow (as long as bounds are consistent) */
14852 dst_reg->umin_value = umin_ptr - umax_val;
14853 dst_reg->umax_value = umax_ptr - umin_val;
14854 }
14855 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
14856 dst_reg->off = ptr_reg->off;
14857 dst_reg->raw = ptr_reg->raw;
14858 if (reg_is_pkt_pointer(ptr_reg)) {
14859 dst_reg->id = ++env->id_gen;
14860 /* something was added to pkt_ptr, set range to zero */
14861 if (smin_val < 0)
14862 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
14863 }
14864 break;
14865 case BPF_AND:
14866 case BPF_OR:
14867 case BPF_XOR:
14868 /* bitwise ops on pointers are troublesome, prohibit. */
14869 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
14870 dst, bpf_alu_string[opcode >> 4]);
14871 return -EACCES;
14872 default:
14873 /* other operators (e.g. MUL,LSH) produce non-pointer results */
14874 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
14875 dst, bpf_alu_string[opcode >> 4]);
14876 return -EACCES;
14877 }
14878
14879 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
14880 return -EINVAL;
14881 reg_bounds_sync(dst_reg);
14882 bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
14883 if (bounds_ret == -EACCES)
14884 return bounds_ret;
14885 if (sanitize_needed(opcode)) {
14886 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
14887 &info, true);
14888 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn)
14889 && !env->cur_state->speculative
14890 && bounds_ret
14891 && !ret,
14892 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) {
14893 return -EFAULT;
14894 }
14895 if (ret < 0)
14896 return sanitize_err(env, insn, ret, off_reg, dst_reg);
14897 }
14898
14899 return 0;
14900 }
14901
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14902 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
14903 struct bpf_reg_state *src_reg)
14904 {
14905 s32 *dst_smin = &dst_reg->s32_min_value;
14906 s32 *dst_smax = &dst_reg->s32_max_value;
14907 u32 *dst_umin = &dst_reg->u32_min_value;
14908 u32 *dst_umax = &dst_reg->u32_max_value;
14909 u32 umin_val = src_reg->u32_min_value;
14910 u32 umax_val = src_reg->u32_max_value;
14911 bool min_overflow, max_overflow;
14912
14913 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) ||
14914 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) {
14915 *dst_smin = S32_MIN;
14916 *dst_smax = S32_MAX;
14917 }
14918
14919 /* If either all additions overflow or no additions overflow, then
14920 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14921 * dst_umax + src_umax. Otherwise (some additions overflow), set
14922 * the output bounds to unbounded.
14923 */
14924 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14925 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14926
14927 if (!min_overflow && max_overflow) {
14928 *dst_umin = 0;
14929 *dst_umax = U32_MAX;
14930 }
14931 }
14932
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14933 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
14934 struct bpf_reg_state *src_reg)
14935 {
14936 s64 *dst_smin = &dst_reg->smin_value;
14937 s64 *dst_smax = &dst_reg->smax_value;
14938 u64 *dst_umin = &dst_reg->umin_value;
14939 u64 *dst_umax = &dst_reg->umax_value;
14940 u64 umin_val = src_reg->umin_value;
14941 u64 umax_val = src_reg->umax_value;
14942 bool min_overflow, max_overflow;
14943
14944 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) ||
14945 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) {
14946 *dst_smin = S64_MIN;
14947 *dst_smax = S64_MAX;
14948 }
14949
14950 /* If either all additions overflow or no additions overflow, then
14951 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax =
14952 * dst_umax + src_umax. Otherwise (some additions overflow), set
14953 * the output bounds to unbounded.
14954 */
14955 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin);
14956 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax);
14957
14958 if (!min_overflow && max_overflow) {
14959 *dst_umin = 0;
14960 *dst_umax = U64_MAX;
14961 }
14962 }
14963
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14964 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
14965 struct bpf_reg_state *src_reg)
14966 {
14967 s32 *dst_smin = &dst_reg->s32_min_value;
14968 s32 *dst_smax = &dst_reg->s32_max_value;
14969 u32 *dst_umin = &dst_reg->u32_min_value;
14970 u32 *dst_umax = &dst_reg->u32_max_value;
14971 u32 umin_val = src_reg->u32_min_value;
14972 u32 umax_val = src_reg->u32_max_value;
14973 bool min_underflow, max_underflow;
14974
14975 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) ||
14976 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) {
14977 /* Overflow possible, we know nothing */
14978 *dst_smin = S32_MIN;
14979 *dst_smax = S32_MAX;
14980 }
14981
14982 /* If either all subtractions underflow or no subtractions
14983 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
14984 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
14985 * underflow), set the output bounds to unbounded.
14986 */
14987 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
14988 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
14989
14990 if (min_underflow && !max_underflow) {
14991 *dst_umin = 0;
14992 *dst_umax = U32_MAX;
14993 }
14994 }
14995
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)14996 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
14997 struct bpf_reg_state *src_reg)
14998 {
14999 s64 *dst_smin = &dst_reg->smin_value;
15000 s64 *dst_smax = &dst_reg->smax_value;
15001 u64 *dst_umin = &dst_reg->umin_value;
15002 u64 *dst_umax = &dst_reg->umax_value;
15003 u64 umin_val = src_reg->umin_value;
15004 u64 umax_val = src_reg->umax_value;
15005 bool min_underflow, max_underflow;
15006
15007 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) ||
15008 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) {
15009 /* Overflow possible, we know nothing */
15010 *dst_smin = S64_MIN;
15011 *dst_smax = S64_MAX;
15012 }
15013
15014 /* If either all subtractions underflow or no subtractions
15015 * underflow, it is okay to set: dst_umin = dst_umin - src_umax,
15016 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions
15017 * underflow), set the output bounds to unbounded.
15018 */
15019 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin);
15020 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax);
15021
15022 if (min_underflow && !max_underflow) {
15023 *dst_umin = 0;
15024 *dst_umax = U64_MAX;
15025 }
15026 }
15027
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15028 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
15029 struct bpf_reg_state *src_reg)
15030 {
15031 s32 *dst_smin = &dst_reg->s32_min_value;
15032 s32 *dst_smax = &dst_reg->s32_max_value;
15033 u32 *dst_umin = &dst_reg->u32_min_value;
15034 u32 *dst_umax = &dst_reg->u32_max_value;
15035 s32 tmp_prod[4];
15036
15037 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) ||
15038 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) {
15039 /* Overflow possible, we know nothing */
15040 *dst_umin = 0;
15041 *dst_umax = U32_MAX;
15042 }
15043 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) ||
15044 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) ||
15045 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) ||
15046 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) {
15047 /* Overflow possible, we know nothing */
15048 *dst_smin = S32_MIN;
15049 *dst_smax = S32_MAX;
15050 } else {
15051 *dst_smin = min_array(tmp_prod, 4);
15052 *dst_smax = max_array(tmp_prod, 4);
15053 }
15054 }
15055
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15056 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
15057 struct bpf_reg_state *src_reg)
15058 {
15059 s64 *dst_smin = &dst_reg->smin_value;
15060 s64 *dst_smax = &dst_reg->smax_value;
15061 u64 *dst_umin = &dst_reg->umin_value;
15062 u64 *dst_umax = &dst_reg->umax_value;
15063 s64 tmp_prod[4];
15064
15065 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) ||
15066 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) {
15067 /* Overflow possible, we know nothing */
15068 *dst_umin = 0;
15069 *dst_umax = U64_MAX;
15070 }
15071 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) ||
15072 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) ||
15073 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) ||
15074 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) {
15075 /* Overflow possible, we know nothing */
15076 *dst_smin = S64_MIN;
15077 *dst_smax = S64_MAX;
15078 } else {
15079 *dst_smin = min_array(tmp_prod, 4);
15080 *dst_smax = max_array(tmp_prod, 4);
15081 }
15082 }
15083
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15084 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
15085 struct bpf_reg_state *src_reg)
15086 {
15087 bool src_known = tnum_subreg_is_const(src_reg->var_off);
15088 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15089 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15090 u32 umax_val = src_reg->u32_max_value;
15091
15092 if (src_known && dst_known) {
15093 __mark_reg32_known(dst_reg, var32_off.value);
15094 return;
15095 }
15096
15097 /* We get our minimum from the var_off, since that's inherently
15098 * bitwise. Our maximum is the minimum of the operands' maxima.
15099 */
15100 dst_reg->u32_min_value = var32_off.value;
15101 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
15102
15103 /* Safe to set s32 bounds by casting u32 result into s32 when u32
15104 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15105 */
15106 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15107 dst_reg->s32_min_value = dst_reg->u32_min_value;
15108 dst_reg->s32_max_value = dst_reg->u32_max_value;
15109 } else {
15110 dst_reg->s32_min_value = S32_MIN;
15111 dst_reg->s32_max_value = S32_MAX;
15112 }
15113 }
15114
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15115 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
15116 struct bpf_reg_state *src_reg)
15117 {
15118 bool src_known = tnum_is_const(src_reg->var_off);
15119 bool dst_known = tnum_is_const(dst_reg->var_off);
15120 u64 umax_val = src_reg->umax_value;
15121
15122 if (src_known && dst_known) {
15123 __mark_reg_known(dst_reg, dst_reg->var_off.value);
15124 return;
15125 }
15126
15127 /* We get our minimum from the var_off, since that's inherently
15128 * bitwise. Our maximum is the minimum of the operands' maxima.
15129 */
15130 dst_reg->umin_value = dst_reg->var_off.value;
15131 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
15132
15133 /* Safe to set s64 bounds by casting u64 result into s64 when u64
15134 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15135 */
15136 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15137 dst_reg->smin_value = dst_reg->umin_value;
15138 dst_reg->smax_value = dst_reg->umax_value;
15139 } else {
15140 dst_reg->smin_value = S64_MIN;
15141 dst_reg->smax_value = S64_MAX;
15142 }
15143 /* We may learn something more from the var_off */
15144 __update_reg_bounds(dst_reg);
15145 }
15146
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15147 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
15148 struct bpf_reg_state *src_reg)
15149 {
15150 bool src_known = tnum_subreg_is_const(src_reg->var_off);
15151 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15152 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15153 u32 umin_val = src_reg->u32_min_value;
15154
15155 if (src_known && dst_known) {
15156 __mark_reg32_known(dst_reg, var32_off.value);
15157 return;
15158 }
15159
15160 /* We get our maximum from the var_off, and our minimum is the
15161 * maximum of the operands' minima
15162 */
15163 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
15164 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15165
15166 /* Safe to set s32 bounds by casting u32 result into s32 when u32
15167 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15168 */
15169 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15170 dst_reg->s32_min_value = dst_reg->u32_min_value;
15171 dst_reg->s32_max_value = dst_reg->u32_max_value;
15172 } else {
15173 dst_reg->s32_min_value = S32_MIN;
15174 dst_reg->s32_max_value = S32_MAX;
15175 }
15176 }
15177
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15178 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
15179 struct bpf_reg_state *src_reg)
15180 {
15181 bool src_known = tnum_is_const(src_reg->var_off);
15182 bool dst_known = tnum_is_const(dst_reg->var_off);
15183 u64 umin_val = src_reg->umin_value;
15184
15185 if (src_known && dst_known) {
15186 __mark_reg_known(dst_reg, dst_reg->var_off.value);
15187 return;
15188 }
15189
15190 /* We get our maximum from the var_off, and our minimum is the
15191 * maximum of the operands' minima
15192 */
15193 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
15194 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15195
15196 /* Safe to set s64 bounds by casting u64 result into s64 when u64
15197 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15198 */
15199 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15200 dst_reg->smin_value = dst_reg->umin_value;
15201 dst_reg->smax_value = dst_reg->umax_value;
15202 } else {
15203 dst_reg->smin_value = S64_MIN;
15204 dst_reg->smax_value = S64_MAX;
15205 }
15206 /* We may learn something more from the var_off */
15207 __update_reg_bounds(dst_reg);
15208 }
15209
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15210 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
15211 struct bpf_reg_state *src_reg)
15212 {
15213 bool src_known = tnum_subreg_is_const(src_reg->var_off);
15214 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
15215 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
15216
15217 if (src_known && dst_known) {
15218 __mark_reg32_known(dst_reg, var32_off.value);
15219 return;
15220 }
15221
15222 /* We get both minimum and maximum from the var32_off. */
15223 dst_reg->u32_min_value = var32_off.value;
15224 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
15225
15226 /* Safe to set s32 bounds by casting u32 result into s32 when u32
15227 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded.
15228 */
15229 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) {
15230 dst_reg->s32_min_value = dst_reg->u32_min_value;
15231 dst_reg->s32_max_value = dst_reg->u32_max_value;
15232 } else {
15233 dst_reg->s32_min_value = S32_MIN;
15234 dst_reg->s32_max_value = S32_MAX;
15235 }
15236 }
15237
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15238 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
15239 struct bpf_reg_state *src_reg)
15240 {
15241 bool src_known = tnum_is_const(src_reg->var_off);
15242 bool dst_known = tnum_is_const(dst_reg->var_off);
15243
15244 if (src_known && dst_known) {
15245 /* dst_reg->var_off.value has been updated earlier */
15246 __mark_reg_known(dst_reg, dst_reg->var_off.value);
15247 return;
15248 }
15249
15250 /* We get both minimum and maximum from the var_off. */
15251 dst_reg->umin_value = dst_reg->var_off.value;
15252 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
15253
15254 /* Safe to set s64 bounds by casting u64 result into s64 when u64
15255 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded.
15256 */
15257 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) {
15258 dst_reg->smin_value = dst_reg->umin_value;
15259 dst_reg->smax_value = dst_reg->umax_value;
15260 } else {
15261 dst_reg->smin_value = S64_MIN;
15262 dst_reg->smax_value = S64_MAX;
15263 }
15264
15265 __update_reg_bounds(dst_reg);
15266 }
15267
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15268 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15269 u64 umin_val, u64 umax_val)
15270 {
15271 /* We lose all sign bit information (except what we can pick
15272 * up from var_off)
15273 */
15274 dst_reg->s32_min_value = S32_MIN;
15275 dst_reg->s32_max_value = S32_MAX;
15276 /* If we might shift our top bit out, then we know nothing */
15277 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
15278 dst_reg->u32_min_value = 0;
15279 dst_reg->u32_max_value = U32_MAX;
15280 } else {
15281 dst_reg->u32_min_value <<= umin_val;
15282 dst_reg->u32_max_value <<= umax_val;
15283 }
15284 }
15285
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15286 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
15287 struct bpf_reg_state *src_reg)
15288 {
15289 u32 umax_val = src_reg->u32_max_value;
15290 u32 umin_val = src_reg->u32_min_value;
15291 /* u32 alu operation will zext upper bits */
15292 struct tnum subreg = tnum_subreg(dst_reg->var_off);
15293
15294 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15295 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
15296 /* Not required but being careful mark reg64 bounds as unknown so
15297 * that we are forced to pick them up from tnum and zext later and
15298 * if some path skips this step we are still safe.
15299 */
15300 __mark_reg64_unbounded(dst_reg);
15301 __update_reg32_bounds(dst_reg);
15302 }
15303
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)15304 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
15305 u64 umin_val, u64 umax_val)
15306 {
15307 /* Special case <<32 because it is a common compiler pattern to sign
15308 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
15309 * positive we know this shift will also be positive so we can track
15310 * bounds correctly. Otherwise we lose all sign bit information except
15311 * what we can pick up from var_off. Perhaps we can generalize this
15312 * later to shifts of any length.
15313 */
15314 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
15315 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
15316 else
15317 dst_reg->smax_value = S64_MAX;
15318
15319 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
15320 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
15321 else
15322 dst_reg->smin_value = S64_MIN;
15323
15324 /* If we might shift our top bit out, then we know nothing */
15325 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
15326 dst_reg->umin_value = 0;
15327 dst_reg->umax_value = U64_MAX;
15328 } else {
15329 dst_reg->umin_value <<= umin_val;
15330 dst_reg->umax_value <<= umax_val;
15331 }
15332 }
15333
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15334 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
15335 struct bpf_reg_state *src_reg)
15336 {
15337 u64 umax_val = src_reg->umax_value;
15338 u64 umin_val = src_reg->umin_value;
15339
15340 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
15341 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
15342 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
15343
15344 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
15345 /* We may learn something more from the var_off */
15346 __update_reg_bounds(dst_reg);
15347 }
15348
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15349 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
15350 struct bpf_reg_state *src_reg)
15351 {
15352 struct tnum subreg = tnum_subreg(dst_reg->var_off);
15353 u32 umax_val = src_reg->u32_max_value;
15354 u32 umin_val = src_reg->u32_min_value;
15355
15356 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
15357 * be negative, then either:
15358 * 1) src_reg might be zero, so the sign bit of the result is
15359 * unknown, so we lose our signed bounds
15360 * 2) it's known negative, thus the unsigned bounds capture the
15361 * signed bounds
15362 * 3) the signed bounds cross zero, so they tell us nothing
15363 * about the result
15364 * If the value in dst_reg is known nonnegative, then again the
15365 * unsigned bounds capture the signed bounds.
15366 * Thus, in all cases it suffices to blow away our signed bounds
15367 * and rely on inferring new ones from the unsigned bounds and
15368 * var_off of the result.
15369 */
15370 dst_reg->s32_min_value = S32_MIN;
15371 dst_reg->s32_max_value = S32_MAX;
15372
15373 dst_reg->var_off = tnum_rshift(subreg, umin_val);
15374 dst_reg->u32_min_value >>= umax_val;
15375 dst_reg->u32_max_value >>= umin_val;
15376
15377 __mark_reg64_unbounded(dst_reg);
15378 __update_reg32_bounds(dst_reg);
15379 }
15380
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15381 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
15382 struct bpf_reg_state *src_reg)
15383 {
15384 u64 umax_val = src_reg->umax_value;
15385 u64 umin_val = src_reg->umin_value;
15386
15387 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
15388 * be negative, then either:
15389 * 1) src_reg might be zero, so the sign bit of the result is
15390 * unknown, so we lose our signed bounds
15391 * 2) it's known negative, thus the unsigned bounds capture the
15392 * signed bounds
15393 * 3) the signed bounds cross zero, so they tell us nothing
15394 * about the result
15395 * If the value in dst_reg is known nonnegative, then again the
15396 * unsigned bounds capture the signed bounds.
15397 * Thus, in all cases it suffices to blow away our signed bounds
15398 * and rely on inferring new ones from the unsigned bounds and
15399 * var_off of the result.
15400 */
15401 dst_reg->smin_value = S64_MIN;
15402 dst_reg->smax_value = S64_MAX;
15403 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
15404 dst_reg->umin_value >>= umax_val;
15405 dst_reg->umax_value >>= umin_val;
15406
15407 /* Its not easy to operate on alu32 bounds here because it depends
15408 * on bits being shifted in. Take easy way out and mark unbounded
15409 * so we can recalculate later from tnum.
15410 */
15411 __mark_reg32_unbounded(dst_reg);
15412 __update_reg_bounds(dst_reg);
15413 }
15414
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15415 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
15416 struct bpf_reg_state *src_reg)
15417 {
15418 u64 umin_val = src_reg->u32_min_value;
15419
15420 /* Upon reaching here, src_known is true and
15421 * umax_val is equal to umin_val.
15422 */
15423 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
15424 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
15425
15426 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
15427
15428 /* blow away the dst_reg umin_value/umax_value and rely on
15429 * dst_reg var_off to refine the result.
15430 */
15431 dst_reg->u32_min_value = 0;
15432 dst_reg->u32_max_value = U32_MAX;
15433
15434 __mark_reg64_unbounded(dst_reg);
15435 __update_reg32_bounds(dst_reg);
15436 }
15437
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)15438 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
15439 struct bpf_reg_state *src_reg)
15440 {
15441 u64 umin_val = src_reg->umin_value;
15442
15443 /* Upon reaching here, src_known is true and umax_val is equal
15444 * to umin_val.
15445 */
15446 dst_reg->smin_value >>= umin_val;
15447 dst_reg->smax_value >>= umin_val;
15448
15449 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
15450
15451 /* blow away the dst_reg umin_value/umax_value and rely on
15452 * dst_reg var_off to refine the result.
15453 */
15454 dst_reg->umin_value = 0;
15455 dst_reg->umax_value = U64_MAX;
15456
15457 /* Its not easy to operate on alu32 bounds here because it depends
15458 * on bits being shifted in from upper 32-bits. Take easy way out
15459 * and mark unbounded so we can recalculate later from tnum.
15460 */
15461 __mark_reg32_unbounded(dst_reg);
15462 __update_reg_bounds(dst_reg);
15463 }
15464
is_safe_to_compute_dst_reg_range(struct bpf_insn * insn,const struct bpf_reg_state * src_reg)15465 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn,
15466 const struct bpf_reg_state *src_reg)
15467 {
15468 bool src_is_const = false;
15469 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
15470
15471 if (insn_bitness == 32) {
15472 if (tnum_subreg_is_const(src_reg->var_off)
15473 && src_reg->s32_min_value == src_reg->s32_max_value
15474 && src_reg->u32_min_value == src_reg->u32_max_value)
15475 src_is_const = true;
15476 } else {
15477 if (tnum_is_const(src_reg->var_off)
15478 && src_reg->smin_value == src_reg->smax_value
15479 && src_reg->umin_value == src_reg->umax_value)
15480 src_is_const = true;
15481 }
15482
15483 switch (BPF_OP(insn->code)) {
15484 case BPF_ADD:
15485 case BPF_SUB:
15486 case BPF_NEG:
15487 case BPF_AND:
15488 case BPF_XOR:
15489 case BPF_OR:
15490 case BPF_MUL:
15491 return true;
15492
15493 /* Shift operators range is only computable if shift dimension operand
15494 * is a constant. Shifts greater than 31 or 63 are undefined. This
15495 * includes shifts by a negative number.
15496 */
15497 case BPF_LSH:
15498 case BPF_RSH:
15499 case BPF_ARSH:
15500 return (src_is_const && src_reg->umax_value < insn_bitness);
15501 default:
15502 return false;
15503 }
15504 }
15505
15506 /* WARNING: This function does calculations on 64-bit values, but the actual
15507 * execution may occur on 32-bit values. Therefore, things like bitshifts
15508 * need extra checks in the 32-bit case.
15509 */
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)15510 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
15511 struct bpf_insn *insn,
15512 struct bpf_reg_state *dst_reg,
15513 struct bpf_reg_state src_reg)
15514 {
15515 u8 opcode = BPF_OP(insn->code);
15516 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15517 int ret;
15518
15519 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) {
15520 __mark_reg_unknown(env, dst_reg);
15521 return 0;
15522 }
15523
15524 if (sanitize_needed(opcode)) {
15525 ret = sanitize_val_alu(env, insn);
15526 if (ret < 0)
15527 return sanitize_err(env, insn, ret, NULL, NULL);
15528 }
15529
15530 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
15531 * There are two classes of instructions: The first class we track both
15532 * alu32 and alu64 sign/unsigned bounds independently this provides the
15533 * greatest amount of precision when alu operations are mixed with jmp32
15534 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
15535 * and BPF_OR. This is possible because these ops have fairly easy to
15536 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
15537 * See alu32 verifier tests for examples. The second class of
15538 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
15539 * with regards to tracking sign/unsigned bounds because the bits may
15540 * cross subreg boundaries in the alu64 case. When this happens we mark
15541 * the reg unbounded in the subreg bound space and use the resulting
15542 * tnum to calculate an approximation of the sign/unsigned bounds.
15543 */
15544 switch (opcode) {
15545 case BPF_ADD:
15546 scalar32_min_max_add(dst_reg, &src_reg);
15547 scalar_min_max_add(dst_reg, &src_reg);
15548 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
15549 break;
15550 case BPF_SUB:
15551 scalar32_min_max_sub(dst_reg, &src_reg);
15552 scalar_min_max_sub(dst_reg, &src_reg);
15553 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
15554 break;
15555 case BPF_NEG:
15556 env->fake_reg[0] = *dst_reg;
15557 __mark_reg_known(dst_reg, 0);
15558 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]);
15559 scalar_min_max_sub(dst_reg, &env->fake_reg[0]);
15560 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off);
15561 break;
15562 case BPF_MUL:
15563 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
15564 scalar32_min_max_mul(dst_reg, &src_reg);
15565 scalar_min_max_mul(dst_reg, &src_reg);
15566 break;
15567 case BPF_AND:
15568 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
15569 scalar32_min_max_and(dst_reg, &src_reg);
15570 scalar_min_max_and(dst_reg, &src_reg);
15571 break;
15572 case BPF_OR:
15573 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
15574 scalar32_min_max_or(dst_reg, &src_reg);
15575 scalar_min_max_or(dst_reg, &src_reg);
15576 break;
15577 case BPF_XOR:
15578 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
15579 scalar32_min_max_xor(dst_reg, &src_reg);
15580 scalar_min_max_xor(dst_reg, &src_reg);
15581 break;
15582 case BPF_LSH:
15583 if (alu32)
15584 scalar32_min_max_lsh(dst_reg, &src_reg);
15585 else
15586 scalar_min_max_lsh(dst_reg, &src_reg);
15587 break;
15588 case BPF_RSH:
15589 if (alu32)
15590 scalar32_min_max_rsh(dst_reg, &src_reg);
15591 else
15592 scalar_min_max_rsh(dst_reg, &src_reg);
15593 break;
15594 case BPF_ARSH:
15595 if (alu32)
15596 scalar32_min_max_arsh(dst_reg, &src_reg);
15597 else
15598 scalar_min_max_arsh(dst_reg, &src_reg);
15599 break;
15600 default:
15601 break;
15602 }
15603
15604 /* ALU32 ops are zero extended into 64bit register */
15605 if (alu32)
15606 zext_32_to_64(dst_reg);
15607 reg_bounds_sync(dst_reg);
15608 return 0;
15609 }
15610
15611 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
15612 * and var_off.
15613 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)15614 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
15615 struct bpf_insn *insn)
15616 {
15617 struct bpf_verifier_state *vstate = env->cur_state;
15618 struct bpf_func_state *state = vstate->frame[vstate->curframe];
15619 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
15620 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
15621 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
15622 u8 opcode = BPF_OP(insn->code);
15623 int err;
15624
15625 dst_reg = ®s[insn->dst_reg];
15626 src_reg = NULL;
15627
15628 if (dst_reg->type == PTR_TO_ARENA) {
15629 struct bpf_insn_aux_data *aux = cur_aux(env);
15630
15631 if (BPF_CLASS(insn->code) == BPF_ALU64)
15632 /*
15633 * 32-bit operations zero upper bits automatically.
15634 * 64-bit operations need to be converted to 32.
15635 */
15636 aux->needs_zext = true;
15637
15638 /* Any arithmetic operations are allowed on arena pointers */
15639 return 0;
15640 }
15641
15642 if (dst_reg->type != SCALAR_VALUE)
15643 ptr_reg = dst_reg;
15644
15645 if (BPF_SRC(insn->code) == BPF_X) {
15646 src_reg = ®s[insn->src_reg];
15647 if (src_reg->type != SCALAR_VALUE) {
15648 if (dst_reg->type != SCALAR_VALUE) {
15649 /* Combining two pointers by any ALU op yields
15650 * an arbitrary scalar. Disallow all math except
15651 * pointer subtraction
15652 */
15653 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
15654 mark_reg_unknown(env, regs, insn->dst_reg);
15655 return 0;
15656 }
15657 verbose(env, "R%d pointer %s pointer prohibited\n",
15658 insn->dst_reg,
15659 bpf_alu_string[opcode >> 4]);
15660 return -EACCES;
15661 } else {
15662 /* scalar += pointer
15663 * This is legal, but we have to reverse our
15664 * src/dest handling in computing the range
15665 */
15666 err = mark_chain_precision(env, insn->dst_reg);
15667 if (err)
15668 return err;
15669 return adjust_ptr_min_max_vals(env, insn,
15670 src_reg, dst_reg);
15671 }
15672 } else if (ptr_reg) {
15673 /* pointer += scalar */
15674 err = mark_chain_precision(env, insn->src_reg);
15675 if (err)
15676 return err;
15677 return adjust_ptr_min_max_vals(env, insn,
15678 dst_reg, src_reg);
15679 } else if (dst_reg->precise) {
15680 /* if dst_reg is precise, src_reg should be precise as well */
15681 err = mark_chain_precision(env, insn->src_reg);
15682 if (err)
15683 return err;
15684 }
15685 } else {
15686 /* Pretend the src is a reg with a known value, since we only
15687 * need to be able to read from this state.
15688 */
15689 off_reg.type = SCALAR_VALUE;
15690 __mark_reg_known(&off_reg, insn->imm);
15691 src_reg = &off_reg;
15692 if (ptr_reg) /* pointer += K */
15693 return adjust_ptr_min_max_vals(env, insn,
15694 ptr_reg, src_reg);
15695 }
15696
15697 /* Got here implies adding two SCALAR_VALUEs */
15698 if (WARN_ON_ONCE(ptr_reg)) {
15699 print_verifier_state(env, vstate, vstate->curframe, true);
15700 verbose(env, "verifier internal error: unexpected ptr_reg\n");
15701 return -EFAULT;
15702 }
15703 if (WARN_ON(!src_reg)) {
15704 print_verifier_state(env, vstate, vstate->curframe, true);
15705 verbose(env, "verifier internal error: no src_reg\n");
15706 return -EFAULT;
15707 }
15708 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
15709 if (err)
15710 return err;
15711 /*
15712 * Compilers can generate the code
15713 * r1 = r2
15714 * r1 += 0x1
15715 * if r2 < 1000 goto ...
15716 * use r1 in memory access
15717 * So for 64-bit alu remember constant delta between r2 and r1 and
15718 * update r1 after 'if' condition.
15719 */
15720 if (env->bpf_capable &&
15721 BPF_OP(insn->code) == BPF_ADD && !alu32 &&
15722 dst_reg->id && is_reg_const(src_reg, false)) {
15723 u64 val = reg_const_value(src_reg, false);
15724
15725 if ((dst_reg->id & BPF_ADD_CONST) ||
15726 /* prevent overflow in sync_linked_regs() later */
15727 val > (u32)S32_MAX) {
15728 /*
15729 * If the register already went through rX += val
15730 * we cannot accumulate another val into rx->off.
15731 */
15732 dst_reg->off = 0;
15733 dst_reg->id = 0;
15734 } else {
15735 dst_reg->id |= BPF_ADD_CONST;
15736 dst_reg->off = val;
15737 }
15738 } else {
15739 /*
15740 * Make sure ID is cleared otherwise dst_reg min/max could be
15741 * incorrectly propagated into other registers by sync_linked_regs()
15742 */
15743 dst_reg->id = 0;
15744 }
15745 return 0;
15746 }
15747
15748 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)15749 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
15750 {
15751 struct bpf_reg_state *regs = cur_regs(env);
15752 u8 opcode = BPF_OP(insn->code);
15753 int err;
15754
15755 if (opcode == BPF_END || opcode == BPF_NEG) {
15756 if (opcode == BPF_NEG) {
15757 if (BPF_SRC(insn->code) != BPF_K ||
15758 insn->src_reg != BPF_REG_0 ||
15759 insn->off != 0 || insn->imm != 0) {
15760 verbose(env, "BPF_NEG uses reserved fields\n");
15761 return -EINVAL;
15762 }
15763 } else {
15764 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
15765 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
15766 (BPF_CLASS(insn->code) == BPF_ALU64 &&
15767 BPF_SRC(insn->code) != BPF_TO_LE)) {
15768 verbose(env, "BPF_END uses reserved fields\n");
15769 return -EINVAL;
15770 }
15771 }
15772
15773 /* check src operand */
15774 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15775 if (err)
15776 return err;
15777
15778 if (is_pointer_value(env, insn->dst_reg)) {
15779 verbose(env, "R%d pointer arithmetic prohibited\n",
15780 insn->dst_reg);
15781 return -EACCES;
15782 }
15783
15784 /* check dest operand */
15785 if (opcode == BPF_NEG &&
15786 regs[insn->dst_reg].type == SCALAR_VALUE) {
15787 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15788 err = err ?: adjust_scalar_min_max_vals(env, insn,
15789 ®s[insn->dst_reg],
15790 regs[insn->dst_reg]);
15791 } else {
15792 err = check_reg_arg(env, insn->dst_reg, DST_OP);
15793 }
15794 if (err)
15795 return err;
15796
15797 } else if (opcode == BPF_MOV) {
15798
15799 if (BPF_SRC(insn->code) == BPF_X) {
15800 if (BPF_CLASS(insn->code) == BPF_ALU) {
15801 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) ||
15802 insn->imm) {
15803 verbose(env, "BPF_MOV uses reserved fields\n");
15804 return -EINVAL;
15805 }
15806 } else if (insn->off == BPF_ADDR_SPACE_CAST) {
15807 if (insn->imm != 1 && insn->imm != 1u << 16) {
15808 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n");
15809 return -EINVAL;
15810 }
15811 if (!env->prog->aux->arena) {
15812 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n");
15813 return -EINVAL;
15814 }
15815 } else {
15816 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 &&
15817 insn->off != 32) || insn->imm) {
15818 verbose(env, "BPF_MOV uses reserved fields\n");
15819 return -EINVAL;
15820 }
15821 }
15822
15823 /* check src operand */
15824 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15825 if (err)
15826 return err;
15827 } else {
15828 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
15829 verbose(env, "BPF_MOV uses reserved fields\n");
15830 return -EINVAL;
15831 }
15832 }
15833
15834 /* check dest operand, mark as required later */
15835 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15836 if (err)
15837 return err;
15838
15839 if (BPF_SRC(insn->code) == BPF_X) {
15840 struct bpf_reg_state *src_reg = regs + insn->src_reg;
15841 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
15842
15843 if (BPF_CLASS(insn->code) == BPF_ALU64) {
15844 if (insn->imm) {
15845 /* off == BPF_ADDR_SPACE_CAST */
15846 mark_reg_unknown(env, regs, insn->dst_reg);
15847 if (insn->imm == 1) { /* cast from as(1) to as(0) */
15848 dst_reg->type = PTR_TO_ARENA;
15849 /* PTR_TO_ARENA is 32-bit */
15850 dst_reg->subreg_def = env->insn_idx + 1;
15851 }
15852 } else if (insn->off == 0) {
15853 /* case: R1 = R2
15854 * copy register state to dest reg
15855 */
15856 assign_scalar_id_before_mov(env, src_reg);
15857 copy_register_state(dst_reg, src_reg);
15858 dst_reg->subreg_def = DEF_NOT_SUBREG;
15859 } else {
15860 /* case: R1 = (s8, s16 s32)R2 */
15861 if (is_pointer_value(env, insn->src_reg)) {
15862 verbose(env,
15863 "R%d sign-extension part of pointer\n",
15864 insn->src_reg);
15865 return -EACCES;
15866 } else if (src_reg->type == SCALAR_VALUE) {
15867 bool no_sext;
15868
15869 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15870 if (no_sext)
15871 assign_scalar_id_before_mov(env, src_reg);
15872 copy_register_state(dst_reg, src_reg);
15873 if (!no_sext)
15874 dst_reg->id = 0;
15875 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
15876 dst_reg->subreg_def = DEF_NOT_SUBREG;
15877 } else {
15878 mark_reg_unknown(env, regs, insn->dst_reg);
15879 }
15880 }
15881 } else {
15882 /* R1 = (u32) R2 */
15883 if (is_pointer_value(env, insn->src_reg)) {
15884 verbose(env,
15885 "R%d partial copy of pointer\n",
15886 insn->src_reg);
15887 return -EACCES;
15888 } else if (src_reg->type == SCALAR_VALUE) {
15889 if (insn->off == 0) {
15890 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32;
15891
15892 if (is_src_reg_u32)
15893 assign_scalar_id_before_mov(env, src_reg);
15894 copy_register_state(dst_reg, src_reg);
15895 /* Make sure ID is cleared if src_reg is not in u32
15896 * range otherwise dst_reg min/max could be incorrectly
15897 * propagated into src_reg by sync_linked_regs()
15898 */
15899 if (!is_src_reg_u32)
15900 dst_reg->id = 0;
15901 dst_reg->subreg_def = env->insn_idx + 1;
15902 } else {
15903 /* case: W1 = (s8, s16)W2 */
15904 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
15905
15906 if (no_sext)
15907 assign_scalar_id_before_mov(env, src_reg);
15908 copy_register_state(dst_reg, src_reg);
15909 if (!no_sext)
15910 dst_reg->id = 0;
15911 dst_reg->subreg_def = env->insn_idx + 1;
15912 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
15913 }
15914 } else {
15915 mark_reg_unknown(env, regs,
15916 insn->dst_reg);
15917 }
15918 zext_32_to_64(dst_reg);
15919 reg_bounds_sync(dst_reg);
15920 }
15921 } else {
15922 /* case: R = imm
15923 * remember the value we stored into this reg
15924 */
15925 /* clear any state __mark_reg_known doesn't set */
15926 mark_reg_unknown(env, regs, insn->dst_reg);
15927 regs[insn->dst_reg].type = SCALAR_VALUE;
15928 if (BPF_CLASS(insn->code) == BPF_ALU64) {
15929 __mark_reg_known(regs + insn->dst_reg,
15930 insn->imm);
15931 } else {
15932 __mark_reg_known(regs + insn->dst_reg,
15933 (u32)insn->imm);
15934 }
15935 }
15936
15937 } else if (opcode > BPF_END) {
15938 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
15939 return -EINVAL;
15940
15941 } else { /* all other ALU ops: and, sub, xor, add, ... */
15942
15943 if (BPF_SRC(insn->code) == BPF_X) {
15944 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) ||
15945 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15946 verbose(env, "BPF_ALU uses reserved fields\n");
15947 return -EINVAL;
15948 }
15949 /* check src1 operand */
15950 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15951 if (err)
15952 return err;
15953 } else {
15954 if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) ||
15955 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
15956 verbose(env, "BPF_ALU uses reserved fields\n");
15957 return -EINVAL;
15958 }
15959 }
15960
15961 /* check src2 operand */
15962 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
15963 if (err)
15964 return err;
15965
15966 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
15967 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
15968 verbose(env, "div by zero\n");
15969 return -EINVAL;
15970 }
15971
15972 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
15973 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
15974 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
15975
15976 if (insn->imm < 0 || insn->imm >= size) {
15977 verbose(env, "invalid shift %d\n", insn->imm);
15978 return -EINVAL;
15979 }
15980 }
15981
15982 /* check dest operand */
15983 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
15984 err = err ?: adjust_reg_min_max_vals(env, insn);
15985 if (err)
15986 return err;
15987 }
15988
15989 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu");
15990 }
15991
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)15992 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
15993 struct bpf_reg_state *dst_reg,
15994 enum bpf_reg_type type,
15995 bool range_right_open)
15996 {
15997 struct bpf_func_state *state;
15998 struct bpf_reg_state *reg;
15999 int new_range;
16000
16001 if (dst_reg->off < 0 ||
16002 (dst_reg->off == 0 && range_right_open))
16003 /* This doesn't give us any range */
16004 return;
16005
16006 if (dst_reg->umax_value > MAX_PACKET_OFF ||
16007 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
16008 /* Risk of overflow. For instance, ptr + (1<<63) may be less
16009 * than pkt_end, but that's because it's also less than pkt.
16010 */
16011 return;
16012
16013 new_range = dst_reg->off;
16014 if (range_right_open)
16015 new_range++;
16016
16017 /* Examples for register markings:
16018 *
16019 * pkt_data in dst register:
16020 *
16021 * r2 = r3;
16022 * r2 += 8;
16023 * if (r2 > pkt_end) goto <handle exception>
16024 * <access okay>
16025 *
16026 * r2 = r3;
16027 * r2 += 8;
16028 * if (r2 < pkt_end) goto <access okay>
16029 * <handle exception>
16030 *
16031 * Where:
16032 * r2 == dst_reg, pkt_end == src_reg
16033 * r2=pkt(id=n,off=8,r=0)
16034 * r3=pkt(id=n,off=0,r=0)
16035 *
16036 * pkt_data in src register:
16037 *
16038 * r2 = r3;
16039 * r2 += 8;
16040 * if (pkt_end >= r2) goto <access okay>
16041 * <handle exception>
16042 *
16043 * r2 = r3;
16044 * r2 += 8;
16045 * if (pkt_end <= r2) goto <handle exception>
16046 * <access okay>
16047 *
16048 * Where:
16049 * pkt_end == dst_reg, r2 == src_reg
16050 * r2=pkt(id=n,off=8,r=0)
16051 * r3=pkt(id=n,off=0,r=0)
16052 *
16053 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
16054 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
16055 * and [r3, r3 + 8-1) respectively is safe to access depending on
16056 * the check.
16057 */
16058
16059 /* If our ids match, then we must have the same max_value. And we
16060 * don't care about the other reg's fixed offset, since if it's too big
16061 * the range won't allow anything.
16062 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
16063 */
16064 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16065 if (reg->type == type && reg->id == dst_reg->id)
16066 /* keep the maximum range already checked */
16067 reg->range = max(reg->range, new_range);
16068 }));
16069 }
16070
16071 /*
16072 * <reg1> <op> <reg2>, currently assuming reg2 is a constant
16073 */
is_scalar_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16074 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16075 u8 opcode, bool is_jmp32)
16076 {
16077 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off;
16078 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off;
16079 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value;
16080 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value;
16081 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value;
16082 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value;
16083 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value;
16084 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value;
16085 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value;
16086 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value;
16087
16088 if (reg1 == reg2) {
16089 switch (opcode) {
16090 case BPF_JGE:
16091 case BPF_JLE:
16092 case BPF_JSGE:
16093 case BPF_JSLE:
16094 case BPF_JEQ:
16095 return 1;
16096 case BPF_JGT:
16097 case BPF_JLT:
16098 case BPF_JSGT:
16099 case BPF_JSLT:
16100 case BPF_JNE:
16101 return 0;
16102 case BPF_JSET:
16103 if (tnum_is_const(t1))
16104 return t1.value != 0;
16105 else
16106 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1;
16107 default:
16108 return -1;
16109 }
16110 }
16111
16112 switch (opcode) {
16113 case BPF_JEQ:
16114 /* constants, umin/umax and smin/smax checks would be
16115 * redundant in this case because they all should match
16116 */
16117 if (tnum_is_const(t1) && tnum_is_const(t2))
16118 return t1.value == t2.value;
16119 if (!tnum_overlap(t1, t2))
16120 return 0;
16121 /* non-overlapping ranges */
16122 if (umin1 > umax2 || umax1 < umin2)
16123 return 0;
16124 if (smin1 > smax2 || smax1 < smin2)
16125 return 0;
16126 if (!is_jmp32) {
16127 /* if 64-bit ranges are inconclusive, see if we can
16128 * utilize 32-bit subrange knowledge to eliminate
16129 * branches that can't be taken a priori
16130 */
16131 if (reg1->u32_min_value > reg2->u32_max_value ||
16132 reg1->u32_max_value < reg2->u32_min_value)
16133 return 0;
16134 if (reg1->s32_min_value > reg2->s32_max_value ||
16135 reg1->s32_max_value < reg2->s32_min_value)
16136 return 0;
16137 }
16138 break;
16139 case BPF_JNE:
16140 /* constants, umin/umax and smin/smax checks would be
16141 * redundant in this case because they all should match
16142 */
16143 if (tnum_is_const(t1) && tnum_is_const(t2))
16144 return t1.value != t2.value;
16145 if (!tnum_overlap(t1, t2))
16146 return 1;
16147 /* non-overlapping ranges */
16148 if (umin1 > umax2 || umax1 < umin2)
16149 return 1;
16150 if (smin1 > smax2 || smax1 < smin2)
16151 return 1;
16152 if (!is_jmp32) {
16153 /* if 64-bit ranges are inconclusive, see if we can
16154 * utilize 32-bit subrange knowledge to eliminate
16155 * branches that can't be taken a priori
16156 */
16157 if (reg1->u32_min_value > reg2->u32_max_value ||
16158 reg1->u32_max_value < reg2->u32_min_value)
16159 return 1;
16160 if (reg1->s32_min_value > reg2->s32_max_value ||
16161 reg1->s32_max_value < reg2->s32_min_value)
16162 return 1;
16163 }
16164 break;
16165 case BPF_JSET:
16166 if (!is_reg_const(reg2, is_jmp32)) {
16167 swap(reg1, reg2);
16168 swap(t1, t2);
16169 }
16170 if (!is_reg_const(reg2, is_jmp32))
16171 return -1;
16172 if ((~t1.mask & t1.value) & t2.value)
16173 return 1;
16174 if (!((t1.mask | t1.value) & t2.value))
16175 return 0;
16176 break;
16177 case BPF_JGT:
16178 if (umin1 > umax2)
16179 return 1;
16180 else if (umax1 <= umin2)
16181 return 0;
16182 break;
16183 case BPF_JSGT:
16184 if (smin1 > smax2)
16185 return 1;
16186 else if (smax1 <= smin2)
16187 return 0;
16188 break;
16189 case BPF_JLT:
16190 if (umax1 < umin2)
16191 return 1;
16192 else if (umin1 >= umax2)
16193 return 0;
16194 break;
16195 case BPF_JSLT:
16196 if (smax1 < smin2)
16197 return 1;
16198 else if (smin1 >= smax2)
16199 return 0;
16200 break;
16201 case BPF_JGE:
16202 if (umin1 >= umax2)
16203 return 1;
16204 else if (umax1 < umin2)
16205 return 0;
16206 break;
16207 case BPF_JSGE:
16208 if (smin1 >= smax2)
16209 return 1;
16210 else if (smax1 < smin2)
16211 return 0;
16212 break;
16213 case BPF_JLE:
16214 if (umax1 <= umin2)
16215 return 1;
16216 else if (umin1 > umax2)
16217 return 0;
16218 break;
16219 case BPF_JSLE:
16220 if (smax1 <= smin2)
16221 return 1;
16222 else if (smin1 > smax2)
16223 return 0;
16224 break;
16225 }
16226
16227 return -1;
16228 }
16229
flip_opcode(u32 opcode)16230 static int flip_opcode(u32 opcode)
16231 {
16232 /* How can we transform "a <op> b" into "b <op> a"? */
16233 static const u8 opcode_flip[16] = {
16234 /* these stay the same */
16235 [BPF_JEQ >> 4] = BPF_JEQ,
16236 [BPF_JNE >> 4] = BPF_JNE,
16237 [BPF_JSET >> 4] = BPF_JSET,
16238 /* these swap "lesser" and "greater" (L and G in the opcodes) */
16239 [BPF_JGE >> 4] = BPF_JLE,
16240 [BPF_JGT >> 4] = BPF_JLT,
16241 [BPF_JLE >> 4] = BPF_JGE,
16242 [BPF_JLT >> 4] = BPF_JGT,
16243 [BPF_JSGE >> 4] = BPF_JSLE,
16244 [BPF_JSGT >> 4] = BPF_JSLT,
16245 [BPF_JSLE >> 4] = BPF_JSGE,
16246 [BPF_JSLT >> 4] = BPF_JSGT
16247 };
16248 return opcode_flip[opcode >> 4];
16249 }
16250
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)16251 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
16252 struct bpf_reg_state *src_reg,
16253 u8 opcode)
16254 {
16255 struct bpf_reg_state *pkt;
16256
16257 if (src_reg->type == PTR_TO_PACKET_END) {
16258 pkt = dst_reg;
16259 } else if (dst_reg->type == PTR_TO_PACKET_END) {
16260 pkt = src_reg;
16261 opcode = flip_opcode(opcode);
16262 } else {
16263 return -1;
16264 }
16265
16266 if (pkt->range >= 0)
16267 return -1;
16268
16269 switch (opcode) {
16270 case BPF_JLE:
16271 /* pkt <= pkt_end */
16272 fallthrough;
16273 case BPF_JGT:
16274 /* pkt > pkt_end */
16275 if (pkt->range == BEYOND_PKT_END)
16276 /* pkt has at last one extra byte beyond pkt_end */
16277 return opcode == BPF_JGT;
16278 break;
16279 case BPF_JLT:
16280 /* pkt < pkt_end */
16281 fallthrough;
16282 case BPF_JGE:
16283 /* pkt >= pkt_end */
16284 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
16285 return opcode == BPF_JGE;
16286 break;
16287 }
16288 return -1;
16289 }
16290
16291 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;"
16292 * and return:
16293 * 1 - branch will be taken and "goto target" will be executed
16294 * 0 - branch will not be taken and fall-through to next insn
16295 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value
16296 * range [0,10]
16297 */
is_branch_taken(struct bpf_reg_state * reg1,struct bpf_reg_state * reg2,u8 opcode,bool is_jmp32)16298 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16299 u8 opcode, bool is_jmp32)
16300 {
16301 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32)
16302 return is_pkt_ptr_branch_taken(reg1, reg2, opcode);
16303
16304 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) {
16305 u64 val;
16306
16307 /* arrange that reg2 is a scalar, and reg1 is a pointer */
16308 if (!is_reg_const(reg2, is_jmp32)) {
16309 opcode = flip_opcode(opcode);
16310 swap(reg1, reg2);
16311 }
16312 /* and ensure that reg2 is a constant */
16313 if (!is_reg_const(reg2, is_jmp32))
16314 return -1;
16315
16316 if (!reg_not_null(reg1))
16317 return -1;
16318
16319 /* If pointer is valid tests against zero will fail so we can
16320 * use this to direct branch taken.
16321 */
16322 val = reg_const_value(reg2, is_jmp32);
16323 if (val != 0)
16324 return -1;
16325
16326 switch (opcode) {
16327 case BPF_JEQ:
16328 return 0;
16329 case BPF_JNE:
16330 return 1;
16331 default:
16332 return -1;
16333 }
16334 }
16335
16336 /* now deal with two scalars, but not necessarily constants */
16337 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32);
16338 }
16339
16340 /* Opcode that corresponds to a *false* branch condition.
16341 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2
16342 */
rev_opcode(u8 opcode)16343 static u8 rev_opcode(u8 opcode)
16344 {
16345 switch (opcode) {
16346 case BPF_JEQ: return BPF_JNE;
16347 case BPF_JNE: return BPF_JEQ;
16348 /* JSET doesn't have it's reverse opcode in BPF, so add
16349 * BPF_X flag to denote the reverse of that operation
16350 */
16351 case BPF_JSET: return BPF_JSET | BPF_X;
16352 case BPF_JSET | BPF_X: return BPF_JSET;
16353 case BPF_JGE: return BPF_JLT;
16354 case BPF_JGT: return BPF_JLE;
16355 case BPF_JLE: return BPF_JGT;
16356 case BPF_JLT: return BPF_JGE;
16357 case BPF_JSGE: return BPF_JSLT;
16358 case BPF_JSGT: return BPF_JSLE;
16359 case BPF_JSLE: return BPF_JSGT;
16360 case BPF_JSLT: return BPF_JSGE;
16361 default: return 0;
16362 }
16363 }
16364
16365 /* 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)16366 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2,
16367 u8 opcode, bool is_jmp32)
16368 {
16369 struct tnum t;
16370 u64 val;
16371
16372 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */
16373 switch (opcode) {
16374 case BPF_JGE:
16375 case BPF_JGT:
16376 case BPF_JSGE:
16377 case BPF_JSGT:
16378 opcode = flip_opcode(opcode);
16379 swap(reg1, reg2);
16380 break;
16381 default:
16382 break;
16383 }
16384
16385 switch (opcode) {
16386 case BPF_JEQ:
16387 if (is_jmp32) {
16388 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16389 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16390 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16391 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16392 reg2->u32_min_value = reg1->u32_min_value;
16393 reg2->u32_max_value = reg1->u32_max_value;
16394 reg2->s32_min_value = reg1->s32_min_value;
16395 reg2->s32_max_value = reg1->s32_max_value;
16396
16397 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off));
16398 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16399 reg2->var_off = tnum_with_subreg(reg2->var_off, t);
16400 } else {
16401 reg1->umin_value = max(reg1->umin_value, reg2->umin_value);
16402 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16403 reg1->smin_value = max(reg1->smin_value, reg2->smin_value);
16404 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16405 reg2->umin_value = reg1->umin_value;
16406 reg2->umax_value = reg1->umax_value;
16407 reg2->smin_value = reg1->smin_value;
16408 reg2->smax_value = reg1->smax_value;
16409
16410 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off);
16411 reg2->var_off = reg1->var_off;
16412 }
16413 break;
16414 case BPF_JNE:
16415 if (!is_reg_const(reg2, is_jmp32))
16416 swap(reg1, reg2);
16417 if (!is_reg_const(reg2, is_jmp32))
16418 break;
16419
16420 /* try to recompute the bound of reg1 if reg2 is a const and
16421 * is exactly the edge of reg1.
16422 */
16423 val = reg_const_value(reg2, is_jmp32);
16424 if (is_jmp32) {
16425 /* u32_min_value is not equal to 0xffffffff at this point,
16426 * because otherwise u32_max_value is 0xffffffff as well,
16427 * in such a case both reg1 and reg2 would be constants,
16428 * jump would be predicted and reg_set_min_max() won't
16429 * be called.
16430 *
16431 * Same reasoning works for all {u,s}{min,max}{32,64} cases
16432 * below.
16433 */
16434 if (reg1->u32_min_value == (u32)val)
16435 reg1->u32_min_value++;
16436 if (reg1->u32_max_value == (u32)val)
16437 reg1->u32_max_value--;
16438 if (reg1->s32_min_value == (s32)val)
16439 reg1->s32_min_value++;
16440 if (reg1->s32_max_value == (s32)val)
16441 reg1->s32_max_value--;
16442 } else {
16443 if (reg1->umin_value == (u64)val)
16444 reg1->umin_value++;
16445 if (reg1->umax_value == (u64)val)
16446 reg1->umax_value--;
16447 if (reg1->smin_value == (s64)val)
16448 reg1->smin_value++;
16449 if (reg1->smax_value == (s64)val)
16450 reg1->smax_value--;
16451 }
16452 break;
16453 case BPF_JSET:
16454 if (!is_reg_const(reg2, is_jmp32))
16455 swap(reg1, reg2);
16456 if (!is_reg_const(reg2, is_jmp32))
16457 break;
16458 val = reg_const_value(reg2, is_jmp32);
16459 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X)
16460 * requires single bit to learn something useful. E.g., if we
16461 * know that `r1 & 0x3` is true, then which bits (0, 1, or both)
16462 * are actually set? We can learn something definite only if
16463 * it's a single-bit value to begin with.
16464 *
16465 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have
16466 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor
16467 * bit 1 is set, which we can readily use in adjustments.
16468 */
16469 if (!is_power_of_2(val))
16470 break;
16471 if (is_jmp32) {
16472 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val));
16473 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16474 } else {
16475 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val));
16476 }
16477 break;
16478 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */
16479 if (!is_reg_const(reg2, is_jmp32))
16480 swap(reg1, reg2);
16481 if (!is_reg_const(reg2, is_jmp32))
16482 break;
16483 val = reg_const_value(reg2, is_jmp32);
16484 /* Forget the ranges before narrowing tnums, to avoid invariant
16485 * violations if we're on a dead branch.
16486 */
16487 __mark_reg_unbounded(reg1);
16488 if (is_jmp32) {
16489 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val));
16490 reg1->var_off = tnum_with_subreg(reg1->var_off, t);
16491 } else {
16492 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val));
16493 }
16494 break;
16495 case BPF_JLE:
16496 if (is_jmp32) {
16497 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value);
16498 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value);
16499 } else {
16500 reg1->umax_value = min(reg1->umax_value, reg2->umax_value);
16501 reg2->umin_value = max(reg1->umin_value, reg2->umin_value);
16502 }
16503 break;
16504 case BPF_JLT:
16505 if (is_jmp32) {
16506 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1);
16507 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value);
16508 } else {
16509 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1);
16510 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value);
16511 }
16512 break;
16513 case BPF_JSLE:
16514 if (is_jmp32) {
16515 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value);
16516 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value);
16517 } else {
16518 reg1->smax_value = min(reg1->smax_value, reg2->smax_value);
16519 reg2->smin_value = max(reg1->smin_value, reg2->smin_value);
16520 }
16521 break;
16522 case BPF_JSLT:
16523 if (is_jmp32) {
16524 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1);
16525 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value);
16526 } else {
16527 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1);
16528 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value);
16529 }
16530 break;
16531 default:
16532 return;
16533 }
16534 }
16535
16536 /* Adjusts the register min/max values in the case that the dst_reg and
16537 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K
16538 * check, in which case we have a fake SCALAR_VALUE representing insn->imm).
16539 * Technically we can do similar adjustments for pointers to the same object,
16540 * but we don't support that right now.
16541 */
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)16542 static int reg_set_min_max(struct bpf_verifier_env *env,
16543 struct bpf_reg_state *true_reg1,
16544 struct bpf_reg_state *true_reg2,
16545 struct bpf_reg_state *false_reg1,
16546 struct bpf_reg_state *false_reg2,
16547 u8 opcode, bool is_jmp32)
16548 {
16549 int err;
16550
16551 /* If either register is a pointer, we can't learn anything about its
16552 * variable offset from the compare (unless they were a pointer into
16553 * the same object, but we don't bother with that).
16554 */
16555 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE)
16556 return 0;
16557
16558 /* We compute branch direction for same SCALAR_VALUE registers in
16559 * is_scalar_branch_taken(). For unknown branch directions (e.g., BPF_JSET)
16560 * on the same registers, we don't need to adjust the min/max values.
16561 */
16562 if (false_reg1 == false_reg2)
16563 return 0;
16564
16565 /* fallthrough (FALSE) branch */
16566 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32);
16567 reg_bounds_sync(false_reg1);
16568 reg_bounds_sync(false_reg2);
16569
16570 /* jump (TRUE) branch */
16571 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32);
16572 reg_bounds_sync(true_reg1);
16573 reg_bounds_sync(true_reg2);
16574
16575 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1");
16576 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2");
16577 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1");
16578 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2");
16579 return err;
16580 }
16581
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)16582 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
16583 struct bpf_reg_state *reg, u32 id,
16584 bool is_null)
16585 {
16586 if (type_may_be_null(reg->type) && reg->id == id &&
16587 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
16588 /* Old offset (both fixed and variable parts) should have been
16589 * known-zero, because we don't allow pointer arithmetic on
16590 * pointers that might be NULL. If we see this happening, don't
16591 * convert the register.
16592 *
16593 * But in some cases, some helpers that return local kptrs
16594 * advance offset for the returned pointer. In those cases, it
16595 * is fine to expect to see reg->off.
16596 */
16597 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
16598 return;
16599 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
16600 WARN_ON_ONCE(reg->off))
16601 return;
16602
16603 if (is_null) {
16604 reg->type = SCALAR_VALUE;
16605 /* We don't need id and ref_obj_id from this point
16606 * onwards anymore, thus we should better reset it,
16607 * so that state pruning has chances to take effect.
16608 */
16609 reg->id = 0;
16610 reg->ref_obj_id = 0;
16611
16612 return;
16613 }
16614
16615 mark_ptr_not_null_reg(reg);
16616
16617 if (!reg_may_point_to_spin_lock(reg)) {
16618 /* For not-NULL ptr, reg->ref_obj_id will be reset
16619 * in release_reference().
16620 *
16621 * reg->id is still used by spin_lock ptr. Other
16622 * than spin_lock ptr type, reg->id can be reset.
16623 */
16624 reg->id = 0;
16625 }
16626 }
16627 }
16628
16629 /* The logic is similar to find_good_pkt_pointers(), both could eventually
16630 * be folded together at some point.
16631 */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)16632 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
16633 bool is_null)
16634 {
16635 struct bpf_func_state *state = vstate->frame[vstate->curframe];
16636 struct bpf_reg_state *regs = state->regs, *reg;
16637 u32 ref_obj_id = regs[regno].ref_obj_id;
16638 u32 id = regs[regno].id;
16639
16640 if (ref_obj_id && ref_obj_id == id && is_null)
16641 /* regs[regno] is in the " == NULL" branch.
16642 * No one could have freed the reference state before
16643 * doing the NULL check.
16644 */
16645 WARN_ON_ONCE(release_reference_nomark(vstate, id));
16646
16647 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
16648 mark_ptr_or_null_reg(state, reg, id, is_null);
16649 }));
16650 }
16651
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)16652 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
16653 struct bpf_reg_state *dst_reg,
16654 struct bpf_reg_state *src_reg,
16655 struct bpf_verifier_state *this_branch,
16656 struct bpf_verifier_state *other_branch)
16657 {
16658 if (BPF_SRC(insn->code) != BPF_X)
16659 return false;
16660
16661 /* Pointers are always 64-bit. */
16662 if (BPF_CLASS(insn->code) == BPF_JMP32)
16663 return false;
16664
16665 switch (BPF_OP(insn->code)) {
16666 case BPF_JGT:
16667 if ((dst_reg->type == PTR_TO_PACKET &&
16668 src_reg->type == PTR_TO_PACKET_END) ||
16669 (dst_reg->type == PTR_TO_PACKET_META &&
16670 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16671 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
16672 find_good_pkt_pointers(this_branch, dst_reg,
16673 dst_reg->type, false);
16674 mark_pkt_end(other_branch, insn->dst_reg, true);
16675 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16676 src_reg->type == PTR_TO_PACKET) ||
16677 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16678 src_reg->type == PTR_TO_PACKET_META)) {
16679 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
16680 find_good_pkt_pointers(other_branch, src_reg,
16681 src_reg->type, true);
16682 mark_pkt_end(this_branch, insn->src_reg, false);
16683 } else {
16684 return false;
16685 }
16686 break;
16687 case BPF_JLT:
16688 if ((dst_reg->type == PTR_TO_PACKET &&
16689 src_reg->type == PTR_TO_PACKET_END) ||
16690 (dst_reg->type == PTR_TO_PACKET_META &&
16691 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16692 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
16693 find_good_pkt_pointers(other_branch, dst_reg,
16694 dst_reg->type, true);
16695 mark_pkt_end(this_branch, insn->dst_reg, false);
16696 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16697 src_reg->type == PTR_TO_PACKET) ||
16698 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16699 src_reg->type == PTR_TO_PACKET_META)) {
16700 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
16701 find_good_pkt_pointers(this_branch, src_reg,
16702 src_reg->type, false);
16703 mark_pkt_end(other_branch, insn->src_reg, true);
16704 } else {
16705 return false;
16706 }
16707 break;
16708 case BPF_JGE:
16709 if ((dst_reg->type == PTR_TO_PACKET &&
16710 src_reg->type == PTR_TO_PACKET_END) ||
16711 (dst_reg->type == PTR_TO_PACKET_META &&
16712 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16713 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
16714 find_good_pkt_pointers(this_branch, dst_reg,
16715 dst_reg->type, true);
16716 mark_pkt_end(other_branch, insn->dst_reg, false);
16717 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16718 src_reg->type == PTR_TO_PACKET) ||
16719 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16720 src_reg->type == PTR_TO_PACKET_META)) {
16721 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
16722 find_good_pkt_pointers(other_branch, src_reg,
16723 src_reg->type, false);
16724 mark_pkt_end(this_branch, insn->src_reg, true);
16725 } else {
16726 return false;
16727 }
16728 break;
16729 case BPF_JLE:
16730 if ((dst_reg->type == PTR_TO_PACKET &&
16731 src_reg->type == PTR_TO_PACKET_END) ||
16732 (dst_reg->type == PTR_TO_PACKET_META &&
16733 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
16734 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
16735 find_good_pkt_pointers(other_branch, dst_reg,
16736 dst_reg->type, false);
16737 mark_pkt_end(this_branch, insn->dst_reg, true);
16738 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
16739 src_reg->type == PTR_TO_PACKET) ||
16740 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
16741 src_reg->type == PTR_TO_PACKET_META)) {
16742 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
16743 find_good_pkt_pointers(this_branch, src_reg,
16744 src_reg->type, true);
16745 mark_pkt_end(other_branch, insn->src_reg, false);
16746 } else {
16747 return false;
16748 }
16749 break;
16750 default:
16751 return false;
16752 }
16753
16754 return true;
16755 }
16756
__collect_linked_regs(struct linked_regs * reg_set,struct bpf_reg_state * reg,u32 id,u32 frameno,u32 spi_or_reg,bool is_reg)16757 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg,
16758 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg)
16759 {
16760 struct linked_reg *e;
16761
16762 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id)
16763 return;
16764
16765 e = linked_regs_push(reg_set);
16766 if (e) {
16767 e->frameno = frameno;
16768 e->is_reg = is_reg;
16769 e->regno = spi_or_reg;
16770 } else {
16771 reg->id = 0;
16772 }
16773 }
16774
16775 /* For all R being scalar registers or spilled scalar registers
16776 * in verifier state, save R in linked_regs if R->id == id.
16777 * If there are too many Rs sharing same id, reset id for leftover Rs.
16778 */
collect_linked_regs(struct bpf_verifier_state * vstate,u32 id,struct linked_regs * linked_regs)16779 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id,
16780 struct linked_regs *linked_regs)
16781 {
16782 struct bpf_func_state *func;
16783 struct bpf_reg_state *reg;
16784 int i, j;
16785
16786 id = id & ~BPF_ADD_CONST;
16787 for (i = vstate->curframe; i >= 0; i--) {
16788 func = vstate->frame[i];
16789 for (j = 0; j < BPF_REG_FP; j++) {
16790 reg = &func->regs[j];
16791 __collect_linked_regs(linked_regs, reg, id, i, j, true);
16792 }
16793 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
16794 if (!is_spilled_reg(&func->stack[j]))
16795 continue;
16796 reg = &func->stack[j].spilled_ptr;
16797 __collect_linked_regs(linked_regs, reg, id, i, j, false);
16798 }
16799 }
16800 }
16801
16802 /* For all R in linked_regs, copy known_reg range into R
16803 * if R->id == known_reg->id.
16804 */
sync_linked_regs(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg,struct linked_regs * linked_regs)16805 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg,
16806 struct linked_regs *linked_regs)
16807 {
16808 struct bpf_reg_state fake_reg;
16809 struct bpf_reg_state *reg;
16810 struct linked_reg *e;
16811 int i;
16812
16813 for (i = 0; i < linked_regs->cnt; ++i) {
16814 e = &linked_regs->entries[i];
16815 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno]
16816 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr;
16817 if (reg->type != SCALAR_VALUE || reg == known_reg)
16818 continue;
16819 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST))
16820 continue;
16821 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) ||
16822 reg->off == known_reg->off) {
16823 s32 saved_subreg_def = reg->subreg_def;
16824
16825 copy_register_state(reg, known_reg);
16826 reg->subreg_def = saved_subreg_def;
16827 } else {
16828 s32 saved_subreg_def = reg->subreg_def;
16829 s32 saved_off = reg->off;
16830
16831 fake_reg.type = SCALAR_VALUE;
16832 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off);
16833
16834 /* reg = known_reg; reg += delta */
16835 copy_register_state(reg, known_reg);
16836 /*
16837 * Must preserve off, id and add_const flag,
16838 * otherwise another sync_linked_regs() will be incorrect.
16839 */
16840 reg->off = saved_off;
16841 reg->subreg_def = saved_subreg_def;
16842
16843 scalar32_min_max_add(reg, &fake_reg);
16844 scalar_min_max_add(reg, &fake_reg);
16845 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off);
16846 }
16847 }
16848 }
16849
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)16850 static int check_cond_jmp_op(struct bpf_verifier_env *env,
16851 struct bpf_insn *insn, int *insn_idx)
16852 {
16853 struct bpf_verifier_state *this_branch = env->cur_state;
16854 struct bpf_verifier_state *other_branch;
16855 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
16856 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
16857 struct bpf_reg_state *eq_branch_regs;
16858 struct linked_regs linked_regs = {};
16859 u8 opcode = BPF_OP(insn->code);
16860 int insn_flags = 0;
16861 bool is_jmp32;
16862 int pred = -1;
16863 int err;
16864
16865 /* Only conditional jumps are expected to reach here. */
16866 if (opcode == BPF_JA || opcode > BPF_JCOND) {
16867 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
16868 return -EINVAL;
16869 }
16870
16871 if (opcode == BPF_JCOND) {
16872 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
16873 int idx = *insn_idx;
16874
16875 if (insn->code != (BPF_JMP | BPF_JCOND) ||
16876 insn->src_reg != BPF_MAY_GOTO ||
16877 insn->dst_reg || insn->imm) {
16878 verbose(env, "invalid may_goto imm %d\n", insn->imm);
16879 return -EINVAL;
16880 }
16881 prev_st = find_prev_entry(env, cur_st->parent, idx);
16882
16883 /* branch out 'fallthrough' insn as a new state to explore */
16884 queued_st = push_stack(env, idx + 1, idx, false);
16885 if (IS_ERR(queued_st))
16886 return PTR_ERR(queued_st);
16887
16888 queued_st->may_goto_depth++;
16889 if (prev_st)
16890 widen_imprecise_scalars(env, prev_st, queued_st);
16891 *insn_idx += insn->off;
16892 return 0;
16893 }
16894
16895 /* check src2 operand */
16896 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16897 if (err)
16898 return err;
16899
16900 dst_reg = ®s[insn->dst_reg];
16901 if (BPF_SRC(insn->code) == BPF_X) {
16902 if (insn->imm != 0) {
16903 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16904 return -EINVAL;
16905 }
16906
16907 /* check src1 operand */
16908 err = check_reg_arg(env, insn->src_reg, SRC_OP);
16909 if (err)
16910 return err;
16911
16912 src_reg = ®s[insn->src_reg];
16913 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
16914 is_pointer_value(env, insn->src_reg)) {
16915 verbose(env, "R%d pointer comparison prohibited\n",
16916 insn->src_reg);
16917 return -EACCES;
16918 }
16919
16920 if (src_reg->type == PTR_TO_STACK)
16921 insn_flags |= INSN_F_SRC_REG_STACK;
16922 if (dst_reg->type == PTR_TO_STACK)
16923 insn_flags |= INSN_F_DST_REG_STACK;
16924 } else {
16925 if (insn->src_reg != BPF_REG_0) {
16926 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
16927 return -EINVAL;
16928 }
16929 src_reg = &env->fake_reg[0];
16930 memset(src_reg, 0, sizeof(*src_reg));
16931 src_reg->type = SCALAR_VALUE;
16932 __mark_reg_known(src_reg, insn->imm);
16933
16934 if (dst_reg->type == PTR_TO_STACK)
16935 insn_flags |= INSN_F_DST_REG_STACK;
16936 }
16937
16938 if (insn_flags) {
16939 err = push_jmp_history(env, this_branch, insn_flags, 0);
16940 if (err)
16941 return err;
16942 }
16943
16944 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
16945 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32);
16946 if (pred >= 0) {
16947 /* If we get here with a dst_reg pointer type it is because
16948 * above is_branch_taken() special cased the 0 comparison.
16949 */
16950 if (!__is_pointer_value(false, dst_reg))
16951 err = mark_chain_precision(env, insn->dst_reg);
16952 if (BPF_SRC(insn->code) == BPF_X && !err &&
16953 !__is_pointer_value(false, src_reg))
16954 err = mark_chain_precision(env, insn->src_reg);
16955 if (err)
16956 return err;
16957 }
16958
16959 if (pred == 1) {
16960 /* Only follow the goto, ignore fall-through. If needed, push
16961 * the fall-through branch for simulation under speculative
16962 * execution.
16963 */
16964 if (!env->bypass_spec_v1) {
16965 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx);
16966 if (err < 0)
16967 return err;
16968 }
16969 if (env->log.level & BPF_LOG_LEVEL)
16970 print_insn_state(env, this_branch, this_branch->curframe);
16971 *insn_idx += insn->off;
16972 return 0;
16973 } else if (pred == 0) {
16974 /* Only follow the fall-through branch, since that's where the
16975 * program will go. If needed, push the goto branch for
16976 * simulation under speculative execution.
16977 */
16978 if (!env->bypass_spec_v1) {
16979 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1,
16980 *insn_idx);
16981 if (err < 0)
16982 return err;
16983 }
16984 if (env->log.level & BPF_LOG_LEVEL)
16985 print_insn_state(env, this_branch, this_branch->curframe);
16986 return 0;
16987 }
16988
16989 /* Push scalar registers sharing same ID to jump history,
16990 * do this before creating 'other_branch', so that both
16991 * 'this_branch' and 'other_branch' share this history
16992 * if parent state is created.
16993 */
16994 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id)
16995 collect_linked_regs(this_branch, src_reg->id, &linked_regs);
16996 if (dst_reg->type == SCALAR_VALUE && dst_reg->id)
16997 collect_linked_regs(this_branch, dst_reg->id, &linked_regs);
16998 if (linked_regs.cnt > 1) {
16999 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs));
17000 if (err)
17001 return err;
17002 }
17003
17004 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
17005 if (IS_ERR(other_branch))
17006 return PTR_ERR(other_branch);
17007 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17008
17009 if (BPF_SRC(insn->code) == BPF_X) {
17010 err = reg_set_min_max(env,
17011 &other_branch_regs[insn->dst_reg],
17012 &other_branch_regs[insn->src_reg],
17013 dst_reg, src_reg, opcode, is_jmp32);
17014 } else /* BPF_SRC(insn->code) == BPF_K */ {
17015 /* reg_set_min_max() can mangle the fake_reg. Make a copy
17016 * so that these are two different memory locations. The
17017 * src_reg is not used beyond here in context of K.
17018 */
17019 memcpy(&env->fake_reg[1], &env->fake_reg[0],
17020 sizeof(env->fake_reg[0]));
17021 err = reg_set_min_max(env,
17022 &other_branch_regs[insn->dst_reg],
17023 &env->fake_reg[0],
17024 dst_reg, &env->fake_reg[1],
17025 opcode, is_jmp32);
17026 }
17027 if (err)
17028 return err;
17029
17030 if (BPF_SRC(insn->code) == BPF_X &&
17031 src_reg->type == SCALAR_VALUE && src_reg->id &&
17032 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
17033 sync_linked_regs(this_branch, src_reg, &linked_regs);
17034 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs);
17035 }
17036 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
17037 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
17038 sync_linked_regs(this_branch, dst_reg, &linked_regs);
17039 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs);
17040 }
17041
17042 /* if one pointer register is compared to another pointer
17043 * register check if PTR_MAYBE_NULL could be lifted.
17044 * E.g. register A - maybe null
17045 * register B - not null
17046 * for JNE A, B, ... - A is not null in the false branch;
17047 * for JEQ A, B, ... - A is not null in the true branch.
17048 *
17049 * Since PTR_TO_BTF_ID points to a kernel struct that does
17050 * not need to be null checked by the BPF program, i.e.,
17051 * could be null even without PTR_MAYBE_NULL marking, so
17052 * only propagate nullness when neither reg is that type.
17053 */
17054 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
17055 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
17056 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
17057 base_type(src_reg->type) != PTR_TO_BTF_ID &&
17058 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
17059 eq_branch_regs = NULL;
17060 switch (opcode) {
17061 case BPF_JEQ:
17062 eq_branch_regs = other_branch_regs;
17063 break;
17064 case BPF_JNE:
17065 eq_branch_regs = regs;
17066 break;
17067 default:
17068 /* do nothing */
17069 break;
17070 }
17071 if (eq_branch_regs) {
17072 if (type_may_be_null(src_reg->type))
17073 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
17074 else
17075 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
17076 }
17077 }
17078
17079 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
17080 * NOTE: these optimizations below are related with pointer comparison
17081 * which will never be JMP32.
17082 */
17083 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
17084 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
17085 type_may_be_null(dst_reg->type)) {
17086 /* Mark all identical registers in each branch as either
17087 * safe or unknown depending R == 0 or R != 0 conditional.
17088 */
17089 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
17090 opcode == BPF_JNE);
17091 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
17092 opcode == BPF_JEQ);
17093 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
17094 this_branch, other_branch) &&
17095 is_pointer_value(env, insn->dst_reg)) {
17096 verbose(env, "R%d pointer comparison prohibited\n",
17097 insn->dst_reg);
17098 return -EACCES;
17099 }
17100 if (env->log.level & BPF_LOG_LEVEL)
17101 print_insn_state(env, this_branch, this_branch->curframe);
17102 return 0;
17103 }
17104
17105 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)17106 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17107 {
17108 struct bpf_insn_aux_data *aux = cur_aux(env);
17109 struct bpf_reg_state *regs = cur_regs(env);
17110 struct bpf_reg_state *dst_reg;
17111 struct bpf_map *map;
17112 int err;
17113
17114 if (BPF_SIZE(insn->code) != BPF_DW) {
17115 verbose(env, "invalid BPF_LD_IMM insn\n");
17116 return -EINVAL;
17117 }
17118 if (insn->off != 0) {
17119 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17120 return -EINVAL;
17121 }
17122
17123 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17124 if (err)
17125 return err;
17126
17127 dst_reg = ®s[insn->dst_reg];
17128 if (insn->src_reg == 0) {
17129 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
17130
17131 dst_reg->type = SCALAR_VALUE;
17132 __mark_reg_known(®s[insn->dst_reg], imm);
17133 return 0;
17134 }
17135
17136 /* All special src_reg cases are listed below. From this point onwards
17137 * we either succeed and assign a corresponding dst_reg->type after
17138 * zeroing the offset, or fail and reject the program.
17139 */
17140 mark_reg_known_zero(env, regs, insn->dst_reg);
17141
17142 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
17143 dst_reg->type = aux->btf_var.reg_type;
17144 switch (base_type(dst_reg->type)) {
17145 case PTR_TO_MEM:
17146 dst_reg->mem_size = aux->btf_var.mem_size;
17147 break;
17148 case PTR_TO_BTF_ID:
17149 dst_reg->btf = aux->btf_var.btf;
17150 dst_reg->btf_id = aux->btf_var.btf_id;
17151 break;
17152 default:
17153 verifier_bug(env, "pseudo btf id: unexpected dst reg type");
17154 return -EFAULT;
17155 }
17156 return 0;
17157 }
17158
17159 if (insn->src_reg == BPF_PSEUDO_FUNC) {
17160 struct bpf_prog_aux *aux = env->prog->aux;
17161 u32 subprogno = find_subprog(env,
17162 env->insn_idx + insn->imm + 1);
17163
17164 if (!aux->func_info) {
17165 verbose(env, "missing btf func_info\n");
17166 return -EINVAL;
17167 }
17168 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
17169 verbose(env, "callback function not static\n");
17170 return -EINVAL;
17171 }
17172
17173 dst_reg->type = PTR_TO_FUNC;
17174 dst_reg->subprogno = subprogno;
17175 return 0;
17176 }
17177
17178 map = env->used_maps[aux->map_index];
17179 dst_reg->map_ptr = map;
17180
17181 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
17182 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
17183 if (map->map_type == BPF_MAP_TYPE_ARENA) {
17184 __mark_reg_unknown(env, dst_reg);
17185 return 0;
17186 }
17187 dst_reg->type = PTR_TO_MAP_VALUE;
17188 dst_reg->off = aux->map_off;
17189 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY &&
17190 map->max_entries != 1);
17191 /* We want reg->id to be same (0) as map_value is not distinct */
17192 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
17193 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
17194 dst_reg->type = CONST_PTR_TO_MAP;
17195 } else {
17196 verifier_bug(env, "unexpected src reg value for ldimm64");
17197 return -EFAULT;
17198 }
17199
17200 return 0;
17201 }
17202
may_access_skb(enum bpf_prog_type type)17203 static bool may_access_skb(enum bpf_prog_type type)
17204 {
17205 switch (type) {
17206 case BPF_PROG_TYPE_SOCKET_FILTER:
17207 case BPF_PROG_TYPE_SCHED_CLS:
17208 case BPF_PROG_TYPE_SCHED_ACT:
17209 return true;
17210 default:
17211 return false;
17212 }
17213 }
17214
17215 /* verify safety of LD_ABS|LD_IND instructions:
17216 * - they can only appear in the programs where ctx == skb
17217 * - since they are wrappers of function calls, they scratch R1-R5 registers,
17218 * preserve R6-R9, and store return value into R0
17219 *
17220 * Implicit input:
17221 * ctx == skb == R6 == CTX
17222 *
17223 * Explicit input:
17224 * SRC == any register
17225 * IMM == 32-bit immediate
17226 *
17227 * Output:
17228 * R0 - 8/16/32-bit skb data converted to cpu endianness
17229 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)17230 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
17231 {
17232 struct bpf_reg_state *regs = cur_regs(env);
17233 static const int ctx_reg = BPF_REG_6;
17234 u8 mode = BPF_MODE(insn->code);
17235 int i, err;
17236
17237 if (!may_access_skb(resolve_prog_type(env->prog))) {
17238 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
17239 return -EINVAL;
17240 }
17241
17242 if (!env->ops->gen_ld_abs) {
17243 verifier_bug(env, "gen_ld_abs is null");
17244 return -EFAULT;
17245 }
17246
17247 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
17248 BPF_SIZE(insn->code) == BPF_DW ||
17249 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
17250 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
17251 return -EINVAL;
17252 }
17253
17254 /* check whether implicit source operand (register R6) is readable */
17255 err = check_reg_arg(env, ctx_reg, SRC_OP);
17256 if (err)
17257 return err;
17258
17259 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
17260 * gen_ld_abs() may terminate the program at runtime, leading to
17261 * reference leak.
17262 */
17263 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
17264 if (err)
17265 return err;
17266
17267 if (regs[ctx_reg].type != PTR_TO_CTX) {
17268 verbose(env,
17269 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
17270 return -EINVAL;
17271 }
17272
17273 if (mode == BPF_IND) {
17274 /* check explicit source operand */
17275 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17276 if (err)
17277 return err;
17278 }
17279
17280 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
17281 if (err < 0)
17282 return err;
17283
17284 /* reset caller saved regs to unreadable */
17285 for (i = 0; i < CALLER_SAVED_REGS; i++) {
17286 mark_reg_not_init(env, regs, caller_saved[i]);
17287 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
17288 }
17289
17290 /* mark destination R0 register as readable, since it contains
17291 * the value fetched from the packet.
17292 * Already marked as written above.
17293 */
17294 mark_reg_unknown(env, regs, BPF_REG_0);
17295 /* ld_abs load up to 32-bit skb data. */
17296 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
17297 return 0;
17298 }
17299
check_return_code(struct bpf_verifier_env * env,int regno,const char * reg_name)17300 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name)
17301 {
17302 const char *exit_ctx = "At program exit";
17303 struct tnum enforce_attach_type_range = tnum_unknown;
17304 const struct bpf_prog *prog = env->prog;
17305 struct bpf_reg_state *reg = reg_state(env, regno);
17306 struct bpf_retval_range range = retval_range(0, 1);
17307 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
17308 int err;
17309 struct bpf_func_state *frame = env->cur_state->frame[0];
17310 const bool is_subprog = frame->subprogno;
17311 bool return_32bit = false;
17312 const struct btf_type *reg_type, *ret_type = NULL;
17313
17314 /* LSM and struct_ops func-ptr's return type could be "void" */
17315 if (!is_subprog || frame->in_exception_callback_fn) {
17316 switch (prog_type) {
17317 case BPF_PROG_TYPE_LSM:
17318 if (prog->expected_attach_type == BPF_LSM_CGROUP)
17319 /* See below, can be 0 or 0-1 depending on hook. */
17320 break;
17321 if (!prog->aux->attach_func_proto->type)
17322 return 0;
17323 break;
17324 case BPF_PROG_TYPE_STRUCT_OPS:
17325 if (!prog->aux->attach_func_proto->type)
17326 return 0;
17327
17328 if (frame->in_exception_callback_fn)
17329 break;
17330
17331 /* Allow a struct_ops program to return a referenced kptr if it
17332 * matches the operator's return type and is in its unmodified
17333 * form. A scalar zero (i.e., a null pointer) is also allowed.
17334 */
17335 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL;
17336 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf,
17337 prog->aux->attach_func_proto->type,
17338 NULL);
17339 if (ret_type && ret_type == reg_type && reg->ref_obj_id)
17340 return __check_ptr_off_reg(env, reg, regno, false);
17341 break;
17342 default:
17343 break;
17344 }
17345 }
17346
17347 /* eBPF calling convention is such that R0 is used
17348 * to return the value from eBPF program.
17349 * Make sure that it's readable at this time
17350 * of bpf_exit, which means that program wrote
17351 * something into it earlier
17352 */
17353 err = check_reg_arg(env, regno, SRC_OP);
17354 if (err)
17355 return err;
17356
17357 if (is_pointer_value(env, regno)) {
17358 verbose(env, "R%d leaks addr as return value\n", regno);
17359 return -EACCES;
17360 }
17361
17362 if (frame->in_async_callback_fn) {
17363 exit_ctx = "At async callback return";
17364 range = frame->callback_ret_range;
17365 goto enforce_retval;
17366 }
17367
17368 if (is_subprog && !frame->in_exception_callback_fn) {
17369 if (reg->type != SCALAR_VALUE) {
17370 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
17371 regno, reg_type_str(env, reg->type));
17372 return -EINVAL;
17373 }
17374 return 0;
17375 }
17376
17377 switch (prog_type) {
17378 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
17379 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
17380 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
17381 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
17382 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
17383 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
17384 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
17385 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
17386 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
17387 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
17388 range = retval_range(1, 1);
17389 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
17390 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
17391 range = retval_range(0, 3);
17392 break;
17393 case BPF_PROG_TYPE_CGROUP_SKB:
17394 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
17395 range = retval_range(0, 3);
17396 enforce_attach_type_range = tnum_range(2, 3);
17397 }
17398 break;
17399 case BPF_PROG_TYPE_CGROUP_SOCK:
17400 case BPF_PROG_TYPE_SOCK_OPS:
17401 case BPF_PROG_TYPE_CGROUP_DEVICE:
17402 case BPF_PROG_TYPE_CGROUP_SYSCTL:
17403 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
17404 break;
17405 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17406 if (!env->prog->aux->attach_btf_id)
17407 return 0;
17408 range = retval_range(0, 0);
17409 break;
17410 case BPF_PROG_TYPE_TRACING:
17411 switch (env->prog->expected_attach_type) {
17412 case BPF_TRACE_FENTRY:
17413 case BPF_TRACE_FEXIT:
17414 range = retval_range(0, 0);
17415 break;
17416 case BPF_TRACE_RAW_TP:
17417 case BPF_MODIFY_RETURN:
17418 return 0;
17419 case BPF_TRACE_ITER:
17420 break;
17421 default:
17422 return -ENOTSUPP;
17423 }
17424 break;
17425 case BPF_PROG_TYPE_KPROBE:
17426 switch (env->prog->expected_attach_type) {
17427 case BPF_TRACE_KPROBE_SESSION:
17428 case BPF_TRACE_UPROBE_SESSION:
17429 range = retval_range(0, 1);
17430 break;
17431 default:
17432 return 0;
17433 }
17434 break;
17435 case BPF_PROG_TYPE_SK_LOOKUP:
17436 range = retval_range(SK_DROP, SK_PASS);
17437 break;
17438
17439 case BPF_PROG_TYPE_LSM:
17440 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
17441 /* no range found, any return value is allowed */
17442 if (!get_func_retval_range(env->prog, &range))
17443 return 0;
17444 /* no restricted range, any return value is allowed */
17445 if (range.minval == S32_MIN && range.maxval == S32_MAX)
17446 return 0;
17447 return_32bit = true;
17448 } else if (!env->prog->aux->attach_func_proto->type) {
17449 /* Make sure programs that attach to void
17450 * hooks don't try to modify return value.
17451 */
17452 range = retval_range(1, 1);
17453 }
17454 break;
17455
17456 case BPF_PROG_TYPE_NETFILTER:
17457 range = retval_range(NF_DROP, NF_ACCEPT);
17458 break;
17459 case BPF_PROG_TYPE_STRUCT_OPS:
17460 if (!ret_type)
17461 return 0;
17462 range = retval_range(0, 0);
17463 break;
17464 case BPF_PROG_TYPE_EXT:
17465 /* freplace program can return anything as its return value
17466 * depends on the to-be-replaced kernel func or bpf program.
17467 */
17468 default:
17469 return 0;
17470 }
17471
17472 enforce_retval:
17473 if (reg->type != SCALAR_VALUE) {
17474 verbose(env, "%s the register R%d is not a known value (%s)\n",
17475 exit_ctx, regno, reg_type_str(env, reg->type));
17476 return -EINVAL;
17477 }
17478
17479 err = mark_chain_precision(env, regno);
17480 if (err)
17481 return err;
17482
17483 if (!retval_range_within(range, reg, return_32bit)) {
17484 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name);
17485 if (!is_subprog &&
17486 prog->expected_attach_type == BPF_LSM_CGROUP &&
17487 prog_type == BPF_PROG_TYPE_LSM &&
17488 !prog->aux->attach_func_proto->type)
17489 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
17490 return -EINVAL;
17491 }
17492
17493 if (!tnum_is_unknown(enforce_attach_type_range) &&
17494 tnum_in(enforce_attach_type_range, reg->var_off))
17495 env->prog->enforce_expected_attach_type = 1;
17496 return 0;
17497 }
17498
mark_subprog_changes_pkt_data(struct bpf_verifier_env * env,int off)17499 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off)
17500 {
17501 struct bpf_subprog_info *subprog;
17502
17503 subprog = bpf_find_containing_subprog(env, off);
17504 subprog->changes_pkt_data = true;
17505 }
17506
mark_subprog_might_sleep(struct bpf_verifier_env * env,int off)17507 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off)
17508 {
17509 struct bpf_subprog_info *subprog;
17510
17511 subprog = bpf_find_containing_subprog(env, off);
17512 subprog->might_sleep = true;
17513 }
17514
17515 /* 't' is an index of a call-site.
17516 * 'w' is a callee entry point.
17517 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED.
17518 * Rely on DFS traversal order and absence of recursive calls to guarantee that
17519 * callee's change_pkt_data marks would be correct at that moment.
17520 */
merge_callee_effects(struct bpf_verifier_env * env,int t,int w)17521 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w)
17522 {
17523 struct bpf_subprog_info *caller, *callee;
17524
17525 caller = bpf_find_containing_subprog(env, t);
17526 callee = bpf_find_containing_subprog(env, w);
17527 caller->changes_pkt_data |= callee->changes_pkt_data;
17528 caller->might_sleep |= callee->might_sleep;
17529 }
17530
17531 /* non-recursive DFS pseudo code
17532 * 1 procedure DFS-iterative(G,v):
17533 * 2 label v as discovered
17534 * 3 let S be a stack
17535 * 4 S.push(v)
17536 * 5 while S is not empty
17537 * 6 t <- S.peek()
17538 * 7 if t is what we're looking for:
17539 * 8 return t
17540 * 9 for all edges e in G.adjacentEdges(t) do
17541 * 10 if edge e is already labelled
17542 * 11 continue with the next edge
17543 * 12 w <- G.adjacentVertex(t,e)
17544 * 13 if vertex w is not discovered and not explored
17545 * 14 label e as tree-edge
17546 * 15 label w as discovered
17547 * 16 S.push(w)
17548 * 17 continue at 5
17549 * 18 else if vertex w is discovered
17550 * 19 label e as back-edge
17551 * 20 else
17552 * 21 // vertex w is explored
17553 * 22 label e as forward- or cross-edge
17554 * 23 label t as explored
17555 * 24 S.pop()
17556 *
17557 * convention:
17558 * 0x10 - discovered
17559 * 0x11 - discovered and fall-through edge labelled
17560 * 0x12 - discovered and fall-through and branch edges labelled
17561 * 0x20 - explored
17562 */
17563
17564 enum {
17565 DISCOVERED = 0x10,
17566 EXPLORED = 0x20,
17567 FALLTHROUGH = 1,
17568 BRANCH = 2,
17569 };
17570
mark_prune_point(struct bpf_verifier_env * env,int idx)17571 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
17572 {
17573 env->insn_aux_data[idx].prune_point = true;
17574 }
17575
is_prune_point(struct bpf_verifier_env * env,int insn_idx)17576 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
17577 {
17578 return env->insn_aux_data[insn_idx].prune_point;
17579 }
17580
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)17581 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
17582 {
17583 env->insn_aux_data[idx].force_checkpoint = true;
17584 }
17585
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)17586 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
17587 {
17588 return env->insn_aux_data[insn_idx].force_checkpoint;
17589 }
17590
mark_calls_callback(struct bpf_verifier_env * env,int idx)17591 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
17592 {
17593 env->insn_aux_data[idx].calls_callback = true;
17594 }
17595
bpf_calls_callback(struct bpf_verifier_env * env,int insn_idx)17596 bool bpf_calls_callback(struct bpf_verifier_env *env, int insn_idx)
17597 {
17598 return env->insn_aux_data[insn_idx].calls_callback;
17599 }
17600
17601 enum {
17602 DONE_EXPLORING = 0,
17603 KEEP_EXPLORING = 1,
17604 };
17605
17606 /* t, w, e - match pseudo-code above:
17607 * t - index of current instruction
17608 * w - next instruction
17609 * e - edge
17610 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)17611 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
17612 {
17613 int *insn_stack = env->cfg.insn_stack;
17614 int *insn_state = env->cfg.insn_state;
17615
17616 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
17617 return DONE_EXPLORING;
17618
17619 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
17620 return DONE_EXPLORING;
17621
17622 if (w < 0 || w >= env->prog->len) {
17623 verbose_linfo(env, t, "%d: ", t);
17624 verbose(env, "jump out of range from insn %d to %d\n", t, w);
17625 return -EINVAL;
17626 }
17627
17628 if (e == BRANCH) {
17629 /* mark branch target for state pruning */
17630 mark_prune_point(env, w);
17631 mark_jmp_point(env, w);
17632 }
17633
17634 if (insn_state[w] == 0) {
17635 /* tree-edge */
17636 insn_state[t] = DISCOVERED | e;
17637 insn_state[w] = DISCOVERED;
17638 if (env->cfg.cur_stack >= env->prog->len)
17639 return -E2BIG;
17640 insn_stack[env->cfg.cur_stack++] = w;
17641 return KEEP_EXPLORING;
17642 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
17643 if (env->bpf_capable)
17644 return DONE_EXPLORING;
17645 verbose_linfo(env, t, "%d: ", t);
17646 verbose_linfo(env, w, "%d: ", w);
17647 verbose(env, "back-edge from insn %d to %d\n", t, w);
17648 return -EINVAL;
17649 } else if (insn_state[w] == EXPLORED) {
17650 /* forward- or cross-edge */
17651 insn_state[t] = DISCOVERED | e;
17652 } else {
17653 verifier_bug(env, "insn state internal bug");
17654 return -EFAULT;
17655 }
17656 return DONE_EXPLORING;
17657 }
17658
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)17659 static int visit_func_call_insn(int t, struct bpf_insn *insns,
17660 struct bpf_verifier_env *env,
17661 bool visit_callee)
17662 {
17663 int ret, insn_sz;
17664 int w;
17665
17666 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
17667 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
17668 if (ret)
17669 return ret;
17670
17671 mark_prune_point(env, t + insn_sz);
17672 /* when we exit from subprog, we need to record non-linear history */
17673 mark_jmp_point(env, t + insn_sz);
17674
17675 if (visit_callee) {
17676 w = t + insns[t].imm + 1;
17677 mark_prune_point(env, t);
17678 merge_callee_effects(env, t, w);
17679 ret = push_insn(t, w, BRANCH, env);
17680 }
17681 return ret;
17682 }
17683
17684 /* Bitmask with 1s for all caller saved registers */
17685 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
17686
17687 /* True if do_misc_fixups() replaces calls to helper number 'imm',
17688 * replacement patch is presumed to follow bpf_fastcall contract
17689 * (see mark_fastcall_pattern_for_call() below).
17690 */
verifier_inlines_helper_call(struct bpf_verifier_env * env,s32 imm)17691 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm)
17692 {
17693 switch (imm) {
17694 #ifdef CONFIG_X86_64
17695 case BPF_FUNC_get_smp_processor_id:
17696 return env->prog->jit_requested && bpf_jit_supports_percpu_insn();
17697 #endif
17698 default:
17699 return false;
17700 }
17701 }
17702
17703 struct call_summary {
17704 u8 num_params;
17705 bool is_void;
17706 bool fastcall;
17707 };
17708
17709 /* If @call is a kfunc or helper call, fills @cs and returns true,
17710 * otherwise returns false.
17711 */
get_call_summary(struct bpf_verifier_env * env,struct bpf_insn * call,struct call_summary * cs)17712 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
17713 struct call_summary *cs)
17714 {
17715 struct bpf_kfunc_call_arg_meta meta;
17716 const struct bpf_func_proto *fn;
17717 int i;
17718
17719 if (bpf_helper_call(call)) {
17720
17721 if (get_helper_proto(env, call->imm, &fn) < 0)
17722 /* error would be reported later */
17723 return false;
17724 cs->fastcall = fn->allow_fastcall &&
17725 (verifier_inlines_helper_call(env, call->imm) ||
17726 bpf_jit_inlines_helper_call(call->imm));
17727 cs->is_void = fn->ret_type == RET_VOID;
17728 cs->num_params = 0;
17729 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) {
17730 if (fn->arg_type[i] == ARG_DONTCARE)
17731 break;
17732 cs->num_params++;
17733 }
17734 return true;
17735 }
17736
17737 if (bpf_pseudo_kfunc_call(call)) {
17738 int err;
17739
17740 err = fetch_kfunc_meta(env, call, &meta, NULL);
17741 if (err < 0)
17742 /* error would be reported later */
17743 return false;
17744 cs->num_params = btf_type_vlen(meta.func_proto);
17745 cs->fastcall = meta.kfunc_flags & KF_FASTCALL;
17746 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type));
17747 return true;
17748 }
17749
17750 return false;
17751 }
17752
17753 /* LLVM define a bpf_fastcall function attribute.
17754 * This attribute means that function scratches only some of
17755 * the caller saved registers defined by ABI.
17756 * For BPF the set of such registers could be defined as follows:
17757 * - R0 is scratched only if function is non-void;
17758 * - R1-R5 are scratched only if corresponding parameter type is defined
17759 * in the function prototype.
17760 *
17761 * The contract between kernel and clang allows to simultaneously use
17762 * such functions and maintain backwards compatibility with old
17763 * kernels that don't understand bpf_fastcall calls:
17764 *
17765 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5
17766 * registers are not scratched by the call;
17767 *
17768 * - as a post-processing step, clang visits each bpf_fastcall call and adds
17769 * spill/fill for every live r0-r5;
17770 *
17771 * - stack offsets used for the spill/fill are allocated as lowest
17772 * stack offsets in whole function and are not used for any other
17773 * purposes;
17774 *
17775 * - when kernel loads a program, it looks for such patterns
17776 * (bpf_fastcall function surrounded by spills/fills) and checks if
17777 * spill/fill stack offsets are used exclusively in fastcall patterns;
17778 *
17779 * - if so, and if verifier or current JIT inlines the call to the
17780 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary
17781 * spill/fill pairs;
17782 *
17783 * - when old kernel loads a program, presence of spill/fill pairs
17784 * keeps BPF program valid, albeit slightly less efficient.
17785 *
17786 * For example:
17787 *
17788 * r1 = 1;
17789 * r2 = 2;
17790 * *(u64 *)(r10 - 8) = r1; r1 = 1;
17791 * *(u64 *)(r10 - 16) = r2; r2 = 2;
17792 * call %[to_be_inlined] --> call %[to_be_inlined]
17793 * r2 = *(u64 *)(r10 - 16); r0 = r1;
17794 * r1 = *(u64 *)(r10 - 8); r0 += r2;
17795 * r0 = r1; exit;
17796 * r0 += r2;
17797 * exit;
17798 *
17799 * The purpose of mark_fastcall_pattern_for_call is to:
17800 * - look for such patterns;
17801 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern;
17802 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction;
17803 * - update env->subprog_info[*]->fastcall_stack_off to find an offset
17804 * at which bpf_fastcall spill/fill stack slots start;
17805 * - update env->subprog_info[*]->keep_fastcall_stack.
17806 *
17807 * The .fastcall_pattern and .fastcall_stack_off are used by
17808 * check_fastcall_stack_contract() to check if every stack access to
17809 * fastcall spill/fill stack slot originates from spill/fill
17810 * instructions, members of fastcall patterns.
17811 *
17812 * If such condition holds true for a subprogram, fastcall patterns could
17813 * be rewritten by remove_fastcall_spills_fills().
17814 * Otherwise bpf_fastcall patterns are not changed in the subprogram
17815 * (code, presumably, generated by an older clang version).
17816 *
17817 * For example, it is *not* safe to remove spill/fill below:
17818 *
17819 * r1 = 1;
17820 * *(u64 *)(r10 - 8) = r1; r1 = 1;
17821 * call %[to_be_inlined] --> call %[to_be_inlined]
17822 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!!
17823 * r0 = *(u64 *)(r10 - 8); r0 += r1;
17824 * r0 += r1; exit;
17825 * exit;
17826 */
mark_fastcall_pattern_for_call(struct bpf_verifier_env * env,struct bpf_subprog_info * subprog,int insn_idx,s16 lowest_off)17827 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env,
17828 struct bpf_subprog_info *subprog,
17829 int insn_idx, s16 lowest_off)
17830 {
17831 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx;
17832 struct bpf_insn *call = &env->prog->insnsi[insn_idx];
17833 u32 clobbered_regs_mask;
17834 struct call_summary cs;
17835 u32 expected_regs_mask;
17836 s16 off;
17837 int i;
17838
17839 if (!get_call_summary(env, call, &cs))
17840 return;
17841
17842 /* A bitmask specifying which caller saved registers are clobbered
17843 * by a call to a helper/kfunc *as if* this helper/kfunc follows
17844 * bpf_fastcall contract:
17845 * - includes R0 if function is non-void;
17846 * - includes R1-R5 if corresponding parameter has is described
17847 * in the function prototype.
17848 */
17849 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0);
17850 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */
17851 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS;
17852
17853 /* match pairs of form:
17854 *
17855 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0)
17856 * ...
17857 * call %[to_be_inlined]
17858 * ...
17859 * rX = *(u64 *)(r10 - Y)
17860 */
17861 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) {
17862 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len)
17863 break;
17864 stx = &insns[insn_idx - i];
17865 ldx = &insns[insn_idx + i];
17866 /* must be a stack spill/fill pair */
17867 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17868 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) ||
17869 stx->dst_reg != BPF_REG_10 ||
17870 ldx->src_reg != BPF_REG_10)
17871 break;
17872 /* must be a spill/fill for the same reg */
17873 if (stx->src_reg != ldx->dst_reg)
17874 break;
17875 /* must be one of the previously unseen registers */
17876 if ((BIT(stx->src_reg) & expected_regs_mask) == 0)
17877 break;
17878 /* must be a spill/fill for the same expected offset,
17879 * no need to check offset alignment, BPF_DW stack access
17880 * is always 8-byte aligned.
17881 */
17882 if (stx->off != off || ldx->off != off)
17883 break;
17884 expected_regs_mask &= ~BIT(stx->src_reg);
17885 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1;
17886 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1;
17887 }
17888 if (i == 1)
17889 return;
17890
17891 /* Conditionally set 'fastcall_spills_num' to allow forward
17892 * compatibility when more helper functions are marked as
17893 * bpf_fastcall at compile time than current kernel supports, e.g:
17894 *
17895 * 1: *(u64 *)(r10 - 8) = r1
17896 * 2: call A ;; assume A is bpf_fastcall for current kernel
17897 * 3: r1 = *(u64 *)(r10 - 8)
17898 * 4: *(u64 *)(r10 - 8) = r1
17899 * 5: call B ;; assume B is not bpf_fastcall for current kernel
17900 * 6: r1 = *(u64 *)(r10 - 8)
17901 *
17902 * There is no need to block bpf_fastcall rewrite for such program.
17903 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy,
17904 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills()
17905 * does not remove spill/fill pair {4,6}.
17906 */
17907 if (cs.fastcall)
17908 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1;
17909 else
17910 subprog->keep_fastcall_stack = 1;
17911 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off);
17912 }
17913
mark_fastcall_patterns(struct bpf_verifier_env * env)17914 static int mark_fastcall_patterns(struct bpf_verifier_env *env)
17915 {
17916 struct bpf_subprog_info *subprog = env->subprog_info;
17917 struct bpf_insn *insn;
17918 s16 lowest_off;
17919 int s, i;
17920
17921 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) {
17922 /* find lowest stack spill offset used in this subprog */
17923 lowest_off = 0;
17924 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17925 insn = env->prog->insnsi + i;
17926 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) ||
17927 insn->dst_reg != BPF_REG_10)
17928 continue;
17929 lowest_off = min(lowest_off, insn->off);
17930 }
17931 /* use this offset to find fastcall patterns */
17932 for (i = subprog->start; i < (subprog + 1)->start; ++i) {
17933 insn = env->prog->insnsi + i;
17934 if (insn->code != (BPF_JMP | BPF_CALL))
17935 continue;
17936 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off);
17937 }
17938 }
17939 return 0;
17940 }
17941
iarray_realloc(struct bpf_iarray * old,size_t n_elem)17942 static struct bpf_iarray *iarray_realloc(struct bpf_iarray *old, size_t n_elem)
17943 {
17944 size_t new_size = sizeof(struct bpf_iarray) + n_elem * sizeof(old->items[0]);
17945 struct bpf_iarray *new;
17946
17947 new = kvrealloc(old, new_size, GFP_KERNEL_ACCOUNT);
17948 if (!new) {
17949 /* this is what callers always want, so simplify the call site */
17950 kvfree(old);
17951 return NULL;
17952 }
17953
17954 new->cnt = n_elem;
17955 return new;
17956 }
17957
copy_insn_array(struct bpf_map * map,u32 start,u32 end,u32 * items)17958 static int copy_insn_array(struct bpf_map *map, u32 start, u32 end, u32 *items)
17959 {
17960 struct bpf_insn_array_value *value;
17961 u32 i;
17962
17963 for (i = start; i <= end; i++) {
17964 value = map->ops->map_lookup_elem(map, &i);
17965 /*
17966 * map_lookup_elem of an array map will never return an error,
17967 * but not checking it makes some static analysers to worry
17968 */
17969 if (IS_ERR(value))
17970 return PTR_ERR(value);
17971 else if (!value)
17972 return -EINVAL;
17973 items[i - start] = value->xlated_off;
17974 }
17975 return 0;
17976 }
17977
cmp_ptr_to_u32(const void * a,const void * b)17978 static int cmp_ptr_to_u32(const void *a, const void *b)
17979 {
17980 return *(u32 *)a - *(u32 *)b;
17981 }
17982
sort_insn_array_uniq(u32 * items,int cnt)17983 static int sort_insn_array_uniq(u32 *items, int cnt)
17984 {
17985 int unique = 1;
17986 int i;
17987
17988 sort(items, cnt, sizeof(items[0]), cmp_ptr_to_u32, NULL);
17989
17990 for (i = 1; i < cnt; i++)
17991 if (items[i] != items[unique - 1])
17992 items[unique++] = items[i];
17993
17994 return unique;
17995 }
17996
17997 /*
17998 * sort_unique({map[start], ..., map[end]}) into off
17999 */
copy_insn_array_uniq(struct bpf_map * map,u32 start,u32 end,u32 * off)18000 static int copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off)
18001 {
18002 u32 n = end - start + 1;
18003 int err;
18004
18005 err = copy_insn_array(map, start, end, off);
18006 if (err)
18007 return err;
18008
18009 return sort_insn_array_uniq(off, n);
18010 }
18011
18012 /*
18013 * Copy all unique offsets from the map
18014 */
jt_from_map(struct bpf_map * map)18015 static struct bpf_iarray *jt_from_map(struct bpf_map *map)
18016 {
18017 struct bpf_iarray *jt;
18018 int err;
18019 int n;
18020
18021 jt = iarray_realloc(NULL, map->max_entries);
18022 if (!jt)
18023 return ERR_PTR(-ENOMEM);
18024
18025 n = copy_insn_array_uniq(map, 0, map->max_entries - 1, jt->items);
18026 if (n < 0) {
18027 err = n;
18028 goto err_free;
18029 }
18030 if (n == 0) {
18031 err = -EINVAL;
18032 goto err_free;
18033 }
18034 jt->cnt = n;
18035 return jt;
18036
18037 err_free:
18038 kvfree(jt);
18039 return ERR_PTR(err);
18040 }
18041
18042 /*
18043 * Find and collect all maps which fit in the subprog. Return the result as one
18044 * combined jump table in jt->items (allocated with kvcalloc)
18045 */
jt_from_subprog(struct bpf_verifier_env * env,int subprog_start,int subprog_end)18046 static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
18047 int subprog_start, int subprog_end)
18048 {
18049 struct bpf_iarray *jt = NULL;
18050 struct bpf_map *map;
18051 struct bpf_iarray *jt_cur;
18052 int i;
18053
18054 for (i = 0; i < env->insn_array_map_cnt; i++) {
18055 /*
18056 * TODO (when needed): collect only jump tables, not static keys
18057 * or maps for indirect calls
18058 */
18059 map = env->insn_array_maps[i];
18060
18061 jt_cur = jt_from_map(map);
18062 if (IS_ERR(jt_cur)) {
18063 kvfree(jt);
18064 return jt_cur;
18065 }
18066
18067 /*
18068 * This is enough to check one element. The full table is
18069 * checked to fit inside the subprog later in create_jt()
18070 */
18071 if (jt_cur->items[0] >= subprog_start && jt_cur->items[0] < subprog_end) {
18072 u32 old_cnt = jt ? jt->cnt : 0;
18073 jt = iarray_realloc(jt, old_cnt + jt_cur->cnt);
18074 if (!jt) {
18075 kvfree(jt_cur);
18076 return ERR_PTR(-ENOMEM);
18077 }
18078 memcpy(jt->items + old_cnt, jt_cur->items, jt_cur->cnt << 2);
18079 }
18080
18081 kvfree(jt_cur);
18082 }
18083
18084 if (!jt) {
18085 verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
18086 return ERR_PTR(-EINVAL);
18087 }
18088
18089 jt->cnt = sort_insn_array_uniq(jt->items, jt->cnt);
18090 return jt;
18091 }
18092
18093 static struct bpf_iarray *
create_jt(int t,struct bpf_verifier_env * env)18094 create_jt(int t, struct bpf_verifier_env *env)
18095 {
18096 static struct bpf_subprog_info *subprog;
18097 int subprog_start, subprog_end;
18098 struct bpf_iarray *jt;
18099 int i;
18100
18101 subprog = bpf_find_containing_subprog(env, t);
18102 subprog_start = subprog->start;
18103 subprog_end = (subprog + 1)->start;
18104 jt = jt_from_subprog(env, subprog_start, subprog_end);
18105 if (IS_ERR(jt))
18106 return jt;
18107
18108 /* Check that the every element of the jump table fits within the given subprogram */
18109 for (i = 0; i < jt->cnt; i++) {
18110 if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
18111 verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
18112 t, subprog_start, subprog_end);
18113 kvfree(jt);
18114 return ERR_PTR(-EINVAL);
18115 }
18116 }
18117
18118 return jt;
18119 }
18120
18121 /* "conditional jump with N edges" */
visit_gotox_insn(int t,struct bpf_verifier_env * env)18122 static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
18123 {
18124 int *insn_stack = env->cfg.insn_stack;
18125 int *insn_state = env->cfg.insn_state;
18126 bool keep_exploring = false;
18127 struct bpf_iarray *jt;
18128 int i, w;
18129
18130 jt = env->insn_aux_data[t].jt;
18131 if (!jt) {
18132 jt = create_jt(t, env);
18133 if (IS_ERR(jt))
18134 return PTR_ERR(jt);
18135
18136 env->insn_aux_data[t].jt = jt;
18137 }
18138
18139 mark_prune_point(env, t);
18140 for (i = 0; i < jt->cnt; i++) {
18141 w = jt->items[i];
18142 if (w < 0 || w >= env->prog->len) {
18143 verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
18144 return -EINVAL;
18145 }
18146
18147 mark_jmp_point(env, w);
18148
18149 /* EXPLORED || DISCOVERED */
18150 if (insn_state[w])
18151 continue;
18152
18153 if (env->cfg.cur_stack >= env->prog->len)
18154 return -E2BIG;
18155
18156 insn_stack[env->cfg.cur_stack++] = w;
18157 insn_state[w] |= DISCOVERED;
18158 keep_exploring = true;
18159 }
18160
18161 return keep_exploring ? KEEP_EXPLORING : DONE_EXPLORING;
18162 }
18163
visit_tailcall_insn(struct bpf_verifier_env * env,int t)18164 static int visit_tailcall_insn(struct bpf_verifier_env *env, int t)
18165 {
18166 static struct bpf_subprog_info *subprog;
18167 struct bpf_iarray *jt;
18168
18169 if (env->insn_aux_data[t].jt)
18170 return 0;
18171
18172 jt = iarray_realloc(NULL, 2);
18173 if (!jt)
18174 return -ENOMEM;
18175
18176 subprog = bpf_find_containing_subprog(env, t);
18177 jt->items[0] = t + 1;
18178 jt->items[1] = subprog->exit_idx;
18179 env->insn_aux_data[t].jt = jt;
18180 return 0;
18181 }
18182
18183 /* Visits the instruction at index t and returns one of the following:
18184 * < 0 - an error occurred
18185 * DONE_EXPLORING - the instruction was fully explored
18186 * KEEP_EXPLORING - there is still work to be done before it is fully explored
18187 */
visit_insn(int t,struct bpf_verifier_env * env)18188 static int visit_insn(int t, struct bpf_verifier_env *env)
18189 {
18190 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
18191 int ret, off, insn_sz;
18192
18193 if (bpf_pseudo_func(insn))
18194 return visit_func_call_insn(t, insns, env, true);
18195
18196 /* All non-branch instructions have a single fall-through edge. */
18197 if (BPF_CLASS(insn->code) != BPF_JMP &&
18198 BPF_CLASS(insn->code) != BPF_JMP32) {
18199 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
18200 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
18201 }
18202
18203 switch (BPF_OP(insn->code)) {
18204 case BPF_EXIT:
18205 return DONE_EXPLORING;
18206
18207 case BPF_CALL:
18208 if (is_async_callback_calling_insn(insn))
18209 /* Mark this call insn as a prune point to trigger
18210 * is_state_visited() check before call itself is
18211 * processed by __check_func_call(). Otherwise new
18212 * async state will be pushed for further exploration.
18213 */
18214 mark_prune_point(env, t);
18215 /* For functions that invoke callbacks it is not known how many times
18216 * callback would be called. Verifier models callback calling functions
18217 * by repeatedly visiting callback bodies and returning to origin call
18218 * instruction.
18219 * In order to stop such iteration verifier needs to identify when a
18220 * state identical some state from a previous iteration is reached.
18221 * Check below forces creation of checkpoint before callback calling
18222 * instruction to allow search for such identical states.
18223 */
18224 if (is_sync_callback_calling_insn(insn)) {
18225 mark_calls_callback(env, t);
18226 mark_force_checkpoint(env, t);
18227 mark_prune_point(env, t);
18228 mark_jmp_point(env, t);
18229 }
18230 if (bpf_helper_call(insn)) {
18231 const struct bpf_func_proto *fp;
18232
18233 ret = get_helper_proto(env, insn->imm, &fp);
18234 /* If called in a non-sleepable context program will be
18235 * rejected anyway, so we should end up with precise
18236 * sleepable marks on subprogs, except for dead code
18237 * elimination.
18238 */
18239 if (ret == 0 && fp->might_sleep)
18240 mark_subprog_might_sleep(env, t);
18241 if (bpf_helper_changes_pkt_data(insn->imm))
18242 mark_subprog_changes_pkt_data(env, t);
18243 if (insn->imm == BPF_FUNC_tail_call)
18244 visit_tailcall_insn(env, t);
18245 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18246 struct bpf_kfunc_call_arg_meta meta;
18247
18248 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
18249 if (ret == 0 && is_iter_next_kfunc(&meta)) {
18250 mark_prune_point(env, t);
18251 /* Checking and saving state checkpoints at iter_next() call
18252 * is crucial for fast convergence of open-coded iterator loop
18253 * logic, so we need to force it. If we don't do that,
18254 * is_state_visited() might skip saving a checkpoint, causing
18255 * unnecessarily long sequence of not checkpointed
18256 * instructions and jumps, leading to exhaustion of jump
18257 * history buffer, and potentially other undesired outcomes.
18258 * It is expected that with correct open-coded iterators
18259 * convergence will happen quickly, so we don't run a risk of
18260 * exhausting memory.
18261 */
18262 mark_force_checkpoint(env, t);
18263 }
18264 /* Same as helpers, if called in a non-sleepable context
18265 * program will be rejected anyway, so we should end up
18266 * with precise sleepable marks on subprogs, except for
18267 * dead code elimination.
18268 */
18269 if (ret == 0 && is_kfunc_sleepable(&meta))
18270 mark_subprog_might_sleep(env, t);
18271 if (ret == 0 && is_kfunc_pkt_changing(&meta))
18272 mark_subprog_changes_pkt_data(env, t);
18273 }
18274 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
18275
18276 case BPF_JA:
18277 if (BPF_SRC(insn->code) == BPF_X)
18278 return visit_gotox_insn(t, env);
18279
18280 if (BPF_CLASS(insn->code) == BPF_JMP)
18281 off = insn->off;
18282 else
18283 off = insn->imm;
18284
18285 /* unconditional jump with single edge */
18286 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
18287 if (ret)
18288 return ret;
18289
18290 mark_prune_point(env, t + off + 1);
18291 mark_jmp_point(env, t + off + 1);
18292
18293 return ret;
18294
18295 default:
18296 /* conditional jump with two edges */
18297 mark_prune_point(env, t);
18298 if (is_may_goto_insn(insn))
18299 mark_force_checkpoint(env, t);
18300
18301 ret = push_insn(t, t + 1, FALLTHROUGH, env);
18302 if (ret)
18303 return ret;
18304
18305 return push_insn(t, t + insn->off + 1, BRANCH, env);
18306 }
18307 }
18308
18309 /* non-recursive depth-first-search to detect loops in BPF program
18310 * loop == back-edge in directed graph
18311 */
check_cfg(struct bpf_verifier_env * env)18312 static int check_cfg(struct bpf_verifier_env *env)
18313 {
18314 int insn_cnt = env->prog->len;
18315 int *insn_stack, *insn_state;
18316 int ex_insn_beg, i, ret = 0;
18317
18318 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18319 if (!insn_state)
18320 return -ENOMEM;
18321
18322 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
18323 if (!insn_stack) {
18324 kvfree(insn_state);
18325 return -ENOMEM;
18326 }
18327
18328 ex_insn_beg = env->exception_callback_subprog
18329 ? env->subprog_info[env->exception_callback_subprog].start
18330 : 0;
18331
18332 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
18333 insn_stack[0] = 0; /* 0 is the first instruction */
18334 env->cfg.cur_stack = 1;
18335
18336 walk_cfg:
18337 while (env->cfg.cur_stack > 0) {
18338 int t = insn_stack[env->cfg.cur_stack - 1];
18339
18340 ret = visit_insn(t, env);
18341 switch (ret) {
18342 case DONE_EXPLORING:
18343 insn_state[t] = EXPLORED;
18344 env->cfg.cur_stack--;
18345 break;
18346 case KEEP_EXPLORING:
18347 break;
18348 default:
18349 if (ret > 0) {
18350 verifier_bug(env, "visit_insn internal bug");
18351 ret = -EFAULT;
18352 }
18353 goto err_free;
18354 }
18355 }
18356
18357 if (env->cfg.cur_stack < 0) {
18358 verifier_bug(env, "pop stack internal bug");
18359 ret = -EFAULT;
18360 goto err_free;
18361 }
18362
18363 if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) {
18364 insn_state[ex_insn_beg] = DISCOVERED;
18365 insn_stack[0] = ex_insn_beg;
18366 env->cfg.cur_stack = 1;
18367 goto walk_cfg;
18368 }
18369
18370 for (i = 0; i < insn_cnt; i++) {
18371 struct bpf_insn *insn = &env->prog->insnsi[i];
18372
18373 if (insn_state[i] != EXPLORED) {
18374 verbose(env, "unreachable insn %d\n", i);
18375 ret = -EINVAL;
18376 goto err_free;
18377 }
18378 if (bpf_is_ldimm64(insn)) {
18379 if (insn_state[i + 1] != 0) {
18380 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
18381 ret = -EINVAL;
18382 goto err_free;
18383 }
18384 i++; /* skip second half of ldimm64 */
18385 }
18386 }
18387 ret = 0; /* cfg looks good */
18388 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data;
18389 env->prog->aux->might_sleep = env->subprog_info[0].might_sleep;
18390
18391 err_free:
18392 kvfree(insn_state);
18393 kvfree(insn_stack);
18394 env->cfg.insn_state = env->cfg.insn_stack = NULL;
18395 return ret;
18396 }
18397
18398 /*
18399 * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range
18400 * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start)
18401 * with indices of 'i' instructions in postorder.
18402 */
compute_postorder(struct bpf_verifier_env * env)18403 static int compute_postorder(struct bpf_verifier_env *env)
18404 {
18405 u32 cur_postorder, i, top, stack_sz, s;
18406 int *stack = NULL, *postorder = NULL, *state = NULL;
18407 struct bpf_iarray *succ;
18408
18409 postorder = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18410 state = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18411 stack = kvcalloc(env->prog->len, sizeof(int), GFP_KERNEL_ACCOUNT);
18412 if (!postorder || !state || !stack) {
18413 kvfree(postorder);
18414 kvfree(state);
18415 kvfree(stack);
18416 return -ENOMEM;
18417 }
18418 cur_postorder = 0;
18419 for (i = 0; i < env->subprog_cnt; i++) {
18420 env->subprog_info[i].postorder_start = cur_postorder;
18421 stack[0] = env->subprog_info[i].start;
18422 stack_sz = 1;
18423 do {
18424 top = stack[stack_sz - 1];
18425 state[top] |= DISCOVERED;
18426 if (state[top] & EXPLORED) {
18427 postorder[cur_postorder++] = top;
18428 stack_sz--;
18429 continue;
18430 }
18431 succ = bpf_insn_successors(env, top);
18432 for (s = 0; s < succ->cnt; ++s) {
18433 if (!state[succ->items[s]]) {
18434 stack[stack_sz++] = succ->items[s];
18435 state[succ->items[s]] |= DISCOVERED;
18436 }
18437 }
18438 state[top] |= EXPLORED;
18439 } while (stack_sz);
18440 }
18441 env->subprog_info[i].postorder_start = cur_postorder;
18442 env->cfg.insn_postorder = postorder;
18443 env->cfg.cur_postorder = cur_postorder;
18444 kvfree(stack);
18445 kvfree(state);
18446 return 0;
18447 }
18448
check_abnormal_return(struct bpf_verifier_env * env)18449 static int check_abnormal_return(struct bpf_verifier_env *env)
18450 {
18451 int i;
18452
18453 for (i = 1; i < env->subprog_cnt; i++) {
18454 if (env->subprog_info[i].has_ld_abs) {
18455 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
18456 return -EINVAL;
18457 }
18458 if (env->subprog_info[i].has_tail_call) {
18459 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
18460 return -EINVAL;
18461 }
18462 }
18463 return 0;
18464 }
18465
18466 /* The minimum supported BTF func info size */
18467 #define MIN_BPF_FUNCINFO_SIZE 8
18468 #define MAX_FUNCINFO_REC_SIZE 252
18469
check_btf_func_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18470 static int check_btf_func_early(struct bpf_verifier_env *env,
18471 const union bpf_attr *attr,
18472 bpfptr_t uattr)
18473 {
18474 u32 krec_size = sizeof(struct bpf_func_info);
18475 const struct btf_type *type, *func_proto;
18476 u32 i, nfuncs, urec_size, min_size;
18477 struct bpf_func_info *krecord;
18478 struct bpf_prog *prog;
18479 const struct btf *btf;
18480 u32 prev_offset = 0;
18481 bpfptr_t urecord;
18482 int ret = -ENOMEM;
18483
18484 nfuncs = attr->func_info_cnt;
18485 if (!nfuncs) {
18486 if (check_abnormal_return(env))
18487 return -EINVAL;
18488 return 0;
18489 }
18490
18491 urec_size = attr->func_info_rec_size;
18492 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
18493 urec_size > MAX_FUNCINFO_REC_SIZE ||
18494 urec_size % sizeof(u32)) {
18495 verbose(env, "invalid func info rec size %u\n", urec_size);
18496 return -EINVAL;
18497 }
18498
18499 prog = env->prog;
18500 btf = prog->aux->btf;
18501
18502 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18503 min_size = min_t(u32, krec_size, urec_size);
18504
18505 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18506 if (!krecord)
18507 return -ENOMEM;
18508
18509 for (i = 0; i < nfuncs; i++) {
18510 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
18511 if (ret) {
18512 if (ret == -E2BIG) {
18513 verbose(env, "nonzero tailing record in func info");
18514 /* set the size kernel expects so loader can zero
18515 * out the rest of the record.
18516 */
18517 if (copy_to_bpfptr_offset(uattr,
18518 offsetof(union bpf_attr, func_info_rec_size),
18519 &min_size, sizeof(min_size)))
18520 ret = -EFAULT;
18521 }
18522 goto err_free;
18523 }
18524
18525 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
18526 ret = -EFAULT;
18527 goto err_free;
18528 }
18529
18530 /* check insn_off */
18531 ret = -EINVAL;
18532 if (i == 0) {
18533 if (krecord[i].insn_off) {
18534 verbose(env,
18535 "nonzero insn_off %u for the first func info record",
18536 krecord[i].insn_off);
18537 goto err_free;
18538 }
18539 } else if (krecord[i].insn_off <= prev_offset) {
18540 verbose(env,
18541 "same or smaller insn offset (%u) than previous func info record (%u)",
18542 krecord[i].insn_off, prev_offset);
18543 goto err_free;
18544 }
18545
18546 /* check type_id */
18547 type = btf_type_by_id(btf, krecord[i].type_id);
18548 if (!type || !btf_type_is_func(type)) {
18549 verbose(env, "invalid type id %d in func info",
18550 krecord[i].type_id);
18551 goto err_free;
18552 }
18553
18554 func_proto = btf_type_by_id(btf, type->type);
18555 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
18556 /* btf_func_check() already verified it during BTF load */
18557 goto err_free;
18558
18559 prev_offset = krecord[i].insn_off;
18560 bpfptr_add(&urecord, urec_size);
18561 }
18562
18563 prog->aux->func_info = krecord;
18564 prog->aux->func_info_cnt = nfuncs;
18565 return 0;
18566
18567 err_free:
18568 kvfree(krecord);
18569 return ret;
18570 }
18571
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18572 static int check_btf_func(struct bpf_verifier_env *env,
18573 const union bpf_attr *attr,
18574 bpfptr_t uattr)
18575 {
18576 const struct btf_type *type, *func_proto, *ret_type;
18577 u32 i, nfuncs, urec_size;
18578 struct bpf_func_info *krecord;
18579 struct bpf_func_info_aux *info_aux = NULL;
18580 struct bpf_prog *prog;
18581 const struct btf *btf;
18582 bpfptr_t urecord;
18583 bool scalar_return;
18584 int ret = -ENOMEM;
18585
18586 nfuncs = attr->func_info_cnt;
18587 if (!nfuncs) {
18588 if (check_abnormal_return(env))
18589 return -EINVAL;
18590 return 0;
18591 }
18592 if (nfuncs != env->subprog_cnt) {
18593 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
18594 return -EINVAL;
18595 }
18596
18597 urec_size = attr->func_info_rec_size;
18598
18599 prog = env->prog;
18600 btf = prog->aux->btf;
18601
18602 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
18603
18604 krecord = prog->aux->func_info;
18605 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18606 if (!info_aux)
18607 return -ENOMEM;
18608
18609 for (i = 0; i < nfuncs; i++) {
18610 /* check insn_off */
18611 ret = -EINVAL;
18612
18613 if (env->subprog_info[i].start != krecord[i].insn_off) {
18614 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
18615 goto err_free;
18616 }
18617
18618 /* Already checked type_id */
18619 type = btf_type_by_id(btf, krecord[i].type_id);
18620 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
18621 /* Already checked func_proto */
18622 func_proto = btf_type_by_id(btf, type->type);
18623
18624 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
18625 scalar_return =
18626 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
18627 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
18628 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
18629 goto err_free;
18630 }
18631 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
18632 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
18633 goto err_free;
18634 }
18635
18636 bpfptr_add(&urecord, urec_size);
18637 }
18638
18639 prog->aux->func_info_aux = info_aux;
18640 return 0;
18641
18642 err_free:
18643 kfree(info_aux);
18644 return ret;
18645 }
18646
adjust_btf_func(struct bpf_verifier_env * env)18647 static void adjust_btf_func(struct bpf_verifier_env *env)
18648 {
18649 struct bpf_prog_aux *aux = env->prog->aux;
18650 int i;
18651
18652 if (!aux->func_info)
18653 return;
18654
18655 /* func_info is not available for hidden subprogs */
18656 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
18657 aux->func_info[i].insn_off = env->subprog_info[i].start;
18658 }
18659
18660 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
18661 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
18662
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18663 static int check_btf_line(struct bpf_verifier_env *env,
18664 const union bpf_attr *attr,
18665 bpfptr_t uattr)
18666 {
18667 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
18668 struct bpf_subprog_info *sub;
18669 struct bpf_line_info *linfo;
18670 struct bpf_prog *prog;
18671 const struct btf *btf;
18672 bpfptr_t ulinfo;
18673 int err;
18674
18675 nr_linfo = attr->line_info_cnt;
18676 if (!nr_linfo)
18677 return 0;
18678 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
18679 return -EINVAL;
18680
18681 rec_size = attr->line_info_rec_size;
18682 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
18683 rec_size > MAX_LINEINFO_REC_SIZE ||
18684 rec_size & (sizeof(u32) - 1))
18685 return -EINVAL;
18686
18687 /* Need to zero it in case the userspace may
18688 * pass in a smaller bpf_line_info object.
18689 */
18690 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
18691 GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
18692 if (!linfo)
18693 return -ENOMEM;
18694
18695 prog = env->prog;
18696 btf = prog->aux->btf;
18697
18698 s = 0;
18699 sub = env->subprog_info;
18700 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
18701 expected_size = sizeof(struct bpf_line_info);
18702 ncopy = min_t(u32, expected_size, rec_size);
18703 for (i = 0; i < nr_linfo; i++) {
18704 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
18705 if (err) {
18706 if (err == -E2BIG) {
18707 verbose(env, "nonzero tailing record in line_info");
18708 if (copy_to_bpfptr_offset(uattr,
18709 offsetof(union bpf_attr, line_info_rec_size),
18710 &expected_size, sizeof(expected_size)))
18711 err = -EFAULT;
18712 }
18713 goto err_free;
18714 }
18715
18716 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
18717 err = -EFAULT;
18718 goto err_free;
18719 }
18720
18721 /*
18722 * Check insn_off to ensure
18723 * 1) strictly increasing AND
18724 * 2) bounded by prog->len
18725 *
18726 * The linfo[0].insn_off == 0 check logically falls into
18727 * the later "missing bpf_line_info for func..." case
18728 * because the first linfo[0].insn_off must be the
18729 * first sub also and the first sub must have
18730 * subprog_info[0].start == 0.
18731 */
18732 if ((i && linfo[i].insn_off <= prev_offset) ||
18733 linfo[i].insn_off >= prog->len) {
18734 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
18735 i, linfo[i].insn_off, prev_offset,
18736 prog->len);
18737 err = -EINVAL;
18738 goto err_free;
18739 }
18740
18741 if (!prog->insnsi[linfo[i].insn_off].code) {
18742 verbose(env,
18743 "Invalid insn code at line_info[%u].insn_off\n",
18744 i);
18745 err = -EINVAL;
18746 goto err_free;
18747 }
18748
18749 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
18750 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
18751 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
18752 err = -EINVAL;
18753 goto err_free;
18754 }
18755
18756 if (s != env->subprog_cnt) {
18757 if (linfo[i].insn_off == sub[s].start) {
18758 sub[s].linfo_idx = i;
18759 s++;
18760 } else if (sub[s].start < linfo[i].insn_off) {
18761 verbose(env, "missing bpf_line_info for func#%u\n", s);
18762 err = -EINVAL;
18763 goto err_free;
18764 }
18765 }
18766
18767 prev_offset = linfo[i].insn_off;
18768 bpfptr_add(&ulinfo, rec_size);
18769 }
18770
18771 if (s != env->subprog_cnt) {
18772 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
18773 env->subprog_cnt - s, s);
18774 err = -EINVAL;
18775 goto err_free;
18776 }
18777
18778 prog->aux->linfo = linfo;
18779 prog->aux->nr_linfo = nr_linfo;
18780
18781 return 0;
18782
18783 err_free:
18784 kvfree(linfo);
18785 return err;
18786 }
18787
18788 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
18789 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
18790
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18791 static int check_core_relo(struct bpf_verifier_env *env,
18792 const union bpf_attr *attr,
18793 bpfptr_t uattr)
18794 {
18795 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
18796 struct bpf_core_relo core_relo = {};
18797 struct bpf_prog *prog = env->prog;
18798 const struct btf *btf = prog->aux->btf;
18799 struct bpf_core_ctx ctx = {
18800 .log = &env->log,
18801 .btf = btf,
18802 };
18803 bpfptr_t u_core_relo;
18804 int err;
18805
18806 nr_core_relo = attr->core_relo_cnt;
18807 if (!nr_core_relo)
18808 return 0;
18809 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
18810 return -EINVAL;
18811
18812 rec_size = attr->core_relo_rec_size;
18813 if (rec_size < MIN_CORE_RELO_SIZE ||
18814 rec_size > MAX_CORE_RELO_SIZE ||
18815 rec_size % sizeof(u32))
18816 return -EINVAL;
18817
18818 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
18819 expected_size = sizeof(struct bpf_core_relo);
18820 ncopy = min_t(u32, expected_size, rec_size);
18821
18822 /* Unlike func_info and line_info, copy and apply each CO-RE
18823 * relocation record one at a time.
18824 */
18825 for (i = 0; i < nr_core_relo; i++) {
18826 /* future proofing when sizeof(bpf_core_relo) changes */
18827 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
18828 if (err) {
18829 if (err == -E2BIG) {
18830 verbose(env, "nonzero tailing record in core_relo");
18831 if (copy_to_bpfptr_offset(uattr,
18832 offsetof(union bpf_attr, core_relo_rec_size),
18833 &expected_size, sizeof(expected_size)))
18834 err = -EFAULT;
18835 }
18836 break;
18837 }
18838
18839 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
18840 err = -EFAULT;
18841 break;
18842 }
18843
18844 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
18845 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
18846 i, core_relo.insn_off, prog->len);
18847 err = -EINVAL;
18848 break;
18849 }
18850
18851 err = bpf_core_apply(&ctx, &core_relo, i,
18852 &prog->insnsi[core_relo.insn_off / 8]);
18853 if (err)
18854 break;
18855 bpfptr_add(&u_core_relo, rec_size);
18856 }
18857 return err;
18858 }
18859
check_btf_info_early(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18860 static int check_btf_info_early(struct bpf_verifier_env *env,
18861 const union bpf_attr *attr,
18862 bpfptr_t uattr)
18863 {
18864 struct btf *btf;
18865 int err;
18866
18867 if (!attr->func_info_cnt && !attr->line_info_cnt) {
18868 if (check_abnormal_return(env))
18869 return -EINVAL;
18870 return 0;
18871 }
18872
18873 btf = btf_get_by_fd(attr->prog_btf_fd);
18874 if (IS_ERR(btf))
18875 return PTR_ERR(btf);
18876 if (btf_is_kernel(btf)) {
18877 btf_put(btf);
18878 return -EACCES;
18879 }
18880 env->prog->aux->btf = btf;
18881
18882 err = check_btf_func_early(env, attr, uattr);
18883 if (err)
18884 return err;
18885 return 0;
18886 }
18887
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)18888 static int check_btf_info(struct bpf_verifier_env *env,
18889 const union bpf_attr *attr,
18890 bpfptr_t uattr)
18891 {
18892 int err;
18893
18894 if (!attr->func_info_cnt && !attr->line_info_cnt) {
18895 if (check_abnormal_return(env))
18896 return -EINVAL;
18897 return 0;
18898 }
18899
18900 err = check_btf_func(env, attr, uattr);
18901 if (err)
18902 return err;
18903
18904 err = check_btf_line(env, attr, uattr);
18905 if (err)
18906 return err;
18907
18908 err = check_core_relo(env, attr, uattr);
18909 if (err)
18910 return err;
18911
18912 return 0;
18913 }
18914
18915 /* check %cur's range satisfies %old's */
range_within(const struct bpf_reg_state * old,const struct bpf_reg_state * cur)18916 static bool range_within(const struct bpf_reg_state *old,
18917 const struct bpf_reg_state *cur)
18918 {
18919 return old->umin_value <= cur->umin_value &&
18920 old->umax_value >= cur->umax_value &&
18921 old->smin_value <= cur->smin_value &&
18922 old->smax_value >= cur->smax_value &&
18923 old->u32_min_value <= cur->u32_min_value &&
18924 old->u32_max_value >= cur->u32_max_value &&
18925 old->s32_min_value <= cur->s32_min_value &&
18926 old->s32_max_value >= cur->s32_max_value;
18927 }
18928
18929 /* If in the old state two registers had the same id, then they need to have
18930 * the same id in the new state as well. But that id could be different from
18931 * the old state, so we need to track the mapping from old to new ids.
18932 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
18933 * regs with old id 5 must also have new id 9 for the new state to be safe. But
18934 * regs with a different old id could still have new id 9, we don't care about
18935 * that.
18936 * So we look through our idmap to see if this old id has been seen before. If
18937 * so, we require the new id to match; otherwise, we add the id pair to the map.
18938 */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18939 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18940 {
18941 struct bpf_id_pair *map = idmap->map;
18942 unsigned int i;
18943
18944 /* either both IDs should be set or both should be zero */
18945 if (!!old_id != !!cur_id)
18946 return false;
18947
18948 if (old_id == 0) /* cur_id == 0 as well */
18949 return true;
18950
18951 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
18952 if (!map[i].old) {
18953 /* Reached an empty slot; haven't seen this id before */
18954 map[i].old = old_id;
18955 map[i].cur = cur_id;
18956 return true;
18957 }
18958 if (map[i].old == old_id)
18959 return map[i].cur == cur_id;
18960 if (map[i].cur == cur_id)
18961 return false;
18962 }
18963 /* We ran out of idmap slots, which should be impossible */
18964 WARN_ON_ONCE(1);
18965 return false;
18966 }
18967
18968 /* Similar to check_ids(), but allocate a unique temporary ID
18969 * for 'old_id' or 'cur_id' of zero.
18970 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
18971 */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)18972 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
18973 {
18974 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
18975 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
18976
18977 return check_ids(old_id, cur_id, idmap);
18978 }
18979
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st,u32 ip)18980 static void clean_func_state(struct bpf_verifier_env *env,
18981 struct bpf_func_state *st,
18982 u32 ip)
18983 {
18984 u16 live_regs = env->insn_aux_data[ip].live_regs_before;
18985 int i, j;
18986
18987 for (i = 0; i < BPF_REG_FP; i++) {
18988 /* liveness must not touch this register anymore */
18989 if (!(live_regs & BIT(i)))
18990 /* since the register is unused, clear its state
18991 * to make further comparison simpler
18992 */
18993 __mark_reg_not_init(env, &st->regs[i]);
18994 }
18995
18996 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
18997 if (!bpf_stack_slot_alive(env, st->frameno, i)) {
18998 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
18999 for (j = 0; j < BPF_REG_SIZE; j++)
19000 st->stack[i].slot_type[j] = STACK_INVALID;
19001 }
19002 }
19003 }
19004
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)19005 static void clean_verifier_state(struct bpf_verifier_env *env,
19006 struct bpf_verifier_state *st)
19007 {
19008 int i, ip;
19009
19010 bpf_live_stack_query_init(env, st);
19011 st->cleaned = true;
19012 for (i = 0; i <= st->curframe; i++) {
19013 ip = frame_insn_idx(st, i);
19014 clean_func_state(env, st->frame[i], ip);
19015 }
19016 }
19017
19018 /* the parentage chains form a tree.
19019 * the verifier states are added to state lists at given insn and
19020 * pushed into state stack for future exploration.
19021 * when the verifier reaches bpf_exit insn some of the verifier states
19022 * stored in the state lists have their final liveness state already,
19023 * but a lot of states will get revised from liveness point of view when
19024 * the verifier explores other branches.
19025 * Example:
19026 * 1: *(u64)(r10 - 8) = 1
19027 * 2: if r1 == 100 goto pc+1
19028 * 3: *(u64)(r10 - 8) = 2
19029 * 4: r0 = *(u64)(r10 - 8)
19030 * 5: exit
19031 * when the verifier reaches exit insn the stack slot -8 in the state list of
19032 * insn 2 is not yet marked alive. Then the verifier pops the other_branch
19033 * of insn 2 and goes exploring further. After the insn 4 read, liveness
19034 * analysis would propagate read mark for -8 at insn 2.
19035 *
19036 * Since the verifier pushes the branch states as it sees them while exploring
19037 * the program the condition of walking the branch instruction for the second
19038 * time means that all states below this branch were already explored and
19039 * their final liveness marks are already propagated.
19040 * Hence when the verifier completes the search of state list in is_state_visited()
19041 * we can call this clean_live_states() function to clear dead the registers and stack
19042 * slots to simplify state merging.
19043 *
19044 * Important note here that walking the same branch instruction in the callee
19045 * doesn't meant that the states are DONE. The verifier has to compare
19046 * the callsites
19047 */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)19048 static void clean_live_states(struct bpf_verifier_env *env, int insn,
19049 struct bpf_verifier_state *cur)
19050 {
19051 struct bpf_verifier_state_list *sl;
19052 struct list_head *pos, *head;
19053
19054 head = explored_state(env, insn);
19055 list_for_each(pos, head) {
19056 sl = container_of(pos, struct bpf_verifier_state_list, node);
19057 if (sl->state.branches)
19058 continue;
19059 if (sl->state.insn_idx != insn ||
19060 !same_callsites(&sl->state, cur))
19061 continue;
19062 if (sl->state.cleaned)
19063 /* all regs in this state in all frames were already marked */
19064 continue;
19065 if (incomplete_read_marks(env, &sl->state))
19066 continue;
19067 clean_verifier_state(env, &sl->state);
19068 }
19069 }
19070
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)19071 static bool regs_exact(const struct bpf_reg_state *rold,
19072 const struct bpf_reg_state *rcur,
19073 struct bpf_idmap *idmap)
19074 {
19075 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19076 check_ids(rold->id, rcur->id, idmap) &&
19077 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19078 }
19079
19080 enum exact_level {
19081 NOT_EXACT,
19082 EXACT,
19083 RANGE_WITHIN
19084 };
19085
19086 /* 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)19087 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
19088 struct bpf_reg_state *rcur, struct bpf_idmap *idmap,
19089 enum exact_level exact)
19090 {
19091 if (exact == EXACT)
19092 return regs_exact(rold, rcur, idmap);
19093
19094 if (rold->type == NOT_INIT) {
19095 if (exact == NOT_EXACT || rcur->type == NOT_INIT)
19096 /* explored state can't have used this */
19097 return true;
19098 }
19099
19100 /* Enforce that register types have to match exactly, including their
19101 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
19102 * rule.
19103 *
19104 * One can make a point that using a pointer register as unbounded
19105 * SCALAR would be technically acceptable, but this could lead to
19106 * pointer leaks because scalars are allowed to leak while pointers
19107 * are not. We could make this safe in special cases if root is
19108 * calling us, but it's probably not worth the hassle.
19109 *
19110 * Also, register types that are *not* MAYBE_NULL could technically be
19111 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
19112 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
19113 * to the same map).
19114 * However, if the old MAYBE_NULL register then got NULL checked,
19115 * doing so could have affected others with the same id, and we can't
19116 * check for that because we lost the id when we converted to
19117 * a non-MAYBE_NULL variant.
19118 * So, as a general rule we don't allow mixing MAYBE_NULL and
19119 * non-MAYBE_NULL registers as well.
19120 */
19121 if (rold->type != rcur->type)
19122 return false;
19123
19124 switch (base_type(rold->type)) {
19125 case SCALAR_VALUE:
19126 if (env->explore_alu_limits) {
19127 /* explore_alu_limits disables tnum_in() and range_within()
19128 * logic and requires everything to be strict
19129 */
19130 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
19131 check_scalar_ids(rold->id, rcur->id, idmap);
19132 }
19133 if (!rold->precise && exact == NOT_EXACT)
19134 return true;
19135 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST))
19136 return false;
19137 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off))
19138 return false;
19139 /* Why check_ids() for scalar registers?
19140 *
19141 * Consider the following BPF code:
19142 * 1: r6 = ... unbound scalar, ID=a ...
19143 * 2: r7 = ... unbound scalar, ID=b ...
19144 * 3: if (r6 > r7) goto +1
19145 * 4: r6 = r7
19146 * 5: if (r6 > X) goto ...
19147 * 6: ... memory operation using r7 ...
19148 *
19149 * First verification path is [1-6]:
19150 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
19151 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark
19152 * r7 <= X, because r6 and r7 share same id.
19153 * Next verification path is [1-4, 6].
19154 *
19155 * Instruction (6) would be reached in two states:
19156 * I. r6{.id=b}, r7{.id=b} via path 1-6;
19157 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
19158 *
19159 * Use check_ids() to distinguish these states.
19160 * ---
19161 * Also verify that new value satisfies old value range knowledge.
19162 */
19163 return range_within(rold, rcur) &&
19164 tnum_in(rold->var_off, rcur->var_off) &&
19165 check_scalar_ids(rold->id, rcur->id, idmap);
19166 case PTR_TO_MAP_KEY:
19167 case PTR_TO_MAP_VALUE:
19168 case PTR_TO_MEM:
19169 case PTR_TO_BUF:
19170 case PTR_TO_TP_BUFFER:
19171 /* If the new min/max/var_off satisfy the old ones and
19172 * everything else matches, we are OK.
19173 */
19174 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19175 range_within(rold, rcur) &&
19176 tnum_in(rold->var_off, rcur->var_off) &&
19177 check_ids(rold->id, rcur->id, idmap) &&
19178 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
19179 case PTR_TO_PACKET_META:
19180 case PTR_TO_PACKET:
19181 /* We must have at least as much range as the old ptr
19182 * did, so that any accesses which were safe before are
19183 * still safe. This is true even if old range < old off,
19184 * since someone could have accessed through (ptr - k), or
19185 * even done ptr -= k in a register, to get a safe access.
19186 */
19187 if (rold->range > rcur->range)
19188 return false;
19189 /* If the offsets don't match, we can't trust our alignment;
19190 * nor can we be sure that we won't fall out of range.
19191 */
19192 if (rold->off != rcur->off)
19193 return false;
19194 /* id relations must be preserved */
19195 if (!check_ids(rold->id, rcur->id, idmap))
19196 return false;
19197 /* new val must satisfy old val knowledge */
19198 return range_within(rold, rcur) &&
19199 tnum_in(rold->var_off, rcur->var_off);
19200 case PTR_TO_STACK:
19201 /* two stack pointers are equal only if they're pointing to
19202 * the same stack frame, since fp-8 in foo != fp-8 in bar
19203 */
19204 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
19205 case PTR_TO_ARENA:
19206 return true;
19207 case PTR_TO_INSN:
19208 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
19209 rold->off == rcur->off && range_within(rold, rcur) &&
19210 tnum_in(rold->var_off, rcur->var_off);
19211 default:
19212 return regs_exact(rold, rcur, idmap);
19213 }
19214 }
19215
19216 static struct bpf_reg_state unbound_reg;
19217
unbound_reg_init(void)19218 static __init int unbound_reg_init(void)
19219 {
19220 __mark_reg_unknown_imprecise(&unbound_reg);
19221 return 0;
19222 }
19223 late_initcall(unbound_reg_init);
19224
is_stack_all_misc(struct bpf_verifier_env * env,struct bpf_stack_state * stack)19225 static bool is_stack_all_misc(struct bpf_verifier_env *env,
19226 struct bpf_stack_state *stack)
19227 {
19228 u32 i;
19229
19230 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) {
19231 if ((stack->slot_type[i] == STACK_MISC) ||
19232 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack))
19233 continue;
19234 return false;
19235 }
19236
19237 return true;
19238 }
19239
scalar_reg_for_stack(struct bpf_verifier_env * env,struct bpf_stack_state * stack)19240 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env,
19241 struct bpf_stack_state *stack)
19242 {
19243 if (is_spilled_scalar_reg64(stack))
19244 return &stack->spilled_ptr;
19245
19246 if (is_stack_all_misc(env, stack))
19247 return &unbound_reg;
19248
19249 return NULL;
19250 }
19251
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,enum exact_level exact)19252 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
19253 struct bpf_func_state *cur, struct bpf_idmap *idmap,
19254 enum exact_level exact)
19255 {
19256 int i, spi;
19257
19258 /* walk slots of the explored stack and ignore any additional
19259 * slots in the current stack, since explored(safe) state
19260 * didn't use them
19261 */
19262 for (i = 0; i < old->allocated_stack; i++) {
19263 struct bpf_reg_state *old_reg, *cur_reg;
19264
19265 spi = i / BPF_REG_SIZE;
19266
19267 if (exact != NOT_EXACT &&
19268 (i >= cur->allocated_stack ||
19269 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19270 cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
19271 return false;
19272
19273 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
19274 continue;
19275
19276 if (env->allow_uninit_stack &&
19277 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
19278 continue;
19279
19280 /* explored stack has more populated slots than current stack
19281 * and these slots were used
19282 */
19283 if (i >= cur->allocated_stack)
19284 return false;
19285
19286 /* 64-bit scalar spill vs all slots MISC and vice versa.
19287 * Load from all slots MISC produces unbound scalar.
19288 * Construct a fake register for such stack and call
19289 * regsafe() to ensure scalar ids are compared.
19290 */
19291 old_reg = scalar_reg_for_stack(env, &old->stack[spi]);
19292 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]);
19293 if (old_reg && cur_reg) {
19294 if (!regsafe(env, old_reg, cur_reg, idmap, exact))
19295 return false;
19296 i += BPF_REG_SIZE - 1;
19297 continue;
19298 }
19299
19300 /* if old state was safe with misc data in the stack
19301 * it will be safe with zero-initialized stack.
19302 * The opposite is not true
19303 */
19304 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
19305 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
19306 continue;
19307 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
19308 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
19309 /* Ex: old explored (safe) state has STACK_SPILL in
19310 * this stack slot, but current has STACK_MISC ->
19311 * this verifier states are not equivalent,
19312 * return false to continue verification of this path
19313 */
19314 return false;
19315 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
19316 continue;
19317 /* Both old and cur are having same slot_type */
19318 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
19319 case STACK_SPILL:
19320 /* when explored and current stack slot are both storing
19321 * spilled registers, check that stored pointers types
19322 * are the same as well.
19323 * Ex: explored safe path could have stored
19324 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
19325 * but current path has stored:
19326 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
19327 * such verifier states are not equivalent.
19328 * return false to continue verification of this path
19329 */
19330 if (!regsafe(env, &old->stack[spi].spilled_ptr,
19331 &cur->stack[spi].spilled_ptr, idmap, exact))
19332 return false;
19333 break;
19334 case STACK_DYNPTR:
19335 old_reg = &old->stack[spi].spilled_ptr;
19336 cur_reg = &cur->stack[spi].spilled_ptr;
19337 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
19338 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
19339 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19340 return false;
19341 break;
19342 case STACK_ITER:
19343 old_reg = &old->stack[spi].spilled_ptr;
19344 cur_reg = &cur->stack[spi].spilled_ptr;
19345 /* iter.depth is not compared between states as it
19346 * doesn't matter for correctness and would otherwise
19347 * prevent convergence; we maintain it only to prevent
19348 * infinite loop check triggering, see
19349 * iter_active_depths_differ()
19350 */
19351 if (old_reg->iter.btf != cur_reg->iter.btf ||
19352 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
19353 old_reg->iter.state != cur_reg->iter.state ||
19354 /* ignore {old_reg,cur_reg}->iter.depth, see above */
19355 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
19356 return false;
19357 break;
19358 case STACK_IRQ_FLAG:
19359 old_reg = &old->stack[spi].spilled_ptr;
19360 cur_reg = &cur->stack[spi].spilled_ptr;
19361 if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) ||
19362 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class)
19363 return false;
19364 break;
19365 case STACK_MISC:
19366 case STACK_ZERO:
19367 case STACK_INVALID:
19368 continue;
19369 /* Ensure that new unhandled slot types return false by default */
19370 default:
19371 return false;
19372 }
19373 }
19374 return true;
19375 }
19376
refsafe(struct bpf_verifier_state * old,struct bpf_verifier_state * cur,struct bpf_idmap * idmap)19377 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur,
19378 struct bpf_idmap *idmap)
19379 {
19380 int i;
19381
19382 if (old->acquired_refs != cur->acquired_refs)
19383 return false;
19384
19385 if (old->active_locks != cur->active_locks)
19386 return false;
19387
19388 if (old->active_preempt_locks != cur->active_preempt_locks)
19389 return false;
19390
19391 if (old->active_rcu_locks != cur->active_rcu_locks)
19392 return false;
19393
19394 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap))
19395 return false;
19396
19397 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) ||
19398 old->active_lock_ptr != cur->active_lock_ptr)
19399 return false;
19400
19401 for (i = 0; i < old->acquired_refs; i++) {
19402 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) ||
19403 old->refs[i].type != cur->refs[i].type)
19404 return false;
19405 switch (old->refs[i].type) {
19406 case REF_TYPE_PTR:
19407 case REF_TYPE_IRQ:
19408 break;
19409 case REF_TYPE_LOCK:
19410 case REF_TYPE_RES_LOCK:
19411 case REF_TYPE_RES_LOCK_IRQ:
19412 if (old->refs[i].ptr != cur->refs[i].ptr)
19413 return false;
19414 break;
19415 default:
19416 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type);
19417 return false;
19418 }
19419 }
19420
19421 return true;
19422 }
19423
19424 /* compare two verifier states
19425 *
19426 * all states stored in state_list are known to be valid, since
19427 * verifier reached 'bpf_exit' instruction through them
19428 *
19429 * this function is called when verifier exploring different branches of
19430 * execution popped from the state stack. If it sees an old state that has
19431 * more strict register state and more strict stack state then this execution
19432 * branch doesn't need to be explored further, since verifier already
19433 * concluded that more strict state leads to valid finish.
19434 *
19435 * Therefore two states are equivalent if register state is more conservative
19436 * and explored stack state is more conservative than the current one.
19437 * Example:
19438 * explored current
19439 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
19440 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
19441 *
19442 * In other words if current stack state (one being explored) has more
19443 * valid slots than old one that already passed validation, it means
19444 * the verifier can stop exploring and conclude that current state is valid too
19445 *
19446 * Similarly with registers. If explored state has register type as invalid
19447 * whereas register type in current state is meaningful, it means that
19448 * the current state will reach 'bpf_exit' instruction safely
19449 */
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)19450 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
19451 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact)
19452 {
19453 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
19454 u16 i;
19455
19456 if (old->callback_depth > cur->callback_depth)
19457 return false;
19458
19459 for (i = 0; i < MAX_BPF_REG; i++)
19460 if (((1 << i) & live_regs) &&
19461 !regsafe(env, &old->regs[i], &cur->regs[i],
19462 &env->idmap_scratch, exact))
19463 return false;
19464
19465 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
19466 return false;
19467
19468 return true;
19469 }
19470
reset_idmap_scratch(struct bpf_verifier_env * env)19471 static void reset_idmap_scratch(struct bpf_verifier_env *env)
19472 {
19473 env->idmap_scratch.tmp_id_gen = env->id_gen;
19474 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
19475 }
19476
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,enum exact_level exact)19477 static bool states_equal(struct bpf_verifier_env *env,
19478 struct bpf_verifier_state *old,
19479 struct bpf_verifier_state *cur,
19480 enum exact_level exact)
19481 {
19482 u32 insn_idx;
19483 int i;
19484
19485 if (old->curframe != cur->curframe)
19486 return false;
19487
19488 reset_idmap_scratch(env);
19489
19490 /* Verification state from speculative execution simulation
19491 * must never prune a non-speculative execution one.
19492 */
19493 if (old->speculative && !cur->speculative)
19494 return false;
19495
19496 if (old->in_sleepable != cur->in_sleepable)
19497 return false;
19498
19499 if (!refsafe(old, cur, &env->idmap_scratch))
19500 return false;
19501
19502 /* for states to be equal callsites have to be the same
19503 * and all frame states need to be equivalent
19504 */
19505 for (i = 0; i <= old->curframe; i++) {
19506 insn_idx = frame_insn_idx(old, i);
19507 if (old->frame[i]->callsite != cur->frame[i]->callsite)
19508 return false;
19509 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact))
19510 return false;
19511 }
19512 return true;
19513 }
19514
19515 /* find precise scalars in the previous equivalent state and
19516 * propagate them into the current state
19517 */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool * changed)19518 static int propagate_precision(struct bpf_verifier_env *env,
19519 const struct bpf_verifier_state *old,
19520 struct bpf_verifier_state *cur,
19521 bool *changed)
19522 {
19523 struct bpf_reg_state *state_reg;
19524 struct bpf_func_state *state;
19525 int i, err = 0, fr;
19526 bool first;
19527
19528 for (fr = old->curframe; fr >= 0; fr--) {
19529 state = old->frame[fr];
19530 state_reg = state->regs;
19531 first = true;
19532 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
19533 if (state_reg->type != SCALAR_VALUE ||
19534 !state_reg->precise)
19535 continue;
19536 if (env->log.level & BPF_LOG_LEVEL2) {
19537 if (first)
19538 verbose(env, "frame %d: propagating r%d", fr, i);
19539 else
19540 verbose(env, ",r%d", i);
19541 }
19542 bt_set_frame_reg(&env->bt, fr, i);
19543 first = false;
19544 }
19545
19546 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19547 if (!is_spilled_reg(&state->stack[i]))
19548 continue;
19549 state_reg = &state->stack[i].spilled_ptr;
19550 if (state_reg->type != SCALAR_VALUE ||
19551 !state_reg->precise)
19552 continue;
19553 if (env->log.level & BPF_LOG_LEVEL2) {
19554 if (first)
19555 verbose(env, "frame %d: propagating fp%d",
19556 fr, (-i - 1) * BPF_REG_SIZE);
19557 else
19558 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
19559 }
19560 bt_set_frame_slot(&env->bt, fr, i);
19561 first = false;
19562 }
19563 if (!first && (env->log.level & BPF_LOG_LEVEL2))
19564 verbose(env, "\n");
19565 }
19566
19567 err = __mark_chain_precision(env, cur, -1, changed);
19568 if (err < 0)
19569 return err;
19570
19571 return 0;
19572 }
19573
19574 #define MAX_BACKEDGE_ITERS 64
19575
19576 /* Propagate read and precision marks from visit->backedges[*].state->equal_state
19577 * to corresponding parent states of visit->backedges[*].state until fixed point is reached,
19578 * then free visit->backedges.
19579 * After execution of this function incomplete_read_marks() will return false
19580 * for all states corresponding to @visit->callchain.
19581 */
propagate_backedges(struct bpf_verifier_env * env,struct bpf_scc_visit * visit)19582 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit)
19583 {
19584 struct bpf_scc_backedge *backedge;
19585 struct bpf_verifier_state *st;
19586 bool changed;
19587 int i, err;
19588
19589 i = 0;
19590 do {
19591 if (i++ > MAX_BACKEDGE_ITERS) {
19592 if (env->log.level & BPF_LOG_LEVEL2)
19593 verbose(env, "%s: too many iterations\n", __func__);
19594 for (backedge = visit->backedges; backedge; backedge = backedge->next)
19595 mark_all_scalars_precise(env, &backedge->state);
19596 break;
19597 }
19598 changed = false;
19599 for (backedge = visit->backedges; backedge; backedge = backedge->next) {
19600 st = &backedge->state;
19601 err = propagate_precision(env, st->equal_state, st, &changed);
19602 if (err)
19603 return err;
19604 }
19605 } while (changed);
19606
19607 free_backedges(visit);
19608 return 0;
19609 }
19610
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19611 static bool states_maybe_looping(struct bpf_verifier_state *old,
19612 struct bpf_verifier_state *cur)
19613 {
19614 struct bpf_func_state *fold, *fcur;
19615 int i, fr = cur->curframe;
19616
19617 if (old->curframe != fr)
19618 return false;
19619
19620 fold = old->frame[fr];
19621 fcur = cur->frame[fr];
19622 for (i = 0; i < MAX_BPF_REG; i++)
19623 if (memcmp(&fold->regs[i], &fcur->regs[i],
19624 offsetof(struct bpf_reg_state, frameno)))
19625 return false;
19626 return true;
19627 }
19628
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)19629 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
19630 {
19631 return env->insn_aux_data[insn_idx].is_iter_next;
19632 }
19633
19634 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
19635 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
19636 * states to match, which otherwise would look like an infinite loop. So while
19637 * iter_next() calls are taken care of, we still need to be careful and
19638 * prevent erroneous and too eager declaration of "infinite loop", when
19639 * iterators are involved.
19640 *
19641 * Here's a situation in pseudo-BPF assembly form:
19642 *
19643 * 0: again: ; set up iter_next() call args
19644 * 1: r1 = &it ; <CHECKPOINT HERE>
19645 * 2: call bpf_iter_num_next ; this is iter_next() call
19646 * 3: if r0 == 0 goto done
19647 * 4: ... something useful here ...
19648 * 5: goto again ; another iteration
19649 * 6: done:
19650 * 7: r1 = &it
19651 * 8: call bpf_iter_num_destroy ; clean up iter state
19652 * 9: exit
19653 *
19654 * This is a typical loop. Let's assume that we have a prune point at 1:,
19655 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
19656 * again`, assuming other heuristics don't get in a way).
19657 *
19658 * When we first time come to 1:, let's say we have some state X. We proceed
19659 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
19660 * Now we come back to validate that forked ACTIVE state. We proceed through
19661 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
19662 * are converging. But the problem is that we don't know that yet, as this
19663 * convergence has to happen at iter_next() call site only. So if nothing is
19664 * done, at 1: verifier will use bounded loop logic and declare infinite
19665 * looping (and would be *technically* correct, if not for iterator's
19666 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
19667 * don't want that. So what we do in process_iter_next_call() when we go on
19668 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
19669 * a different iteration. So when we suspect an infinite loop, we additionally
19670 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
19671 * pretend we are not looping and wait for next iter_next() call.
19672 *
19673 * This only applies to ACTIVE state. In DRAINED state we don't expect to
19674 * loop, because that would actually mean infinite loop, as DRAINED state is
19675 * "sticky", and so we'll keep returning into the same instruction with the
19676 * same state (at least in one of possible code paths).
19677 *
19678 * This approach allows to keep infinite loop heuristic even in the face of
19679 * active iterator. E.g., C snippet below is and will be detected as
19680 * infinitely looping:
19681 *
19682 * struct bpf_iter_num it;
19683 * int *p, x;
19684 *
19685 * bpf_iter_num_new(&it, 0, 10);
19686 * while ((p = bpf_iter_num_next(&t))) {
19687 * x = p;
19688 * while (x--) {} // <<-- infinite loop here
19689 * }
19690 *
19691 */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)19692 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
19693 {
19694 struct bpf_reg_state *slot, *cur_slot;
19695 struct bpf_func_state *state;
19696 int i, fr;
19697
19698 for (fr = old->curframe; fr >= 0; fr--) {
19699 state = old->frame[fr];
19700 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
19701 if (state->stack[i].slot_type[0] != STACK_ITER)
19702 continue;
19703
19704 slot = &state->stack[i].spilled_ptr;
19705 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
19706 continue;
19707
19708 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
19709 if (cur_slot->iter.depth != slot->iter.depth)
19710 return true;
19711 }
19712 }
19713 return false;
19714 }
19715
is_state_visited(struct bpf_verifier_env * env,int insn_idx)19716 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
19717 {
19718 struct bpf_verifier_state_list *new_sl;
19719 struct bpf_verifier_state_list *sl;
19720 struct bpf_verifier_state *cur = env->cur_state, *new;
19721 bool force_new_state, add_new_state, loop;
19722 int n, err, states_cnt = 0;
19723 struct list_head *pos, *tmp, *head;
19724
19725 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) ||
19726 /* Avoid accumulating infinitely long jmp history */
19727 cur->jmp_history_cnt > 40;
19728
19729 /* bpf progs typically have pruning point every 4 instructions
19730 * http://vger.kernel.org/bpfconf2019.html#session-1
19731 * Do not add new state for future pruning if the verifier hasn't seen
19732 * at least 2 jumps and at least 8 instructions.
19733 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
19734 * In tests that amounts to up to 50% reduction into total verifier
19735 * memory consumption and 20% verifier time speedup.
19736 */
19737 add_new_state = force_new_state;
19738 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
19739 env->insn_processed - env->prev_insn_processed >= 8)
19740 add_new_state = true;
19741
19742 clean_live_states(env, insn_idx, cur);
19743
19744 loop = false;
19745 head = explored_state(env, insn_idx);
19746 list_for_each_safe(pos, tmp, head) {
19747 sl = container_of(pos, struct bpf_verifier_state_list, node);
19748 states_cnt++;
19749 if (sl->state.insn_idx != insn_idx)
19750 continue;
19751
19752 if (sl->state.branches) {
19753 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
19754
19755 if (frame->in_async_callback_fn &&
19756 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
19757 /* Different async_entry_cnt means that the verifier is
19758 * processing another entry into async callback.
19759 * Seeing the same state is not an indication of infinite
19760 * loop or infinite recursion.
19761 * But finding the same state doesn't mean that it's safe
19762 * to stop processing the current state. The previous state
19763 * hasn't yet reached bpf_exit, since state.branches > 0.
19764 * Checking in_async_callback_fn alone is not enough either.
19765 * Since the verifier still needs to catch infinite loops
19766 * inside async callbacks.
19767 */
19768 goto skip_inf_loop_check;
19769 }
19770 /* BPF open-coded iterators loop detection is special.
19771 * states_maybe_looping() logic is too simplistic in detecting
19772 * states that *might* be equivalent, because it doesn't know
19773 * about ID remapping, so don't even perform it.
19774 * See process_iter_next_call() and iter_active_depths_differ()
19775 * for overview of the logic. When current and one of parent
19776 * states are detected as equivalent, it's a good thing: we prove
19777 * convergence and can stop simulating further iterations.
19778 * It's safe to assume that iterator loop will finish, taking into
19779 * account iter_next() contract of eventually returning
19780 * sticky NULL result.
19781 *
19782 * Note, that states have to be compared exactly in this case because
19783 * read and precision marks might not be finalized inside the loop.
19784 * E.g. as in the program below:
19785 *
19786 * 1. r7 = -16
19787 * 2. r6 = bpf_get_prandom_u32()
19788 * 3. while (bpf_iter_num_next(&fp[-8])) {
19789 * 4. if (r6 != 42) {
19790 * 5. r7 = -32
19791 * 6. r6 = bpf_get_prandom_u32()
19792 * 7. continue
19793 * 8. }
19794 * 9. r0 = r10
19795 * 10. r0 += r7
19796 * 11. r8 = *(u64 *)(r0 + 0)
19797 * 12. r6 = bpf_get_prandom_u32()
19798 * 13. }
19799 *
19800 * Here verifier would first visit path 1-3, create a checkpoint at 3
19801 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
19802 * not have read or precision mark for r7 yet, thus inexact states
19803 * comparison would discard current state with r7=-32
19804 * => unsafe memory access at 11 would not be caught.
19805 */
19806 if (is_iter_next_insn(env, insn_idx)) {
19807 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19808 struct bpf_func_state *cur_frame;
19809 struct bpf_reg_state *iter_state, *iter_reg;
19810 int spi;
19811
19812 cur_frame = cur->frame[cur->curframe];
19813 /* btf_check_iter_kfuncs() enforces that
19814 * iter state pointer is always the first arg
19815 */
19816 iter_reg = &cur_frame->regs[BPF_REG_1];
19817 /* current state is valid due to states_equal(),
19818 * so we can assume valid iter and reg state,
19819 * no need for extra (re-)validations
19820 */
19821 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
19822 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
19823 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
19824 loop = true;
19825 goto hit;
19826 }
19827 }
19828 goto skip_inf_loop_check;
19829 }
19830 if (is_may_goto_insn_at(env, insn_idx)) {
19831 if (sl->state.may_goto_depth != cur->may_goto_depth &&
19832 states_equal(env, &sl->state, cur, RANGE_WITHIN)) {
19833 loop = true;
19834 goto hit;
19835 }
19836 }
19837 if (bpf_calls_callback(env, insn_idx)) {
19838 if (states_equal(env, &sl->state, cur, RANGE_WITHIN))
19839 goto hit;
19840 goto skip_inf_loop_check;
19841 }
19842 /* attempt to detect infinite loop to avoid unnecessary doomed work */
19843 if (states_maybe_looping(&sl->state, cur) &&
19844 states_equal(env, &sl->state, cur, EXACT) &&
19845 !iter_active_depths_differ(&sl->state, cur) &&
19846 sl->state.may_goto_depth == cur->may_goto_depth &&
19847 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
19848 verbose_linfo(env, insn_idx, "; ");
19849 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
19850 verbose(env, "cur state:");
19851 print_verifier_state(env, cur, cur->curframe, true);
19852 verbose(env, "old state:");
19853 print_verifier_state(env, &sl->state, cur->curframe, true);
19854 return -EINVAL;
19855 }
19856 /* if the verifier is processing a loop, avoid adding new state
19857 * too often, since different loop iterations have distinct
19858 * states and may not help future pruning.
19859 * This threshold shouldn't be too low to make sure that
19860 * a loop with large bound will be rejected quickly.
19861 * The most abusive loop will be:
19862 * r1 += 1
19863 * if r1 < 1000000 goto pc-2
19864 * 1M insn_procssed limit / 100 == 10k peak states.
19865 * This threshold shouldn't be too high either, since states
19866 * at the end of the loop are likely to be useful in pruning.
19867 */
19868 skip_inf_loop_check:
19869 if (!force_new_state &&
19870 env->jmps_processed - env->prev_jmps_processed < 20 &&
19871 env->insn_processed - env->prev_insn_processed < 100)
19872 add_new_state = false;
19873 goto miss;
19874 }
19875 /* See comments for mark_all_regs_read_and_precise() */
19876 loop = incomplete_read_marks(env, &sl->state);
19877 if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) {
19878 hit:
19879 sl->hit_cnt++;
19880
19881 /* if previous state reached the exit with precision and
19882 * current state is equivalent to it (except precision marks)
19883 * the precision needs to be propagated back in
19884 * the current state.
19885 */
19886 err = 0;
19887 if (is_jmp_point(env, env->insn_idx))
19888 err = push_jmp_history(env, cur, 0, 0);
19889 err = err ? : propagate_precision(env, &sl->state, cur, NULL);
19890 if (err)
19891 return err;
19892 /* When processing iterator based loops above propagate_liveness and
19893 * propagate_precision calls are not sufficient to transfer all relevant
19894 * read and precision marks. E.g. consider the following case:
19895 *
19896 * .-> A --. Assume the states are visited in the order A, B, C.
19897 * | | | Assume that state B reaches a state equivalent to state A.
19898 * | v v At this point, state C is not processed yet, so state A
19899 * '-- B C has not received any read or precision marks from C.
19900 * Thus, marks propagated from A to B are incomplete.
19901 *
19902 * The verifier mitigates this by performing the following steps:
19903 *
19904 * - Prior to the main verification pass, strongly connected components
19905 * (SCCs) are computed over the program's control flow graph,
19906 * intraprocedurally.
19907 *
19908 * - During the main verification pass, `maybe_enter_scc()` checks
19909 * whether the current verifier state is entering an SCC. If so, an
19910 * instance of a `bpf_scc_visit` object is created, and the state
19911 * entering the SCC is recorded as the entry state.
19912 *
19913 * - This instance is associated not with the SCC itself, but with a
19914 * `bpf_scc_callchain`: a tuple consisting of the call sites leading to
19915 * the SCC and the SCC id. See `compute_scc_callchain()`.
19916 *
19917 * - When a verification path encounters a `states_equal(...,
19918 * RANGE_WITHIN)` condition, there exists a call chain describing the
19919 * current state and a corresponding `bpf_scc_visit` instance. A copy
19920 * of the current state is created and added to
19921 * `bpf_scc_visit->backedges`.
19922 *
19923 * - When a verification path terminates, `maybe_exit_scc()` is called
19924 * from `update_branch_counts()`. For states with `branches == 0`, it
19925 * checks whether the state is the entry state of any `bpf_scc_visit`
19926 * instance. If it is, this indicates that all paths originating from
19927 * this SCC visit have been explored. `propagate_backedges()` is then
19928 * called, which propagates read and precision marks through the
19929 * backedges until a fixed point is reached.
19930 * (In the earlier example, this would propagate marks from A to B,
19931 * from C to A, and then again from A to B.)
19932 *
19933 * A note on callchains
19934 * --------------------
19935 *
19936 * Consider the following example:
19937 *
19938 * void foo() { loop { ... SCC#1 ... } }
19939 * void main() {
19940 * A: foo();
19941 * B: ...
19942 * C: foo();
19943 * }
19944 *
19945 * Here, there are two distinct callchains leading to SCC#1:
19946 * - (A, SCC#1)
19947 * - (C, SCC#1)
19948 *
19949 * Each callchain identifies a separate `bpf_scc_visit` instance that
19950 * accumulates backedge states. The `propagate_{liveness,precision}()`
19951 * functions traverse the parent state of each backedge state, which
19952 * means these parent states must remain valid (i.e., not freed) while
19953 * the corresponding `bpf_scc_visit` instance exists.
19954 *
19955 * Associating `bpf_scc_visit` instances directly with SCCs instead of
19956 * callchains would break this invariant:
19957 * - States explored during `C: foo()` would contribute backedges to
19958 * SCC#1, but SCC#1 would only be exited once the exploration of
19959 * `A: foo()` completes.
19960 * - By that time, the states explored between `A: foo()` and `C: foo()`
19961 * (i.e., `B: ...`) may have already been freed, causing the parent
19962 * links for states from `C: foo()` to become invalid.
19963 */
19964 if (loop) {
19965 struct bpf_scc_backedge *backedge;
19966
19967 backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT);
19968 if (!backedge)
19969 return -ENOMEM;
19970 err = copy_verifier_state(&backedge->state, cur);
19971 backedge->state.equal_state = &sl->state;
19972 backedge->state.insn_idx = insn_idx;
19973 err = err ?: add_scc_backedge(env, &sl->state, backedge);
19974 if (err) {
19975 free_verifier_state(&backedge->state, false);
19976 kfree(backedge);
19977 return err;
19978 }
19979 }
19980 return 1;
19981 }
19982 miss:
19983 /* when new state is not going to be added do not increase miss count.
19984 * Otherwise several loop iterations will remove the state
19985 * recorded earlier. The goal of these heuristics is to have
19986 * states from some iterations of the loop (some in the beginning
19987 * and some at the end) to help pruning.
19988 */
19989 if (add_new_state)
19990 sl->miss_cnt++;
19991 /* heuristic to determine whether this state is beneficial
19992 * to keep checking from state equivalence point of view.
19993 * Higher numbers increase max_states_per_insn and verification time,
19994 * but do not meaningfully decrease insn_processed.
19995 * 'n' controls how many times state could miss before eviction.
19996 * Use bigger 'n' for checkpoints because evicting checkpoint states
19997 * too early would hinder iterator convergence.
19998 */
19999 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
20000 if (sl->miss_cnt > sl->hit_cnt * n + n) {
20001 /* the state is unlikely to be useful. Remove it to
20002 * speed up verification
20003 */
20004 sl->in_free_list = true;
20005 list_del(&sl->node);
20006 list_add(&sl->node, &env->free_list);
20007 env->free_list_size++;
20008 env->explored_states_size--;
20009 maybe_free_verifier_state(env, sl);
20010 }
20011 }
20012
20013 if (env->max_states_per_insn < states_cnt)
20014 env->max_states_per_insn = states_cnt;
20015
20016 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
20017 return 0;
20018
20019 if (!add_new_state)
20020 return 0;
20021
20022 /* There were no equivalent states, remember the current one.
20023 * Technically the current state is not proven to be safe yet,
20024 * but it will either reach outer most bpf_exit (which means it's safe)
20025 * or it will be rejected. When there are no loops the verifier won't be
20026 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
20027 * again on the way to bpf_exit.
20028 * When looping the sl->state.branches will be > 0 and this state
20029 * will not be considered for equivalence until branches == 0.
20030 */
20031 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT);
20032 if (!new_sl)
20033 return -ENOMEM;
20034 env->total_states++;
20035 env->explored_states_size++;
20036 update_peak_states(env);
20037 env->prev_jmps_processed = env->jmps_processed;
20038 env->prev_insn_processed = env->insn_processed;
20039
20040 /* forget precise markings we inherited, see __mark_chain_precision */
20041 if (env->bpf_capable)
20042 mark_all_scalars_imprecise(env, cur);
20043
20044 /* add new state to the head of linked list */
20045 new = &new_sl->state;
20046 err = copy_verifier_state(new, cur);
20047 if (err) {
20048 free_verifier_state(new, false);
20049 kfree(new_sl);
20050 return err;
20051 }
20052 new->insn_idx = insn_idx;
20053 verifier_bug_if(new->branches != 1, env,
20054 "%s:branches_to_explore=%d insn %d",
20055 __func__, new->branches, insn_idx);
20056 err = maybe_enter_scc(env, new);
20057 if (err) {
20058 free_verifier_state(new, false);
20059 kfree(new_sl);
20060 return err;
20061 }
20062
20063 cur->parent = new;
20064 cur->first_insn_idx = insn_idx;
20065 cur->dfs_depth = new->dfs_depth + 1;
20066 clear_jmp_history(cur);
20067 list_add(&new_sl->node, head);
20068 return 0;
20069 }
20070
20071 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)20072 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
20073 {
20074 switch (base_type(type)) {
20075 case PTR_TO_CTX:
20076 case PTR_TO_SOCKET:
20077 case PTR_TO_SOCK_COMMON:
20078 case PTR_TO_TCP_SOCK:
20079 case PTR_TO_XDP_SOCK:
20080 case PTR_TO_BTF_ID:
20081 case PTR_TO_ARENA:
20082 return false;
20083 default:
20084 return true;
20085 }
20086 }
20087
20088 /* If an instruction was previously used with particular pointer types, then we
20089 * need to be careful to avoid cases such as the below, where it may be ok
20090 * for one branch accessing the pointer, but not ok for the other branch:
20091 *
20092 * R1 = sock_ptr
20093 * goto X;
20094 * ...
20095 * R1 = some_other_valid_ptr;
20096 * goto X;
20097 * ...
20098 * R2 = *(u32 *)(R1 + 0);
20099 */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)20100 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
20101 {
20102 return src != prev && (!reg_type_mismatch_ok(src) ||
20103 !reg_type_mismatch_ok(prev));
20104 }
20105
is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)20106 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type)
20107 {
20108 switch (base_type(type)) {
20109 case PTR_TO_MEM:
20110 case PTR_TO_BTF_ID:
20111 return true;
20112 default:
20113 return false;
20114 }
20115 }
20116
is_ptr_to_mem(enum bpf_reg_type type)20117 static bool is_ptr_to_mem(enum bpf_reg_type type)
20118 {
20119 return base_type(type) == PTR_TO_MEM;
20120 }
20121
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_mismatch)20122 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
20123 bool allow_trust_mismatch)
20124 {
20125 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
20126 enum bpf_reg_type merged_type;
20127
20128 if (*prev_type == NOT_INIT) {
20129 /* Saw a valid insn
20130 * dst_reg = *(u32 *)(src_reg + off)
20131 * save type to validate intersecting paths
20132 */
20133 *prev_type = type;
20134 } else if (reg_type_mismatch(type, *prev_type)) {
20135 /* Abuser program is trying to use the same insn
20136 * dst_reg = *(u32*) (src_reg + off)
20137 * with different pointer types:
20138 * src_reg == ctx in one branch and
20139 * src_reg == stack|map in some other branch.
20140 * Reject it.
20141 */
20142 if (allow_trust_mismatch &&
20143 is_ptr_to_mem_or_btf_id(type) &&
20144 is_ptr_to_mem_or_btf_id(*prev_type)) {
20145 /*
20146 * Have to support a use case when one path through
20147 * the program yields TRUSTED pointer while another
20148 * is UNTRUSTED. Fallback to UNTRUSTED to generate
20149 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
20150 * Same behavior of MEM_RDONLY flag.
20151 */
20152 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type))
20153 merged_type = PTR_TO_MEM;
20154 else
20155 merged_type = PTR_TO_BTF_ID;
20156 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED))
20157 merged_type |= PTR_UNTRUSTED;
20158 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY))
20159 merged_type |= MEM_RDONLY;
20160 *prev_type = merged_type;
20161 } else {
20162 verbose(env, "same insn cannot be used with different pointers\n");
20163 return -EINVAL;
20164 }
20165 }
20166
20167 return 0;
20168 }
20169
20170 enum {
20171 PROCESS_BPF_EXIT = 1
20172 };
20173
process_bpf_exit_full(struct bpf_verifier_env * env,bool * do_print_state,bool exception_exit)20174 static int process_bpf_exit_full(struct bpf_verifier_env *env,
20175 bool *do_print_state,
20176 bool exception_exit)
20177 {
20178 /* We must do check_reference_leak here before
20179 * prepare_func_exit to handle the case when
20180 * state->curframe > 0, it may be a callback function,
20181 * for which reference_state must match caller reference
20182 * state when it exits.
20183 */
20184 int err = check_resource_leak(env, exception_exit,
20185 !env->cur_state->curframe,
20186 "BPF_EXIT instruction in main prog");
20187 if (err)
20188 return err;
20189
20190 /* The side effect of the prepare_func_exit which is
20191 * being skipped is that it frees bpf_func_state.
20192 * Typically, process_bpf_exit will only be hit with
20193 * outermost exit. copy_verifier_state in pop_stack will
20194 * handle freeing of any extra bpf_func_state left over
20195 * from not processing all nested function exits. We
20196 * also skip return code checks as they are not needed
20197 * for exceptional exits.
20198 */
20199 if (exception_exit)
20200 return PROCESS_BPF_EXIT;
20201
20202 if (env->cur_state->curframe) {
20203 /* exit from nested function */
20204 err = prepare_func_exit(env, &env->insn_idx);
20205 if (err)
20206 return err;
20207 *do_print_state = true;
20208 return 0;
20209 }
20210
20211 err = check_return_code(env, BPF_REG_0, "R0");
20212 if (err)
20213 return err;
20214 return PROCESS_BPF_EXIT;
20215 }
20216
indirect_jump_min_max_index(struct bpf_verifier_env * env,int regno,struct bpf_map * map,u32 * pmin_index,u32 * pmax_index)20217 static int indirect_jump_min_max_index(struct bpf_verifier_env *env,
20218 int regno,
20219 struct bpf_map *map,
20220 u32 *pmin_index, u32 *pmax_index)
20221 {
20222 struct bpf_reg_state *reg = reg_state(env, regno);
20223 u64 min_index, max_index;
20224 const u32 size = 8;
20225
20226 if (check_add_overflow(reg->umin_value, reg->off, &min_index) ||
20227 (min_index > (u64) U32_MAX * size)) {
20228 verbose(env, "the sum of R%u umin_value %llu and off %u is too big\n",
20229 regno, reg->umin_value, reg->off);
20230 return -ERANGE;
20231 }
20232 if (check_add_overflow(reg->umax_value, reg->off, &max_index) ||
20233 (max_index > (u64) U32_MAX * size)) {
20234 verbose(env, "the sum of R%u umax_value %llu and off %u is too big\n",
20235 regno, reg->umax_value, reg->off);
20236 return -ERANGE;
20237 }
20238
20239 min_index /= size;
20240 max_index /= size;
20241
20242 if (max_index >= map->max_entries) {
20243 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n",
20244 regno, min_index, max_index, map->max_entries);
20245 return -EINVAL;
20246 }
20247
20248 *pmin_index = min_index;
20249 *pmax_index = max_index;
20250 return 0;
20251 }
20252
20253 /* gotox *dst_reg */
check_indirect_jump(struct bpf_verifier_env * env,struct bpf_insn * insn)20254 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn)
20255 {
20256 struct bpf_verifier_state *other_branch;
20257 struct bpf_reg_state *dst_reg;
20258 struct bpf_map *map;
20259 u32 min_index, max_index;
20260 int err = 0;
20261 int n;
20262 int i;
20263
20264 dst_reg = reg_state(env, insn->dst_reg);
20265 if (dst_reg->type != PTR_TO_INSN) {
20266 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n",
20267 insn->dst_reg, reg_type_str(env, dst_reg->type));
20268 return -EINVAL;
20269 }
20270
20271 map = dst_reg->map_ptr;
20272 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg))
20273 return -EFAULT;
20274
20275 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env,
20276 "R%d has incorrect map type %d", insn->dst_reg, map->map_type))
20277 return -EFAULT;
20278
20279 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index);
20280 if (err)
20281 return err;
20282
20283 /* Ensure that the buffer is large enough */
20284 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) {
20285 env->gotox_tmp_buf = iarray_realloc(env->gotox_tmp_buf,
20286 max_index - min_index + 1);
20287 if (!env->gotox_tmp_buf)
20288 return -ENOMEM;
20289 }
20290
20291 n = copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items);
20292 if (n < 0)
20293 return n;
20294 if (n == 0) {
20295 verbose(env, "register R%d doesn't point to any offset in map id=%d\n",
20296 insn->dst_reg, map->id);
20297 return -EINVAL;
20298 }
20299
20300 for (i = 0; i < n - 1; i++) {
20301 other_branch = push_stack(env, env->gotox_tmp_buf->items[i],
20302 env->insn_idx, env->cur_state->speculative);
20303 if (IS_ERR(other_branch))
20304 return PTR_ERR(other_branch);
20305 }
20306 env->insn_idx = env->gotox_tmp_buf->items[n-1];
20307 return 0;
20308 }
20309
do_check_insn(struct bpf_verifier_env * env,bool * do_print_state)20310 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
20311 {
20312 int err;
20313 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
20314 u8 class = BPF_CLASS(insn->code);
20315
20316 if (class == BPF_ALU || class == BPF_ALU64) {
20317 err = check_alu_op(env, insn);
20318 if (err)
20319 return err;
20320
20321 } else if (class == BPF_LDX) {
20322 bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX;
20323
20324 /* Check for reserved fields is already done in
20325 * resolve_pseudo_ldimm64().
20326 */
20327 err = check_load_mem(env, insn, false, is_ldsx, true, "ldx");
20328 if (err)
20329 return err;
20330 } else if (class == BPF_STX) {
20331 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
20332 err = check_atomic(env, insn);
20333 if (err)
20334 return err;
20335 env->insn_idx++;
20336 return 0;
20337 }
20338
20339 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
20340 verbose(env, "BPF_STX uses reserved fields\n");
20341 return -EINVAL;
20342 }
20343
20344 err = check_store_reg(env, insn, false);
20345 if (err)
20346 return err;
20347 } else if (class == BPF_ST) {
20348 enum bpf_reg_type dst_reg_type;
20349
20350 if (BPF_MODE(insn->code) != BPF_MEM ||
20351 insn->src_reg != BPF_REG_0) {
20352 verbose(env, "BPF_ST uses reserved fields\n");
20353 return -EINVAL;
20354 }
20355 /* check src operand */
20356 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
20357 if (err)
20358 return err;
20359
20360 dst_reg_type = cur_regs(env)[insn->dst_reg].type;
20361
20362 /* check that memory (dst_reg + off) is writeable */
20363 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
20364 insn->off, BPF_SIZE(insn->code),
20365 BPF_WRITE, -1, false, false);
20366 if (err)
20367 return err;
20368
20369 err = save_aux_ptr_type(env, dst_reg_type, false);
20370 if (err)
20371 return err;
20372 } else if (class == BPF_JMP || class == BPF_JMP32) {
20373 u8 opcode = BPF_OP(insn->code);
20374
20375 env->jmps_processed++;
20376 if (opcode == BPF_CALL) {
20377 if (BPF_SRC(insn->code) != BPF_K ||
20378 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL &&
20379 insn->off != 0) ||
20380 (insn->src_reg != BPF_REG_0 &&
20381 insn->src_reg != BPF_PSEUDO_CALL &&
20382 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
20383 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) {
20384 verbose(env, "BPF_CALL uses reserved fields\n");
20385 return -EINVAL;
20386 }
20387
20388 if (env->cur_state->active_locks) {
20389 if ((insn->src_reg == BPF_REG_0 &&
20390 insn->imm != BPF_FUNC_spin_unlock) ||
20391 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
20392 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) {
20393 verbose(env,
20394 "function calls are not allowed while holding a lock\n");
20395 return -EINVAL;
20396 }
20397 }
20398 if (insn->src_reg == BPF_PSEUDO_CALL) {
20399 err = check_func_call(env, insn, &env->insn_idx);
20400 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
20401 err = check_kfunc_call(env, insn, &env->insn_idx);
20402 if (!err && is_bpf_throw_kfunc(insn))
20403 return process_bpf_exit_full(env, do_print_state, true);
20404 } else {
20405 err = check_helper_call(env, insn, &env->insn_idx);
20406 }
20407 if (err)
20408 return err;
20409
20410 mark_reg_scratched(env, BPF_REG_0);
20411 } else if (opcode == BPF_JA) {
20412 if (BPF_SRC(insn->code) == BPF_X) {
20413 if (insn->src_reg != BPF_REG_0 ||
20414 insn->imm != 0 || insn->off != 0) {
20415 verbose(env, "BPF_JA|BPF_X uses reserved fields\n");
20416 return -EINVAL;
20417 }
20418 return check_indirect_jump(env, insn);
20419 }
20420
20421 if (BPF_SRC(insn->code) != BPF_K ||
20422 insn->src_reg != BPF_REG_0 ||
20423 insn->dst_reg != BPF_REG_0 ||
20424 (class == BPF_JMP && insn->imm != 0) ||
20425 (class == BPF_JMP32 && insn->off != 0)) {
20426 verbose(env, "BPF_JA uses reserved fields\n");
20427 return -EINVAL;
20428 }
20429
20430 if (class == BPF_JMP)
20431 env->insn_idx += insn->off + 1;
20432 else
20433 env->insn_idx += insn->imm + 1;
20434 return 0;
20435 } else if (opcode == BPF_EXIT) {
20436 if (BPF_SRC(insn->code) != BPF_K ||
20437 insn->imm != 0 ||
20438 insn->src_reg != BPF_REG_0 ||
20439 insn->dst_reg != BPF_REG_0 ||
20440 class == BPF_JMP32) {
20441 verbose(env, "BPF_EXIT uses reserved fields\n");
20442 return -EINVAL;
20443 }
20444 return process_bpf_exit_full(env, do_print_state, false);
20445 } else {
20446 err = check_cond_jmp_op(env, insn, &env->insn_idx);
20447 if (err)
20448 return err;
20449 }
20450 } else if (class == BPF_LD) {
20451 u8 mode = BPF_MODE(insn->code);
20452
20453 if (mode == BPF_ABS || mode == BPF_IND) {
20454 err = check_ld_abs(env, insn);
20455 if (err)
20456 return err;
20457
20458 } else if (mode == BPF_IMM) {
20459 err = check_ld_imm(env, insn);
20460 if (err)
20461 return err;
20462
20463 env->insn_idx++;
20464 sanitize_mark_insn_seen(env);
20465 } else {
20466 verbose(env, "invalid BPF_LD mode\n");
20467 return -EINVAL;
20468 }
20469 } else {
20470 verbose(env, "unknown insn class %d\n", class);
20471 return -EINVAL;
20472 }
20473
20474 env->insn_idx++;
20475 return 0;
20476 }
20477
do_check(struct bpf_verifier_env * env)20478 static int do_check(struct bpf_verifier_env *env)
20479 {
20480 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
20481 struct bpf_verifier_state *state = env->cur_state;
20482 struct bpf_insn *insns = env->prog->insnsi;
20483 int insn_cnt = env->prog->len;
20484 bool do_print_state = false;
20485 int prev_insn_idx = -1;
20486
20487 for (;;) {
20488 struct bpf_insn *insn;
20489 struct bpf_insn_aux_data *insn_aux;
20490 int err, marks_err;
20491
20492 /* reset current history entry on each new instruction */
20493 env->cur_hist_ent = NULL;
20494
20495 env->prev_insn_idx = prev_insn_idx;
20496 if (env->insn_idx >= insn_cnt) {
20497 verbose(env, "invalid insn idx %d insn_cnt %d\n",
20498 env->insn_idx, insn_cnt);
20499 return -EFAULT;
20500 }
20501
20502 insn = &insns[env->insn_idx];
20503 insn_aux = &env->insn_aux_data[env->insn_idx];
20504
20505 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
20506 verbose(env,
20507 "BPF program is too large. Processed %d insn\n",
20508 env->insn_processed);
20509 return -E2BIG;
20510 }
20511
20512 state->last_insn_idx = env->prev_insn_idx;
20513 state->insn_idx = env->insn_idx;
20514
20515 if (is_prune_point(env, env->insn_idx)) {
20516 err = is_state_visited(env, env->insn_idx);
20517 if (err < 0)
20518 return err;
20519 if (err == 1) {
20520 /* found equivalent state, can prune the search */
20521 if (env->log.level & BPF_LOG_LEVEL) {
20522 if (do_print_state)
20523 verbose(env, "\nfrom %d to %d%s: safe\n",
20524 env->prev_insn_idx, env->insn_idx,
20525 env->cur_state->speculative ?
20526 " (speculative execution)" : "");
20527 else
20528 verbose(env, "%d: safe\n", env->insn_idx);
20529 }
20530 goto process_bpf_exit;
20531 }
20532 }
20533
20534 if (is_jmp_point(env, env->insn_idx)) {
20535 err = push_jmp_history(env, state, 0, 0);
20536 if (err)
20537 return err;
20538 }
20539
20540 if (signal_pending(current))
20541 return -EAGAIN;
20542
20543 if (need_resched())
20544 cond_resched();
20545
20546 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
20547 verbose(env, "\nfrom %d to %d%s:",
20548 env->prev_insn_idx, env->insn_idx,
20549 env->cur_state->speculative ?
20550 " (speculative execution)" : "");
20551 print_verifier_state(env, state, state->curframe, true);
20552 do_print_state = false;
20553 }
20554
20555 if (env->log.level & BPF_LOG_LEVEL) {
20556 if (verifier_state_scratched(env))
20557 print_insn_state(env, state, state->curframe);
20558
20559 verbose_linfo(env, env->insn_idx, "; ");
20560 env->prev_log_pos = env->log.end_pos;
20561 verbose(env, "%d: ", env->insn_idx);
20562 verbose_insn(env, insn);
20563 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
20564 env->prev_log_pos = env->log.end_pos;
20565 }
20566
20567 if (bpf_prog_is_offloaded(env->prog->aux)) {
20568 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
20569 env->prev_insn_idx);
20570 if (err)
20571 return err;
20572 }
20573
20574 sanitize_mark_insn_seen(env);
20575 prev_insn_idx = env->insn_idx;
20576
20577 /* Reduce verification complexity by stopping speculative path
20578 * verification when a nospec is encountered.
20579 */
20580 if (state->speculative && insn_aux->nospec)
20581 goto process_bpf_exit;
20582
20583 err = bpf_reset_stack_write_marks(env, env->insn_idx);
20584 if (err)
20585 return err;
20586 err = do_check_insn(env, &do_print_state);
20587 if (err >= 0 || error_recoverable_with_nospec(err)) {
20588 marks_err = bpf_commit_stack_write_marks(env);
20589 if (marks_err)
20590 return marks_err;
20591 }
20592 if (error_recoverable_with_nospec(err) && state->speculative) {
20593 /* Prevent this speculative path from ever reaching the
20594 * insn that would have been unsafe to execute.
20595 */
20596 insn_aux->nospec = true;
20597 /* If it was an ADD/SUB insn, potentially remove any
20598 * markings for alu sanitization.
20599 */
20600 insn_aux->alu_state = 0;
20601 goto process_bpf_exit;
20602 } else if (err < 0) {
20603 return err;
20604 } else if (err == PROCESS_BPF_EXIT) {
20605 goto process_bpf_exit;
20606 }
20607 WARN_ON_ONCE(err);
20608
20609 if (state->speculative && insn_aux->nospec_result) {
20610 /* If we are on a path that performed a jump-op, this
20611 * may skip a nospec patched-in after the jump. This can
20612 * currently never happen because nospec_result is only
20613 * used for the write-ops
20614 * `*(size*)(dst_reg+off)=src_reg|imm32` which must
20615 * never skip the following insn. Still, add a warning
20616 * to document this in case nospec_result is used
20617 * elsewhere in the future.
20618 *
20619 * All non-branch instructions have a single
20620 * fall-through edge. For these, nospec_result should
20621 * already work.
20622 */
20623 if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP ||
20624 BPF_CLASS(insn->code) == BPF_JMP32, env,
20625 "speculation barrier after jump instruction may not have the desired effect"))
20626 return -EFAULT;
20627 process_bpf_exit:
20628 mark_verifier_state_scratched(env);
20629 err = update_branch_counts(env, env->cur_state);
20630 if (err)
20631 return err;
20632 err = bpf_update_live_stack(env);
20633 if (err)
20634 return err;
20635 err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
20636 pop_log);
20637 if (err < 0) {
20638 if (err != -ENOENT)
20639 return err;
20640 break;
20641 } else {
20642 do_print_state = true;
20643 continue;
20644 }
20645 }
20646 }
20647
20648 return 0;
20649 }
20650
find_btf_percpu_datasec(struct btf * btf)20651 static int find_btf_percpu_datasec(struct btf *btf)
20652 {
20653 const struct btf_type *t;
20654 const char *tname;
20655 int i, n;
20656
20657 /*
20658 * Both vmlinux and module each have their own ".data..percpu"
20659 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
20660 * types to look at only module's own BTF types.
20661 */
20662 n = btf_nr_types(btf);
20663 if (btf_is_module(btf))
20664 i = btf_nr_types(btf_vmlinux);
20665 else
20666 i = 1;
20667
20668 for(; i < n; i++) {
20669 t = btf_type_by_id(btf, i);
20670 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
20671 continue;
20672
20673 tname = btf_name_by_offset(btf, t->name_off);
20674 if (!strcmp(tname, ".data..percpu"))
20675 return i;
20676 }
20677
20678 return -ENOENT;
20679 }
20680
20681 /*
20682 * Add btf to the used_btfs array and return the index. (If the btf was
20683 * already added, then just return the index.) Upon successful insertion
20684 * increase btf refcnt, and, if present, also refcount the corresponding
20685 * kernel module.
20686 */
__add_used_btf(struct bpf_verifier_env * env,struct btf * btf)20687 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf)
20688 {
20689 struct btf_mod_pair *btf_mod;
20690 int i;
20691
20692 /* check whether we recorded this BTF (and maybe module) already */
20693 for (i = 0; i < env->used_btf_cnt; i++)
20694 if (env->used_btfs[i].btf == btf)
20695 return i;
20696
20697 if (env->used_btf_cnt >= MAX_USED_BTFS) {
20698 verbose(env, "The total number of btfs per program has reached the limit of %u\n",
20699 MAX_USED_BTFS);
20700 return -E2BIG;
20701 }
20702
20703 btf_get(btf);
20704
20705 btf_mod = &env->used_btfs[env->used_btf_cnt];
20706 btf_mod->btf = btf;
20707 btf_mod->module = NULL;
20708
20709 /* if we reference variables from kernel module, bump its refcount */
20710 if (btf_is_module(btf)) {
20711 btf_mod->module = btf_try_get_module(btf);
20712 if (!btf_mod->module) {
20713 btf_put(btf);
20714 return -ENXIO;
20715 }
20716 }
20717
20718 return env->used_btf_cnt++;
20719 }
20720
20721 /* 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)20722 static int __check_pseudo_btf_id(struct bpf_verifier_env *env,
20723 struct bpf_insn *insn,
20724 struct bpf_insn_aux_data *aux,
20725 struct btf *btf)
20726 {
20727 const struct btf_var_secinfo *vsi;
20728 const struct btf_type *datasec;
20729 const struct btf_type *t;
20730 const char *sym_name;
20731 bool percpu = false;
20732 u32 type, id = insn->imm;
20733 s32 datasec_id;
20734 u64 addr;
20735 int i;
20736
20737 t = btf_type_by_id(btf, id);
20738 if (!t) {
20739 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
20740 return -ENOENT;
20741 }
20742
20743 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
20744 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
20745 return -EINVAL;
20746 }
20747
20748 sym_name = btf_name_by_offset(btf, t->name_off);
20749 addr = kallsyms_lookup_name(sym_name);
20750 if (!addr) {
20751 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
20752 sym_name);
20753 return -ENOENT;
20754 }
20755 insn[0].imm = (u32)addr;
20756 insn[1].imm = addr >> 32;
20757
20758 if (btf_type_is_func(t)) {
20759 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20760 aux->btf_var.mem_size = 0;
20761 return 0;
20762 }
20763
20764 datasec_id = find_btf_percpu_datasec(btf);
20765 if (datasec_id > 0) {
20766 datasec = btf_type_by_id(btf, datasec_id);
20767 for_each_vsi(i, datasec, vsi) {
20768 if (vsi->type == id) {
20769 percpu = true;
20770 break;
20771 }
20772 }
20773 }
20774
20775 type = t->type;
20776 t = btf_type_skip_modifiers(btf, type, NULL);
20777 if (percpu) {
20778 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
20779 aux->btf_var.btf = btf;
20780 aux->btf_var.btf_id = type;
20781 } else if (!btf_type_is_struct(t)) {
20782 const struct btf_type *ret;
20783 const char *tname;
20784 u32 tsize;
20785
20786 /* resolve the type size of ksym. */
20787 ret = btf_resolve_size(btf, t, &tsize);
20788 if (IS_ERR(ret)) {
20789 tname = btf_name_by_offset(btf, t->name_off);
20790 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
20791 tname, PTR_ERR(ret));
20792 return -EINVAL;
20793 }
20794 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
20795 aux->btf_var.mem_size = tsize;
20796 } else {
20797 aux->btf_var.reg_type = PTR_TO_BTF_ID;
20798 aux->btf_var.btf = btf;
20799 aux->btf_var.btf_id = type;
20800 }
20801
20802 return 0;
20803 }
20804
check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux)20805 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
20806 struct bpf_insn *insn,
20807 struct bpf_insn_aux_data *aux)
20808 {
20809 struct btf *btf;
20810 int btf_fd;
20811 int err;
20812
20813 btf_fd = insn[1].imm;
20814 if (btf_fd) {
20815 CLASS(fd, f)(btf_fd);
20816
20817 btf = __btf_get_by_fd(f);
20818 if (IS_ERR(btf)) {
20819 verbose(env, "invalid module BTF object FD specified.\n");
20820 return -EINVAL;
20821 }
20822 } else {
20823 if (!btf_vmlinux) {
20824 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
20825 return -EINVAL;
20826 }
20827 btf = btf_vmlinux;
20828 }
20829
20830 err = __check_pseudo_btf_id(env, insn, aux, btf);
20831 if (err)
20832 return err;
20833
20834 err = __add_used_btf(env, btf);
20835 if (err < 0)
20836 return err;
20837 return 0;
20838 }
20839
is_tracing_prog_type(enum bpf_prog_type type)20840 static bool is_tracing_prog_type(enum bpf_prog_type type)
20841 {
20842 switch (type) {
20843 case BPF_PROG_TYPE_KPROBE:
20844 case BPF_PROG_TYPE_TRACEPOINT:
20845 case BPF_PROG_TYPE_PERF_EVENT:
20846 case BPF_PROG_TYPE_RAW_TRACEPOINT:
20847 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
20848 return true;
20849 default:
20850 return false;
20851 }
20852 }
20853
bpf_map_is_cgroup_storage(struct bpf_map * map)20854 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
20855 {
20856 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
20857 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
20858 }
20859
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)20860 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
20861 struct bpf_map *map,
20862 struct bpf_prog *prog)
20863
20864 {
20865 enum bpf_prog_type prog_type = resolve_prog_type(prog);
20866
20867 if (map->excl_prog_sha &&
20868 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) {
20869 verbose(env, "program's hash doesn't match map's excl_prog_hash\n");
20870 return -EACCES;
20871 }
20872
20873 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
20874 btf_record_has_field(map->record, BPF_RB_ROOT)) {
20875 if (is_tracing_prog_type(prog_type)) {
20876 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
20877 return -EINVAL;
20878 }
20879 }
20880
20881 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) {
20882 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
20883 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
20884 return -EINVAL;
20885 }
20886
20887 if (is_tracing_prog_type(prog_type)) {
20888 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
20889 return -EINVAL;
20890 }
20891 }
20892
20893 if (btf_record_has_field(map->record, BPF_TIMER)) {
20894 if (is_tracing_prog_type(prog_type)) {
20895 verbose(env, "tracing progs cannot use bpf_timer yet\n");
20896 return -EINVAL;
20897 }
20898 }
20899
20900 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) {
20901 if (is_tracing_prog_type(prog_type)) {
20902 verbose(env, "tracing progs cannot use bpf_wq yet\n");
20903 return -EINVAL;
20904 }
20905 }
20906
20907 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
20908 !bpf_offload_prog_map_match(prog, map)) {
20909 verbose(env, "offload device mismatch between prog and map\n");
20910 return -EINVAL;
20911 }
20912
20913 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
20914 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
20915 return -EINVAL;
20916 }
20917
20918 if (prog->sleepable)
20919 switch (map->map_type) {
20920 case BPF_MAP_TYPE_HASH:
20921 case BPF_MAP_TYPE_LRU_HASH:
20922 case BPF_MAP_TYPE_ARRAY:
20923 case BPF_MAP_TYPE_PERCPU_HASH:
20924 case BPF_MAP_TYPE_PERCPU_ARRAY:
20925 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
20926 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
20927 case BPF_MAP_TYPE_HASH_OF_MAPS:
20928 case BPF_MAP_TYPE_RINGBUF:
20929 case BPF_MAP_TYPE_USER_RINGBUF:
20930 case BPF_MAP_TYPE_INODE_STORAGE:
20931 case BPF_MAP_TYPE_SK_STORAGE:
20932 case BPF_MAP_TYPE_TASK_STORAGE:
20933 case BPF_MAP_TYPE_CGRP_STORAGE:
20934 case BPF_MAP_TYPE_QUEUE:
20935 case BPF_MAP_TYPE_STACK:
20936 case BPF_MAP_TYPE_ARENA:
20937 case BPF_MAP_TYPE_INSN_ARRAY:
20938 break;
20939 default:
20940 verbose(env,
20941 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
20942 return -EINVAL;
20943 }
20944
20945 if (bpf_map_is_cgroup_storage(map) &&
20946 bpf_cgroup_storage_assign(env->prog->aux, map)) {
20947 verbose(env, "only one cgroup storage of each type is allowed\n");
20948 return -EBUSY;
20949 }
20950
20951 if (map->map_type == BPF_MAP_TYPE_ARENA) {
20952 if (env->prog->aux->arena) {
20953 verbose(env, "Only one arena per program\n");
20954 return -EBUSY;
20955 }
20956 if (!env->allow_ptr_leaks || !env->bpf_capable) {
20957 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n");
20958 return -EPERM;
20959 }
20960 if (!env->prog->jit_requested) {
20961 verbose(env, "JIT is required to use arena\n");
20962 return -EOPNOTSUPP;
20963 }
20964 if (!bpf_jit_supports_arena()) {
20965 verbose(env, "JIT doesn't support arena\n");
20966 return -EOPNOTSUPP;
20967 }
20968 env->prog->aux->arena = (void *)map;
20969 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) {
20970 verbose(env, "arena's user address must be set via map_extra or mmap()\n");
20971 return -EINVAL;
20972 }
20973 }
20974
20975 return 0;
20976 }
20977
__add_used_map(struct bpf_verifier_env * env,struct bpf_map * map)20978 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map)
20979 {
20980 int i, err;
20981
20982 /* check whether we recorded this map already */
20983 for (i = 0; i < env->used_map_cnt; i++)
20984 if (env->used_maps[i] == map)
20985 return i;
20986
20987 if (env->used_map_cnt >= MAX_USED_MAPS) {
20988 verbose(env, "The total number of maps per program has reached the limit of %u\n",
20989 MAX_USED_MAPS);
20990 return -E2BIG;
20991 }
20992
20993 err = check_map_prog_compatibility(env, map, env->prog);
20994 if (err)
20995 return err;
20996
20997 if (env->prog->sleepable)
20998 atomic64_inc(&map->sleepable_refcnt);
20999
21000 /* hold the map. If the program is rejected by verifier,
21001 * the map will be released by release_maps() or it
21002 * will be used by the valid program until it's unloaded
21003 * and all maps are released in bpf_free_used_maps()
21004 */
21005 bpf_map_inc(map);
21006
21007 env->used_maps[env->used_map_cnt++] = map;
21008
21009 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) {
21010 err = bpf_insn_array_init(map, env->prog);
21011 if (err) {
21012 verbose(env, "Failed to properly initialize insn array\n");
21013 return err;
21014 }
21015 env->insn_array_maps[env->insn_array_map_cnt++] = map;
21016 }
21017
21018 return env->used_map_cnt - 1;
21019 }
21020
21021 /* Add map behind fd to used maps list, if it's not already there, and return
21022 * its index.
21023 * Returns <0 on error, or >= 0 index, on success.
21024 */
add_used_map(struct bpf_verifier_env * env,int fd)21025 static int add_used_map(struct bpf_verifier_env *env, int fd)
21026 {
21027 struct bpf_map *map;
21028 CLASS(fd, f)(fd);
21029
21030 map = __bpf_map_get(f);
21031 if (IS_ERR(map)) {
21032 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
21033 return PTR_ERR(map);
21034 }
21035
21036 return __add_used_map(env, map);
21037 }
21038
21039 /* find and rewrite pseudo imm in ld_imm64 instructions:
21040 *
21041 * 1. if it accesses map FD, replace it with actual map pointer.
21042 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
21043 *
21044 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
21045 */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)21046 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
21047 {
21048 struct bpf_insn *insn = env->prog->insnsi;
21049 int insn_cnt = env->prog->len;
21050 int i, err;
21051
21052 err = bpf_prog_calc_tag(env->prog);
21053 if (err)
21054 return err;
21055
21056 for (i = 0; i < insn_cnt; i++, insn++) {
21057 if (BPF_CLASS(insn->code) == BPF_LDX &&
21058 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
21059 insn->imm != 0)) {
21060 verbose(env, "BPF_LDX uses reserved fields\n");
21061 return -EINVAL;
21062 }
21063
21064 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
21065 struct bpf_insn_aux_data *aux;
21066 struct bpf_map *map;
21067 int map_idx;
21068 u64 addr;
21069 u32 fd;
21070
21071 if (i == insn_cnt - 1 || insn[1].code != 0 ||
21072 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
21073 insn[1].off != 0) {
21074 verbose(env, "invalid bpf_ld_imm64 insn\n");
21075 return -EINVAL;
21076 }
21077
21078 if (insn[0].src_reg == 0)
21079 /* valid generic load 64-bit imm */
21080 goto next_insn;
21081
21082 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
21083 aux = &env->insn_aux_data[i];
21084 err = check_pseudo_btf_id(env, insn, aux);
21085 if (err)
21086 return err;
21087 goto next_insn;
21088 }
21089
21090 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
21091 aux = &env->insn_aux_data[i];
21092 aux->ptr_type = PTR_TO_FUNC;
21093 goto next_insn;
21094 }
21095
21096 /* In final convert_pseudo_ld_imm64() step, this is
21097 * converted into regular 64-bit imm load insn.
21098 */
21099 switch (insn[0].src_reg) {
21100 case BPF_PSEUDO_MAP_VALUE:
21101 case BPF_PSEUDO_MAP_IDX_VALUE:
21102 break;
21103 case BPF_PSEUDO_MAP_FD:
21104 case BPF_PSEUDO_MAP_IDX:
21105 if (insn[1].imm == 0)
21106 break;
21107 fallthrough;
21108 default:
21109 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
21110 return -EINVAL;
21111 }
21112
21113 switch (insn[0].src_reg) {
21114 case BPF_PSEUDO_MAP_IDX_VALUE:
21115 case BPF_PSEUDO_MAP_IDX:
21116 if (bpfptr_is_null(env->fd_array)) {
21117 verbose(env, "fd_idx without fd_array is invalid\n");
21118 return -EPROTO;
21119 }
21120 if (copy_from_bpfptr_offset(&fd, env->fd_array,
21121 insn[0].imm * sizeof(fd),
21122 sizeof(fd)))
21123 return -EFAULT;
21124 break;
21125 default:
21126 fd = insn[0].imm;
21127 break;
21128 }
21129
21130 map_idx = add_used_map(env, fd);
21131 if (map_idx < 0)
21132 return map_idx;
21133 map = env->used_maps[map_idx];
21134
21135 aux = &env->insn_aux_data[i];
21136 aux->map_index = map_idx;
21137
21138 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
21139 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
21140 addr = (unsigned long)map;
21141 } else {
21142 u32 off = insn[1].imm;
21143
21144 if (off >= BPF_MAX_VAR_OFF) {
21145 verbose(env, "direct value offset of %u is not allowed\n", off);
21146 return -EINVAL;
21147 }
21148
21149 if (!map->ops->map_direct_value_addr) {
21150 verbose(env, "no direct value access support for this map type\n");
21151 return -EINVAL;
21152 }
21153
21154 err = map->ops->map_direct_value_addr(map, &addr, off);
21155 if (err) {
21156 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
21157 map->value_size, off);
21158 return err;
21159 }
21160
21161 aux->map_off = off;
21162 addr += off;
21163 }
21164
21165 insn[0].imm = (u32)addr;
21166 insn[1].imm = addr >> 32;
21167
21168 next_insn:
21169 insn++;
21170 i++;
21171 continue;
21172 }
21173
21174 /* Basic sanity check before we invest more work here. */
21175 if (!bpf_opcode_in_insntable(insn->code)) {
21176 verbose(env, "unknown opcode %02x\n", insn->code);
21177 return -EINVAL;
21178 }
21179 }
21180
21181 /* now all pseudo BPF_LD_IMM64 instructions load valid
21182 * 'struct bpf_map *' into a register instead of user map_fd.
21183 * These pointers will be used later by verifier to validate map access.
21184 */
21185 return 0;
21186 }
21187
21188 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)21189 static void release_maps(struct bpf_verifier_env *env)
21190 {
21191 __bpf_free_used_maps(env->prog->aux, env->used_maps,
21192 env->used_map_cnt);
21193 }
21194
21195 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)21196 static void release_btfs(struct bpf_verifier_env *env)
21197 {
21198 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt);
21199 }
21200
21201 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)21202 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
21203 {
21204 struct bpf_insn *insn = env->prog->insnsi;
21205 int insn_cnt = env->prog->len;
21206 int i;
21207
21208 for (i = 0; i < insn_cnt; i++, insn++) {
21209 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
21210 continue;
21211 if (insn->src_reg == BPF_PSEUDO_FUNC)
21212 continue;
21213 insn->src_reg = 0;
21214 }
21215 }
21216
21217 /* single env->prog->insni[off] instruction was replaced with the range
21218 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
21219 * [0, off) and [off, end) to new locations, so the patched range stays zero
21220 */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_prog * new_prog,u32 off,u32 cnt)21221 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
21222 struct bpf_prog *new_prog, u32 off, u32 cnt)
21223 {
21224 struct bpf_insn_aux_data *data = env->insn_aux_data;
21225 struct bpf_insn *insn = new_prog->insnsi;
21226 u32 old_seen = data[off].seen;
21227 u32 prog_len;
21228 int i;
21229
21230 /* aux info at OFF always needs adjustment, no matter fast path
21231 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
21232 * original insn at old prog.
21233 */
21234 data[off].zext_dst = insn_has_def32(insn + off + cnt - 1);
21235
21236 if (cnt == 1)
21237 return;
21238 prog_len = new_prog->len;
21239
21240 memmove(data + off + cnt - 1, data + off,
21241 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
21242 memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
21243 for (i = off; i < off + cnt - 1; i++) {
21244 /* Expand insni[off]'s seen count to the patched range. */
21245 data[i].seen = old_seen;
21246 data[i].zext_dst = insn_has_def32(insn + i);
21247 }
21248 }
21249
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)21250 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
21251 {
21252 int i;
21253
21254 if (len == 1)
21255 return;
21256 /* NOTE: fake 'exit' subprog should be updated as well. */
21257 for (i = 0; i <= env->subprog_cnt; i++) {
21258 if (env->subprog_info[i].start <= off)
21259 continue;
21260 env->subprog_info[i].start += len - 1;
21261 }
21262 }
21263
release_insn_arrays(struct bpf_verifier_env * env)21264 static void release_insn_arrays(struct bpf_verifier_env *env)
21265 {
21266 int i;
21267
21268 for (i = 0; i < env->insn_array_map_cnt; i++)
21269 bpf_insn_array_release(env->insn_array_maps[i]);
21270 }
21271
adjust_insn_arrays(struct bpf_verifier_env * env,u32 off,u32 len)21272 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 off, u32 len)
21273 {
21274 int i;
21275
21276 if (len == 1)
21277 return;
21278
21279 for (i = 0; i < env->insn_array_map_cnt; i++)
21280 bpf_insn_array_adjust(env->insn_array_maps[i], off, len);
21281 }
21282
adjust_insn_arrays_after_remove(struct bpf_verifier_env * env,u32 off,u32 len)21283 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
21284 {
21285 int i;
21286
21287 for (i = 0; i < env->insn_array_map_cnt; i++)
21288 bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
21289 }
21290
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)21291 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
21292 {
21293 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
21294 int i, sz = prog->aux->size_poke_tab;
21295 struct bpf_jit_poke_descriptor *desc;
21296
21297 for (i = 0; i < sz; i++) {
21298 desc = &tab[i];
21299 if (desc->insn_idx <= off)
21300 continue;
21301 desc->insn_idx += len - 1;
21302 }
21303 }
21304
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)21305 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
21306 const struct bpf_insn *patch, u32 len)
21307 {
21308 struct bpf_prog *new_prog;
21309 struct bpf_insn_aux_data *new_data = NULL;
21310
21311 if (len > 1) {
21312 new_data = vrealloc(env->insn_aux_data,
21313 array_size(env->prog->len + len - 1,
21314 sizeof(struct bpf_insn_aux_data)),
21315 GFP_KERNEL_ACCOUNT | __GFP_ZERO);
21316 if (!new_data)
21317 return NULL;
21318
21319 env->insn_aux_data = new_data;
21320 }
21321
21322 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
21323 if (IS_ERR(new_prog)) {
21324 if (PTR_ERR(new_prog) == -ERANGE)
21325 verbose(env,
21326 "insn %d cannot be patched due to 16-bit range\n",
21327 env->insn_aux_data[off].orig_idx);
21328 return NULL;
21329 }
21330 adjust_insn_aux_data(env, new_prog, off, len);
21331 adjust_subprog_starts(env, off, len);
21332 adjust_insn_arrays(env, off, len);
21333 adjust_poke_descs(new_prog, off, len);
21334 return new_prog;
21335 }
21336
21337 /*
21338 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
21339 * jump offset by 'delta'.
21340 */
adjust_jmp_off(struct bpf_prog * prog,u32 tgt_idx,u32 delta)21341 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
21342 {
21343 struct bpf_insn *insn = prog->insnsi;
21344 u32 insn_cnt = prog->len, i;
21345 s32 imm;
21346 s16 off;
21347
21348 for (i = 0; i < insn_cnt; i++, insn++) {
21349 u8 code = insn->code;
21350
21351 if (tgt_idx <= i && i < tgt_idx + delta)
21352 continue;
21353
21354 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
21355 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
21356 continue;
21357
21358 if (insn->code == (BPF_JMP32 | BPF_JA)) {
21359 if (i + 1 + insn->imm != tgt_idx)
21360 continue;
21361 if (check_add_overflow(insn->imm, delta, &imm))
21362 return -ERANGE;
21363 insn->imm = imm;
21364 } else {
21365 if (i + 1 + insn->off != tgt_idx)
21366 continue;
21367 if (check_add_overflow(insn->off, delta, &off))
21368 return -ERANGE;
21369 insn->off = off;
21370 }
21371 }
21372 return 0;
21373 }
21374
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)21375 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
21376 u32 off, u32 cnt)
21377 {
21378 int i, j;
21379
21380 /* find first prog starting at or after off (first to remove) */
21381 for (i = 0; i < env->subprog_cnt; i++)
21382 if (env->subprog_info[i].start >= off)
21383 break;
21384 /* find first prog starting at or after off + cnt (first to stay) */
21385 for (j = i; j < env->subprog_cnt; j++)
21386 if (env->subprog_info[j].start >= off + cnt)
21387 break;
21388 /* if j doesn't start exactly at off + cnt, we are just removing
21389 * the front of previous prog
21390 */
21391 if (env->subprog_info[j].start != off + cnt)
21392 j--;
21393
21394 if (j > i) {
21395 struct bpf_prog_aux *aux = env->prog->aux;
21396 int move;
21397
21398 /* move fake 'exit' subprog as well */
21399 move = env->subprog_cnt + 1 - j;
21400
21401 memmove(env->subprog_info + i,
21402 env->subprog_info + j,
21403 sizeof(*env->subprog_info) * move);
21404 env->subprog_cnt -= j - i;
21405
21406 /* remove func_info */
21407 if (aux->func_info) {
21408 move = aux->func_info_cnt - j;
21409
21410 memmove(aux->func_info + i,
21411 aux->func_info + j,
21412 sizeof(*aux->func_info) * move);
21413 aux->func_info_cnt -= j - i;
21414 /* func_info->insn_off is set after all code rewrites,
21415 * in adjust_btf_func() - no need to adjust
21416 */
21417 }
21418 } else {
21419 /* convert i from "first prog to remove" to "first to adjust" */
21420 if (env->subprog_info[i].start == off)
21421 i++;
21422 }
21423
21424 /* update fake 'exit' subprog as well */
21425 for (; i <= env->subprog_cnt; i++)
21426 env->subprog_info[i].start -= cnt;
21427
21428 return 0;
21429 }
21430
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)21431 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
21432 u32 cnt)
21433 {
21434 struct bpf_prog *prog = env->prog;
21435 u32 i, l_off, l_cnt, nr_linfo;
21436 struct bpf_line_info *linfo;
21437
21438 nr_linfo = prog->aux->nr_linfo;
21439 if (!nr_linfo)
21440 return 0;
21441
21442 linfo = prog->aux->linfo;
21443
21444 /* find first line info to remove, count lines to be removed */
21445 for (i = 0; i < nr_linfo; i++)
21446 if (linfo[i].insn_off >= off)
21447 break;
21448
21449 l_off = i;
21450 l_cnt = 0;
21451 for (; i < nr_linfo; i++)
21452 if (linfo[i].insn_off < off + cnt)
21453 l_cnt++;
21454 else
21455 break;
21456
21457 /* First live insn doesn't match first live linfo, it needs to "inherit"
21458 * last removed linfo. prog is already modified, so prog->len == off
21459 * means no live instructions after (tail of the program was removed).
21460 */
21461 if (prog->len != off && l_cnt &&
21462 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
21463 l_cnt--;
21464 linfo[--i].insn_off = off + cnt;
21465 }
21466
21467 /* remove the line info which refer to the removed instructions */
21468 if (l_cnt) {
21469 memmove(linfo + l_off, linfo + i,
21470 sizeof(*linfo) * (nr_linfo - i));
21471
21472 prog->aux->nr_linfo -= l_cnt;
21473 nr_linfo = prog->aux->nr_linfo;
21474 }
21475
21476 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
21477 for (i = l_off; i < nr_linfo; i++)
21478 linfo[i].insn_off -= cnt;
21479
21480 /* fix up all subprogs (incl. 'exit') which start >= off */
21481 for (i = 0; i <= env->subprog_cnt; i++)
21482 if (env->subprog_info[i].linfo_idx > l_off) {
21483 /* program may have started in the removed region but
21484 * may not be fully removed
21485 */
21486 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
21487 env->subprog_info[i].linfo_idx -= l_cnt;
21488 else
21489 env->subprog_info[i].linfo_idx = l_off;
21490 }
21491
21492 return 0;
21493 }
21494
21495 /*
21496 * Clean up dynamically allocated fields of aux data for instructions [start, ...]
21497 */
clear_insn_aux_data(struct bpf_verifier_env * env,int start,int len)21498 static void clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
21499 {
21500 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21501 struct bpf_insn *insns = env->prog->insnsi;
21502 int end = start + len;
21503 int i;
21504
21505 for (i = start; i < end; i++) {
21506 if (aux_data[i].jt) {
21507 kvfree(aux_data[i].jt);
21508 aux_data[i].jt = NULL;
21509 }
21510
21511 if (bpf_is_ldimm64(&insns[i]))
21512 i++;
21513 }
21514 }
21515
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)21516 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
21517 {
21518 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21519 unsigned int orig_prog_len = env->prog->len;
21520 int err;
21521
21522 if (bpf_prog_is_offloaded(env->prog->aux))
21523 bpf_prog_offload_remove_insns(env, off, cnt);
21524
21525 /* Should be called before bpf_remove_insns, as it uses prog->insnsi */
21526 clear_insn_aux_data(env, off, cnt);
21527
21528 err = bpf_remove_insns(env->prog, off, cnt);
21529 if (err)
21530 return err;
21531
21532 err = adjust_subprog_starts_after_remove(env, off, cnt);
21533 if (err)
21534 return err;
21535
21536 err = bpf_adj_linfo_after_remove(env, off, cnt);
21537 if (err)
21538 return err;
21539
21540 adjust_insn_arrays_after_remove(env, off, cnt);
21541
21542 memmove(aux_data + off, aux_data + off + cnt,
21543 sizeof(*aux_data) * (orig_prog_len - off - cnt));
21544
21545 return 0;
21546 }
21547
21548 /* The verifier does more data flow analysis than llvm and will not
21549 * explore branches that are dead at run time. Malicious programs can
21550 * have dead code too. Therefore replace all dead at-run-time code
21551 * with 'ja -1'.
21552 *
21553 * Just nops are not optimal, e.g. if they would sit at the end of the
21554 * program and through another bug we would manage to jump there, then
21555 * we'd execute beyond program memory otherwise. Returning exception
21556 * code also wouldn't work since we can have subprogs where the dead
21557 * code could be located.
21558 */
sanitize_dead_code(struct bpf_verifier_env * env)21559 static void sanitize_dead_code(struct bpf_verifier_env *env)
21560 {
21561 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21562 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
21563 struct bpf_insn *insn = env->prog->insnsi;
21564 const int insn_cnt = env->prog->len;
21565 int i;
21566
21567 for (i = 0; i < insn_cnt; i++) {
21568 if (aux_data[i].seen)
21569 continue;
21570 memcpy(insn + i, &trap, sizeof(trap));
21571 aux_data[i].zext_dst = false;
21572 }
21573 }
21574
insn_is_cond_jump(u8 code)21575 static bool insn_is_cond_jump(u8 code)
21576 {
21577 u8 op;
21578
21579 op = BPF_OP(code);
21580 if (BPF_CLASS(code) == BPF_JMP32)
21581 return op != BPF_JA;
21582
21583 if (BPF_CLASS(code) != BPF_JMP)
21584 return false;
21585
21586 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
21587 }
21588
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)21589 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
21590 {
21591 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21592 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21593 struct bpf_insn *insn = env->prog->insnsi;
21594 const int insn_cnt = env->prog->len;
21595 int i;
21596
21597 for (i = 0; i < insn_cnt; i++, insn++) {
21598 if (!insn_is_cond_jump(insn->code))
21599 continue;
21600
21601 if (!aux_data[i + 1].seen)
21602 ja.off = insn->off;
21603 else if (!aux_data[i + 1 + insn->off].seen)
21604 ja.off = 0;
21605 else
21606 continue;
21607
21608 if (bpf_prog_is_offloaded(env->prog->aux))
21609 bpf_prog_offload_replace_insn(env, i, &ja);
21610
21611 memcpy(insn, &ja, sizeof(ja));
21612 }
21613 }
21614
opt_remove_dead_code(struct bpf_verifier_env * env)21615 static int opt_remove_dead_code(struct bpf_verifier_env *env)
21616 {
21617 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
21618 int insn_cnt = env->prog->len;
21619 int i, err;
21620
21621 for (i = 0; i < insn_cnt; i++) {
21622 int j;
21623
21624 j = 0;
21625 while (i + j < insn_cnt && !aux_data[i + j].seen)
21626 j++;
21627 if (!j)
21628 continue;
21629
21630 err = verifier_remove_insns(env, i, j);
21631 if (err)
21632 return err;
21633 insn_cnt = env->prog->len;
21634 }
21635
21636 return 0;
21637 }
21638
21639 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
21640 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
21641
opt_remove_nops(struct bpf_verifier_env * env)21642 static int opt_remove_nops(struct bpf_verifier_env *env)
21643 {
21644 struct bpf_insn *insn = env->prog->insnsi;
21645 int insn_cnt = env->prog->len;
21646 bool is_may_goto_0, is_ja;
21647 int i, err;
21648
21649 for (i = 0; i < insn_cnt; i++) {
21650 is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
21651 is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
21652
21653 if (!is_may_goto_0 && !is_ja)
21654 continue;
21655
21656 err = verifier_remove_insns(env, i, 1);
21657 if (err)
21658 return err;
21659 insn_cnt--;
21660 /* Go back one insn to catch may_goto +1; may_goto +0 sequence */
21661 i -= (is_may_goto_0 && i > 0) ? 2 : 1;
21662 }
21663
21664 return 0;
21665 }
21666
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)21667 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
21668 const union bpf_attr *attr)
21669 {
21670 struct bpf_insn *patch;
21671 /* use env->insn_buf as two independent buffers */
21672 struct bpf_insn *zext_patch = env->insn_buf;
21673 struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
21674 struct bpf_insn_aux_data *aux = env->insn_aux_data;
21675 int i, patch_len, delta = 0, len = env->prog->len;
21676 struct bpf_insn *insns = env->prog->insnsi;
21677 struct bpf_prog *new_prog;
21678 bool rnd_hi32;
21679
21680 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
21681 zext_patch[1] = BPF_ZEXT_REG(0);
21682 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
21683 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
21684 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
21685 for (i = 0; i < len; i++) {
21686 int adj_idx = i + delta;
21687 struct bpf_insn insn;
21688 int load_reg;
21689
21690 insn = insns[adj_idx];
21691 load_reg = insn_def_regno(&insn);
21692 if (!aux[adj_idx].zext_dst) {
21693 u8 code, class;
21694 u32 imm_rnd;
21695
21696 if (!rnd_hi32)
21697 continue;
21698
21699 code = insn.code;
21700 class = BPF_CLASS(code);
21701 if (load_reg == -1)
21702 continue;
21703
21704 /* NOTE: arg "reg" (the fourth one) is only used for
21705 * BPF_STX + SRC_OP, so it is safe to pass NULL
21706 * here.
21707 */
21708 if (is_reg64(&insn, load_reg, NULL, DST_OP)) {
21709 if (class == BPF_LD &&
21710 BPF_MODE(code) == BPF_IMM)
21711 i++;
21712 continue;
21713 }
21714
21715 /* ctx load could be transformed into wider load. */
21716 if (class == BPF_LDX &&
21717 aux[adj_idx].ptr_type == PTR_TO_CTX)
21718 continue;
21719
21720 imm_rnd = get_random_u32();
21721 rnd_hi32_patch[0] = insn;
21722 rnd_hi32_patch[1].imm = imm_rnd;
21723 rnd_hi32_patch[3].dst_reg = load_reg;
21724 patch = rnd_hi32_patch;
21725 patch_len = 4;
21726 goto apply_patch_buffer;
21727 }
21728
21729 /* Add in an zero-extend instruction if a) the JIT has requested
21730 * it or b) it's a CMPXCHG.
21731 *
21732 * The latter is because: BPF_CMPXCHG always loads a value into
21733 * R0, therefore always zero-extends. However some archs'
21734 * equivalent instruction only does this load when the
21735 * comparison is successful. This detail of CMPXCHG is
21736 * orthogonal to the general zero-extension behaviour of the
21737 * CPU, so it's treated independently of bpf_jit_needs_zext.
21738 */
21739 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
21740 continue;
21741
21742 /* Zero-extension is done by the caller. */
21743 if (bpf_pseudo_kfunc_call(&insn))
21744 continue;
21745
21746 if (verifier_bug_if(load_reg == -1, env,
21747 "zext_dst is set, but no reg is defined"))
21748 return -EFAULT;
21749
21750 zext_patch[0] = insn;
21751 zext_patch[1].dst_reg = load_reg;
21752 zext_patch[1].src_reg = load_reg;
21753 patch = zext_patch;
21754 patch_len = 2;
21755 apply_patch_buffer:
21756 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
21757 if (!new_prog)
21758 return -ENOMEM;
21759 env->prog = new_prog;
21760 insns = new_prog->insnsi;
21761 aux = env->insn_aux_data;
21762 delta += patch_len - 1;
21763 }
21764
21765 return 0;
21766 }
21767
21768 /* convert load instructions that access fields of a context type into a
21769 * sequence of instructions that access fields of the underlying structure:
21770 * struct __sk_buff -> struct sk_buff
21771 * struct bpf_sock_ops -> struct sock
21772 */
convert_ctx_accesses(struct bpf_verifier_env * env)21773 static int convert_ctx_accesses(struct bpf_verifier_env *env)
21774 {
21775 struct bpf_subprog_info *subprogs = env->subprog_info;
21776 const struct bpf_verifier_ops *ops = env->ops;
21777 int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
21778 const int insn_cnt = env->prog->len;
21779 struct bpf_insn *epilogue_buf = env->epilogue_buf;
21780 struct bpf_insn *insn_buf = env->insn_buf;
21781 struct bpf_insn *insn;
21782 u32 target_size, size_default, off;
21783 struct bpf_prog *new_prog;
21784 enum bpf_access_type type;
21785 bool is_narrower_load;
21786 int epilogue_idx = 0;
21787
21788 if (ops->gen_epilogue) {
21789 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
21790 -(subprogs[0].stack_depth + 8));
21791 if (epilogue_cnt >= INSN_BUF_SIZE) {
21792 verifier_bug(env, "epilogue is too long");
21793 return -EFAULT;
21794 } else if (epilogue_cnt) {
21795 /* Save the ARG_PTR_TO_CTX for the epilogue to use */
21796 cnt = 0;
21797 subprogs[0].stack_depth += 8;
21798 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
21799 -subprogs[0].stack_depth);
21800 insn_buf[cnt++] = env->prog->insnsi[0];
21801 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21802 if (!new_prog)
21803 return -ENOMEM;
21804 env->prog = new_prog;
21805 delta += cnt - 1;
21806
21807 ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
21808 if (ret < 0)
21809 return ret;
21810 }
21811 }
21812
21813 if (ops->gen_prologue || env->seen_direct_write) {
21814 if (!ops->gen_prologue) {
21815 verifier_bug(env, "gen_prologue is null");
21816 return -EFAULT;
21817 }
21818 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
21819 env->prog);
21820 if (cnt >= INSN_BUF_SIZE) {
21821 verifier_bug(env, "prologue is too long");
21822 return -EFAULT;
21823 } else if (cnt) {
21824 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
21825 if (!new_prog)
21826 return -ENOMEM;
21827
21828 env->prog = new_prog;
21829 delta += cnt - 1;
21830
21831 ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
21832 if (ret < 0)
21833 return ret;
21834 }
21835 }
21836
21837 if (delta)
21838 WARN_ON(adjust_jmp_off(env->prog, 0, delta));
21839
21840 if (bpf_prog_is_offloaded(env->prog->aux))
21841 return 0;
21842
21843 insn = env->prog->insnsi + delta;
21844
21845 for (i = 0; i < insn_cnt; i++, insn++) {
21846 bpf_convert_ctx_access_t convert_ctx_access;
21847 u8 mode;
21848
21849 if (env->insn_aux_data[i + delta].nospec) {
21850 WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state);
21851 struct bpf_insn *patch = insn_buf;
21852
21853 *patch++ = BPF_ST_NOSPEC();
21854 *patch++ = *insn;
21855 cnt = patch - insn_buf;
21856 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21857 if (!new_prog)
21858 return -ENOMEM;
21859
21860 delta += cnt - 1;
21861 env->prog = new_prog;
21862 insn = new_prog->insnsi + i + delta;
21863 /* This can not be easily merged with the
21864 * nospec_result-case, because an insn may require a
21865 * nospec before and after itself. Therefore also do not
21866 * 'continue' here but potentially apply further
21867 * patching to insn. *insn should equal patch[1] now.
21868 */
21869 }
21870
21871 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
21872 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
21873 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
21874 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
21875 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
21876 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
21877 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
21878 type = BPF_READ;
21879 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
21880 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
21881 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
21882 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
21883 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
21884 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
21885 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
21886 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
21887 type = BPF_WRITE;
21888 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
21889 insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
21890 insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
21891 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
21892 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
21893 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
21894 env->prog->aux->num_exentries++;
21895 continue;
21896 } else if (insn->code == (BPF_JMP | BPF_EXIT) &&
21897 epilogue_cnt &&
21898 i + delta < subprogs[1].start) {
21899 /* Generate epilogue for the main prog */
21900 if (epilogue_idx) {
21901 /* jump back to the earlier generated epilogue */
21902 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
21903 cnt = 1;
21904 } else {
21905 memcpy(insn_buf, epilogue_buf,
21906 epilogue_cnt * sizeof(*epilogue_buf));
21907 cnt = epilogue_cnt;
21908 /* epilogue_idx cannot be 0. It must have at
21909 * least one ctx ptr saving insn before the
21910 * epilogue.
21911 */
21912 epilogue_idx = i + delta;
21913 }
21914 goto patch_insn_buf;
21915 } else {
21916 continue;
21917 }
21918
21919 if (type == BPF_WRITE &&
21920 env->insn_aux_data[i + delta].nospec_result) {
21921 /* nospec_result is only used to mitigate Spectre v4 and
21922 * to limit verification-time for Spectre v1.
21923 */
21924 struct bpf_insn *patch = insn_buf;
21925
21926 *patch++ = *insn;
21927 *patch++ = BPF_ST_NOSPEC();
21928 cnt = patch - insn_buf;
21929 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
21930 if (!new_prog)
21931 return -ENOMEM;
21932
21933 delta += cnt - 1;
21934 env->prog = new_prog;
21935 insn = new_prog->insnsi + i + delta;
21936 continue;
21937 }
21938
21939 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
21940 case PTR_TO_CTX:
21941 if (!ops->convert_ctx_access)
21942 continue;
21943 convert_ctx_access = ops->convert_ctx_access;
21944 break;
21945 case PTR_TO_SOCKET:
21946 case PTR_TO_SOCK_COMMON:
21947 convert_ctx_access = bpf_sock_convert_ctx_access;
21948 break;
21949 case PTR_TO_TCP_SOCK:
21950 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
21951 break;
21952 case PTR_TO_XDP_SOCK:
21953 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
21954 break;
21955 case PTR_TO_BTF_ID:
21956 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
21957 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
21958 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
21959 * be said once it is marked PTR_UNTRUSTED, hence we must handle
21960 * any faults for loads into such types. BPF_WRITE is disallowed
21961 * for this case.
21962 */
21963 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
21964 case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED:
21965 if (type == BPF_READ) {
21966 if (BPF_MODE(insn->code) == BPF_MEM)
21967 insn->code = BPF_LDX | BPF_PROBE_MEM |
21968 BPF_SIZE((insn)->code);
21969 else
21970 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
21971 BPF_SIZE((insn)->code);
21972 env->prog->aux->num_exentries++;
21973 }
21974 continue;
21975 case PTR_TO_ARENA:
21976 if (BPF_MODE(insn->code) == BPF_MEMSX) {
21977 if (!bpf_jit_supports_insn(insn, true)) {
21978 verbose(env, "sign extending loads from arena are not supported yet\n");
21979 return -EOPNOTSUPP;
21980 }
21981 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
21982 } else {
21983 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
21984 }
21985 env->prog->aux->num_exentries++;
21986 continue;
21987 default:
21988 continue;
21989 }
21990
21991 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
21992 size = BPF_LDST_BYTES(insn);
21993 mode = BPF_MODE(insn->code);
21994
21995 /* If the read access is a narrower load of the field,
21996 * convert to a 4/8-byte load, to minimum program type specific
21997 * convert_ctx_access changes. If conversion is successful,
21998 * we will apply proper mask to the result.
21999 */
22000 is_narrower_load = size < ctx_field_size;
22001 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
22002 off = insn->off;
22003 if (is_narrower_load) {
22004 u8 size_code;
22005
22006 if (type == BPF_WRITE) {
22007 verifier_bug(env, "narrow ctx access misconfigured");
22008 return -EFAULT;
22009 }
22010
22011 size_code = BPF_H;
22012 if (ctx_field_size == 4)
22013 size_code = BPF_W;
22014 else if (ctx_field_size == 8)
22015 size_code = BPF_DW;
22016
22017 insn->off = off & ~(size_default - 1);
22018 insn->code = BPF_LDX | BPF_MEM | size_code;
22019 }
22020
22021 target_size = 0;
22022 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
22023 &target_size);
22024 if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
22025 (ctx_field_size && !target_size)) {
22026 verifier_bug(env, "error during ctx access conversion (%d)", cnt);
22027 return -EFAULT;
22028 }
22029
22030 if (is_narrower_load && size < target_size) {
22031 u8 shift = bpf_ctx_narrow_access_offset(
22032 off, size, size_default) * 8;
22033 if (shift && cnt + 1 >= INSN_BUF_SIZE) {
22034 verifier_bug(env, "narrow ctx load misconfigured");
22035 return -EFAULT;
22036 }
22037 if (ctx_field_size <= 4) {
22038 if (shift)
22039 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
22040 insn->dst_reg,
22041 shift);
22042 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22043 (1 << size * 8) - 1);
22044 } else {
22045 if (shift)
22046 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
22047 insn->dst_reg,
22048 shift);
22049 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
22050 (1ULL << size * 8) - 1);
22051 }
22052 }
22053 if (mode == BPF_MEMSX)
22054 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
22055 insn->dst_reg, insn->dst_reg,
22056 size * 8, 0);
22057
22058 patch_insn_buf:
22059 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22060 if (!new_prog)
22061 return -ENOMEM;
22062
22063 delta += cnt - 1;
22064
22065 /* keep walking new program and skip insns we just inserted */
22066 env->prog = new_prog;
22067 insn = new_prog->insnsi + i + delta;
22068 }
22069
22070 return 0;
22071 }
22072
jit_subprogs(struct bpf_verifier_env * env)22073 static int jit_subprogs(struct bpf_verifier_env *env)
22074 {
22075 struct bpf_prog *prog = env->prog, **func, *tmp;
22076 int i, j, subprog_start, subprog_end = 0, len, subprog;
22077 struct bpf_map *map_ptr;
22078 struct bpf_insn *insn;
22079 void *old_bpf_func;
22080 int err, num_exentries;
22081 int old_len, subprog_start_adjustment = 0;
22082
22083 if (env->subprog_cnt <= 1)
22084 return 0;
22085
22086 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22087 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
22088 continue;
22089
22090 /* Upon error here we cannot fall back to interpreter but
22091 * need a hard reject of the program. Thus -EFAULT is
22092 * propagated in any case.
22093 */
22094 subprog = find_subprog(env, i + insn->imm + 1);
22095 if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
22096 i + insn->imm + 1))
22097 return -EFAULT;
22098 /* temporarily remember subprog id inside insn instead of
22099 * aux_data, since next loop will split up all insns into funcs
22100 */
22101 insn->off = subprog;
22102 /* remember original imm in case JIT fails and fallback
22103 * to interpreter will be needed
22104 */
22105 env->insn_aux_data[i].call_imm = insn->imm;
22106 /* point imm to __bpf_call_base+1 from JITs point of view */
22107 insn->imm = 1;
22108 if (bpf_pseudo_func(insn)) {
22109 #if defined(MODULES_VADDR)
22110 u64 addr = MODULES_VADDR;
22111 #else
22112 u64 addr = VMALLOC_START;
22113 #endif
22114 /* jit (e.g. x86_64) may emit fewer instructions
22115 * if it learns a u32 imm is the same as a u64 imm.
22116 * Set close enough to possible prog address.
22117 */
22118 insn[0].imm = (u32)addr;
22119 insn[1].imm = addr >> 32;
22120 }
22121 }
22122
22123 err = bpf_prog_alloc_jited_linfo(prog);
22124 if (err)
22125 goto out_undo_insn;
22126
22127 err = -ENOMEM;
22128 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
22129 if (!func)
22130 goto out_undo_insn;
22131
22132 for (i = 0; i < env->subprog_cnt; i++) {
22133 subprog_start = subprog_end;
22134 subprog_end = env->subprog_info[i + 1].start;
22135
22136 len = subprog_end - subprog_start;
22137 /* bpf_prog_run() doesn't call subprogs directly,
22138 * hence main prog stats include the runtime of subprogs.
22139 * subprogs don't have IDs and not reachable via prog_get_next_id
22140 * func[i]->stats will never be accessed and stays NULL
22141 */
22142 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
22143 if (!func[i])
22144 goto out_free;
22145 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
22146 len * sizeof(struct bpf_insn));
22147 func[i]->type = prog->type;
22148 func[i]->len = len;
22149 if (bpf_prog_calc_tag(func[i]))
22150 goto out_free;
22151 func[i]->is_func = 1;
22152 func[i]->sleepable = prog->sleepable;
22153 func[i]->aux->func_idx = i;
22154 /* Below members will be freed only at prog->aux */
22155 func[i]->aux->btf = prog->aux->btf;
22156 func[i]->aux->subprog_start = subprog_start + subprog_start_adjustment;
22157 func[i]->aux->func_info = prog->aux->func_info;
22158 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
22159 func[i]->aux->poke_tab = prog->aux->poke_tab;
22160 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
22161 func[i]->aux->main_prog_aux = prog->aux;
22162
22163 for (j = 0; j < prog->aux->size_poke_tab; j++) {
22164 struct bpf_jit_poke_descriptor *poke;
22165
22166 poke = &prog->aux->poke_tab[j];
22167 if (poke->insn_idx < subprog_end &&
22168 poke->insn_idx >= subprog_start)
22169 poke->aux = func[i]->aux;
22170 }
22171
22172 func[i]->aux->name[0] = 'F';
22173 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
22174 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
22175 func[i]->aux->jits_use_priv_stack = true;
22176
22177 func[i]->jit_requested = 1;
22178 func[i]->blinding_requested = prog->blinding_requested;
22179 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
22180 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
22181 func[i]->aux->linfo = prog->aux->linfo;
22182 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
22183 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
22184 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
22185 func[i]->aux->arena = prog->aux->arena;
22186 func[i]->aux->used_maps = env->used_maps;
22187 func[i]->aux->used_map_cnt = env->used_map_cnt;
22188 num_exentries = 0;
22189 insn = func[i]->insnsi;
22190 for (j = 0; j < func[i]->len; j++, insn++) {
22191 if (BPF_CLASS(insn->code) == BPF_LDX &&
22192 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22193 BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
22194 BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
22195 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
22196 num_exentries++;
22197 if ((BPF_CLASS(insn->code) == BPF_STX ||
22198 BPF_CLASS(insn->code) == BPF_ST) &&
22199 BPF_MODE(insn->code) == BPF_PROBE_MEM32)
22200 num_exentries++;
22201 if (BPF_CLASS(insn->code) == BPF_STX &&
22202 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
22203 num_exentries++;
22204 }
22205 func[i]->aux->num_exentries = num_exentries;
22206 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
22207 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
22208 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
22209 func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
22210 if (!i)
22211 func[i]->aux->exception_boundary = env->seen_exception;
22212
22213 /*
22214 * To properly pass the absolute subprog start to jit
22215 * all instruction adjustments should be accumulated
22216 */
22217 old_len = func[i]->len;
22218 func[i] = bpf_int_jit_compile(func[i]);
22219 subprog_start_adjustment += func[i]->len - old_len;
22220
22221 if (!func[i]->jited) {
22222 err = -ENOTSUPP;
22223 goto out_free;
22224 }
22225 cond_resched();
22226 }
22227
22228 /* at this point all bpf functions were successfully JITed
22229 * now populate all bpf_calls with correct addresses and
22230 * run last pass of JIT
22231 */
22232 for (i = 0; i < env->subprog_cnt; i++) {
22233 insn = func[i]->insnsi;
22234 for (j = 0; j < func[i]->len; j++, insn++) {
22235 if (bpf_pseudo_func(insn)) {
22236 subprog = insn->off;
22237 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
22238 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
22239 continue;
22240 }
22241 if (!bpf_pseudo_call(insn))
22242 continue;
22243 subprog = insn->off;
22244 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
22245 }
22246
22247 /* we use the aux data to keep a list of the start addresses
22248 * of the JITed images for each function in the program
22249 *
22250 * for some architectures, such as powerpc64, the imm field
22251 * might not be large enough to hold the offset of the start
22252 * address of the callee's JITed image from __bpf_call_base
22253 *
22254 * in such cases, we can lookup the start address of a callee
22255 * by using its subprog id, available from the off field of
22256 * the call instruction, as an index for this list
22257 */
22258 func[i]->aux->func = func;
22259 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22260 func[i]->aux->real_func_cnt = env->subprog_cnt;
22261 }
22262 for (i = 0; i < env->subprog_cnt; i++) {
22263 old_bpf_func = func[i]->bpf_func;
22264 tmp = bpf_int_jit_compile(func[i]);
22265 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
22266 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
22267 err = -ENOTSUPP;
22268 goto out_free;
22269 }
22270 cond_resched();
22271 }
22272
22273 /*
22274 * Cleanup func[i]->aux fields which aren't required
22275 * or can become invalid in future
22276 */
22277 for (i = 0; i < env->subprog_cnt; i++) {
22278 func[i]->aux->used_maps = NULL;
22279 func[i]->aux->used_map_cnt = 0;
22280 }
22281
22282 /* finally lock prog and jit images for all functions and
22283 * populate kallsysm. Begin at the first subprogram, since
22284 * bpf_prog_load will add the kallsyms for the main program.
22285 */
22286 for (i = 1; i < env->subprog_cnt; i++) {
22287 err = bpf_prog_lock_ro(func[i]);
22288 if (err)
22289 goto out_free;
22290 }
22291
22292 for (i = 1; i < env->subprog_cnt; i++)
22293 bpf_prog_kallsyms_add(func[i]);
22294
22295 /* Last step: make now unused interpreter insns from main
22296 * prog consistent for later dump requests, so they can
22297 * later look the same as if they were interpreted only.
22298 */
22299 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22300 if (bpf_pseudo_func(insn)) {
22301 insn[0].imm = env->insn_aux_data[i].call_imm;
22302 insn[1].imm = insn->off;
22303 insn->off = 0;
22304 continue;
22305 }
22306 if (!bpf_pseudo_call(insn))
22307 continue;
22308 insn->off = env->insn_aux_data[i].call_imm;
22309 subprog = find_subprog(env, i + insn->off + 1);
22310 insn->imm = subprog;
22311 }
22312
22313 prog->jited = 1;
22314 prog->bpf_func = func[0]->bpf_func;
22315 prog->jited_len = func[0]->jited_len;
22316 prog->aux->extable = func[0]->aux->extable;
22317 prog->aux->num_exentries = func[0]->aux->num_exentries;
22318 prog->aux->func = func;
22319 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
22320 prog->aux->real_func_cnt = env->subprog_cnt;
22321 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
22322 prog->aux->exception_boundary = func[0]->aux->exception_boundary;
22323 bpf_prog_jit_attempt_done(prog);
22324 return 0;
22325 out_free:
22326 /* We failed JIT'ing, so at this point we need to unregister poke
22327 * descriptors from subprogs, so that kernel is not attempting to
22328 * patch it anymore as we're freeing the subprog JIT memory.
22329 */
22330 for (i = 0; i < prog->aux->size_poke_tab; i++) {
22331 map_ptr = prog->aux->poke_tab[i].tail_call.map;
22332 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
22333 }
22334 /* At this point we're guaranteed that poke descriptors are not
22335 * live anymore. We can just unlink its descriptor table as it's
22336 * released with the main prog.
22337 */
22338 for (i = 0; i < env->subprog_cnt; i++) {
22339 if (!func[i])
22340 continue;
22341 func[i]->aux->poke_tab = NULL;
22342 bpf_jit_free(func[i]);
22343 }
22344 kfree(func);
22345 out_undo_insn:
22346 /* cleanup main prog to be interpreted */
22347 prog->jit_requested = 0;
22348 prog->blinding_requested = 0;
22349 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
22350 if (!bpf_pseudo_call(insn))
22351 continue;
22352 insn->off = 0;
22353 insn->imm = env->insn_aux_data[i].call_imm;
22354 }
22355 bpf_prog_jit_attempt_done(prog);
22356 return err;
22357 }
22358
fixup_call_args(struct bpf_verifier_env * env)22359 static int fixup_call_args(struct bpf_verifier_env *env)
22360 {
22361 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22362 struct bpf_prog *prog = env->prog;
22363 struct bpf_insn *insn = prog->insnsi;
22364 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
22365 int i, depth;
22366 #endif
22367 int err = 0;
22368
22369 if (env->prog->jit_requested &&
22370 !bpf_prog_is_offloaded(env->prog->aux)) {
22371 err = jit_subprogs(env);
22372 if (err == 0)
22373 return 0;
22374 if (err == -EFAULT)
22375 return err;
22376 }
22377 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
22378 if (has_kfunc_call) {
22379 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
22380 return -EINVAL;
22381 }
22382 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
22383 /* When JIT fails the progs with bpf2bpf calls and tail_calls
22384 * have to be rejected, since interpreter doesn't support them yet.
22385 */
22386 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
22387 return -EINVAL;
22388 }
22389 for (i = 0; i < prog->len; i++, insn++) {
22390 if (bpf_pseudo_func(insn)) {
22391 /* When JIT fails the progs with callback calls
22392 * have to be rejected, since interpreter doesn't support them yet.
22393 */
22394 verbose(env, "callbacks are not allowed in non-JITed programs\n");
22395 return -EINVAL;
22396 }
22397
22398 if (!bpf_pseudo_call(insn))
22399 continue;
22400 depth = get_callee_stack_depth(env, insn, i);
22401 if (depth < 0)
22402 return depth;
22403 bpf_patch_call_args(insn, depth);
22404 }
22405 err = 0;
22406 #endif
22407 return err;
22408 }
22409
22410 /* 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)22411 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx)
22412 {
22413 struct bpf_prog *prog = env->prog;
22414 bool seen_direct_write;
22415 void *xdp_kfunc;
22416 bool is_rdonly;
22417 u32 func_id = desc->func_id;
22418 u16 offset = desc->offset;
22419 unsigned long addr = desc->addr;
22420
22421 if (offset) /* return if module BTF is used */
22422 return 0;
22423
22424 if (bpf_dev_bound_kfunc_id(func_id)) {
22425 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
22426 if (xdp_kfunc)
22427 addr = (unsigned long)xdp_kfunc;
22428 /* fallback to default kfunc when not supported by netdev */
22429 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
22430 seen_direct_write = env->seen_direct_write;
22431 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
22432
22433 if (is_rdonly)
22434 addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
22435
22436 /* restore env->seen_direct_write to its original value, since
22437 * may_access_direct_pkt_data mutates it
22438 */
22439 env->seen_direct_write = seen_direct_write;
22440 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
22441 if (bpf_lsm_has_d_inode_locked(prog))
22442 addr = (unsigned long)bpf_set_dentry_xattr_locked;
22443 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
22444 if (bpf_lsm_has_d_inode_locked(prog))
22445 addr = (unsigned long)bpf_remove_dentry_xattr_locked;
22446 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
22447 if (!env->insn_aux_data[insn_idx].non_sleepable)
22448 addr = (unsigned long)bpf_dynptr_from_file_sleepable;
22449 }
22450 desc->addr = addr;
22451 return 0;
22452 }
22453
__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)22454 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
22455 u16 struct_meta_reg,
22456 u16 node_offset_reg,
22457 struct bpf_insn *insn,
22458 struct bpf_insn *insn_buf,
22459 int *cnt)
22460 {
22461 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
22462 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
22463
22464 insn_buf[0] = addr[0];
22465 insn_buf[1] = addr[1];
22466 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
22467 insn_buf[3] = *insn;
22468 *cnt = 4;
22469 }
22470
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)22471 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
22472 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
22473 {
22474 struct bpf_kfunc_desc *desc;
22475 int err;
22476
22477 if (!insn->imm) {
22478 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
22479 return -EINVAL;
22480 }
22481
22482 *cnt = 0;
22483
22484 /* insn->imm has the btf func_id. Replace it with an offset relative to
22485 * __bpf_call_base, unless the JIT needs to call functions that are
22486 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
22487 */
22488 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
22489 if (!desc) {
22490 verifier_bug(env, "kernel function descriptor not found for func_id %u",
22491 insn->imm);
22492 return -EFAULT;
22493 }
22494
22495 err = specialize_kfunc(env, desc, insn_idx);
22496 if (err)
22497 return err;
22498
22499 if (!bpf_jit_supports_far_kfunc_call())
22500 insn->imm = BPF_CALL_IMM(desc->addr);
22501 if (insn->off)
22502 return 0;
22503 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
22504 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
22505 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22506 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22507 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
22508
22509 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
22510 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22511 insn_idx);
22512 return -EFAULT;
22513 }
22514
22515 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
22516 insn_buf[1] = addr[0];
22517 insn_buf[2] = addr[1];
22518 insn_buf[3] = *insn;
22519 *cnt = 4;
22520 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
22521 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
22522 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
22523 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22524 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
22525
22526 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
22527 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d",
22528 insn_idx);
22529 return -EFAULT;
22530 }
22531
22532 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
22533 !kptr_struct_meta) {
22534 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22535 insn_idx);
22536 return -EFAULT;
22537 }
22538
22539 insn_buf[0] = addr[0];
22540 insn_buf[1] = addr[1];
22541 insn_buf[2] = *insn;
22542 *cnt = 3;
22543 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
22544 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
22545 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22546 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
22547 int struct_meta_reg = BPF_REG_3;
22548 int node_offset_reg = BPF_REG_4;
22549
22550 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
22551 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
22552 struct_meta_reg = BPF_REG_4;
22553 node_offset_reg = BPF_REG_5;
22554 }
22555
22556 if (!kptr_struct_meta) {
22557 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d",
22558 insn_idx);
22559 return -EFAULT;
22560 }
22561
22562 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
22563 node_offset_reg, insn, insn_buf, cnt);
22564 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
22565 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
22566 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22567 *cnt = 1;
22568 }
22569
22570 if (env->insn_aux_data[insn_idx].arg_prog) {
22571 u32 regno = env->insn_aux_data[insn_idx].arg_prog;
22572 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) };
22573 int idx = *cnt;
22574
22575 insn_buf[idx++] = ld_addrs[0];
22576 insn_buf[idx++] = ld_addrs[1];
22577 insn_buf[idx++] = *insn;
22578 *cnt = idx;
22579 }
22580 return 0;
22581 }
22582
22583 /* 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)22584 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
22585 {
22586 struct bpf_subprog_info *info = env->subprog_info;
22587 int cnt = env->subprog_cnt;
22588 struct bpf_prog *prog;
22589
22590 /* We only reserve one slot for hidden subprogs in subprog_info. */
22591 if (env->hidden_subprog_cnt) {
22592 verifier_bug(env, "only one hidden subprog supported");
22593 return -EFAULT;
22594 }
22595 /* We're not patching any existing instruction, just appending the new
22596 * ones for the hidden subprog. Hence all of the adjustment operations
22597 * in bpf_patch_insn_data are no-ops.
22598 */
22599 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
22600 if (!prog)
22601 return -ENOMEM;
22602 env->prog = prog;
22603 info[cnt + 1].start = info[cnt].start;
22604 info[cnt].start = prog->len - len + 1;
22605 env->subprog_cnt++;
22606 env->hidden_subprog_cnt++;
22607 return 0;
22608 }
22609
22610 /* Do various post-verification rewrites in a single program pass.
22611 * These rewrites simplify JIT and interpreter implementations.
22612 */
do_misc_fixups(struct bpf_verifier_env * env)22613 static int do_misc_fixups(struct bpf_verifier_env *env)
22614 {
22615 struct bpf_prog *prog = env->prog;
22616 enum bpf_attach_type eatype = prog->expected_attach_type;
22617 enum bpf_prog_type prog_type = resolve_prog_type(prog);
22618 struct bpf_insn *insn = prog->insnsi;
22619 const struct bpf_func_proto *fn;
22620 const int insn_cnt = prog->len;
22621 const struct bpf_map_ops *ops;
22622 struct bpf_insn_aux_data *aux;
22623 struct bpf_insn *insn_buf = env->insn_buf;
22624 struct bpf_prog *new_prog;
22625 struct bpf_map *map_ptr;
22626 int i, ret, cnt, delta = 0, cur_subprog = 0;
22627 struct bpf_subprog_info *subprogs = env->subprog_info;
22628 u16 stack_depth = subprogs[cur_subprog].stack_depth;
22629 u16 stack_depth_extra = 0;
22630
22631 if (env->seen_exception && !env->exception_callback_subprog) {
22632 struct bpf_insn *patch = insn_buf;
22633
22634 *patch++ = env->prog->insnsi[insn_cnt - 1];
22635 *patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
22636 *patch++ = BPF_EXIT_INSN();
22637 ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
22638 if (ret < 0)
22639 return ret;
22640 prog = env->prog;
22641 insn = prog->insnsi;
22642
22643 env->exception_callback_subprog = env->subprog_cnt - 1;
22644 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
22645 mark_subprog_exc_cb(env, env->exception_callback_subprog);
22646 }
22647
22648 for (i = 0; i < insn_cnt;) {
22649 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) {
22650 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) ||
22651 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) {
22652 /* convert to 32-bit mov that clears upper 32-bit */
22653 insn->code = BPF_ALU | BPF_MOV | BPF_X;
22654 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
22655 insn->off = 0;
22656 insn->imm = 0;
22657 } /* cast from as(0) to as(1) should be handled by JIT */
22658 goto next_insn;
22659 }
22660
22661 if (env->insn_aux_data[i + delta].needs_zext)
22662 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
22663 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
22664
22665 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */
22666 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
22667 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
22668 insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
22669 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
22670 insn->off == 1 && insn->imm == -1) {
22671 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22672 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22673 struct bpf_insn *patch = insn_buf;
22674
22675 if (isdiv)
22676 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22677 BPF_NEG | BPF_K, insn->dst_reg,
22678 0, 0, 0);
22679 else
22680 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22681
22682 cnt = patch - insn_buf;
22683
22684 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22685 if (!new_prog)
22686 return -ENOMEM;
22687
22688 delta += cnt - 1;
22689 env->prog = prog = new_prog;
22690 insn = new_prog->insnsi + i + delta;
22691 goto next_insn;
22692 }
22693
22694 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
22695 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
22696 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
22697 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
22698 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
22699 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
22700 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
22701 bool is_sdiv = isdiv && insn->off == 1;
22702 bool is_smod = !isdiv && insn->off == 1;
22703 struct bpf_insn *patch = insn_buf;
22704
22705 if (is_sdiv) {
22706 /* [R,W]x sdiv 0 -> 0
22707 * LLONG_MIN sdiv -1 -> LLONG_MIN
22708 * INT_MIN sdiv -1 -> INT_MIN
22709 */
22710 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22711 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22712 BPF_ADD | BPF_K, BPF_REG_AX,
22713 0, 0, 1);
22714 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22715 BPF_JGT | BPF_K, BPF_REG_AX,
22716 0, 4, 1);
22717 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22718 BPF_JEQ | BPF_K, BPF_REG_AX,
22719 0, 1, 0);
22720 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22721 BPF_MOV | BPF_K, insn->dst_reg,
22722 0, 0, 0);
22723 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
22724 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22725 BPF_NEG | BPF_K, insn->dst_reg,
22726 0, 0, 0);
22727 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22728 *patch++ = *insn;
22729 cnt = patch - insn_buf;
22730 } else if (is_smod) {
22731 /* [R,W]x mod 0 -> [R,W]x */
22732 /* [R,W]x mod -1 -> 0 */
22733 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22734 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
22735 BPF_ADD | BPF_K, BPF_REG_AX,
22736 0, 0, 1);
22737 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22738 BPF_JGT | BPF_K, BPF_REG_AX,
22739 0, 3, 1);
22740 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22741 BPF_JEQ | BPF_K, BPF_REG_AX,
22742 0, 3 + (is64 ? 0 : 1), 1);
22743 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
22744 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22745 *patch++ = *insn;
22746
22747 if (!is64) {
22748 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22749 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22750 }
22751 cnt = patch - insn_buf;
22752 } else if (isdiv) {
22753 /* [R,W]x div 0 -> 0 */
22754 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22755 BPF_JNE | BPF_K, insn->src_reg,
22756 0, 2, 0);
22757 *patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
22758 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22759 *patch++ = *insn;
22760 cnt = patch - insn_buf;
22761 } else {
22762 /* [R,W]x mod 0 -> [R,W]x */
22763 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
22764 BPF_JEQ | BPF_K, insn->src_reg,
22765 0, 1 + (is64 ? 0 : 1), 0);
22766 *patch++ = *insn;
22767
22768 if (!is64) {
22769 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22770 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
22771 }
22772 cnt = patch - insn_buf;
22773 }
22774
22775 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22776 if (!new_prog)
22777 return -ENOMEM;
22778
22779 delta += cnt - 1;
22780 env->prog = prog = new_prog;
22781 insn = new_prog->insnsi + i + delta;
22782 goto next_insn;
22783 }
22784
22785 /* Make it impossible to de-reference a userspace address */
22786 if (BPF_CLASS(insn->code) == BPF_LDX &&
22787 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
22788 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
22789 struct bpf_insn *patch = insn_buf;
22790 u64 uaddress_limit = bpf_arch_uaddress_limit();
22791
22792 if (!uaddress_limit)
22793 goto next_insn;
22794
22795 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
22796 if (insn->off)
22797 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
22798 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
22799 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
22800 *patch++ = *insn;
22801 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
22802 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
22803
22804 cnt = patch - insn_buf;
22805 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22806 if (!new_prog)
22807 return -ENOMEM;
22808
22809 delta += cnt - 1;
22810 env->prog = prog = new_prog;
22811 insn = new_prog->insnsi + i + delta;
22812 goto next_insn;
22813 }
22814
22815 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
22816 if (BPF_CLASS(insn->code) == BPF_LD &&
22817 (BPF_MODE(insn->code) == BPF_ABS ||
22818 BPF_MODE(insn->code) == BPF_IND)) {
22819 cnt = env->ops->gen_ld_abs(insn, insn_buf);
22820 if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
22821 verifier_bug(env, "%d insns generated for ld_abs", cnt);
22822 return -EFAULT;
22823 }
22824
22825 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22826 if (!new_prog)
22827 return -ENOMEM;
22828
22829 delta += cnt - 1;
22830 env->prog = prog = new_prog;
22831 insn = new_prog->insnsi + i + delta;
22832 goto next_insn;
22833 }
22834
22835 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
22836 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
22837 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
22838 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
22839 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
22840 struct bpf_insn *patch = insn_buf;
22841 bool issrc, isneg, isimm;
22842 u32 off_reg;
22843
22844 aux = &env->insn_aux_data[i + delta];
22845 if (!aux->alu_state ||
22846 aux->alu_state == BPF_ALU_NON_POINTER)
22847 goto next_insn;
22848
22849 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
22850 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
22851 BPF_ALU_SANITIZE_SRC;
22852 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
22853
22854 off_reg = issrc ? insn->src_reg : insn->dst_reg;
22855 if (isimm) {
22856 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22857 } else {
22858 if (isneg)
22859 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22860 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
22861 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
22862 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
22863 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
22864 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
22865 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
22866 }
22867 if (!issrc)
22868 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
22869 insn->src_reg = BPF_REG_AX;
22870 if (isneg)
22871 insn->code = insn->code == code_add ?
22872 code_sub : code_add;
22873 *patch++ = *insn;
22874 if (issrc && isneg && !isimm)
22875 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
22876 cnt = patch - insn_buf;
22877
22878 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22879 if (!new_prog)
22880 return -ENOMEM;
22881
22882 delta += cnt - 1;
22883 env->prog = prog = new_prog;
22884 insn = new_prog->insnsi + i + delta;
22885 goto next_insn;
22886 }
22887
22888 if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) {
22889 int stack_off_cnt = -stack_depth - 16;
22890
22891 /*
22892 * Two 8 byte slots, depth-16 stores the count, and
22893 * depth-8 stores the start timestamp of the loop.
22894 *
22895 * The starting value of count is BPF_MAX_TIMED_LOOPS
22896 * (0xffff). Every iteration loads it and subs it by 1,
22897 * until the value becomes 0 in AX (thus, 1 in stack),
22898 * after which we call arch_bpf_timed_may_goto, which
22899 * either sets AX to 0xffff to keep looping, or to 0
22900 * upon timeout. AX is then stored into the stack. In
22901 * the next iteration, we either see 0 and break out, or
22902 * continue iterating until the next time value is 0
22903 * after subtraction, rinse and repeat.
22904 */
22905 stack_depth_extra = 16;
22906 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt);
22907 if (insn->off >= 0)
22908 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5);
22909 else
22910 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22911 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22912 insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
22913 /*
22914 * AX is used as an argument to pass in stack_off_cnt
22915 * (to add to r10/fp), and also as the return value of
22916 * the call to arch_bpf_timed_may_goto.
22917 */
22918 insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt);
22919 insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
22920 insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt);
22921 cnt = 7;
22922
22923 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22924 if (!new_prog)
22925 return -ENOMEM;
22926
22927 delta += cnt - 1;
22928 env->prog = prog = new_prog;
22929 insn = new_prog->insnsi + i + delta;
22930 goto next_insn;
22931 } else if (is_may_goto_insn(insn)) {
22932 int stack_off = -stack_depth - 8;
22933
22934 stack_depth_extra = 8;
22935 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
22936 if (insn->off >= 0)
22937 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2);
22938 else
22939 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1);
22940 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
22941 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off);
22942 cnt = 4;
22943
22944 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22945 if (!new_prog)
22946 return -ENOMEM;
22947
22948 delta += cnt - 1;
22949 env->prog = prog = new_prog;
22950 insn = new_prog->insnsi + i + delta;
22951 goto next_insn;
22952 }
22953
22954 if (insn->code != (BPF_JMP | BPF_CALL))
22955 goto next_insn;
22956 if (insn->src_reg == BPF_PSEUDO_CALL)
22957 goto next_insn;
22958 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
22959 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
22960 if (ret)
22961 return ret;
22962 if (cnt == 0)
22963 goto next_insn;
22964
22965 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
22966 if (!new_prog)
22967 return -ENOMEM;
22968
22969 delta += cnt - 1;
22970 env->prog = prog = new_prog;
22971 insn = new_prog->insnsi + i + delta;
22972 goto next_insn;
22973 }
22974
22975 /* Skip inlining the helper call if the JIT does it. */
22976 if (bpf_jit_inlines_helper_call(insn->imm))
22977 goto next_insn;
22978
22979 if (insn->imm == BPF_FUNC_get_route_realm)
22980 prog->dst_needed = 1;
22981 if (insn->imm == BPF_FUNC_get_prandom_u32)
22982 bpf_user_rnd_init_once();
22983 if (insn->imm == BPF_FUNC_override_return)
22984 prog->kprobe_override = 1;
22985 if (insn->imm == BPF_FUNC_tail_call) {
22986 /* If we tail call into other programs, we
22987 * cannot make any assumptions since they can
22988 * be replaced dynamically during runtime in
22989 * the program array.
22990 */
22991 prog->cb_access = 1;
22992 if (!allow_tail_call_in_subprogs(env))
22993 prog->aux->stack_depth = MAX_BPF_STACK;
22994 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
22995
22996 /* mark bpf_tail_call as different opcode to avoid
22997 * conditional branch in the interpreter for every normal
22998 * call and to prevent accidental JITing by JIT compiler
22999 * that doesn't support bpf_tail_call yet
23000 */
23001 insn->imm = 0;
23002 insn->code = BPF_JMP | BPF_TAIL_CALL;
23003
23004 aux = &env->insn_aux_data[i + delta];
23005 if (env->bpf_capable && !prog->blinding_requested &&
23006 prog->jit_requested &&
23007 !bpf_map_key_poisoned(aux) &&
23008 !bpf_map_ptr_poisoned(aux) &&
23009 !bpf_map_ptr_unpriv(aux)) {
23010 struct bpf_jit_poke_descriptor desc = {
23011 .reason = BPF_POKE_REASON_TAIL_CALL,
23012 .tail_call.map = aux->map_ptr_state.map_ptr,
23013 .tail_call.key = bpf_map_key_immediate(aux),
23014 .insn_idx = i + delta,
23015 };
23016
23017 ret = bpf_jit_add_poke_descriptor(prog, &desc);
23018 if (ret < 0) {
23019 verbose(env, "adding tail call poke descriptor failed\n");
23020 return ret;
23021 }
23022
23023 insn->imm = ret + 1;
23024 goto next_insn;
23025 }
23026
23027 if (!bpf_map_ptr_unpriv(aux))
23028 goto next_insn;
23029
23030 /* instead of changing every JIT dealing with tail_call
23031 * emit two extra insns:
23032 * if (index >= max_entries) goto out;
23033 * index &= array->index_mask;
23034 * to avoid out-of-bounds cpu speculation
23035 */
23036 if (bpf_map_ptr_poisoned(aux)) {
23037 verbose(env, "tail_call abusing map_ptr\n");
23038 return -EINVAL;
23039 }
23040
23041 map_ptr = aux->map_ptr_state.map_ptr;
23042 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
23043 map_ptr->max_entries, 2);
23044 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
23045 container_of(map_ptr,
23046 struct bpf_array,
23047 map)->index_mask);
23048 insn_buf[2] = *insn;
23049 cnt = 3;
23050 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23051 if (!new_prog)
23052 return -ENOMEM;
23053
23054 delta += cnt - 1;
23055 env->prog = prog = new_prog;
23056 insn = new_prog->insnsi + i + delta;
23057 goto next_insn;
23058 }
23059
23060 if (insn->imm == BPF_FUNC_timer_set_callback) {
23061 /* The verifier will process callback_fn as many times as necessary
23062 * with different maps and the register states prepared by
23063 * set_timer_callback_state will be accurate.
23064 *
23065 * The following use case is valid:
23066 * map1 is shared by prog1, prog2, prog3.
23067 * prog1 calls bpf_timer_init for some map1 elements
23068 * prog2 calls bpf_timer_set_callback for some map1 elements.
23069 * Those that were not bpf_timer_init-ed will return -EINVAL.
23070 * prog3 calls bpf_timer_start for some map1 elements.
23071 * Those that were not both bpf_timer_init-ed and
23072 * bpf_timer_set_callback-ed will return -EINVAL.
23073 */
23074 struct bpf_insn ld_addrs[2] = {
23075 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
23076 };
23077
23078 insn_buf[0] = ld_addrs[0];
23079 insn_buf[1] = ld_addrs[1];
23080 insn_buf[2] = *insn;
23081 cnt = 3;
23082
23083 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23084 if (!new_prog)
23085 return -ENOMEM;
23086
23087 delta += cnt - 1;
23088 env->prog = prog = new_prog;
23089 insn = new_prog->insnsi + i + delta;
23090 goto patch_call_imm;
23091 }
23092
23093 if (is_storage_get_function(insn->imm)) {
23094 if (env->insn_aux_data[i + delta].non_sleepable)
23095 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
23096 else
23097 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
23098 insn_buf[1] = *insn;
23099 cnt = 2;
23100
23101 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23102 if (!new_prog)
23103 return -ENOMEM;
23104
23105 delta += cnt - 1;
23106 env->prog = prog = new_prog;
23107 insn = new_prog->insnsi + i + delta;
23108 goto patch_call_imm;
23109 }
23110
23111 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
23112 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
23113 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
23114 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
23115 */
23116 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
23117 insn_buf[1] = *insn;
23118 cnt = 2;
23119
23120 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23121 if (!new_prog)
23122 return -ENOMEM;
23123
23124 delta += cnt - 1;
23125 env->prog = prog = new_prog;
23126 insn = new_prog->insnsi + i + delta;
23127 goto patch_call_imm;
23128 }
23129
23130 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
23131 * and other inlining handlers are currently limited to 64 bit
23132 * only.
23133 */
23134 if (prog->jit_requested && BITS_PER_LONG == 64 &&
23135 (insn->imm == BPF_FUNC_map_lookup_elem ||
23136 insn->imm == BPF_FUNC_map_update_elem ||
23137 insn->imm == BPF_FUNC_map_delete_elem ||
23138 insn->imm == BPF_FUNC_map_push_elem ||
23139 insn->imm == BPF_FUNC_map_pop_elem ||
23140 insn->imm == BPF_FUNC_map_peek_elem ||
23141 insn->imm == BPF_FUNC_redirect_map ||
23142 insn->imm == BPF_FUNC_for_each_map_elem ||
23143 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
23144 aux = &env->insn_aux_data[i + delta];
23145 if (bpf_map_ptr_poisoned(aux))
23146 goto patch_call_imm;
23147
23148 map_ptr = aux->map_ptr_state.map_ptr;
23149 ops = map_ptr->ops;
23150 if (insn->imm == BPF_FUNC_map_lookup_elem &&
23151 ops->map_gen_lookup) {
23152 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
23153 if (cnt == -EOPNOTSUPP)
23154 goto patch_map_ops_generic;
23155 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
23156 verifier_bug(env, "%d insns generated for map lookup", cnt);
23157 return -EFAULT;
23158 }
23159
23160 new_prog = bpf_patch_insn_data(env, i + delta,
23161 insn_buf, cnt);
23162 if (!new_prog)
23163 return -ENOMEM;
23164
23165 delta += cnt - 1;
23166 env->prog = prog = new_prog;
23167 insn = new_prog->insnsi + i + delta;
23168 goto next_insn;
23169 }
23170
23171 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
23172 (void *(*)(struct bpf_map *map, void *key))NULL));
23173 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
23174 (long (*)(struct bpf_map *map, void *key))NULL));
23175 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
23176 (long (*)(struct bpf_map *map, void *key, void *value,
23177 u64 flags))NULL));
23178 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
23179 (long (*)(struct bpf_map *map, void *value,
23180 u64 flags))NULL));
23181 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
23182 (long (*)(struct bpf_map *map, void *value))NULL));
23183 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
23184 (long (*)(struct bpf_map *map, void *value))NULL));
23185 BUILD_BUG_ON(!__same_type(ops->map_redirect,
23186 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
23187 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
23188 (long (*)(struct bpf_map *map,
23189 bpf_callback_t callback_fn,
23190 void *callback_ctx,
23191 u64 flags))NULL));
23192 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
23193 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
23194
23195 patch_map_ops_generic:
23196 switch (insn->imm) {
23197 case BPF_FUNC_map_lookup_elem:
23198 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
23199 goto next_insn;
23200 case BPF_FUNC_map_update_elem:
23201 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
23202 goto next_insn;
23203 case BPF_FUNC_map_delete_elem:
23204 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
23205 goto next_insn;
23206 case BPF_FUNC_map_push_elem:
23207 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
23208 goto next_insn;
23209 case BPF_FUNC_map_pop_elem:
23210 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
23211 goto next_insn;
23212 case BPF_FUNC_map_peek_elem:
23213 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
23214 goto next_insn;
23215 case BPF_FUNC_redirect_map:
23216 insn->imm = BPF_CALL_IMM(ops->map_redirect);
23217 goto next_insn;
23218 case BPF_FUNC_for_each_map_elem:
23219 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
23220 goto next_insn;
23221 case BPF_FUNC_map_lookup_percpu_elem:
23222 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
23223 goto next_insn;
23224 }
23225
23226 goto patch_call_imm;
23227 }
23228
23229 /* Implement bpf_jiffies64 inline. */
23230 if (prog->jit_requested && BITS_PER_LONG == 64 &&
23231 insn->imm == BPF_FUNC_jiffies64) {
23232 struct bpf_insn ld_jiffies_addr[2] = {
23233 BPF_LD_IMM64(BPF_REG_0,
23234 (unsigned long)&jiffies),
23235 };
23236
23237 insn_buf[0] = ld_jiffies_addr[0];
23238 insn_buf[1] = ld_jiffies_addr[1];
23239 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
23240 BPF_REG_0, 0);
23241 cnt = 3;
23242
23243 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
23244 cnt);
23245 if (!new_prog)
23246 return -ENOMEM;
23247
23248 delta += cnt - 1;
23249 env->prog = prog = new_prog;
23250 insn = new_prog->insnsi + i + delta;
23251 goto next_insn;
23252 }
23253
23254 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
23255 /* Implement bpf_get_smp_processor_id() inline. */
23256 if (insn->imm == BPF_FUNC_get_smp_processor_id &&
23257 verifier_inlines_helper_call(env, insn->imm)) {
23258 /* BPF_FUNC_get_smp_processor_id inlining is an
23259 * optimization, so if cpu_number is ever
23260 * changed in some incompatible and hard to support
23261 * way, it's fine to back out this inlining logic
23262 */
23263 #ifdef CONFIG_SMP
23264 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
23265 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
23266 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
23267 cnt = 3;
23268 #else
23269 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
23270 cnt = 1;
23271 #endif
23272 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23273 if (!new_prog)
23274 return -ENOMEM;
23275
23276 delta += cnt - 1;
23277 env->prog = prog = new_prog;
23278 insn = new_prog->insnsi + i + delta;
23279 goto next_insn;
23280 }
23281 #endif
23282 /* Implement bpf_get_func_arg inline. */
23283 if (prog_type == BPF_PROG_TYPE_TRACING &&
23284 insn->imm == BPF_FUNC_get_func_arg) {
23285 /* Load nr_args from ctx - 8 */
23286 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23287 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
23288 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
23289 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
23290 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
23291 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23292 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
23293 insn_buf[7] = BPF_JMP_A(1);
23294 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23295 cnt = 9;
23296
23297 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23298 if (!new_prog)
23299 return -ENOMEM;
23300
23301 delta += cnt - 1;
23302 env->prog = prog = new_prog;
23303 insn = new_prog->insnsi + i + delta;
23304 goto next_insn;
23305 }
23306
23307 /* Implement bpf_get_func_ret inline. */
23308 if (prog_type == BPF_PROG_TYPE_TRACING &&
23309 insn->imm == BPF_FUNC_get_func_ret) {
23310 if (eatype == BPF_TRACE_FEXIT ||
23311 eatype == BPF_MODIFY_RETURN) {
23312 /* Load nr_args from ctx - 8 */
23313 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23314 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
23315 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
23316 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
23317 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
23318 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
23319 cnt = 6;
23320 } else {
23321 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
23322 cnt = 1;
23323 }
23324
23325 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23326 if (!new_prog)
23327 return -ENOMEM;
23328
23329 delta += cnt - 1;
23330 env->prog = prog = new_prog;
23331 insn = new_prog->insnsi + i + delta;
23332 goto next_insn;
23333 }
23334
23335 /* Implement get_func_arg_cnt inline. */
23336 if (prog_type == BPF_PROG_TYPE_TRACING &&
23337 insn->imm == BPF_FUNC_get_func_arg_cnt) {
23338 /* Load nr_args from ctx - 8 */
23339 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
23340
23341 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23342 if (!new_prog)
23343 return -ENOMEM;
23344
23345 env->prog = prog = new_prog;
23346 insn = new_prog->insnsi + i + delta;
23347 goto next_insn;
23348 }
23349
23350 /* Implement bpf_get_func_ip inline. */
23351 if (prog_type == BPF_PROG_TYPE_TRACING &&
23352 insn->imm == BPF_FUNC_get_func_ip) {
23353 /* Load IP address from ctx - 16 */
23354 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
23355
23356 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
23357 if (!new_prog)
23358 return -ENOMEM;
23359
23360 env->prog = prog = new_prog;
23361 insn = new_prog->insnsi + i + delta;
23362 goto next_insn;
23363 }
23364
23365 /* Implement bpf_get_branch_snapshot inline. */
23366 if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
23367 prog->jit_requested && BITS_PER_LONG == 64 &&
23368 insn->imm == BPF_FUNC_get_branch_snapshot) {
23369 /* We are dealing with the following func protos:
23370 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
23371 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
23372 */
23373 const u32 br_entry_size = sizeof(struct perf_branch_entry);
23374
23375 /* struct perf_branch_entry is part of UAPI and is
23376 * used as an array element, so extremely unlikely to
23377 * ever grow or shrink
23378 */
23379 BUILD_BUG_ON(br_entry_size != 24);
23380
23381 /* if (unlikely(flags)) return -EINVAL */
23382 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
23383
23384 /* Transform size (bytes) into number of entries (cnt = size / 24).
23385 * But to avoid expensive division instruction, we implement
23386 * divide-by-3 through multiplication, followed by further
23387 * division by 8 through 3-bit right shift.
23388 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
23389 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
23390 *
23391 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
23392 */
23393 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
23394 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
23395 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
23396
23397 /* call perf_snapshot_branch_stack implementation */
23398 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
23399 /* if (entry_cnt == 0) return -ENOENT */
23400 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
23401 /* return entry_cnt * sizeof(struct perf_branch_entry) */
23402 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
23403 insn_buf[7] = BPF_JMP_A(3);
23404 /* return -EINVAL; */
23405 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
23406 insn_buf[9] = BPF_JMP_A(1);
23407 /* return -ENOENT; */
23408 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
23409 cnt = 11;
23410
23411 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23412 if (!new_prog)
23413 return -ENOMEM;
23414
23415 delta += cnt - 1;
23416 env->prog = prog = new_prog;
23417 insn = new_prog->insnsi + i + delta;
23418 goto next_insn;
23419 }
23420
23421 /* Implement bpf_kptr_xchg inline */
23422 if (prog->jit_requested && BITS_PER_LONG == 64 &&
23423 insn->imm == BPF_FUNC_kptr_xchg &&
23424 bpf_jit_supports_ptr_xchg()) {
23425 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
23426 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
23427 cnt = 2;
23428
23429 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
23430 if (!new_prog)
23431 return -ENOMEM;
23432
23433 delta += cnt - 1;
23434 env->prog = prog = new_prog;
23435 insn = new_prog->insnsi + i + delta;
23436 goto next_insn;
23437 }
23438 patch_call_imm:
23439 fn = env->ops->get_func_proto(insn->imm, env->prog);
23440 /* all functions that have prototype and verifier allowed
23441 * programs to call them, must be real in-kernel functions
23442 */
23443 if (!fn->func) {
23444 verifier_bug(env,
23445 "not inlined functions %s#%d is missing func",
23446 func_id_name(insn->imm), insn->imm);
23447 return -EFAULT;
23448 }
23449 insn->imm = fn->func - __bpf_call_base;
23450 next_insn:
23451 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23452 subprogs[cur_subprog].stack_depth += stack_depth_extra;
23453 subprogs[cur_subprog].stack_extra = stack_depth_extra;
23454
23455 stack_depth = subprogs[cur_subprog].stack_depth;
23456 if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
23457 verbose(env, "stack size %d(extra %d) is too large\n",
23458 stack_depth, stack_depth_extra);
23459 return -EINVAL;
23460 }
23461 cur_subprog++;
23462 stack_depth = subprogs[cur_subprog].stack_depth;
23463 stack_depth_extra = 0;
23464 }
23465 i++;
23466 insn++;
23467 }
23468
23469 env->prog->aux->stack_depth = subprogs[0].stack_depth;
23470 for (i = 0; i < env->subprog_cnt; i++) {
23471 int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1;
23472 int subprog_start = subprogs[i].start;
23473 int stack_slots = subprogs[i].stack_extra / 8;
23474 int slots = delta, cnt = 0;
23475
23476 if (!stack_slots)
23477 continue;
23478 /* We need two slots in case timed may_goto is supported. */
23479 if (stack_slots > slots) {
23480 verifier_bug(env, "stack_slots supports may_goto only");
23481 return -EFAULT;
23482 }
23483
23484 stack_depth = subprogs[i].stack_depth;
23485 if (bpf_jit_supports_timed_may_goto()) {
23486 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23487 BPF_MAX_TIMED_LOOPS);
23488 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0);
23489 } else {
23490 /* Add ST insn to subprog prologue to init extra stack */
23491 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
23492 BPF_MAX_LOOPS);
23493 }
23494 /* Copy first actual insn to preserve it */
23495 insn_buf[cnt++] = env->prog->insnsi[subprog_start];
23496
23497 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt);
23498 if (!new_prog)
23499 return -ENOMEM;
23500 env->prog = prog = new_prog;
23501 /*
23502 * If may_goto is a first insn of a prog there could be a jmp
23503 * insn that points to it, hence adjust all such jmps to point
23504 * to insn after BPF_ST that inits may_goto count.
23505 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
23506 */
23507 WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta));
23508 }
23509
23510 /* Since poke tab is now finalized, publish aux to tracker. */
23511 for (i = 0; i < prog->aux->size_poke_tab; i++) {
23512 map_ptr = prog->aux->poke_tab[i].tail_call.map;
23513 if (!map_ptr->ops->map_poke_track ||
23514 !map_ptr->ops->map_poke_untrack ||
23515 !map_ptr->ops->map_poke_run) {
23516 verifier_bug(env, "poke tab is misconfigured");
23517 return -EFAULT;
23518 }
23519
23520 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
23521 if (ret < 0) {
23522 verbose(env, "tracking tail call prog failed\n");
23523 return ret;
23524 }
23525 }
23526
23527 ret = sort_kfunc_descs_by_imm_off(env);
23528 if (ret)
23529 return ret;
23530
23531 return 0;
23532 }
23533
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * total_cnt)23534 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
23535 int position,
23536 s32 stack_base,
23537 u32 callback_subprogno,
23538 u32 *total_cnt)
23539 {
23540 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
23541 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
23542 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
23543 int reg_loop_max = BPF_REG_6;
23544 int reg_loop_cnt = BPF_REG_7;
23545 int reg_loop_ctx = BPF_REG_8;
23546
23547 struct bpf_insn *insn_buf = env->insn_buf;
23548 struct bpf_prog *new_prog;
23549 u32 callback_start;
23550 u32 call_insn_offset;
23551 s32 callback_offset;
23552 u32 cnt = 0;
23553
23554 /* This represents an inlined version of bpf_iter.c:bpf_loop,
23555 * be careful to modify this code in sync.
23556 */
23557
23558 /* Return error and jump to the end of the patch if
23559 * expected number of iterations is too big.
23560 */
23561 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
23562 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
23563 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
23564 /* spill R6, R7, R8 to use these as loop vars */
23565 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
23566 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
23567 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
23568 /* initialize loop vars */
23569 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
23570 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
23571 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
23572 /* loop header,
23573 * if reg_loop_cnt >= reg_loop_max skip the loop body
23574 */
23575 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
23576 /* callback call,
23577 * correct callback offset would be set after patching
23578 */
23579 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
23580 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
23581 insn_buf[cnt++] = BPF_CALL_REL(0);
23582 /* increment loop counter */
23583 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
23584 /* jump to loop header if callback returned 0 */
23585 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
23586 /* return value of bpf_loop,
23587 * set R0 to the number of iterations
23588 */
23589 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
23590 /* restore original values of R6, R7, R8 */
23591 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
23592 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
23593 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
23594
23595 *total_cnt = cnt;
23596 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
23597 if (!new_prog)
23598 return new_prog;
23599
23600 /* callback start is known only after patching */
23601 callback_start = env->subprog_info[callback_subprogno].start;
23602 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
23603 call_insn_offset = position + 12;
23604 callback_offset = callback_start - call_insn_offset - 1;
23605 new_prog->insnsi[call_insn_offset].imm = callback_offset;
23606
23607 return new_prog;
23608 }
23609
is_bpf_loop_call(struct bpf_insn * insn)23610 static bool is_bpf_loop_call(struct bpf_insn *insn)
23611 {
23612 return insn->code == (BPF_JMP | BPF_CALL) &&
23613 insn->src_reg == 0 &&
23614 insn->imm == BPF_FUNC_loop;
23615 }
23616
23617 /* For all sub-programs in the program (including main) check
23618 * insn_aux_data to see if there are bpf_loop calls that require
23619 * inlining. If such calls are found the calls are replaced with a
23620 * sequence of instructions produced by `inline_bpf_loop` function and
23621 * subprog stack_depth is increased by the size of 3 registers.
23622 * This stack space is used to spill values of the R6, R7, R8. These
23623 * registers are used to store the loop bound, counter and context
23624 * variables.
23625 */
optimize_bpf_loop(struct bpf_verifier_env * env)23626 static int optimize_bpf_loop(struct bpf_verifier_env *env)
23627 {
23628 struct bpf_subprog_info *subprogs = env->subprog_info;
23629 int i, cur_subprog = 0, cnt, delta = 0;
23630 struct bpf_insn *insn = env->prog->insnsi;
23631 int insn_cnt = env->prog->len;
23632 u16 stack_depth = subprogs[cur_subprog].stack_depth;
23633 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23634 u16 stack_depth_extra = 0;
23635
23636 for (i = 0; i < insn_cnt; i++, insn++) {
23637 struct bpf_loop_inline_state *inline_state =
23638 &env->insn_aux_data[i + delta].loop_inline_state;
23639
23640 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
23641 struct bpf_prog *new_prog;
23642
23643 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
23644 new_prog = inline_bpf_loop(env,
23645 i + delta,
23646 -(stack_depth + stack_depth_extra),
23647 inline_state->callback_subprogno,
23648 &cnt);
23649 if (!new_prog)
23650 return -ENOMEM;
23651
23652 delta += cnt - 1;
23653 env->prog = new_prog;
23654 insn = new_prog->insnsi + i + delta;
23655 }
23656
23657 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
23658 subprogs[cur_subprog].stack_depth += stack_depth_extra;
23659 cur_subprog++;
23660 stack_depth = subprogs[cur_subprog].stack_depth;
23661 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
23662 stack_depth_extra = 0;
23663 }
23664 }
23665
23666 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23667
23668 return 0;
23669 }
23670
23671 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
23672 * adjust subprograms stack depth when possible.
23673 */
remove_fastcall_spills_fills(struct bpf_verifier_env * env)23674 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env)
23675 {
23676 struct bpf_subprog_info *subprog = env->subprog_info;
23677 struct bpf_insn_aux_data *aux = env->insn_aux_data;
23678 struct bpf_insn *insn = env->prog->insnsi;
23679 int insn_cnt = env->prog->len;
23680 u32 spills_num;
23681 bool modified = false;
23682 int i, j;
23683
23684 for (i = 0; i < insn_cnt; i++, insn++) {
23685 if (aux[i].fastcall_spills_num > 0) {
23686 spills_num = aux[i].fastcall_spills_num;
23687 /* NOPs would be removed by opt_remove_nops() */
23688 for (j = 1; j <= spills_num; ++j) {
23689 *(insn - j) = NOP;
23690 *(insn + j) = NOP;
23691 }
23692 modified = true;
23693 }
23694 if ((subprog + 1)->start == i + 1) {
23695 if (modified && !subprog->keep_fastcall_stack)
23696 subprog->stack_depth = -subprog->fastcall_stack_off;
23697 subprog++;
23698 modified = false;
23699 }
23700 }
23701
23702 return 0;
23703 }
23704
free_states(struct bpf_verifier_env * env)23705 static void free_states(struct bpf_verifier_env *env)
23706 {
23707 struct bpf_verifier_state_list *sl;
23708 struct list_head *head, *pos, *tmp;
23709 struct bpf_scc_info *info;
23710 int i, j;
23711
23712 free_verifier_state(env->cur_state, true);
23713 env->cur_state = NULL;
23714 while (!pop_stack(env, NULL, NULL, false));
23715
23716 list_for_each_safe(pos, tmp, &env->free_list) {
23717 sl = container_of(pos, struct bpf_verifier_state_list, node);
23718 free_verifier_state(&sl->state, false);
23719 kfree(sl);
23720 }
23721 INIT_LIST_HEAD(&env->free_list);
23722
23723 for (i = 0; i < env->scc_cnt; ++i) {
23724 info = env->scc_info[i];
23725 if (!info)
23726 continue;
23727 for (j = 0; j < info->num_visits; j++)
23728 free_backedges(&info->visits[j]);
23729 kvfree(info);
23730 env->scc_info[i] = NULL;
23731 }
23732
23733 if (!env->explored_states)
23734 return;
23735
23736 for (i = 0; i < state_htab_size(env); i++) {
23737 head = &env->explored_states[i];
23738
23739 list_for_each_safe(pos, tmp, head) {
23740 sl = container_of(pos, struct bpf_verifier_state_list, node);
23741 free_verifier_state(&sl->state, false);
23742 kfree(sl);
23743 }
23744 INIT_LIST_HEAD(&env->explored_states[i]);
23745 }
23746 }
23747
do_check_common(struct bpf_verifier_env * env,int subprog)23748 static int do_check_common(struct bpf_verifier_env *env, int subprog)
23749 {
23750 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
23751 struct bpf_subprog_info *sub = subprog_info(env, subprog);
23752 struct bpf_prog_aux *aux = env->prog->aux;
23753 struct bpf_verifier_state *state;
23754 struct bpf_reg_state *regs;
23755 int ret, i;
23756
23757 env->prev_linfo = NULL;
23758 env->pass_cnt++;
23759
23760 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT);
23761 if (!state)
23762 return -ENOMEM;
23763 state->curframe = 0;
23764 state->speculative = false;
23765 state->branches = 1;
23766 state->in_sleepable = env->prog->sleepable;
23767 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT);
23768 if (!state->frame[0]) {
23769 kfree(state);
23770 return -ENOMEM;
23771 }
23772 env->cur_state = state;
23773 init_func_state(env, state->frame[0],
23774 BPF_MAIN_FUNC /* callsite */,
23775 0 /* frameno */,
23776 subprog);
23777 state->first_insn_idx = env->subprog_info[subprog].start;
23778 state->last_insn_idx = -1;
23779
23780 regs = state->frame[state->curframe]->regs;
23781 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
23782 const char *sub_name = subprog_name(env, subprog);
23783 struct bpf_subprog_arg_info *arg;
23784 struct bpf_reg_state *reg;
23785
23786 if (env->log.level & BPF_LOG_LEVEL)
23787 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog);
23788 ret = btf_prepare_func_args(env, subprog);
23789 if (ret)
23790 goto out;
23791
23792 if (subprog_is_exc_cb(env, subprog)) {
23793 state->frame[0]->in_exception_callback_fn = true;
23794 /* We have already ensured that the callback returns an integer, just
23795 * like all global subprogs. We need to determine it only has a single
23796 * scalar argument.
23797 */
23798 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) {
23799 verbose(env, "exception cb only supports single integer argument\n");
23800 ret = -EINVAL;
23801 goto out;
23802 }
23803 }
23804 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) {
23805 arg = &sub->args[i - BPF_REG_1];
23806 reg = ®s[i];
23807
23808 if (arg->arg_type == ARG_PTR_TO_CTX) {
23809 reg->type = PTR_TO_CTX;
23810 mark_reg_known_zero(env, regs, i);
23811 } else if (arg->arg_type == ARG_ANYTHING) {
23812 reg->type = SCALAR_VALUE;
23813 mark_reg_unknown(env, regs, i);
23814 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
23815 /* assume unspecial LOCAL dynptr type */
23816 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
23817 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
23818 reg->type = PTR_TO_MEM;
23819 reg->type |= arg->arg_type &
23820 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY);
23821 mark_reg_known_zero(env, regs, i);
23822 reg->mem_size = arg->mem_size;
23823 if (arg->arg_type & PTR_MAYBE_NULL)
23824 reg->id = ++env->id_gen;
23825 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) {
23826 reg->type = PTR_TO_BTF_ID;
23827 if (arg->arg_type & PTR_MAYBE_NULL)
23828 reg->type |= PTR_MAYBE_NULL;
23829 if (arg->arg_type & PTR_UNTRUSTED)
23830 reg->type |= PTR_UNTRUSTED;
23831 if (arg->arg_type & PTR_TRUSTED)
23832 reg->type |= PTR_TRUSTED;
23833 mark_reg_known_zero(env, regs, i);
23834 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */
23835 reg->btf_id = arg->btf_id;
23836 reg->id = ++env->id_gen;
23837 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) {
23838 /* caller can pass either PTR_TO_ARENA or SCALAR */
23839 mark_reg_unknown(env, regs, i);
23840 } else {
23841 verifier_bug(env, "unhandled arg#%d type %d",
23842 i - BPF_REG_1, arg->arg_type);
23843 ret = -EFAULT;
23844 goto out;
23845 }
23846 }
23847 } else {
23848 /* if main BPF program has associated BTF info, validate that
23849 * it's matching expected signature, and otherwise mark BTF
23850 * info for main program as unreliable
23851 */
23852 if (env->prog->aux->func_info_aux) {
23853 ret = btf_prepare_func_args(env, 0);
23854 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX)
23855 env->prog->aux->func_info_aux[0].unreliable = true;
23856 }
23857
23858 /* 1st arg to a function */
23859 regs[BPF_REG_1].type = PTR_TO_CTX;
23860 mark_reg_known_zero(env, regs, BPF_REG_1);
23861 }
23862
23863 /* Acquire references for struct_ops program arguments tagged with "__ref" */
23864 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
23865 for (i = 0; i < aux->ctx_arg_info_size; i++)
23866 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ?
23867 acquire_reference(env, 0) : 0;
23868 }
23869
23870 ret = do_check(env);
23871 out:
23872 if (!ret && pop_log)
23873 bpf_vlog_reset(&env->log, 0);
23874 free_states(env);
23875 return ret;
23876 }
23877
23878 /* Lazily verify all global functions based on their BTF, if they are called
23879 * from main BPF program or any of subprograms transitively.
23880 * BPF global subprogs called from dead code are not validated.
23881 * All callable global functions must pass verification.
23882 * Otherwise the whole program is rejected.
23883 * Consider:
23884 * int bar(int);
23885 * int foo(int f)
23886 * {
23887 * return bar(f);
23888 * }
23889 * int bar(int b)
23890 * {
23891 * ...
23892 * }
23893 * foo() will be verified first for R1=any_scalar_value. During verification it
23894 * will be assumed that bar() already verified successfully and call to bar()
23895 * from foo() will be checked for type match only. Later bar() will be verified
23896 * independently to check that it's safe for R1=any_scalar_value.
23897 */
do_check_subprogs(struct bpf_verifier_env * env)23898 static int do_check_subprogs(struct bpf_verifier_env *env)
23899 {
23900 struct bpf_prog_aux *aux = env->prog->aux;
23901 struct bpf_func_info_aux *sub_aux;
23902 int i, ret, new_cnt;
23903
23904 if (!aux->func_info)
23905 return 0;
23906
23907 /* exception callback is presumed to be always called */
23908 if (env->exception_callback_subprog)
23909 subprog_aux(env, env->exception_callback_subprog)->called = true;
23910
23911 again:
23912 new_cnt = 0;
23913 for (i = 1; i < env->subprog_cnt; i++) {
23914 if (!subprog_is_global(env, i))
23915 continue;
23916
23917 sub_aux = subprog_aux(env, i);
23918 if (!sub_aux->called || sub_aux->verified)
23919 continue;
23920
23921 env->insn_idx = env->subprog_info[i].start;
23922 WARN_ON_ONCE(env->insn_idx == 0);
23923 ret = do_check_common(env, i);
23924 if (ret) {
23925 return ret;
23926 } else if (env->log.level & BPF_LOG_LEVEL) {
23927 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
23928 i, subprog_name(env, i));
23929 }
23930
23931 /* We verified new global subprog, it might have called some
23932 * more global subprogs that we haven't verified yet, so we
23933 * need to do another pass over subprogs to verify those.
23934 */
23935 sub_aux->verified = true;
23936 new_cnt++;
23937 }
23938
23939 /* We can't loop forever as we verify at least one global subprog on
23940 * each pass.
23941 */
23942 if (new_cnt)
23943 goto again;
23944
23945 return 0;
23946 }
23947
do_check_main(struct bpf_verifier_env * env)23948 static int do_check_main(struct bpf_verifier_env *env)
23949 {
23950 int ret;
23951
23952 env->insn_idx = 0;
23953 ret = do_check_common(env, 0);
23954 if (!ret)
23955 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
23956 return ret;
23957 }
23958
23959
print_verification_stats(struct bpf_verifier_env * env)23960 static void print_verification_stats(struct bpf_verifier_env *env)
23961 {
23962 int i;
23963
23964 if (env->log.level & BPF_LOG_STATS) {
23965 verbose(env, "verification time %lld usec\n",
23966 div_u64(env->verification_time, 1000));
23967 verbose(env, "stack depth ");
23968 for (i = 0; i < env->subprog_cnt; i++) {
23969 u32 depth = env->subprog_info[i].stack_depth;
23970
23971 verbose(env, "%d", depth);
23972 if (i + 1 < env->subprog_cnt)
23973 verbose(env, "+");
23974 }
23975 verbose(env, "\n");
23976 }
23977 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
23978 "total_states %d peak_states %d mark_read %d\n",
23979 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
23980 env->max_states_per_insn, env->total_states,
23981 env->peak_states, env->longest_mark_read_walk);
23982 }
23983
bpf_prog_ctx_arg_info_init(struct bpf_prog * prog,const struct bpf_ctx_arg_aux * info,u32 cnt)23984 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
23985 const struct bpf_ctx_arg_aux *info, u32 cnt)
23986 {
23987 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT);
23988 prog->aux->ctx_arg_info_size = cnt;
23989
23990 return prog->aux->ctx_arg_info ? 0 : -ENOMEM;
23991 }
23992
check_struct_ops_btf_id(struct bpf_verifier_env * env)23993 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
23994 {
23995 const struct btf_type *t, *func_proto;
23996 const struct bpf_struct_ops_desc *st_ops_desc;
23997 const struct bpf_struct_ops *st_ops;
23998 const struct btf_member *member;
23999 struct bpf_prog *prog = env->prog;
24000 bool has_refcounted_arg = false;
24001 u32 btf_id, member_idx, member_off;
24002 struct btf *btf;
24003 const char *mname;
24004 int i, err;
24005
24006 if (!prog->gpl_compatible) {
24007 verbose(env, "struct ops programs must have a GPL compatible license\n");
24008 return -EINVAL;
24009 }
24010
24011 if (!prog->aux->attach_btf_id)
24012 return -ENOTSUPP;
24013
24014 btf = prog->aux->attach_btf;
24015 if (btf_is_module(btf)) {
24016 /* Make sure st_ops is valid through the lifetime of env */
24017 env->attach_btf_mod = btf_try_get_module(btf);
24018 if (!env->attach_btf_mod) {
24019 verbose(env, "struct_ops module %s is not found\n",
24020 btf_get_name(btf));
24021 return -ENOTSUPP;
24022 }
24023 }
24024
24025 btf_id = prog->aux->attach_btf_id;
24026 st_ops_desc = bpf_struct_ops_find(btf, btf_id);
24027 if (!st_ops_desc) {
24028 verbose(env, "attach_btf_id %u is not a supported struct\n",
24029 btf_id);
24030 return -ENOTSUPP;
24031 }
24032 st_ops = st_ops_desc->st_ops;
24033
24034 t = st_ops_desc->type;
24035 member_idx = prog->expected_attach_type;
24036 if (member_idx >= btf_type_vlen(t)) {
24037 verbose(env, "attach to invalid member idx %u of struct %s\n",
24038 member_idx, st_ops->name);
24039 return -EINVAL;
24040 }
24041
24042 member = &btf_type_member(t)[member_idx];
24043 mname = btf_name_by_offset(btf, member->name_off);
24044 func_proto = btf_type_resolve_func_ptr(btf, member->type,
24045 NULL);
24046 if (!func_proto) {
24047 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
24048 mname, member_idx, st_ops->name);
24049 return -EINVAL;
24050 }
24051
24052 member_off = __btf_member_bit_offset(t, member) / 8;
24053 err = bpf_struct_ops_supported(st_ops, member_off);
24054 if (err) {
24055 verbose(env, "attach to unsupported member %s of struct %s\n",
24056 mname, st_ops->name);
24057 return err;
24058 }
24059
24060 if (st_ops->check_member) {
24061 err = st_ops->check_member(t, member, prog);
24062
24063 if (err) {
24064 verbose(env, "attach to unsupported member %s of struct %s\n",
24065 mname, st_ops->name);
24066 return err;
24067 }
24068 }
24069
24070 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) {
24071 verbose(env, "Private stack not supported by jit\n");
24072 return -EACCES;
24073 }
24074
24075 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) {
24076 if (st_ops_desc->arg_info[member_idx].info->refcounted) {
24077 has_refcounted_arg = true;
24078 break;
24079 }
24080 }
24081
24082 /* Tail call is not allowed for programs with refcounted arguments since we
24083 * cannot guarantee that valid refcounted kptrs will be passed to the callee.
24084 */
24085 for (i = 0; i < env->subprog_cnt; i++) {
24086 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) {
24087 verbose(env, "program with __ref argument cannot tail call\n");
24088 return -EINVAL;
24089 }
24090 }
24091
24092 prog->aux->st_ops = st_ops;
24093 prog->aux->attach_st_ops_member_off = member_off;
24094
24095 prog->aux->attach_func_proto = func_proto;
24096 prog->aux->attach_func_name = mname;
24097 env->ops = st_ops->verifier_ops;
24098
24099 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info,
24100 st_ops_desc->arg_info[member_idx].cnt);
24101 }
24102 #define SECURITY_PREFIX "security_"
24103
check_attach_modify_return(unsigned long addr,const char * func_name)24104 static int check_attach_modify_return(unsigned long addr, const char *func_name)
24105 {
24106 if (within_error_injection_list(addr) ||
24107 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
24108 return 0;
24109
24110 return -EINVAL;
24111 }
24112
24113 /* list of non-sleepable functions that are otherwise on
24114 * ALLOW_ERROR_INJECTION list
24115 */
24116 BTF_SET_START(btf_non_sleepable_error_inject)
24117 /* Three functions below can be called from sleepable and non-sleepable context.
24118 * Assume non-sleepable from bpf safety point of view.
24119 */
BTF_ID(func,__filemap_add_folio)24120 BTF_ID(func, __filemap_add_folio)
24121 #ifdef CONFIG_FAIL_PAGE_ALLOC
24122 BTF_ID(func, should_fail_alloc_page)
24123 #endif
24124 #ifdef CONFIG_FAILSLAB
24125 BTF_ID(func, should_failslab)
24126 #endif
24127 BTF_SET_END(btf_non_sleepable_error_inject)
24128
24129 static int check_non_sleepable_error_inject(u32 btf_id)
24130 {
24131 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
24132 }
24133
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)24134 int bpf_check_attach_target(struct bpf_verifier_log *log,
24135 const struct bpf_prog *prog,
24136 const struct bpf_prog *tgt_prog,
24137 u32 btf_id,
24138 struct bpf_attach_target_info *tgt_info)
24139 {
24140 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
24141 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING;
24142 char trace_symbol[KSYM_SYMBOL_LEN];
24143 const char prefix[] = "btf_trace_";
24144 struct bpf_raw_event_map *btp;
24145 int ret = 0, subprog = -1, i;
24146 const struct btf_type *t;
24147 bool conservative = true;
24148 const char *tname, *fname;
24149 struct btf *btf;
24150 long addr = 0;
24151 struct module *mod = NULL;
24152
24153 if (!btf_id) {
24154 bpf_log(log, "Tracing programs must provide btf_id\n");
24155 return -EINVAL;
24156 }
24157 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
24158 if (!btf) {
24159 bpf_log(log,
24160 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
24161 return -EINVAL;
24162 }
24163 t = btf_type_by_id(btf, btf_id);
24164 if (!t) {
24165 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
24166 return -EINVAL;
24167 }
24168 tname = btf_name_by_offset(btf, t->name_off);
24169 if (!tname) {
24170 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
24171 return -EINVAL;
24172 }
24173 if (tgt_prog) {
24174 struct bpf_prog_aux *aux = tgt_prog->aux;
24175 bool tgt_changes_pkt_data;
24176 bool tgt_might_sleep;
24177
24178 if (bpf_prog_is_dev_bound(prog->aux) &&
24179 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
24180 bpf_log(log, "Target program bound device mismatch");
24181 return -EINVAL;
24182 }
24183
24184 for (i = 0; i < aux->func_info_cnt; i++)
24185 if (aux->func_info[i].type_id == btf_id) {
24186 subprog = i;
24187 break;
24188 }
24189 if (subprog == -1) {
24190 bpf_log(log, "Subprog %s doesn't exist\n", tname);
24191 return -EINVAL;
24192 }
24193 if (aux->func && aux->func[subprog]->aux->exception_cb) {
24194 bpf_log(log,
24195 "%s programs cannot attach to exception callback\n",
24196 prog_extension ? "Extension" : "FENTRY/FEXIT");
24197 return -EINVAL;
24198 }
24199 conservative = aux->func_info_aux[subprog].unreliable;
24200 if (prog_extension) {
24201 if (conservative) {
24202 bpf_log(log,
24203 "Cannot replace static functions\n");
24204 return -EINVAL;
24205 }
24206 if (!prog->jit_requested) {
24207 bpf_log(log,
24208 "Extension programs should be JITed\n");
24209 return -EINVAL;
24210 }
24211 tgt_changes_pkt_data = aux->func
24212 ? aux->func[subprog]->aux->changes_pkt_data
24213 : aux->changes_pkt_data;
24214 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) {
24215 bpf_log(log,
24216 "Extension program changes packet data, while original does not\n");
24217 return -EINVAL;
24218 }
24219
24220 tgt_might_sleep = aux->func
24221 ? aux->func[subprog]->aux->might_sleep
24222 : aux->might_sleep;
24223 if (prog->aux->might_sleep && !tgt_might_sleep) {
24224 bpf_log(log,
24225 "Extension program may sleep, while original does not\n");
24226 return -EINVAL;
24227 }
24228 }
24229 if (!tgt_prog->jited) {
24230 bpf_log(log, "Can attach to only JITed progs\n");
24231 return -EINVAL;
24232 }
24233 if (prog_tracing) {
24234 if (aux->attach_tracing_prog) {
24235 /*
24236 * Target program is an fentry/fexit which is already attached
24237 * to another tracing program. More levels of nesting
24238 * attachment are not allowed.
24239 */
24240 bpf_log(log, "Cannot nest tracing program attach more than once\n");
24241 return -EINVAL;
24242 }
24243 } else if (tgt_prog->type == prog->type) {
24244 /*
24245 * To avoid potential call chain cycles, prevent attaching of a
24246 * program extension to another extension. It's ok to attach
24247 * fentry/fexit to extension program.
24248 */
24249 bpf_log(log, "Cannot recursively attach\n");
24250 return -EINVAL;
24251 }
24252 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
24253 prog_extension &&
24254 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
24255 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
24256 /* Program extensions can extend all program types
24257 * except fentry/fexit. The reason is the following.
24258 * The fentry/fexit programs are used for performance
24259 * analysis, stats and can be attached to any program
24260 * type. When extension program is replacing XDP function
24261 * it is necessary to allow performance analysis of all
24262 * functions. Both original XDP program and its program
24263 * extension. Hence attaching fentry/fexit to
24264 * BPF_PROG_TYPE_EXT is allowed. If extending of
24265 * fentry/fexit was allowed it would be possible to create
24266 * long call chain fentry->extension->fentry->extension
24267 * beyond reasonable stack size. Hence extending fentry
24268 * is not allowed.
24269 */
24270 bpf_log(log, "Cannot extend fentry/fexit\n");
24271 return -EINVAL;
24272 }
24273 } else {
24274 if (prog_extension) {
24275 bpf_log(log, "Cannot replace kernel functions\n");
24276 return -EINVAL;
24277 }
24278 }
24279
24280 switch (prog->expected_attach_type) {
24281 case BPF_TRACE_RAW_TP:
24282 if (tgt_prog) {
24283 bpf_log(log,
24284 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
24285 return -EINVAL;
24286 }
24287 if (!btf_type_is_typedef(t)) {
24288 bpf_log(log, "attach_btf_id %u is not a typedef\n",
24289 btf_id);
24290 return -EINVAL;
24291 }
24292 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
24293 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
24294 btf_id, tname);
24295 return -EINVAL;
24296 }
24297 tname += sizeof(prefix) - 1;
24298
24299 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument
24300 * names. Thus using bpf_raw_event_map to get argument names.
24301 */
24302 btp = bpf_get_raw_tracepoint(tname);
24303 if (!btp)
24304 return -EINVAL;
24305 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL,
24306 trace_symbol);
24307 bpf_put_raw_tracepoint(btp);
24308
24309 if (fname)
24310 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC);
24311
24312 if (!fname || ret < 0) {
24313 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n",
24314 prefix, tname);
24315 t = btf_type_by_id(btf, t->type);
24316 if (!btf_type_is_ptr(t))
24317 /* should never happen in valid vmlinux build */
24318 return -EINVAL;
24319 } else {
24320 t = btf_type_by_id(btf, ret);
24321 if (!btf_type_is_func(t))
24322 /* should never happen in valid vmlinux build */
24323 return -EINVAL;
24324 }
24325
24326 t = btf_type_by_id(btf, t->type);
24327 if (!btf_type_is_func_proto(t))
24328 /* should never happen in valid vmlinux build */
24329 return -EINVAL;
24330
24331 break;
24332 case BPF_TRACE_ITER:
24333 if (!btf_type_is_func(t)) {
24334 bpf_log(log, "attach_btf_id %u is not a function\n",
24335 btf_id);
24336 return -EINVAL;
24337 }
24338 t = btf_type_by_id(btf, t->type);
24339 if (!btf_type_is_func_proto(t))
24340 return -EINVAL;
24341 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24342 if (ret)
24343 return ret;
24344 break;
24345 default:
24346 if (!prog_extension)
24347 return -EINVAL;
24348 fallthrough;
24349 case BPF_MODIFY_RETURN:
24350 case BPF_LSM_MAC:
24351 case BPF_LSM_CGROUP:
24352 case BPF_TRACE_FENTRY:
24353 case BPF_TRACE_FEXIT:
24354 if (!btf_type_is_func(t)) {
24355 bpf_log(log, "attach_btf_id %u is not a function\n",
24356 btf_id);
24357 return -EINVAL;
24358 }
24359 if (prog_extension &&
24360 btf_check_type_match(log, prog, btf, t))
24361 return -EINVAL;
24362 t = btf_type_by_id(btf, t->type);
24363 if (!btf_type_is_func_proto(t))
24364 return -EINVAL;
24365
24366 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
24367 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
24368 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
24369 return -EINVAL;
24370
24371 if (tgt_prog && conservative)
24372 t = NULL;
24373
24374 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
24375 if (ret < 0)
24376 return ret;
24377
24378 if (tgt_prog) {
24379 if (subprog == 0)
24380 addr = (long) tgt_prog->bpf_func;
24381 else
24382 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
24383 } else {
24384 if (btf_is_module(btf)) {
24385 mod = btf_try_get_module(btf);
24386 if (mod)
24387 addr = find_kallsyms_symbol_value(mod, tname);
24388 else
24389 addr = 0;
24390 } else {
24391 addr = kallsyms_lookup_name(tname);
24392 }
24393 if (!addr) {
24394 module_put(mod);
24395 bpf_log(log,
24396 "The address of function %s cannot be found\n",
24397 tname);
24398 return -ENOENT;
24399 }
24400 }
24401
24402 if (prog->sleepable) {
24403 ret = -EINVAL;
24404 switch (prog->type) {
24405 case BPF_PROG_TYPE_TRACING:
24406
24407 /* fentry/fexit/fmod_ret progs can be sleepable if they are
24408 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
24409 */
24410 if (!check_non_sleepable_error_inject(btf_id) &&
24411 within_error_injection_list(addr))
24412 ret = 0;
24413 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
24414 * in the fmodret id set with the KF_SLEEPABLE flag.
24415 */
24416 else {
24417 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
24418 prog);
24419
24420 if (flags && (*flags & KF_SLEEPABLE))
24421 ret = 0;
24422 }
24423 break;
24424 case BPF_PROG_TYPE_LSM:
24425 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
24426 * Only some of them are sleepable.
24427 */
24428 if (bpf_lsm_is_sleepable_hook(btf_id))
24429 ret = 0;
24430 break;
24431 default:
24432 break;
24433 }
24434 if (ret) {
24435 module_put(mod);
24436 bpf_log(log, "%s is not sleepable\n", tname);
24437 return ret;
24438 }
24439 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
24440 if (tgt_prog) {
24441 module_put(mod);
24442 bpf_log(log, "can't modify return codes of BPF programs\n");
24443 return -EINVAL;
24444 }
24445 ret = -EINVAL;
24446 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
24447 !check_attach_modify_return(addr, tname))
24448 ret = 0;
24449 if (ret) {
24450 module_put(mod);
24451 bpf_log(log, "%s() is not modifiable\n", tname);
24452 return ret;
24453 }
24454 }
24455
24456 break;
24457 }
24458 tgt_info->tgt_addr = addr;
24459 tgt_info->tgt_name = tname;
24460 tgt_info->tgt_type = t;
24461 tgt_info->tgt_mod = mod;
24462 return 0;
24463 }
24464
BTF_SET_START(btf_id_deny)24465 BTF_SET_START(btf_id_deny)
24466 BTF_ID_UNUSED
24467 #ifdef CONFIG_SMP
24468 BTF_ID(func, ___migrate_enable)
24469 BTF_ID(func, migrate_disable)
24470 BTF_ID(func, migrate_enable)
24471 #endif
24472 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
24473 BTF_ID(func, rcu_read_unlock_strict)
24474 #endif
24475 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
24476 BTF_ID(func, preempt_count_add)
24477 BTF_ID(func, preempt_count_sub)
24478 #endif
24479 #ifdef CONFIG_PREEMPT_RCU
24480 BTF_ID(func, __rcu_read_lock)
24481 BTF_ID(func, __rcu_read_unlock)
24482 #endif
24483 BTF_SET_END(btf_id_deny)
24484
24485 /* fexit and fmod_ret can't be used to attach to __noreturn functions.
24486 * Currently, we must manually list all __noreturn functions here. Once a more
24487 * robust solution is implemented, this workaround can be removed.
24488 */
24489 BTF_SET_START(noreturn_deny)
24490 #ifdef CONFIG_IA32_EMULATION
24491 BTF_ID(func, __ia32_sys_exit)
24492 BTF_ID(func, __ia32_sys_exit_group)
24493 #endif
24494 #ifdef CONFIG_KUNIT
24495 BTF_ID(func, __kunit_abort)
24496 BTF_ID(func, kunit_try_catch_throw)
24497 #endif
24498 #ifdef CONFIG_MODULES
24499 BTF_ID(func, __module_put_and_kthread_exit)
24500 #endif
24501 #ifdef CONFIG_X86_64
24502 BTF_ID(func, __x64_sys_exit)
24503 BTF_ID(func, __x64_sys_exit_group)
24504 #endif
24505 BTF_ID(func, do_exit)
24506 BTF_ID(func, do_group_exit)
24507 BTF_ID(func, kthread_complete_and_exit)
24508 BTF_ID(func, kthread_exit)
24509 BTF_ID(func, make_task_dead)
24510 BTF_SET_END(noreturn_deny)
24511
24512 static bool can_be_sleepable(struct bpf_prog *prog)
24513 {
24514 if (prog->type == BPF_PROG_TYPE_TRACING) {
24515 switch (prog->expected_attach_type) {
24516 case BPF_TRACE_FENTRY:
24517 case BPF_TRACE_FEXIT:
24518 case BPF_MODIFY_RETURN:
24519 case BPF_TRACE_ITER:
24520 return true;
24521 default:
24522 return false;
24523 }
24524 }
24525 return prog->type == BPF_PROG_TYPE_LSM ||
24526 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
24527 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
24528 }
24529
check_attach_btf_id(struct bpf_verifier_env * env)24530 static int check_attach_btf_id(struct bpf_verifier_env *env)
24531 {
24532 struct bpf_prog *prog = env->prog;
24533 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
24534 struct bpf_attach_target_info tgt_info = {};
24535 u32 btf_id = prog->aux->attach_btf_id;
24536 struct bpf_trampoline *tr;
24537 int ret;
24538 u64 key;
24539
24540 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
24541 if (prog->sleepable)
24542 /* attach_btf_id checked to be zero already */
24543 return 0;
24544 verbose(env, "Syscall programs can only be sleepable\n");
24545 return -EINVAL;
24546 }
24547
24548 if (prog->sleepable && !can_be_sleepable(prog)) {
24549 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
24550 return -EINVAL;
24551 }
24552
24553 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
24554 return check_struct_ops_btf_id(env);
24555
24556 if (prog->type != BPF_PROG_TYPE_TRACING &&
24557 prog->type != BPF_PROG_TYPE_LSM &&
24558 prog->type != BPF_PROG_TYPE_EXT)
24559 return 0;
24560
24561 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
24562 if (ret)
24563 return ret;
24564
24565 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
24566 /* to make freplace equivalent to their targets, they need to
24567 * inherit env->ops and expected_attach_type for the rest of the
24568 * verification
24569 */
24570 env->ops = bpf_verifier_ops[tgt_prog->type];
24571 prog->expected_attach_type = tgt_prog->expected_attach_type;
24572 }
24573
24574 /* store info about the attachment target that will be used later */
24575 prog->aux->attach_func_proto = tgt_info.tgt_type;
24576 prog->aux->attach_func_name = tgt_info.tgt_name;
24577 prog->aux->mod = tgt_info.tgt_mod;
24578
24579 if (tgt_prog) {
24580 prog->aux->saved_dst_prog_type = tgt_prog->type;
24581 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
24582 }
24583
24584 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
24585 prog->aux->attach_btf_trace = true;
24586 return 0;
24587 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
24588 return bpf_iter_prog_supported(prog);
24589 }
24590
24591 if (prog->type == BPF_PROG_TYPE_LSM) {
24592 ret = bpf_lsm_verify_prog(&env->log, prog);
24593 if (ret < 0)
24594 return ret;
24595 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
24596 btf_id_set_contains(&btf_id_deny, btf_id)) {
24597 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n",
24598 tgt_info.tgt_name);
24599 return -EINVAL;
24600 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT ||
24601 prog->expected_attach_type == BPF_MODIFY_RETURN) &&
24602 btf_id_set_contains(&noreturn_deny, btf_id)) {
24603 verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n",
24604 tgt_info.tgt_name);
24605 return -EINVAL;
24606 }
24607
24608 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
24609 tr = bpf_trampoline_get(key, &tgt_info);
24610 if (!tr)
24611 return -ENOMEM;
24612
24613 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
24614 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
24615
24616 prog->aux->dst_trampoline = tr;
24617 return 0;
24618 }
24619
bpf_get_btf_vmlinux(void)24620 struct btf *bpf_get_btf_vmlinux(void)
24621 {
24622 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
24623 mutex_lock(&bpf_verifier_lock);
24624 if (!btf_vmlinux)
24625 btf_vmlinux = btf_parse_vmlinux();
24626 mutex_unlock(&bpf_verifier_lock);
24627 }
24628 return btf_vmlinux;
24629 }
24630
24631 /*
24632 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In
24633 * this case expect that every file descriptor in the array is either a map or
24634 * a BTF. Everything else is considered to be trash.
24635 */
add_fd_from_fd_array(struct bpf_verifier_env * env,int fd)24636 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd)
24637 {
24638 struct bpf_map *map;
24639 struct btf *btf;
24640 CLASS(fd, f)(fd);
24641 int err;
24642
24643 map = __bpf_map_get(f);
24644 if (!IS_ERR(map)) {
24645 err = __add_used_map(env, map);
24646 if (err < 0)
24647 return err;
24648 return 0;
24649 }
24650
24651 btf = __btf_get_by_fd(f);
24652 if (!IS_ERR(btf)) {
24653 err = __add_used_btf(env, btf);
24654 if (err < 0)
24655 return err;
24656 return 0;
24657 }
24658
24659 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd);
24660 return PTR_ERR(map);
24661 }
24662
process_fd_array(struct bpf_verifier_env * env,union bpf_attr * attr,bpfptr_t uattr)24663 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr)
24664 {
24665 size_t size = sizeof(int);
24666 int ret;
24667 int fd;
24668 u32 i;
24669
24670 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
24671
24672 /*
24673 * The only difference between old (no fd_array_cnt is given) and new
24674 * APIs is that in the latter case the fd_array is expected to be
24675 * continuous and is scanned for map fds right away
24676 */
24677 if (!attr->fd_array_cnt)
24678 return 0;
24679
24680 /* Check for integer overflow */
24681 if (attr->fd_array_cnt >= (U32_MAX / size)) {
24682 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt);
24683 return -EINVAL;
24684 }
24685
24686 for (i = 0; i < attr->fd_array_cnt; i++) {
24687 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size))
24688 return -EFAULT;
24689
24690 ret = add_fd_from_fd_array(env, fd);
24691 if (ret)
24692 return ret;
24693 }
24694
24695 return 0;
24696 }
24697
24698 /* Each field is a register bitmask */
24699 struct insn_live_regs {
24700 u16 use; /* registers read by instruction */
24701 u16 def; /* registers written by instruction */
24702 u16 in; /* registers that may be alive before instruction */
24703 u16 out; /* registers that may be alive after instruction */
24704 };
24705
24706 /* Bitmask with 1s for all caller saved registers */
24707 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
24708
24709 /* 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)24710 static void compute_insn_live_regs(struct bpf_verifier_env *env,
24711 struct bpf_insn *insn,
24712 struct insn_live_regs *info)
24713 {
24714 struct call_summary cs;
24715 u8 class = BPF_CLASS(insn->code);
24716 u8 code = BPF_OP(insn->code);
24717 u8 mode = BPF_MODE(insn->code);
24718 u16 src = BIT(insn->src_reg);
24719 u16 dst = BIT(insn->dst_reg);
24720 u16 r0 = BIT(0);
24721 u16 def = 0;
24722 u16 use = 0xffff;
24723
24724 switch (class) {
24725 case BPF_LD:
24726 switch (mode) {
24727 case BPF_IMM:
24728 if (BPF_SIZE(insn->code) == BPF_DW) {
24729 def = dst;
24730 use = 0;
24731 }
24732 break;
24733 case BPF_LD | BPF_ABS:
24734 case BPF_LD | BPF_IND:
24735 /* stick with defaults */
24736 break;
24737 }
24738 break;
24739 case BPF_LDX:
24740 switch (mode) {
24741 case BPF_MEM:
24742 case BPF_MEMSX:
24743 def = dst;
24744 use = src;
24745 break;
24746 }
24747 break;
24748 case BPF_ST:
24749 switch (mode) {
24750 case BPF_MEM:
24751 def = 0;
24752 use = dst;
24753 break;
24754 }
24755 break;
24756 case BPF_STX:
24757 switch (mode) {
24758 case BPF_MEM:
24759 def = 0;
24760 use = dst | src;
24761 break;
24762 case BPF_ATOMIC:
24763 switch (insn->imm) {
24764 case BPF_CMPXCHG:
24765 use = r0 | dst | src;
24766 def = r0;
24767 break;
24768 case BPF_LOAD_ACQ:
24769 def = dst;
24770 use = src;
24771 break;
24772 case BPF_STORE_REL:
24773 def = 0;
24774 use = dst | src;
24775 break;
24776 default:
24777 use = dst | src;
24778 if (insn->imm & BPF_FETCH)
24779 def = src;
24780 else
24781 def = 0;
24782 }
24783 break;
24784 }
24785 break;
24786 case BPF_ALU:
24787 case BPF_ALU64:
24788 switch (code) {
24789 case BPF_END:
24790 use = dst;
24791 def = dst;
24792 break;
24793 case BPF_MOV:
24794 def = dst;
24795 if (BPF_SRC(insn->code) == BPF_K)
24796 use = 0;
24797 else
24798 use = src;
24799 break;
24800 default:
24801 def = dst;
24802 if (BPF_SRC(insn->code) == BPF_K)
24803 use = dst;
24804 else
24805 use = dst | src;
24806 }
24807 break;
24808 case BPF_JMP:
24809 case BPF_JMP32:
24810 switch (code) {
24811 case BPF_JA:
24812 case BPF_JCOND:
24813 def = 0;
24814 use = 0;
24815 break;
24816 case BPF_EXIT:
24817 def = 0;
24818 use = r0;
24819 break;
24820 case BPF_CALL:
24821 def = ALL_CALLER_SAVED_REGS;
24822 use = def & ~BIT(BPF_REG_0);
24823 if (get_call_summary(env, insn, &cs))
24824 use = GENMASK(cs.num_params, 1);
24825 break;
24826 default:
24827 def = 0;
24828 if (BPF_SRC(insn->code) == BPF_K)
24829 use = dst;
24830 else
24831 use = dst | src;
24832 }
24833 break;
24834 }
24835
24836 info->def = def;
24837 info->use = use;
24838 }
24839
24840 /* Compute may-live registers after each instruction in the program.
24841 * The register is live after the instruction I if it is read by some
24842 * instruction S following I during program execution and is not
24843 * overwritten between I and S.
24844 *
24845 * Store result in env->insn_aux_data[i].live_regs.
24846 */
compute_live_registers(struct bpf_verifier_env * env)24847 static int compute_live_registers(struct bpf_verifier_env *env)
24848 {
24849 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
24850 struct bpf_insn *insns = env->prog->insnsi;
24851 struct insn_live_regs *state;
24852 int insn_cnt = env->prog->len;
24853 int err = 0, i, j;
24854 bool changed;
24855
24856 /* Use the following algorithm:
24857 * - define the following:
24858 * - I.use : a set of all registers read by instruction I;
24859 * - I.def : a set of all registers written by instruction I;
24860 * - I.in : a set of all registers that may be alive before I execution;
24861 * - I.out : a set of all registers that may be alive after I execution;
24862 * - insn_successors(I): a set of instructions S that might immediately
24863 * follow I for some program execution;
24864 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
24865 * - visit each instruction in a postorder and update
24866 * state[i].in, state[i].out as follows:
24867 *
24868 * state[i].out = U [state[s].in for S in insn_successors(i)]
24869 * state[i].in = (state[i].out / state[i].def) U state[i].use
24870 *
24871 * (where U stands for set union, / stands for set difference)
24872 * - repeat the computation while {in,out} fields changes for
24873 * any instruction.
24874 */
24875 state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT);
24876 if (!state) {
24877 err = -ENOMEM;
24878 goto out;
24879 }
24880
24881 for (i = 0; i < insn_cnt; ++i)
24882 compute_insn_live_regs(env, &insns[i], &state[i]);
24883
24884 changed = true;
24885 while (changed) {
24886 changed = false;
24887 for (i = 0; i < env->cfg.cur_postorder; ++i) {
24888 int insn_idx = env->cfg.insn_postorder[i];
24889 struct insn_live_regs *live = &state[insn_idx];
24890 struct bpf_iarray *succ;
24891 u16 new_out = 0;
24892 u16 new_in = 0;
24893
24894 succ = bpf_insn_successors(env, insn_idx);
24895 for (int s = 0; s < succ->cnt; ++s)
24896 new_out |= state[succ->items[s]].in;
24897 new_in = (new_out & ~live->def) | live->use;
24898 if (new_out != live->out || new_in != live->in) {
24899 live->in = new_in;
24900 live->out = new_out;
24901 changed = true;
24902 }
24903 }
24904 }
24905
24906 for (i = 0; i < insn_cnt; ++i)
24907 insn_aux[i].live_regs_before = state[i].in;
24908
24909 if (env->log.level & BPF_LOG_LEVEL2) {
24910 verbose(env, "Live regs before insn:\n");
24911 for (i = 0; i < insn_cnt; ++i) {
24912 if (env->insn_aux_data[i].scc)
24913 verbose(env, "%3d ", env->insn_aux_data[i].scc);
24914 else
24915 verbose(env, " ");
24916 verbose(env, "%3d: ", i);
24917 for (j = BPF_REG_0; j < BPF_REG_10; ++j)
24918 if (insn_aux[i].live_regs_before & BIT(j))
24919 verbose(env, "%d", j);
24920 else
24921 verbose(env, ".");
24922 verbose(env, " ");
24923 verbose_insn(env, &insns[i]);
24924 if (bpf_is_ldimm64(&insns[i]))
24925 i++;
24926 }
24927 }
24928
24929 out:
24930 kvfree(state);
24931 return err;
24932 }
24933
24934 /*
24935 * Compute strongly connected components (SCCs) on the CFG.
24936 * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc.
24937 * If instruction is a sole member of its SCC and there are no self edges,
24938 * assign it SCC number of zero.
24939 * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation.
24940 */
compute_scc(struct bpf_verifier_env * env)24941 static int compute_scc(struct bpf_verifier_env *env)
24942 {
24943 const u32 NOT_ON_STACK = U32_MAX;
24944
24945 struct bpf_insn_aux_data *aux = env->insn_aux_data;
24946 const u32 insn_cnt = env->prog->len;
24947 int stack_sz, dfs_sz, err = 0;
24948 u32 *stack, *pre, *low, *dfs;
24949 u32 i, j, t, w;
24950 u32 next_preorder_num;
24951 u32 next_scc_id;
24952 bool assign_scc;
24953 struct bpf_iarray *succ;
24954
24955 next_preorder_num = 1;
24956 next_scc_id = 1;
24957 /*
24958 * - 'stack' accumulates vertices in DFS order, see invariant comment below;
24959 * - 'pre[t] == p' => preorder number of vertex 't' is 'p';
24960 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n';
24961 * - 'dfs' DFS traversal stack, used to emulate explicit recursion.
24962 */
24963 stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24964 pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24965 low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT);
24966 dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT);
24967 if (!stack || !pre || !low || !dfs) {
24968 err = -ENOMEM;
24969 goto exit;
24970 }
24971 /*
24972 * References:
24973 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms"
24974 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components"
24975 *
24976 * The algorithm maintains the following invariant:
24977 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]';
24978 * - then, vertex 'u' remains on stack while vertex 'v' is on stack.
24979 *
24980 * Consequently:
24981 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u',
24982 * such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack,
24983 * and thus there is an SCC (loop) containing both 'u' and 'v'.
24984 * - If 'low[v] == pre[v]', loops containing 'v' have been explored,
24985 * and 'v' can be considered the root of some SCC.
24986 *
24987 * Here is a pseudo-code for an explicitly recursive version of the algorithm:
24988 *
24989 * NOT_ON_STACK = insn_cnt + 1
24990 * pre = [0] * insn_cnt
24991 * low = [0] * insn_cnt
24992 * scc = [0] * insn_cnt
24993 * stack = []
24994 *
24995 * next_preorder_num = 1
24996 * next_scc_id = 1
24997 *
24998 * def recur(w):
24999 * nonlocal next_preorder_num
25000 * nonlocal next_scc_id
25001 *
25002 * pre[w] = next_preorder_num
25003 * low[w] = next_preorder_num
25004 * next_preorder_num += 1
25005 * stack.append(w)
25006 * for s in successors(w):
25007 * # Note: for classic algorithm the block below should look as:
25008 * #
25009 * # if pre[s] == 0:
25010 * # recur(s)
25011 * # low[w] = min(low[w], low[s])
25012 * # elif low[s] != NOT_ON_STACK:
25013 * # low[w] = min(low[w], pre[s])
25014 * #
25015 * # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])'
25016 * # does not break the invariant and makes itartive version of the algorithm
25017 * # simpler. See 'Algorithm #3' from [2].
25018 *
25019 * # 's' not yet visited
25020 * if pre[s] == 0:
25021 * recur(s)
25022 * # if 's' is on stack, pick lowest reachable preorder number from it;
25023 * # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]',
25024 * # so 'min' would be a noop.
25025 * low[w] = min(low[w], low[s])
25026 *
25027 * if low[w] == pre[w]:
25028 * # 'w' is the root of an SCC, pop all vertices
25029 * # below 'w' on stack and assign same SCC to them.
25030 * while True:
25031 * t = stack.pop()
25032 * low[t] = NOT_ON_STACK
25033 * scc[t] = next_scc_id
25034 * if t == w:
25035 * break
25036 * next_scc_id += 1
25037 *
25038 * for i in range(0, insn_cnt):
25039 * if pre[i] == 0:
25040 * recur(i)
25041 *
25042 * Below implementation replaces explicit recursion with array 'dfs'.
25043 */
25044 for (i = 0; i < insn_cnt; i++) {
25045 if (pre[i])
25046 continue;
25047 stack_sz = 0;
25048 dfs_sz = 1;
25049 dfs[0] = i;
25050 dfs_continue:
25051 while (dfs_sz) {
25052 w = dfs[dfs_sz - 1];
25053 if (pre[w] == 0) {
25054 low[w] = next_preorder_num;
25055 pre[w] = next_preorder_num;
25056 next_preorder_num++;
25057 stack[stack_sz++] = w;
25058 }
25059 /* Visit 'w' successors */
25060 succ = bpf_insn_successors(env, w);
25061 for (j = 0; j < succ->cnt; ++j) {
25062 if (pre[succ->items[j]]) {
25063 low[w] = min(low[w], low[succ->items[j]]);
25064 } else {
25065 dfs[dfs_sz++] = succ->items[j];
25066 goto dfs_continue;
25067 }
25068 }
25069 /*
25070 * Preserve the invariant: if some vertex above in the stack
25071 * is reachable from 'w', keep 'w' on the stack.
25072 */
25073 if (low[w] < pre[w]) {
25074 dfs_sz--;
25075 goto dfs_continue;
25076 }
25077 /*
25078 * Assign SCC number only if component has two or more elements,
25079 * or if component has a self reference.
25080 */
25081 assign_scc = stack[stack_sz - 1] != w;
25082 for (j = 0; j < succ->cnt; ++j) {
25083 if (succ->items[j] == w) {
25084 assign_scc = true;
25085 break;
25086 }
25087 }
25088 /* Pop component elements from stack */
25089 do {
25090 t = stack[--stack_sz];
25091 low[t] = NOT_ON_STACK;
25092 if (assign_scc)
25093 aux[t].scc = next_scc_id;
25094 } while (t != w);
25095 if (assign_scc)
25096 next_scc_id++;
25097 dfs_sz--;
25098 }
25099 }
25100 env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT);
25101 if (!env->scc_info) {
25102 err = -ENOMEM;
25103 goto exit;
25104 }
25105 env->scc_cnt = next_scc_id;
25106 exit:
25107 kvfree(stack);
25108 kvfree(pre);
25109 kvfree(low);
25110 kvfree(dfs);
25111 return err;
25112 }
25113
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)25114 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
25115 {
25116 u64 start_time = ktime_get_ns();
25117 struct bpf_verifier_env *env;
25118 int i, len, ret = -EINVAL, err;
25119 u32 log_true_size;
25120 bool is_priv;
25121
25122 BTF_TYPE_EMIT(enum bpf_features);
25123
25124 /* no program is valid */
25125 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
25126 return -EINVAL;
25127
25128 /* 'struct bpf_verifier_env' can be global, but since it's not small,
25129 * allocate/free it every time bpf_check() is called
25130 */
25131 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT);
25132 if (!env)
25133 return -ENOMEM;
25134
25135 env->bt.env = env;
25136
25137 len = (*prog)->len;
25138 env->insn_aux_data =
25139 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
25140 ret = -ENOMEM;
25141 if (!env->insn_aux_data)
25142 goto err_free_env;
25143 for (i = 0; i < len; i++)
25144 env->insn_aux_data[i].orig_idx = i;
25145 env->succ = iarray_realloc(NULL, 2);
25146 if (!env->succ)
25147 goto err_free_env;
25148 env->prog = *prog;
25149 env->ops = bpf_verifier_ops[env->prog->type];
25150
25151 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token);
25152 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token);
25153 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token);
25154 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token);
25155 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF);
25156
25157 bpf_get_btf_vmlinux();
25158
25159 /* grab the mutex to protect few globals used by verifier */
25160 if (!is_priv)
25161 mutex_lock(&bpf_verifier_lock);
25162
25163 /* user could have requested verbose verifier output
25164 * and supplied buffer to store the verification trace
25165 */
25166 ret = bpf_vlog_init(&env->log, attr->log_level,
25167 (char __user *) (unsigned long) attr->log_buf,
25168 attr->log_size);
25169 if (ret)
25170 goto err_unlock;
25171
25172 ret = process_fd_array(env, attr, uattr);
25173 if (ret)
25174 goto skip_full_check;
25175
25176 mark_verifier_state_clean(env);
25177
25178 if (IS_ERR(btf_vmlinux)) {
25179 /* Either gcc or pahole or kernel are broken. */
25180 verbose(env, "in-kernel BTF is malformed\n");
25181 ret = PTR_ERR(btf_vmlinux);
25182 goto skip_full_check;
25183 }
25184
25185 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
25186 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
25187 env->strict_alignment = true;
25188 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
25189 env->strict_alignment = false;
25190
25191 if (is_priv)
25192 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
25193 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS;
25194
25195 env->explored_states = kvcalloc(state_htab_size(env),
25196 sizeof(struct list_head),
25197 GFP_KERNEL_ACCOUNT);
25198 ret = -ENOMEM;
25199 if (!env->explored_states)
25200 goto skip_full_check;
25201
25202 for (i = 0; i < state_htab_size(env); i++)
25203 INIT_LIST_HEAD(&env->explored_states[i]);
25204 INIT_LIST_HEAD(&env->free_list);
25205
25206 ret = check_btf_info_early(env, attr, uattr);
25207 if (ret < 0)
25208 goto skip_full_check;
25209
25210 ret = add_subprog_and_kfunc(env);
25211 if (ret < 0)
25212 goto skip_full_check;
25213
25214 ret = check_subprogs(env);
25215 if (ret < 0)
25216 goto skip_full_check;
25217
25218 ret = check_btf_info(env, attr, uattr);
25219 if (ret < 0)
25220 goto skip_full_check;
25221
25222 ret = resolve_pseudo_ldimm64(env);
25223 if (ret < 0)
25224 goto skip_full_check;
25225
25226 if (bpf_prog_is_offloaded(env->prog->aux)) {
25227 ret = bpf_prog_offload_verifier_prep(env->prog);
25228 if (ret)
25229 goto skip_full_check;
25230 }
25231
25232 ret = check_cfg(env);
25233 if (ret < 0)
25234 goto skip_full_check;
25235
25236 ret = compute_postorder(env);
25237 if (ret < 0)
25238 goto skip_full_check;
25239
25240 ret = bpf_stack_liveness_init(env);
25241 if (ret)
25242 goto skip_full_check;
25243
25244 ret = check_attach_btf_id(env);
25245 if (ret)
25246 goto skip_full_check;
25247
25248 ret = compute_scc(env);
25249 if (ret < 0)
25250 goto skip_full_check;
25251
25252 ret = compute_live_registers(env);
25253 if (ret < 0)
25254 goto skip_full_check;
25255
25256 ret = mark_fastcall_patterns(env);
25257 if (ret < 0)
25258 goto skip_full_check;
25259
25260 ret = do_check_main(env);
25261 ret = ret ?: do_check_subprogs(env);
25262
25263 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
25264 ret = bpf_prog_offload_finalize(env);
25265
25266 skip_full_check:
25267 kvfree(env->explored_states);
25268
25269 /* might decrease stack depth, keep it before passes that
25270 * allocate additional slots.
25271 */
25272 if (ret == 0)
25273 ret = remove_fastcall_spills_fills(env);
25274
25275 if (ret == 0)
25276 ret = check_max_stack_depth(env);
25277
25278 /* instruction rewrites happen after this point */
25279 if (ret == 0)
25280 ret = optimize_bpf_loop(env);
25281
25282 if (is_priv) {
25283 if (ret == 0)
25284 opt_hard_wire_dead_code_branches(env);
25285 if (ret == 0)
25286 ret = opt_remove_dead_code(env);
25287 if (ret == 0)
25288 ret = opt_remove_nops(env);
25289 } else {
25290 if (ret == 0)
25291 sanitize_dead_code(env);
25292 }
25293
25294 if (ret == 0)
25295 /* program is valid, convert *(u32*)(ctx + off) accesses */
25296 ret = convert_ctx_accesses(env);
25297
25298 if (ret == 0)
25299 ret = do_misc_fixups(env);
25300
25301 /* do 32-bit optimization after insn patching has done so those patched
25302 * insns could be handled correctly.
25303 */
25304 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
25305 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
25306 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
25307 : false;
25308 }
25309
25310 if (ret == 0)
25311 ret = fixup_call_args(env);
25312
25313 env->verification_time = ktime_get_ns() - start_time;
25314 print_verification_stats(env);
25315 env->prog->aux->verified_insns = env->insn_processed;
25316
25317 /* preserve original error even if log finalization is successful */
25318 err = bpf_vlog_finalize(&env->log, &log_true_size);
25319 if (err)
25320 ret = err;
25321
25322 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
25323 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
25324 &log_true_size, sizeof(log_true_size))) {
25325 ret = -EFAULT;
25326 goto err_release_maps;
25327 }
25328
25329 if (ret)
25330 goto err_release_maps;
25331
25332 if (env->used_map_cnt) {
25333 /* if program passed verifier, update used_maps in bpf_prog_info */
25334 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
25335 sizeof(env->used_maps[0]),
25336 GFP_KERNEL_ACCOUNT);
25337
25338 if (!env->prog->aux->used_maps) {
25339 ret = -ENOMEM;
25340 goto err_release_maps;
25341 }
25342
25343 memcpy(env->prog->aux->used_maps, env->used_maps,
25344 sizeof(env->used_maps[0]) * env->used_map_cnt);
25345 env->prog->aux->used_map_cnt = env->used_map_cnt;
25346 }
25347 if (env->used_btf_cnt) {
25348 /* if program passed verifier, update used_btfs in bpf_prog_aux */
25349 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
25350 sizeof(env->used_btfs[0]),
25351 GFP_KERNEL_ACCOUNT);
25352 if (!env->prog->aux->used_btfs) {
25353 ret = -ENOMEM;
25354 goto err_release_maps;
25355 }
25356
25357 memcpy(env->prog->aux->used_btfs, env->used_btfs,
25358 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
25359 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
25360 }
25361 if (env->used_map_cnt || env->used_btf_cnt) {
25362 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
25363 * bpf_ld_imm64 instructions
25364 */
25365 convert_pseudo_ld_imm64(env);
25366 }
25367
25368 adjust_btf_func(env);
25369
25370 err_release_maps:
25371 if (ret)
25372 release_insn_arrays(env);
25373 if (!env->prog->aux->used_maps)
25374 /* if we didn't copy map pointers into bpf_prog_info, release
25375 * them now. Otherwise free_used_maps() will release them.
25376 */
25377 release_maps(env);
25378 if (!env->prog->aux->used_btfs)
25379 release_btfs(env);
25380
25381 /* extension progs temporarily inherit the attach_type of their targets
25382 for verification purposes, so set it back to zero before returning
25383 */
25384 if (env->prog->type == BPF_PROG_TYPE_EXT)
25385 env->prog->expected_attach_type = 0;
25386
25387 *prog = env->prog;
25388
25389 module_put(env->attach_btf_mod);
25390 err_unlock:
25391 if (!is_priv)
25392 mutex_unlock(&bpf_verifier_lock);
25393 clear_insn_aux_data(env, 0, env->prog->len);
25394 vfree(env->insn_aux_data);
25395 err_free_env:
25396 bpf_stack_liveness_free(env);
25397 kvfree(env->cfg.insn_postorder);
25398 kvfree(env->scc_info);
25399 kvfree(env->succ);
25400 kvfree(env->gotox_tmp_buf);
25401 kvfree(env);
25402 return ret;
25403 }
25404